datasource.ts 15 KB

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