datasource.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. 'app/core/utils/datemath',
  6. './query_ctrl',
  7. ],
  8. function (angular, _, moment, dateMath) {
  9. 'use strict';
  10. var durationSplitRegexp = /(\d+)(ms|s|m|h|d|w|M|y)/;
  11. /** @ngInject */
  12. function PrometheusDatasource(instanceSettings, $q, backendSrv, templateSrv) {
  13. this.type = 'prometheus';
  14. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  15. this.name = instanceSettings.name;
  16. this.supportMetrics = true;
  17. this.url = instanceSettings.url;
  18. this.directUrl = instanceSettings.directUrl;
  19. this.basicAuth = instanceSettings.basicAuth;
  20. this.withCredentials = instanceSettings.withCredentials;
  21. this.lastErrors = {};
  22. this._request = function(method, url) {
  23. var options = {
  24. url: this.url + url,
  25. method: method
  26. };
  27. if (this.basicAuth || this.withCredentials) {
  28. options.withCredentials = true;
  29. }
  30. if (this.basicAuth) {
  31. options.headers = {
  32. "Authorization": this.basicAuth
  33. };
  34. }
  35. return backendSrv.datasourceRequest(options);
  36. };
  37. // Called once per panel (graph)
  38. this.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], start, end));
  81. });
  82. });
  83. return { data: result };
  84. });
  85. };
  86. this.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. this.performSuggestQuery = function(query) {
  91. var url = '/api/v1/label/__name__/values';
  92. return this._request('GET', url).then(function(result) {
  93. return _.filter(result.data.data, function (metricName) {
  94. return metricName.indexOf(query) !== 1;
  95. });
  96. });
  97. };
  98. this.metricFindQuery = function(query) {
  99. if (!query) { return $q.when([]); }
  100. var interpolated;
  101. try {
  102. interpolated = templateSrv.replace(query);
  103. }
  104. catch (err) {
  105. return $q.reject(err);
  106. }
  107. var label_values_regex = /^label_values\(([^,]+)(?:,\s*(.+))?\)$/;
  108. var metric_names_regex = /^metrics\((.+)\)$/;
  109. var url;
  110. var label_values_query = interpolated.match(label_values_regex);
  111. if (label_values_query) {
  112. if (!label_values_query[2]) {
  113. // return label values globally
  114. url = '/api/v1/label/' + label_values_query[1] + '/values';
  115. return this._request('GET', url).then(function(result) {
  116. return _.map(result.data.data, function(value) {
  117. return {text: value};
  118. });
  119. });
  120. } else {
  121. url = '/api/v1/series?match[]=' + encodeURIComponent(label_values_query[1]);
  122. return this._request('GET', url)
  123. .then(function(result) {
  124. return _.map(result.data.data, function(metric) {
  125. return {
  126. text: metric[label_values_query[2]],
  127. expandable: true
  128. };
  129. });
  130. });
  131. }
  132. }
  133. var metric_names_query = interpolated.match(metric_names_regex);
  134. if (metric_names_query) {
  135. url = '/api/v1/label/__name__/values';
  136. return this._request('GET', url)
  137. .then(function(result) {
  138. return _.chain(result.data.data)
  139. .filter(function(metricName) {
  140. var r = new RegExp(metric_names_query[1]);
  141. return r.test(metricName);
  142. })
  143. .map(function(matchedMetricName) {
  144. return {
  145. text: matchedMetricName,
  146. expandable: true
  147. };
  148. })
  149. .value();
  150. });
  151. } else {
  152. // if query contains full metric name, return metric name and label list
  153. url = '/api/v1/series?match[]=' + encodeURIComponent(interpolated);
  154. return this._request('GET', url)
  155. .then(function(result) {
  156. return _.map(result.data.data, function(metric) {
  157. return {
  158. text: getOriginalMetricName(metric),
  159. expandable: true
  160. };
  161. });
  162. });
  163. }
  164. };
  165. this.testDatasource = function() {
  166. return this.metricFindQuery('metrics(.*)').then(function() {
  167. return { status: 'success', message: 'Data source is working', title: 'Success' };
  168. });
  169. };
  170. PrometheusDatasource.prototype.calculateInterval = function(interval, intervalFactor) {
  171. var m = interval.match(durationSplitRegexp);
  172. var dur = moment.duration(parseInt(m[1]), m[2]);
  173. var sec = dur.asSeconds();
  174. if (sec < 1) {
  175. sec = 1;
  176. }
  177. return Math.ceil(sec * intervalFactor);
  178. };
  179. function transformMetricData(md, options, start, end) {
  180. var dps = [],
  181. metricLabel = null;
  182. metricLabel = createMetricLabel(md.metric, options);
  183. var stepMs = parseInt(options.step) * 1000;
  184. var baseTimestamp = start * 1000;
  185. _.each(md.values, function(value) {
  186. var dp_value = parseFloat(value[1]);
  187. if (_.isNaN(dp_value)) {
  188. dp_value = null;
  189. }
  190. var timestamp = value[0] * 1000;
  191. for (var t = baseTimestamp; t < timestamp; t += stepMs) {
  192. dps.push([null, t]);
  193. }
  194. baseTimestamp = timestamp + stepMs;
  195. dps.push([dp_value, timestamp]);
  196. });
  197. var endTimestamp = end * 1000;
  198. for (var t = baseTimestamp; t <= endTimestamp; t += stepMs) {
  199. dps.push([null, t]);
  200. }
  201. return { target: metricLabel, datapoints: dps };
  202. }
  203. function createMetricLabel(labelData, options) {
  204. if (_.isUndefined(options) || _.isEmpty(options.legendFormat)) {
  205. return getOriginalMetricName(labelData);
  206. }
  207. var originalSettings = _.templateSettings;
  208. _.templateSettings = {
  209. interpolate: /\{\{(.+?)\}\}/g
  210. };
  211. var template = _.template(templateSrv.replace(options.legendFormat));
  212. var metricName;
  213. try {
  214. metricName = template(labelData);
  215. } catch (e) {
  216. metricName = '{}';
  217. }
  218. _.templateSettings = originalSettings;
  219. return metricName;
  220. }
  221. function getOriginalMetricName(labelData) {
  222. var metricName = labelData.__name__ || '';
  223. delete labelData.__name__;
  224. var labelPart = _.map(_.pairs(labelData), function(label) {
  225. return label[0] + '="' + label[1] + '"';
  226. }).join(',');
  227. return metricName + '{' + labelPart + '}';
  228. }
  229. function getPrometheusTime(date, roundUp) {
  230. if (_.isString(date)) {
  231. date = dateMath.parse(date, roundUp);
  232. }
  233. return (date.valueOf() / 1000).toFixed(0);
  234. }
  235. }
  236. return PrometheusDatasource;
  237. });