datasource.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 PrometheusLanguageProvider from './language_provider';
  8. import { BackendSrv } from 'app/core/services/backend_srv';
  9. import addLabelToQuery from './add_label_to_query';
  10. import { getQueryHints } from './query_hints';
  11. import { expandRecordingRules } from './language_utils';
  12. export function alignRange(start, end, step) {
  13. const alignedEnd = Math.ceil(end / step) * step;
  14. const alignedStart = Math.floor(start / step) * step;
  15. return {
  16. end: alignedEnd,
  17. start: alignedStart,
  18. };
  19. }
  20. export function extractRuleMappingFromGroups(groups: any[]) {
  21. return groups.reduce(
  22. (mapping, group) =>
  23. group.rules.filter(rule => rule.type === 'recording').reduce(
  24. (acc, rule) => ({
  25. ...acc,
  26. [rule.name]: rule.query,
  27. }),
  28. mapping
  29. ),
  30. {}
  31. );
  32. }
  33. export function prometheusRegularEscape(value) {
  34. if (typeof value === 'string') {
  35. return value.replace(/'/g, "\\\\'");
  36. }
  37. return value;
  38. }
  39. export function prometheusSpecialRegexEscape(value) {
  40. if (typeof value === 'string') {
  41. return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()]/g, '\\\\$&'));
  42. }
  43. return value;
  44. }
  45. export class PrometheusDatasource {
  46. type: string;
  47. editorSrc: string;
  48. name: string;
  49. ruleMappings: { [index: string]: string };
  50. url: string;
  51. directUrl: string;
  52. basicAuth: any;
  53. withCredentials: any;
  54. metricsNameCache: any;
  55. interval: string;
  56. queryTimeout: string;
  57. httpMethod: string;
  58. languageProvider: PrometheusLanguageProvider;
  59. resultTransformer: ResultTransformer;
  60. /** @ngInject */
  61. constructor(instanceSettings, private $q, private backendSrv: BackendSrv, private templateSrv, private timeSrv) {
  62. this.type = 'prometheus';
  63. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  64. this.name = instanceSettings.name;
  65. this.url = instanceSettings.url;
  66. this.directUrl = instanceSettings.directUrl;
  67. this.basicAuth = instanceSettings.basicAuth;
  68. this.withCredentials = instanceSettings.withCredentials;
  69. this.interval = instanceSettings.jsonData.timeInterval || '15s';
  70. this.queryTimeout = instanceSettings.jsonData.queryTimeout;
  71. this.httpMethod = instanceSettings.jsonData.httpMethod || 'GET';
  72. this.resultTransformer = new ResultTransformer(templateSrv);
  73. this.ruleMappings = {};
  74. this.languageProvider = new PrometheusLanguageProvider(this);
  75. }
  76. init() {
  77. this.loadRules();
  78. }
  79. _request(url, data?, options?: any) {
  80. options = _.defaults(options || {}, {
  81. url: this.url + url,
  82. method: this.httpMethod,
  83. });
  84. if (options.method === 'GET') {
  85. if (!_.isEmpty(data)) {
  86. options.url =
  87. options.url +
  88. '?' +
  89. _.map(data, (v, k) => {
  90. return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  91. }).join('&');
  92. }
  93. } else {
  94. options.headers = {
  95. 'Content-Type': 'application/x-www-form-urlencoded',
  96. };
  97. options.transformRequest = data => {
  98. return $.param(data);
  99. };
  100. options.data = data;
  101. }
  102. if (this.basicAuth || this.withCredentials) {
  103. options.withCredentials = true;
  104. }
  105. if (this.basicAuth) {
  106. options.headers = {
  107. Authorization: this.basicAuth,
  108. };
  109. }
  110. return this.backendSrv.datasourceRequest(options);
  111. }
  112. // Use this for tab completion features, wont publish response to other components
  113. metadataRequest(url) {
  114. return this._request(url, null, { method: 'GET', silent: true });
  115. }
  116. interpolateQueryExpr(value, variable, defaultFormatFn) {
  117. // if no multi or include all do not regexEscape
  118. if (!variable.multi && !variable.includeAll) {
  119. return prometheusRegularEscape(value);
  120. }
  121. if (typeof value === 'string') {
  122. return prometheusSpecialRegexEscape(value);
  123. }
  124. const escapedValues = _.map(value, prometheusSpecialRegexEscape);
  125. return escapedValues.join('|');
  126. }
  127. targetContainsTemplate(target) {
  128. return this.templateSrv.variableExists(target.expr);
  129. }
  130. query(options) {
  131. const start = this.getPrometheusTime(options.range.from, false);
  132. const end = this.getPrometheusTime(options.range.to, true);
  133. const queries = [];
  134. const activeTargets = [];
  135. options = _.clone(options);
  136. for (const target of options.targets) {
  137. if (!target.expr || target.hide) {
  138. continue;
  139. }
  140. activeTargets.push(target);
  141. queries.push(this.createQuery(target, options, start, end));
  142. }
  143. // No valid targets, return the empty result to save a round trip.
  144. if (_.isEmpty(queries)) {
  145. return this.$q.when({ data: [] });
  146. }
  147. const allQueryPromise = _.map(queries, query => {
  148. if (!query.instant) {
  149. return this.performTimeSeriesQuery(query, query.start, query.end);
  150. } else {
  151. return this.performInstantQuery(query, end);
  152. }
  153. });
  154. return this.$q.all(allQueryPromise).then(responseList => {
  155. let result = [];
  156. _.each(responseList, (response, index) => {
  157. if (response.status === 'error') {
  158. const error = {
  159. index,
  160. ...response.error,
  161. };
  162. throw error;
  163. }
  164. // Keeping original start/end for transformers
  165. const transformerOptions = {
  166. format: activeTargets[index].format,
  167. step: queries[index].step,
  168. legendFormat: activeTargets[index].legendFormat,
  169. start: queries[index].start,
  170. end: queries[index].end,
  171. query: queries[index].expr,
  172. responseListLength: responseList.length,
  173. refId: activeTargets[index].refId,
  174. valueWithRefId: activeTargets[index].valueWithRefId,
  175. };
  176. const series = this.resultTransformer.transform(response, transformerOptions);
  177. result = [...result, ...series];
  178. });
  179. return { data: result };
  180. });
  181. }
  182. createQuery(target, options, start, end) {
  183. const query: any = {
  184. hinting: target.hinting,
  185. instant: target.instant,
  186. };
  187. const range = Math.ceil(end - start);
  188. let interval = kbn.interval_to_seconds(options.interval);
  189. // Minimum interval ("Min step"), if specified for the query. or same as interval otherwise
  190. const minInterval = kbn.interval_to_seconds(
  191. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  192. );
  193. const intervalFactor = target.intervalFactor || 1;
  194. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  195. const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  196. let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars() };
  197. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  198. if (interval !== adjustedInterval) {
  199. interval = adjustedInterval;
  200. scopedVars = Object.assign({}, options.scopedVars, {
  201. __interval: { text: interval + 's', value: interval + 's' },
  202. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  203. ...this.getRangeScopedVars(),
  204. });
  205. }
  206. query.step = interval;
  207. let expr = target.expr;
  208. // Apply adhoc filters
  209. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  210. expr = adhocFilters.reduce((acc, filter) => {
  211. const { key, operator } = filter;
  212. let { value } = filter;
  213. if (operator === '=~' || operator === '!~') {
  214. value = prometheusSpecialRegexEscape(value);
  215. }
  216. return addLabelToQuery(acc, key, value, operator);
  217. }, expr);
  218. // Only replace vars in expression after having (possibly) updated interval vars
  219. query.expr = this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr);
  220. query.requestId = options.panelId + target.refId;
  221. // Align query interval with step
  222. const adjusted = alignRange(start, end, query.step);
  223. query.start = adjusted.start;
  224. query.end = adjusted.end;
  225. return query;
  226. }
  227. adjustInterval(interval, minInterval, range, intervalFactor) {
  228. // Prometheus will drop queries that might return more than 11000 data points.
  229. // Calibrate interval if it is too small.
  230. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  231. interval = Math.ceil(range / intervalFactor / 11000);
  232. }
  233. return Math.max(interval * intervalFactor, minInterval, 1);
  234. }
  235. performTimeSeriesQuery(query, start, end) {
  236. if (start > end) {
  237. throw { message: 'Invalid time range' };
  238. }
  239. const url = '/api/v1/query_range';
  240. const data = {
  241. query: query.expr,
  242. start: start,
  243. end: end,
  244. step: query.step,
  245. };
  246. if (this.queryTimeout) {
  247. data['timeout'] = this.queryTimeout;
  248. }
  249. return this._request(url, data, { requestId: query.requestId });
  250. }
  251. performInstantQuery(query, time) {
  252. const url = '/api/v1/query';
  253. const data = {
  254. query: query.expr,
  255. time: time,
  256. };
  257. if (this.queryTimeout) {
  258. data['timeout'] = this.queryTimeout;
  259. }
  260. return this._request(url, data, { requestId: query.requestId });
  261. }
  262. performSuggestQuery(query, cache = false) {
  263. const url = '/api/v1/label/__name__/values';
  264. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  265. return this.$q.when(
  266. _.filter(this.metricsNameCache.data, metricName => {
  267. return metricName.indexOf(query) !== 1;
  268. })
  269. );
  270. }
  271. return this.metadataRequest(url).then(result => {
  272. this.metricsNameCache = {
  273. data: result.data.data,
  274. expire: Date.now() + 60 * 1000,
  275. };
  276. return _.filter(result.data.data, metricName => {
  277. return metricName.indexOf(query) !== 1;
  278. });
  279. });
  280. }
  281. metricFindQuery(query) {
  282. if (!query) {
  283. return this.$q.when([]);
  284. }
  285. const scopedVars = {
  286. __interval: { text: this.interval, value: this.interval },
  287. __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
  288. ...this.getRangeScopedVars(),
  289. };
  290. const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
  291. const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  292. return metricFindQuery.process();
  293. }
  294. getRangeScopedVars() {
  295. const range = this.timeSrv.timeRange();
  296. const msRange = range.to.diff(range.from);
  297. const sRange = Math.round(msRange / 1000);
  298. const regularRange = kbn.secondsToHms(msRange / 1000);
  299. return {
  300. __range_ms: { text: msRange, value: msRange },
  301. __range_s: { text: sRange, value: sRange },
  302. __range: { text: regularRange, value: regularRange },
  303. };
  304. }
  305. annotationQuery(options) {
  306. const annotation = options.annotation;
  307. const expr = annotation.expr || '';
  308. let tagKeys = annotation.tagKeys || '';
  309. const titleFormat = annotation.titleFormat || '';
  310. const textFormat = annotation.textFormat || '';
  311. if (!expr) {
  312. return this.$q.when([]);
  313. }
  314. const step = annotation.step || '60s';
  315. const start = this.getPrometheusTime(options.range.from, false);
  316. const end = this.getPrometheusTime(options.range.to, true);
  317. // Unsetting min interval
  318. const queryOptions = {
  319. ...options,
  320. interval: '0s',
  321. };
  322. const query = this.createQuery({ expr, interval: step }, queryOptions, start, end);
  323. const self = this;
  324. return this.performTimeSeriesQuery(query, query.start, query.end).then(results => {
  325. const eventList = [];
  326. tagKeys = tagKeys.split(',');
  327. _.each(results.data.data.result, series => {
  328. const tags = _.chain(series.metric)
  329. .filter((v, k) => {
  330. return _.includes(tagKeys, k);
  331. })
  332. .value();
  333. for (const value of series.values) {
  334. const valueIsTrue = value[1] === '1'; // e.g. ALERTS
  335. if (valueIsTrue || annotation.useValueForTime) {
  336. const event = {
  337. annotation: annotation,
  338. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  339. tags: tags,
  340. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  341. };
  342. if (annotation.useValueForTime) {
  343. event['time'] = Math.floor(parseFloat(value[1]));
  344. } else {
  345. event['time'] = Math.floor(parseFloat(value[0])) * 1000;
  346. }
  347. eventList.push(event);
  348. }
  349. }
  350. });
  351. return eventList;
  352. });
  353. }
  354. testDatasource() {
  355. const now = new Date().getTime();
  356. return this.performInstantQuery({ expr: '1+1' }, now / 1000).then(response => {
  357. if (response.data.status === 'success') {
  358. return { status: 'success', message: 'Data source is working' };
  359. } else {
  360. return { status: 'error', message: response.error };
  361. }
  362. });
  363. }
  364. getExploreState(targets: any[]) {
  365. let state = {};
  366. if (targets && targets.length > 0) {
  367. const queries = targets.map(t => ({
  368. query: this.templateSrv.replace(t.expr, {}, this.interpolateQueryExpr),
  369. format: t.format,
  370. }));
  371. state = {
  372. ...state,
  373. queries,
  374. datasource: this.name,
  375. };
  376. }
  377. return state;
  378. }
  379. getQueryHints(query: string, result: any[]) {
  380. return getQueryHints(query, result, this);
  381. }
  382. loadRules() {
  383. this.metadataRequest('/api/v1/rules')
  384. .then(res => res.data || res.json())
  385. .then(body => {
  386. const groups = _.get(body, ['data', 'groups']);
  387. if (groups) {
  388. this.ruleMappings = extractRuleMappingFromGroups(groups);
  389. }
  390. })
  391. .catch(e => {
  392. console.log('Rules API is experimental. Ignore next error.');
  393. console.error(e);
  394. });
  395. }
  396. modifyQuery(query: string, action: any): string {
  397. switch (action.type) {
  398. case 'ADD_FILTER': {
  399. return addLabelToQuery(query, action.key, action.value);
  400. }
  401. case 'ADD_HISTOGRAM_QUANTILE': {
  402. return `histogram_quantile(0.95, sum(rate(${query}[5m])) by (le))`;
  403. }
  404. case 'ADD_RATE': {
  405. return `rate(${query}[5m])`;
  406. }
  407. case 'ADD_SUM': {
  408. return `sum(${query.trim()}) by ($1)`;
  409. }
  410. case 'EXPAND_RULES': {
  411. if (action.mapping) {
  412. return expandRecordingRules(query, action.mapping);
  413. }
  414. }
  415. default:
  416. return query;
  417. }
  418. }
  419. getPrometheusTime(date, roundUp) {
  420. if (_.isString(date)) {
  421. date = dateMath.parse(date, roundUp);
  422. }
  423. return Math.ceil(date.valueOf() / 1000);
  424. }
  425. getTimeRange(): { start: number; end: number } {
  426. const range = this.timeSrv.timeRange();
  427. return {
  428. start: this.getPrometheusTime(range.from, false),
  429. end: this.getPrometheusTime(range.to, true),
  430. };
  431. }
  432. getOriginalMetricName(labelData) {
  433. return this.resultTransformer.getOriginalMetricName(labelData);
  434. }
  435. }