datasource.ts 11 KB

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