datasource.ts 15 KB

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