datasource.js 8.4 KB

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