datasource.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 (query.indexOf('rate(') === -1 && 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. url: string;
  141. directUrl: string;
  142. basicAuth: any;
  143. withCredentials: any;
  144. metricsNameCache: any;
  145. interval: string;
  146. queryTimeout: string;
  147. httpMethod: string;
  148. resultTransformer: ResultTransformer;
  149. /** @ngInject */
  150. constructor(instanceSettings, private $q, private backendSrv: BackendSrv, private templateSrv, private timeSrv) {
  151. this.type = 'prometheus';
  152. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  153. this.name = instanceSettings.name;
  154. this.url = instanceSettings.url;
  155. this.directUrl = instanceSettings.directUrl;
  156. this.basicAuth = instanceSettings.basicAuth;
  157. this.withCredentials = instanceSettings.withCredentials;
  158. this.interval = instanceSettings.jsonData.timeInterval || '15s';
  159. this.queryTimeout = instanceSettings.jsonData.queryTimeout;
  160. this.httpMethod = instanceSettings.jsonData.httpMethod || 'GET';
  161. this.resultTransformer = new ResultTransformer(templateSrv);
  162. this.ruleMappings = {};
  163. }
  164. init() {
  165. this.loadRules();
  166. }
  167. _request(url, data?, options?: any) {
  168. options = _.defaults(options || {}, {
  169. url: this.url + url,
  170. method: this.httpMethod,
  171. });
  172. if (options.method === 'GET') {
  173. if (!_.isEmpty(data)) {
  174. options.url =
  175. options.url +
  176. '?' +
  177. _.map(data, (v, k) => {
  178. return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  179. }).join('&');
  180. }
  181. } else {
  182. options.headers = {
  183. 'Content-Type': 'application/x-www-form-urlencoded',
  184. };
  185. options.transformRequest = data => {
  186. return $.param(data);
  187. };
  188. options.data = data;
  189. }
  190. if (this.basicAuth || this.withCredentials) {
  191. options.withCredentials = true;
  192. }
  193. if (this.basicAuth) {
  194. options.headers = {
  195. Authorization: this.basicAuth,
  196. };
  197. }
  198. return this.backendSrv.datasourceRequest(options);
  199. }
  200. // Use this for tab completion features, wont publish response to other components
  201. metadataRequest(url) {
  202. return this._request(url, null, { method: 'GET', silent: true });
  203. }
  204. interpolateQueryExpr(value, variable, defaultFormatFn) {
  205. // if no multi or include all do not regexEscape
  206. if (!variable.multi && !variable.includeAll) {
  207. return prometheusRegularEscape(value);
  208. }
  209. if (typeof value === 'string') {
  210. return prometheusSpecialRegexEscape(value);
  211. }
  212. const escapedValues = _.map(value, prometheusSpecialRegexEscape);
  213. return escapedValues.join('|');
  214. }
  215. targetContainsTemplate(target) {
  216. return this.templateSrv.variableExists(target.expr);
  217. }
  218. query(options) {
  219. const start = this.getPrometheusTime(options.range.from, false);
  220. const end = this.getPrometheusTime(options.range.to, true);
  221. const queries = [];
  222. const activeTargets = [];
  223. options = _.clone(options);
  224. for (const target of options.targets) {
  225. if (!target.expr || target.hide) {
  226. continue;
  227. }
  228. activeTargets.push(target);
  229. queries.push(this.createQuery(target, options, start, end));
  230. }
  231. // No valid targets, return the empty result to save a round trip.
  232. if (_.isEmpty(queries)) {
  233. return this.$q.when({ data: [] });
  234. }
  235. const allQueryPromise = _.map(queries, query => {
  236. if (!query.instant) {
  237. return this.performTimeSeriesQuery(query, query.start, query.end);
  238. } else {
  239. return this.performInstantQuery(query, end);
  240. }
  241. });
  242. return this.$q.all(allQueryPromise).then(responseList => {
  243. let result = [];
  244. let hints = [];
  245. _.each(responseList, (response, index) => {
  246. if (response.status === 'error') {
  247. const error = {
  248. index,
  249. ...response.error,
  250. };
  251. throw error;
  252. }
  253. // Keeping original start/end for transformers
  254. const transformerOptions = {
  255. format: activeTargets[index].format,
  256. step: queries[index].step,
  257. legendFormat: activeTargets[index].legendFormat,
  258. start: queries[index].start,
  259. end: queries[index].end,
  260. query: queries[index].expr,
  261. responseListLength: responseList.length,
  262. responseIndex: index,
  263. refId: activeTargets[index].refId,
  264. };
  265. const series = this.resultTransformer.transform(response, transformerOptions);
  266. result = [...result, ...series];
  267. if (queries[index].hinting) {
  268. const queryHints = determineQueryHints(series, this);
  269. hints = [...hints, ...queryHints];
  270. }
  271. });
  272. return { data: result, hints };
  273. });
  274. }
  275. createQuery(target, options, start, end) {
  276. const query: any = {
  277. hinting: target.hinting,
  278. instant: target.instant,
  279. };
  280. const range = Math.ceil(end - start);
  281. let interval = kbn.interval_to_seconds(options.interval);
  282. // Minimum interval ("Min step"), if specified for the query. or same as interval otherwise
  283. const minInterval = kbn.interval_to_seconds(
  284. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  285. );
  286. const intervalFactor = target.intervalFactor || 1;
  287. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  288. const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  289. let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars() };
  290. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  291. if (interval !== adjustedInterval) {
  292. interval = adjustedInterval;
  293. scopedVars = Object.assign({}, options.scopedVars, {
  294. __interval: { text: interval + 's', value: interval + 's' },
  295. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  296. ...this.getRangeScopedVars(),
  297. });
  298. }
  299. query.step = interval;
  300. let expr = target.expr;
  301. // Apply adhoc filters
  302. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  303. expr = adhocFilters.reduce((acc, filter) => {
  304. const { key, operator } = filter;
  305. let { value } = filter;
  306. if (operator === '=~' || operator === '!~') {
  307. value = prometheusSpecialRegexEscape(value);
  308. }
  309. return addLabelToQuery(acc, key, value, operator);
  310. }, expr);
  311. // Only replace vars in expression after having (possibly) updated interval vars
  312. query.expr = this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr);
  313. query.requestId = options.panelId + target.refId;
  314. // Align query interval with step
  315. const adjusted = alignRange(start, end, query.step);
  316. query.start = adjusted.start;
  317. query.end = adjusted.end;
  318. return query;
  319. }
  320. adjustInterval(interval, minInterval, range, intervalFactor) {
  321. // Prometheus will drop queries that might return more than 11000 data points.
  322. // Calibrate interval if it is too small.
  323. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  324. interval = Math.ceil(range / intervalFactor / 11000);
  325. }
  326. return Math.max(interval * intervalFactor, minInterval, 1);
  327. }
  328. performTimeSeriesQuery(query, start, end) {
  329. if (start > end) {
  330. throw { message: 'Invalid time range' };
  331. }
  332. const url = '/api/v1/query_range';
  333. const data = {
  334. query: query.expr,
  335. start: start,
  336. end: end,
  337. step: query.step,
  338. };
  339. if (this.queryTimeout) {
  340. data['timeout'] = this.queryTimeout;
  341. }
  342. return this._request(url, data, { requestId: query.requestId });
  343. }
  344. performInstantQuery(query, time) {
  345. const url = '/api/v1/query';
  346. const data = {
  347. query: query.expr,
  348. time: time,
  349. };
  350. if (this.queryTimeout) {
  351. data['timeout'] = this.queryTimeout;
  352. }
  353. return this._request(url, data, { requestId: query.requestId });
  354. }
  355. performSuggestQuery(query, cache = false) {
  356. const url = '/api/v1/label/__name__/values';
  357. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  358. return this.$q.when(
  359. _.filter(this.metricsNameCache.data, metricName => {
  360. return metricName.indexOf(query) !== 1;
  361. })
  362. );
  363. }
  364. return this.metadataRequest(url).then(result => {
  365. this.metricsNameCache = {
  366. data: result.data.data,
  367. expire: Date.now() + 60 * 1000,
  368. };
  369. return _.filter(result.data.data, metricName => {
  370. return metricName.indexOf(query) !== 1;
  371. });
  372. });
  373. }
  374. metricFindQuery(query) {
  375. if (!query) {
  376. return this.$q.when([]);
  377. }
  378. const scopedVars = {
  379. __interval: { text: this.interval, value: this.interval },
  380. __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
  381. ...this.getRangeScopedVars(),
  382. };
  383. const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
  384. const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  385. return metricFindQuery.process();
  386. }
  387. getRangeScopedVars() {
  388. const range = this.timeSrv.timeRange();
  389. const msRange = range.to.diff(range.from);
  390. const sRange = Math.round(msRange / 1000);
  391. const regularRange = kbn.secondsToHms(msRange / 1000);
  392. return {
  393. __range_ms: { text: msRange, value: msRange },
  394. __range_s: { text: sRange, value: sRange },
  395. __range: { text: regularRange, value: regularRange },
  396. };
  397. }
  398. annotationQuery(options) {
  399. const annotation = options.annotation;
  400. const expr = annotation.expr || '';
  401. let tagKeys = annotation.tagKeys || '';
  402. const titleFormat = annotation.titleFormat || '';
  403. const textFormat = annotation.textFormat || '';
  404. if (!expr) {
  405. return this.$q.when([]);
  406. }
  407. const step = annotation.step || '60s';
  408. const start = this.getPrometheusTime(options.range.from, false);
  409. const end = this.getPrometheusTime(options.range.to, true);
  410. // Unsetting min interval
  411. const queryOptions = {
  412. ...options,
  413. interval: '0s',
  414. };
  415. const query = this.createQuery({ expr, interval: step }, queryOptions, start, end);
  416. const self = this;
  417. return this.performTimeSeriesQuery(query, query.start, query.end).then(results => {
  418. const eventList = [];
  419. tagKeys = tagKeys.split(',');
  420. _.each(results.data.data.result, series => {
  421. const tags = _.chain(series.metric)
  422. .filter((v, k) => {
  423. return _.includes(tagKeys, k);
  424. })
  425. .value();
  426. for (const value of series.values) {
  427. const valueIsTrue = value[1] === '1'; // e.g. ALERTS
  428. if (valueIsTrue || annotation.useValueForTime) {
  429. const event = {
  430. annotation: annotation,
  431. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  432. tags: tags,
  433. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  434. };
  435. if (annotation.useValueForTime) {
  436. event['time'] = Math.floor(parseFloat(value[1]));
  437. } else {
  438. event['time'] = Math.floor(parseFloat(value[0])) * 1000;
  439. }
  440. eventList.push(event);
  441. }
  442. }
  443. });
  444. return eventList;
  445. });
  446. }
  447. testDatasource() {
  448. const now = new Date().getTime();
  449. return this.performInstantQuery({ expr: '1+1' }, now / 1000).then(response => {
  450. if (response.data.status === 'success') {
  451. return { status: 'success', message: 'Data source is working' };
  452. } else {
  453. return { status: 'error', message: response.error };
  454. }
  455. });
  456. }
  457. getExploreState(targets: any[]) {
  458. let state = {};
  459. if (targets && targets.length > 0) {
  460. const queries = targets.map(t => ({
  461. query: this.templateSrv.replace(t.expr, {}, this.interpolateQueryExpr),
  462. format: t.format,
  463. }));
  464. state = {
  465. ...state,
  466. queries,
  467. datasource: this.name,
  468. };
  469. }
  470. return state;
  471. }
  472. loadRules() {
  473. this.metadataRequest('/api/v1/rules')
  474. .then(res => res.data || res.json())
  475. .then(body => {
  476. const groups = _.get(body, ['data', 'groups']);
  477. if (groups) {
  478. this.ruleMappings = extractRuleMappingFromGroups(groups);
  479. }
  480. })
  481. .catch(e => {
  482. console.log('Rules API is experimental. Ignore next error.');
  483. console.error(e);
  484. });
  485. }
  486. modifyQuery(query: string, action: any): string {
  487. switch (action.type) {
  488. case 'ADD_FILTER': {
  489. return addLabelToQuery(query, action.key, action.value);
  490. }
  491. case 'ADD_HISTOGRAM_QUANTILE': {
  492. return `histogram_quantile(0.95, sum(rate(${query}[5m])) by (le))`;
  493. }
  494. case 'ADD_RATE': {
  495. return `rate(${query}[5m])`;
  496. }
  497. case 'EXPAND_RULES': {
  498. const mapping = action.mapping;
  499. if (mapping) {
  500. const ruleNames = Object.keys(mapping);
  501. const rulesRegex = new RegExp(`(\\s|^)(${ruleNames.join('|')})(\\s|$|\\()`, 'ig');
  502. return query.replace(rulesRegex, (match, pre, name, post) => mapping[name]);
  503. }
  504. }
  505. default:
  506. return query;
  507. }
  508. }
  509. getPrometheusTime(date, roundUp) {
  510. if (_.isString(date)) {
  511. date = dateMath.parse(date, roundUp);
  512. }
  513. return Math.ceil(date.valueOf() / 1000);
  514. }
  515. getTimeRange(): { start: number; end: number } {
  516. const range = this.timeSrv.timeRange();
  517. return {
  518. start: this.getPrometheusTime(range.from, false),
  519. end: this.getPrometheusTime(range.to, true),
  520. };
  521. }
  522. getOriginalMetricName(labelData) {
  523. return this.resultTransformer.getOriginalMetricName(labelData);
  524. }
  525. }