datasource.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. _.each(responseList, (response, index) => {
  153. if (response.status === 'error') {
  154. const error = {
  155. index,
  156. ...response.error,
  157. };
  158. throw error;
  159. }
  160. // Keeping original start/end for transformers
  161. const transformerOptions = {
  162. format: activeTargets[index].format,
  163. step: queries[index].step,
  164. legendFormat: activeTargets[index].legendFormat,
  165. start: queries[index].start,
  166. end: queries[index].end,
  167. query: queries[index].expr,
  168. responseListLength: responseList.length,
  169. refId: activeTargets[index].refId,
  170. valueWithRefId: activeTargets[index].valueWithRefId,
  171. };
  172. const series = this.resultTransformer.transform(response, transformerOptions);
  173. result = [...result, ...series];
  174. });
  175. return { data: result };
  176. });
  177. }
  178. createQuery(target, options, start, end) {
  179. const query: any = {
  180. hinting: target.hinting,
  181. instant: target.instant,
  182. };
  183. const range = Math.ceil(end - start);
  184. let interval = kbn.interval_to_seconds(options.interval);
  185. // Minimum interval ("Min step"), if specified for the query. or same as interval otherwise
  186. const minInterval = kbn.interval_to_seconds(
  187. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  188. );
  189. const intervalFactor = target.intervalFactor || 1;
  190. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  191. const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  192. let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars() };
  193. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  194. if (interval !== adjustedInterval) {
  195. interval = adjustedInterval;
  196. scopedVars = Object.assign({}, options.scopedVars, {
  197. __interval: { text: interval + 's', value: interval + 's' },
  198. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  199. ...this.getRangeScopedVars(),
  200. });
  201. }
  202. query.step = interval;
  203. let expr = target.expr;
  204. // Apply adhoc filters
  205. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  206. expr = adhocFilters.reduce((acc, filter) => {
  207. const { key, operator } = filter;
  208. let { value } = filter;
  209. if (operator === '=~' || operator === '!~') {
  210. value = prometheusSpecialRegexEscape(value);
  211. }
  212. return addLabelToQuery(acc, key, value, operator);
  213. }, expr);
  214. // Only replace vars in expression after having (possibly) updated interval vars
  215. query.expr = this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr);
  216. query.requestId = options.panelId + target.refId;
  217. // Align query interval with step
  218. const adjusted = alignRange(start, end, query.step);
  219. query.start = adjusted.start;
  220. query.end = adjusted.end;
  221. return query;
  222. }
  223. adjustInterval(interval, minInterval, range, intervalFactor) {
  224. // Prometheus will drop queries that might return more than 11000 data points.
  225. // Calibrate interval if it is too small.
  226. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  227. interval = Math.ceil(range / intervalFactor / 11000);
  228. }
  229. return Math.max(interval * intervalFactor, minInterval, 1);
  230. }
  231. performTimeSeriesQuery(query, start, end) {
  232. if (start > end) {
  233. throw { message: 'Invalid time range' };
  234. }
  235. const url = '/api/v1/query_range';
  236. const data = {
  237. query: query.expr,
  238. start: start,
  239. end: end,
  240. step: query.step,
  241. };
  242. if (this.queryTimeout) {
  243. data['timeout'] = this.queryTimeout;
  244. }
  245. return this._request(url, data, { requestId: query.requestId });
  246. }
  247. performInstantQuery(query, time) {
  248. const url = '/api/v1/query';
  249. const data = {
  250. query: query.expr,
  251. time: time,
  252. };
  253. if (this.queryTimeout) {
  254. data['timeout'] = this.queryTimeout;
  255. }
  256. return this._request(url, data, { requestId: query.requestId });
  257. }
  258. performSuggestQuery(query, cache = false) {
  259. const url = '/api/v1/label/__name__/values';
  260. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  261. return this.$q.when(
  262. _.filter(this.metricsNameCache.data, metricName => {
  263. return metricName.indexOf(query) !== 1;
  264. })
  265. );
  266. }
  267. return this.metadataRequest(url).then(result => {
  268. this.metricsNameCache = {
  269. data: result.data.data,
  270. expire: Date.now() + 60 * 1000,
  271. };
  272. return _.filter(result.data.data, metricName => {
  273. return metricName.indexOf(query) !== 1;
  274. });
  275. });
  276. }
  277. metricFindQuery(query) {
  278. if (!query) {
  279. return this.$q.when([]);
  280. }
  281. const scopedVars = {
  282. __interval: { text: this.interval, value: this.interval },
  283. __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
  284. ...this.getRangeScopedVars(),
  285. };
  286. const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
  287. const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  288. return metricFindQuery.process();
  289. }
  290. getRangeScopedVars() {
  291. const range = this.timeSrv.timeRange();
  292. const msRange = range.to.diff(range.from);
  293. const sRange = Math.round(msRange / 1000);
  294. const regularRange = kbn.secondsToHms(msRange / 1000);
  295. return {
  296. __range_ms: { text: msRange, value: msRange },
  297. __range_s: { text: sRange, value: sRange },
  298. __range: { text: regularRange, value: regularRange },
  299. };
  300. }
  301. annotationQuery(options) {
  302. const annotation = options.annotation;
  303. const expr = annotation.expr || '';
  304. let tagKeys = annotation.tagKeys || '';
  305. const titleFormat = annotation.titleFormat || '';
  306. const textFormat = annotation.textFormat || '';
  307. if (!expr) {
  308. return this.$q.when([]);
  309. }
  310. const step = annotation.step || '60s';
  311. const start = this.getPrometheusTime(options.range.from, false);
  312. const end = this.getPrometheusTime(options.range.to, true);
  313. // Unsetting min interval
  314. const queryOptions = {
  315. ...options,
  316. interval: '0s',
  317. };
  318. const query = this.createQuery({ expr, interval: step }, queryOptions, start, end);
  319. const self = this;
  320. return this.performTimeSeriesQuery(query, query.start, query.end).then(results => {
  321. const eventList = [];
  322. tagKeys = tagKeys.split(',');
  323. _.each(results.data.data.result, series => {
  324. const tags = _.chain(series.metric)
  325. .filter((v, k) => {
  326. return _.includes(tagKeys, k);
  327. })
  328. .value();
  329. for (const value of series.values) {
  330. const valueIsTrue = value[1] === '1'; // e.g. ALERTS
  331. if (valueIsTrue || annotation.useValueForTime) {
  332. const event = {
  333. annotation: annotation,
  334. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  335. tags: tags,
  336. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  337. };
  338. if (annotation.useValueForTime) {
  339. event['time'] = Math.floor(parseFloat(value[1]));
  340. } else {
  341. event['time'] = Math.floor(parseFloat(value[0])) * 1000;
  342. }
  343. eventList.push(event);
  344. }
  345. }
  346. });
  347. return eventList;
  348. });
  349. }
  350. testDatasource() {
  351. const now = new Date().getTime();
  352. return this.performInstantQuery({ expr: '1+1' }, now / 1000).then(response => {
  353. if (response.data.status === 'success') {
  354. return { status: 'success', message: 'Data source is working' };
  355. } else {
  356. return { status: 'error', message: response.error };
  357. }
  358. });
  359. }
  360. getExploreState(targets: any[]) {
  361. let state = {};
  362. if (targets && targets.length > 0) {
  363. const queries = targets.map(t => ({
  364. query: this.templateSrv.replace(t.expr, {}, this.interpolateQueryExpr),
  365. format: t.format,
  366. }));
  367. state = {
  368. ...state,
  369. queries,
  370. datasource: this.name,
  371. };
  372. }
  373. return state;
  374. }
  375. getQueryHints(query: string, result: any[]) {
  376. return getQueryHints(query, result, this);
  377. }
  378. loadRules() {
  379. this.metadataRequest('/api/v1/rules')
  380. .then(res => res.data || res.json())
  381. .then(body => {
  382. const groups = _.get(body, ['data', 'groups']);
  383. if (groups) {
  384. this.ruleMappings = extractRuleMappingFromGroups(groups);
  385. }
  386. })
  387. .catch(e => {
  388. console.log('Rules API is experimental. Ignore next error.');
  389. console.error(e);
  390. });
  391. }
  392. modifyQuery(query: string, action: any): string {
  393. switch (action.type) {
  394. case 'ADD_FILTER': {
  395. return addLabelToQuery(query, action.key, action.value);
  396. }
  397. case 'ADD_HISTOGRAM_QUANTILE': {
  398. return `histogram_quantile(0.95, sum(rate(${query}[5m])) by (le))`;
  399. }
  400. case 'ADD_RATE': {
  401. return `rate(${query}[5m])`;
  402. }
  403. case 'EXPAND_RULES': {
  404. const mapping = action.mapping;
  405. if (mapping) {
  406. const ruleNames = Object.keys(mapping);
  407. const rulesRegex = new RegExp(`(\\s|^)(${ruleNames.join('|')})(\\s|$|\\()`, 'ig');
  408. return query.replace(rulesRegex, (match, pre, name, post) => mapping[name]);
  409. }
  410. }
  411. default:
  412. return query;
  413. }
  414. }
  415. getPrometheusTime(date, roundUp) {
  416. if (_.isString(date)) {
  417. date = dateMath.parse(date, roundUp);
  418. }
  419. return Math.ceil(date.valueOf() / 1000);
  420. }
  421. getTimeRange(): { start: number; end: number } {
  422. const range = this.timeSrv.timeRange();
  423. return {
  424. start: this.getPrometheusTime(range.from, false),
  425. end: this.getPrometheusTime(range.to, true),
  426. };
  427. }
  428. getOriginalMetricName(labelData) {
  429. return this.resultTransformer.getOriginalMetricName(labelData);
  430. }
  431. }