datasource.ts 11 KB

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