datasource.ts 16 KB

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