datasource.ts 7.9 KB

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