datasource.ts 17 KB

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