datasource.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import _ from 'lodash';
  2. import $ from 'jquery';
  3. import kbn from 'app/core/utils/kbn';
  4. import * as dateMath from 'app/core/utils/datemath';
  5. import PrometheusMetricFindQuery from './metric_find_query';
  6. import { ResultTransformer } from './result_transformer';
  7. export function prometheusRegularEscape(value) {
  8. return value.replace(/'/g, "\\\\'");
  9. }
  10. export function prometheusSpecialRegexEscape(value) {
  11. return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()]/g, '\\\\$&'));
  12. }
  13. export class PrometheusDatasource {
  14. type: string;
  15. editorSrc: string;
  16. name: string;
  17. supportMetrics: boolean;
  18. url: string;
  19. directUrl: string;
  20. basicAuth: any;
  21. withCredentials: any;
  22. metricsNameCache: any;
  23. interval: string;
  24. httpMethod: string;
  25. resultTransformer: ResultTransformer;
  26. /** @ngInject */
  27. constructor(instanceSettings, private $q, private backendSrv, private templateSrv, private timeSrv) {
  28. this.type = 'prometheus';
  29. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  30. this.name = instanceSettings.name;
  31. this.supportMetrics = true;
  32. this.url = instanceSettings.url;
  33. this.directUrl = instanceSettings.directUrl;
  34. this.basicAuth = instanceSettings.basicAuth;
  35. this.withCredentials = instanceSettings.withCredentials;
  36. this.interval = instanceSettings.jsonData.timeInterval || '15s';
  37. this.httpMethod = instanceSettings.jsonData.httpMethod || 'GET';
  38. this.resultTransformer = new ResultTransformer(templateSrv);
  39. }
  40. _request(method, url, data?, requestId?) {
  41. var options: any = {
  42. url: this.url + url,
  43. method: method,
  44. requestId: requestId,
  45. };
  46. if (method === 'GET') {
  47. if (!_.isEmpty(data)) {
  48. options.url =
  49. options.url +
  50. '?' +
  51. _.map(data, (v, k) => {
  52. return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  53. }).join('&');
  54. }
  55. } else {
  56. options.headers = {
  57. 'Content-Type': 'application/x-www-form-urlencoded',
  58. };
  59. options.transformRequest = data => {
  60. return $.param(data);
  61. };
  62. options.data = data;
  63. }
  64. if (this.basicAuth || this.withCredentials) {
  65. options.withCredentials = true;
  66. }
  67. if (this.basicAuth) {
  68. options.headers = {
  69. Authorization: this.basicAuth,
  70. };
  71. }
  72. return this.backendSrv.datasourceRequest(options);
  73. }
  74. interpolateQueryExpr(value, variable, defaultFormatFn) {
  75. // if no multi or include all do not regexEscape
  76. if (!variable.multi && !variable.includeAll) {
  77. return prometheusRegularEscape(value);
  78. }
  79. if (typeof value === 'string') {
  80. return prometheusSpecialRegexEscape(value);
  81. }
  82. var escapedValues = _.map(value, prometheusSpecialRegexEscape);
  83. return escapedValues.join('|');
  84. }
  85. targetContainsTemplate(target) {
  86. return this.templateSrv.variableExists(target.expr);
  87. }
  88. query(options) {
  89. var start = this.getPrometheusTime(options.range.from, false);
  90. var end = this.getPrometheusTime(options.range.to, true);
  91. var range = Math.ceil(end - start);
  92. var queries = [];
  93. var activeTargets = [];
  94. options = _.clone(options);
  95. for (let target of options.targets) {
  96. if (!target.expr || target.hide) {
  97. continue;
  98. }
  99. activeTargets.push(target);
  100. queries.push(this.createQuery(target, options, range));
  101. }
  102. // No valid targets, return the empty result to save a round trip.
  103. if (_.isEmpty(queries)) {
  104. return this.$q.when({ data: [] });
  105. }
  106. var allQueryPromise = _.map(queries, query => {
  107. if (!query.instant) {
  108. return this.performTimeSeriesQuery(query, start, end);
  109. } else {
  110. return this.performInstantQuery(query, end);
  111. }
  112. });
  113. return this.$q.all(allQueryPromise).then(responseList => {
  114. let result = [];
  115. _.each(responseList, (response, index) => {
  116. if (response.status === 'error') {
  117. throw response.error;
  118. }
  119. let transformerOptions = {
  120. format: activeTargets[index].format,
  121. step: queries[index].step,
  122. legendFormat: activeTargets[index].legendFormat,
  123. start: start,
  124. end: end,
  125. responseListLength: responseList.length,
  126. responseIndex: index,
  127. };
  128. this.resultTransformer.transform(result, response, transformerOptions);
  129. });
  130. return { data: result };
  131. });
  132. }
  133. createQuery(target, options, range) {
  134. var query: any = {};
  135. query.instant = target.instant;
  136. var interval = kbn.interval_to_seconds(options.interval);
  137. // Minimum interval ("Min step"), if specified for the query. or same as interval otherwise
  138. var minInterval = kbn.interval_to_seconds(
  139. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  140. );
  141. var intervalFactor = target.intervalFactor || 1;
  142. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  143. var adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  144. var scopedVars = options.scopedVars;
  145. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  146. if (interval !== adjustedInterval) {
  147. interval = adjustedInterval;
  148. scopedVars = Object.assign({}, options.scopedVars, {
  149. __interval: { text: interval + 's', value: interval + 's' },
  150. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  151. });
  152. }
  153. query.step = interval;
  154. // Only replace vars in expression after having (possibly) updated interval vars
  155. query.expr = this.templateSrv.replace(target.expr, scopedVars, this.interpolateQueryExpr);
  156. query.requestId = options.panelId + target.refId;
  157. return query;
  158. }
  159. adjustInterval(interval, minInterval, range, intervalFactor) {
  160. // Prometheus will drop queries that might return more than 11000 data points.
  161. // Calibrate interval if it is too small.
  162. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  163. interval = Math.ceil(range / intervalFactor / 11000);
  164. }
  165. return Math.max(interval * intervalFactor, minInterval, 1);
  166. }
  167. performTimeSeriesQuery(query, start, end) {
  168. if (start > end) {
  169. throw { message: 'Invalid time range' };
  170. }
  171. var url = '/api/v1/query_range';
  172. var data = {
  173. query: query.expr,
  174. start: start,
  175. end: end,
  176. step: query.step,
  177. };
  178. return this._request(this.httpMethod, url, data, query.requestId);
  179. }
  180. performInstantQuery(query, time) {
  181. var url = '/api/v1/query';
  182. var data = {
  183. query: query.expr,
  184. time: time,
  185. };
  186. return this._request(this.httpMethod, url, data, query.requestId);
  187. }
  188. performSuggestQuery(query, cache = false) {
  189. var url = '/api/v1/label/__name__/values';
  190. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  191. return this.$q.when(
  192. _.filter(this.metricsNameCache.data, metricName => {
  193. return metricName.indexOf(query) !== 1;
  194. })
  195. );
  196. }
  197. return this._request('GET', url).then(result => {
  198. this.metricsNameCache = {
  199. data: result.data.data,
  200. expire: Date.now() + 60 * 1000,
  201. };
  202. return _.filter(result.data.data, metricName => {
  203. return metricName.indexOf(query) !== 1;
  204. });
  205. });
  206. }
  207. metricFindQuery(query) {
  208. if (!query) {
  209. return this.$q.when([]);
  210. }
  211. let interpolated = this.templateSrv.replace(query, {}, this.interpolateQueryExpr);
  212. var metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  213. return metricFindQuery.process();
  214. }
  215. annotationQuery(options) {
  216. var annotation = options.annotation;
  217. var expr = annotation.expr || '';
  218. var tagKeys = annotation.tagKeys || '';
  219. var titleFormat = annotation.titleFormat || '';
  220. var textFormat = annotation.textFormat || '';
  221. if (!expr) {
  222. return this.$q.when([]);
  223. }
  224. var interpolated = this.templateSrv.replace(expr, {}, this.interpolateQueryExpr);
  225. var step = '60s';
  226. if (annotation.step) {
  227. step = this.templateSrv.replace(annotation.step);
  228. }
  229. var start = this.getPrometheusTime(options.range.from, false);
  230. var end = this.getPrometheusTime(options.range.to, true);
  231. var query = {
  232. expr: interpolated,
  233. step: this.adjustInterval(kbn.interval_to_seconds(step), 0, Math.ceil(end - start), 1) + 's',
  234. };
  235. var self = this;
  236. return this.performTimeSeriesQuery(query, start, end).then(function(results) {
  237. var eventList = [];
  238. tagKeys = tagKeys.split(',');
  239. _.each(results.data.data.result, function(series) {
  240. var tags = _.chain(series.metric)
  241. .filter(function(v, k) {
  242. return _.includes(tagKeys, k);
  243. })
  244. .value();
  245. for (let value of series.values) {
  246. if (value[1] === '1') {
  247. var event = {
  248. annotation: annotation,
  249. time: Math.floor(parseFloat(value[0])) * 1000,
  250. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  251. tags: tags,
  252. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  253. };
  254. eventList.push(event);
  255. }
  256. }
  257. });
  258. return eventList;
  259. });
  260. }
  261. testDatasource() {
  262. let now = new Date().getTime();
  263. return this.performInstantQuery({ expr: '1+1' }, now / 1000).then(response => {
  264. if (response.data.status === 'success') {
  265. return { status: 'success', message: 'Data source is working' };
  266. } else {
  267. return { status: 'error', message: response.error };
  268. }
  269. });
  270. }
  271. getPrometheusTime(date, roundUp) {
  272. if (_.isString(date)) {
  273. date = dateMath.parse(date, roundUp);
  274. }
  275. return Math.ceil(date.valueOf() / 1000);
  276. }
  277. }