datasource.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. // Libraries
  2. import _ from 'lodash';
  3. import $ from 'jquery';
  4. // Services & Utils
  5. import kbn from 'app/core/utils/kbn';
  6. import { dateMath, TimeRange, DateTime, AnnotationEvent, LoadingState } from '@grafana/data';
  7. import { Observable, from, of } from 'rxjs';
  8. import { single, filter, mergeMap, catchError } from 'rxjs/operators';
  9. import PrometheusMetricFindQuery from './metric_find_query';
  10. import { ResultTransformer } from './result_transformer';
  11. import PrometheusLanguageProvider from './language_provider';
  12. import { BackendSrv } from 'app/core/services/backend_srv';
  13. import addLabelToQuery from './add_label_to_query';
  14. import { getQueryHints } from './query_hints';
  15. import { expandRecordingRules } from './language_utils';
  16. // Types
  17. import { PromQuery, PromOptions, PromQueryRequest, PromContext } from './types';
  18. import {
  19. DataQueryRequest,
  20. DataSourceApi,
  21. DataSourceInstanceSettings,
  22. DataQueryError,
  23. DataStreamObserver,
  24. DataQueryResponseData,
  25. DataStreamState,
  26. } from '@grafana/ui';
  27. import { ExploreUrlState } from 'app/types/explore';
  28. import { safeStringifyValue } from 'app/core/utils/explore';
  29. import { TemplateSrv } from 'app/features/templating/template_srv';
  30. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  31. export interface PromDataQueryResponse {
  32. data: {
  33. status: string;
  34. data: {
  35. resultType: string;
  36. results?: DataQueryResponseData[];
  37. result?: DataQueryResponseData[];
  38. };
  39. };
  40. cancelled?: boolean;
  41. }
  42. export class PrometheusDatasource extends DataSourceApi<PromQuery, PromOptions> {
  43. type: string;
  44. editorSrc: string;
  45. ruleMappings: { [index: string]: string };
  46. url: string;
  47. directUrl: string;
  48. basicAuth: any;
  49. withCredentials: any;
  50. metricsNameCache: any;
  51. interval: string;
  52. queryTimeout: string;
  53. httpMethod: string;
  54. languageProvider: PrometheusLanguageProvider;
  55. resultTransformer: ResultTransformer;
  56. /** @ngInject */
  57. constructor(
  58. instanceSettings: DataSourceInstanceSettings<PromOptions>,
  59. private $q: angular.IQService,
  60. private backendSrv: BackendSrv,
  61. private templateSrv: TemplateSrv,
  62. private timeSrv: TimeSrv
  63. ) {
  64. super(instanceSettings);
  65. this.type = 'prometheus';
  66. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  67. this.url = instanceSettings.url;
  68. this.basicAuth = instanceSettings.basicAuth;
  69. this.withCredentials = instanceSettings.withCredentials;
  70. this.interval = instanceSettings.jsonData.timeInterval || '15s';
  71. this.queryTimeout = instanceSettings.jsonData.queryTimeout;
  72. this.httpMethod = instanceSettings.jsonData.httpMethod || 'GET';
  73. this.directUrl = instanceSettings.jsonData.directUrl;
  74. this.resultTransformer = new ResultTransformer(templateSrv);
  75. this.ruleMappings = {};
  76. this.languageProvider = new PrometheusLanguageProvider(this);
  77. }
  78. init = () => {
  79. this.loadRules();
  80. };
  81. getQueryDisplayText(query: PromQuery) {
  82. return query.expr;
  83. }
  84. _addTracingHeaders(httpOptions: any, options: any) {
  85. httpOptions.headers = options.headers || {};
  86. const proxyMode = !this.url.match(/^http/);
  87. if (proxyMode) {
  88. httpOptions.headers['X-Dashboard-Id'] = options.dashboardId;
  89. httpOptions.headers['X-Panel-Id'] = options.panelId;
  90. }
  91. }
  92. _request(url: string, data?: any, options?: any) {
  93. options = _.defaults(options || {}, {
  94. url: this.url + url,
  95. method: this.httpMethod,
  96. headers: {},
  97. });
  98. if (options.method === 'GET') {
  99. if (!_.isEmpty(data)) {
  100. options.url =
  101. options.url +
  102. '?' +
  103. _.map(data, (v, k) => {
  104. return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  105. }).join('&');
  106. }
  107. } else {
  108. options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  109. options.transformRequest = (data: any) => {
  110. return $.param(data);
  111. };
  112. options.data = data;
  113. }
  114. if (this.basicAuth || this.withCredentials) {
  115. options.withCredentials = true;
  116. }
  117. if (this.basicAuth) {
  118. options.headers.Authorization = this.basicAuth;
  119. }
  120. return this.backendSrv.datasourceRequest(options);
  121. }
  122. // Use this for tab completion features, wont publish response to other components
  123. metadataRequest(url: string) {
  124. return this._request(url, null, { method: 'GET', silent: true });
  125. }
  126. interpolateQueryExpr(value: any, variable: any, defaultFormatFn: any) {
  127. // if no multi or include all do not regexEscape
  128. if (!variable.multi && !variable.includeAll) {
  129. return prometheusRegularEscape(value);
  130. }
  131. if (typeof value === 'string') {
  132. return prometheusSpecialRegexEscape(value);
  133. }
  134. const escapedValues = _.map(value, prometheusSpecialRegexEscape);
  135. return escapedValues.join('|');
  136. }
  137. targetContainsTemplate(target: PromQuery) {
  138. return this.templateSrv.variableExists(target.expr);
  139. }
  140. processResult = (response: any, query: PromQueryRequest, target: PromQuery, responseListLength: number) => {
  141. // Keeping original start/end for transformers
  142. const transformerOptions = {
  143. format: target.format,
  144. step: query.step,
  145. legendFormat: target.legendFormat,
  146. start: query.start,
  147. end: query.end,
  148. query: query.expr,
  149. responseListLength,
  150. refId: target.refId,
  151. valueWithRefId: target.valueWithRefId,
  152. };
  153. const series = this.resultTransformer.transform(response, transformerOptions);
  154. return series;
  155. };
  156. runObserverQueries = (
  157. options: DataQueryRequest<PromQuery>,
  158. observer: DataStreamObserver,
  159. queries: PromQueryRequest[],
  160. activeTargets: PromQuery[],
  161. end: number
  162. ) => {
  163. for (let index = 0; index < queries.length; index++) {
  164. const query = queries[index];
  165. const target = activeTargets[index];
  166. let observable: Observable<any> = null;
  167. if (query.instant) {
  168. observable = from(this.performInstantQuery(query, end));
  169. } else {
  170. observable = from(this.performTimeSeriesQuery(query, query.start, query.end));
  171. }
  172. observable
  173. .pipe(
  174. single(), // unsubscribes automatically after first result
  175. filter((response: any) => (response.cancelled ? false : true)),
  176. mergeMap((response: any) => {
  177. const data = this.processResult(response, query, target, queries.length);
  178. const state: DataStreamState = {
  179. key: `prometheus-${target.refId}`,
  180. state: LoadingState.Done,
  181. request: options,
  182. // TODO this is obviously wrong as data is not a DataFrame and needs to be dealt with later on
  183. // in PanelQueryState
  184. data: data as any,
  185. unsubscribe: () => undefined,
  186. };
  187. return [state];
  188. }),
  189. catchError(err => {
  190. const error = this.handleErrors(err, target);
  191. const state: DataStreamState = {
  192. key: `prometheus-${target.refId}`,
  193. request: options,
  194. state: LoadingState.Error,
  195. error,
  196. unsubscribe: () => undefined,
  197. };
  198. return of(state);
  199. })
  200. )
  201. .subscribe({
  202. next: state => observer(state),
  203. });
  204. }
  205. };
  206. prepareTargets = (options: DataQueryRequest<PromQuery>, start: number, end: number) => {
  207. const queries: PromQueryRequest[] = [];
  208. const activeTargets: PromQuery[] = [];
  209. for (const target of options.targets) {
  210. if (!target.expr || target.hide) {
  211. continue;
  212. }
  213. if (target.context === PromContext.Explore) {
  214. target.format = 'time_series';
  215. target.instant = false;
  216. const instantTarget: any = _.cloneDeep(target);
  217. instantTarget.format = 'table';
  218. instantTarget.instant = true;
  219. instantTarget.valueWithRefId = true;
  220. delete instantTarget.maxDataPoints;
  221. instantTarget.requestId += '_instant';
  222. instantTarget.refId += '_instant';
  223. activeTargets.push(instantTarget);
  224. queries.push(this.createQuery(instantTarget, options, start, end));
  225. }
  226. activeTargets.push(target);
  227. queries.push(this.createQuery(target, options, start, end));
  228. }
  229. return {
  230. queries,
  231. activeTargets,
  232. };
  233. };
  234. query(options: DataQueryRequest<PromQuery>, observer?: DataStreamObserver): Promise<{ data: any }> {
  235. const start = this.getPrometheusTime(options.range.from, false);
  236. const end = this.getPrometheusTime(options.range.to, true);
  237. options = _.clone(options);
  238. const { queries, activeTargets } = this.prepareTargets(options, start, end);
  239. // No valid targets, return the empty result to save a round trip.
  240. if (_.isEmpty(queries)) {
  241. return this.$q.when({ data: [] }) as Promise<{ data: any }>;
  242. }
  243. if (
  244. observer &&
  245. options.targets.filter(target => target.context === PromContext.Explore).length === options.targets.length
  246. ) {
  247. // using observer to make the instant query return immediately
  248. this.runObserverQueries(options, observer, queries, activeTargets, end);
  249. return this.$q.when({ data: [] }) as Promise<{ data: any }>;
  250. }
  251. const allQueryPromise = _.map(queries, query => {
  252. if (query.instant) {
  253. return this.performInstantQuery(query, end);
  254. } else {
  255. return this.performTimeSeriesQuery(query, query.start, query.end);
  256. }
  257. });
  258. const allPromise = this.$q.all(allQueryPromise).then((responseList: any) => {
  259. let result: any[] = [];
  260. _.each(responseList, (response, index: number) => {
  261. if (response.cancelled) {
  262. return;
  263. }
  264. const target = activeTargets[index];
  265. const query = queries[index];
  266. const series = this.processResult(response, query, target, queries.length);
  267. result = [...result, ...series];
  268. });
  269. return { data: result };
  270. });
  271. return allPromise as Promise<{ data: any }>;
  272. }
  273. createQuery(target: PromQuery, options: DataQueryRequest<PromQuery>, start: number, end: number) {
  274. const query: PromQueryRequest = {
  275. hinting: target.hinting,
  276. instant: target.instant,
  277. step: 0,
  278. expr: '',
  279. requestId: '',
  280. refId: '',
  281. start: 0,
  282. end: 0,
  283. };
  284. const range = Math.ceil(end - start);
  285. // options.interval is the dynamically calculated interval
  286. let interval = kbn.interval_to_seconds(options.interval);
  287. // Minimum interval ("Min step"), if specified for the query or datasource. or same as interval otherwise
  288. const minInterval = kbn.interval_to_seconds(
  289. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  290. );
  291. const intervalFactor = target.intervalFactor || 1;
  292. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  293. const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  294. let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars(options.range) };
  295. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  296. if (interval !== adjustedInterval) {
  297. interval = adjustedInterval;
  298. scopedVars = Object.assign({}, options.scopedVars, {
  299. __interval: { text: interval + 's', value: interval + 's' },
  300. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  301. ...this.getRangeScopedVars(options.range),
  302. });
  303. }
  304. query.step = interval;
  305. let expr = target.expr;
  306. // Apply adhoc filters
  307. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  308. expr = adhocFilters.reduce((acc: string, filter: { key?: any; operator?: any; value?: any }) => {
  309. const { key, operator } = filter;
  310. let { value } = filter;
  311. if (operator === '=~' || operator === '!~') {
  312. value = prometheusRegularEscape(value);
  313. }
  314. return addLabelToQuery(acc, key, value, operator);
  315. }, expr);
  316. // Only replace vars in expression after having (possibly) updated interval vars
  317. query.expr = this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr);
  318. query.requestId = options.panelId + target.refId;
  319. query.refId = target.refId;
  320. // Align query interval with step to allow query caching and to ensure
  321. // that about-same-time query results look the same.
  322. const adjusted = alignRange(start, end, query.step, this.timeSrv.timeRange().to.utcOffset() * 60);
  323. query.start = adjusted.start;
  324. query.end = adjusted.end;
  325. this._addTracingHeaders(query, options);
  326. return query;
  327. }
  328. adjustInterval(interval: number, minInterval: number, range: number, intervalFactor: number) {
  329. // Prometheus will drop queries that might return more than 11000 data points.
  330. // Calibrate interval if it is too small.
  331. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  332. interval = Math.ceil(range / intervalFactor / 11000);
  333. }
  334. return Math.max(interval * intervalFactor, minInterval, 1);
  335. }
  336. performTimeSeriesQuery(query: PromQueryRequest, start: number, end: number) {
  337. if (start > end) {
  338. throw { message: 'Invalid time range' };
  339. }
  340. const url = '/api/v1/query_range';
  341. const data: any = {
  342. query: query.expr,
  343. start,
  344. end,
  345. step: query.step,
  346. };
  347. if (this.queryTimeout) {
  348. data['timeout'] = this.queryTimeout;
  349. }
  350. return this._request(url, data, { requestId: query.requestId, headers: query.headers }).catch((err: any) => {
  351. if (err.cancelled) {
  352. return err;
  353. }
  354. throw this.handleErrors(err, query);
  355. });
  356. }
  357. performInstantQuery(query: PromQueryRequest, time: number) {
  358. const url = '/api/v1/query';
  359. const data: any = {
  360. query: query.expr,
  361. time,
  362. };
  363. if (this.queryTimeout) {
  364. data['timeout'] = this.queryTimeout;
  365. }
  366. return this._request(url, data, { requestId: query.requestId, headers: query.headers }).catch((err: any) => {
  367. if (err.cancelled) {
  368. return err;
  369. }
  370. throw this.handleErrors(err, query);
  371. });
  372. }
  373. handleErrors = (err: any, target: PromQuery) => {
  374. const error: DataQueryError = {
  375. message: 'Unknown error during query transaction. Please check JS console logs.',
  376. refId: target.refId,
  377. };
  378. if (err.data) {
  379. if (typeof err.data === 'string') {
  380. error.message = err.data;
  381. } else if (err.data.error) {
  382. error.message = safeStringifyValue(err.data.error);
  383. }
  384. } else if (err.message) {
  385. error.message = err.message;
  386. } else if (typeof err === 'string') {
  387. error.message = err;
  388. }
  389. error.status = err.status;
  390. error.statusText = err.statusText;
  391. return error;
  392. };
  393. performSuggestQuery(query: string, cache = false) {
  394. const url = '/api/v1/label/__name__/values';
  395. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  396. return this.$q.when(
  397. _.filter(this.metricsNameCache.data, metricName => {
  398. return metricName.indexOf(query) !== 1;
  399. })
  400. );
  401. }
  402. return this.metadataRequest(url).then((result: PromDataQueryResponse) => {
  403. this.metricsNameCache = {
  404. data: result.data.data,
  405. expire: Date.now() + 60 * 1000,
  406. };
  407. return _.filter(result.data.data, metricName => {
  408. return metricName.indexOf(query) !== 1;
  409. });
  410. });
  411. }
  412. metricFindQuery(query: string) {
  413. if (!query) {
  414. return this.$q.when([]);
  415. }
  416. const scopedVars = {
  417. __interval: { text: this.interval, value: this.interval },
  418. __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
  419. ...this.getRangeScopedVars(this.timeSrv.timeRange()),
  420. };
  421. const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
  422. const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  423. return metricFindQuery.process();
  424. }
  425. getRangeScopedVars(range: TimeRange) {
  426. range = range || this.timeSrv.timeRange();
  427. const msRange = range.to.diff(range.from);
  428. const sRange = Math.round(msRange / 1000);
  429. const regularRange = kbn.secondsToHms(msRange / 1000);
  430. return {
  431. __range_ms: { text: msRange, value: msRange },
  432. __range_s: { text: sRange, value: sRange },
  433. __range: { text: regularRange, value: regularRange },
  434. };
  435. }
  436. annotationQuery(options: any) {
  437. const annotation = options.annotation;
  438. const expr = annotation.expr || '';
  439. let tagKeys = annotation.tagKeys || '';
  440. const titleFormat = annotation.titleFormat || '';
  441. const textFormat = annotation.textFormat || '';
  442. if (!expr) {
  443. return this.$q.when([]);
  444. }
  445. const step = annotation.step || '60s';
  446. const start = this.getPrometheusTime(options.range.from, false);
  447. const end = this.getPrometheusTime(options.range.to, true);
  448. const queryOptions = {
  449. ...options,
  450. interval: step,
  451. };
  452. // Unsetting min interval for accurate event resolution
  453. const minStep = '1s';
  454. const query = this.createQuery({ expr, interval: minStep, refId: 'X' }, queryOptions, start, end);
  455. const self = this;
  456. return this.performTimeSeriesQuery(query, query.start, query.end).then((results: PromDataQueryResponse) => {
  457. const eventList: AnnotationEvent[] = [];
  458. tagKeys = tagKeys.split(',');
  459. if (results.cancelled) {
  460. return [];
  461. }
  462. _.each(results.data.data.result, series => {
  463. const tags = _.chain(series.metric)
  464. .filter((v, k) => {
  465. return _.includes(tagKeys, k);
  466. })
  467. .value();
  468. const dupCheck: { [key: number]: boolean } = {};
  469. for (const value of series.values) {
  470. const valueIsTrue = value[1] === '1'; // e.g. ALERTS
  471. if (valueIsTrue || annotation.useValueForTime) {
  472. const event: AnnotationEvent = {
  473. annotation: annotation,
  474. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  475. tags: tags,
  476. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  477. };
  478. if (annotation.useValueForTime) {
  479. const timestampValue = Math.floor(parseFloat(value[1]));
  480. if (dupCheck[timestampValue]) {
  481. continue;
  482. }
  483. dupCheck[timestampValue] = true;
  484. event.time = timestampValue;
  485. } else {
  486. event.time = Math.floor(parseFloat(value[0])) * 1000;
  487. }
  488. eventList.push(event);
  489. }
  490. }
  491. });
  492. return eventList;
  493. });
  494. }
  495. getTagKeys(options: any = {}) {
  496. const url = '/api/v1/labels';
  497. return this.metadataRequest(url).then((result: any) => {
  498. return _.map(result.data.data, value => {
  499. return { text: value };
  500. });
  501. });
  502. }
  503. getTagValues(options: any = {}) {
  504. const url = '/api/v1/label/' + options.key + '/values';
  505. return this.metadataRequest(url).then((result: any) => {
  506. return _.map(result.data.data, value => {
  507. return { text: value };
  508. });
  509. });
  510. }
  511. testDatasource() {
  512. const now = new Date().getTime();
  513. const query = { expr: '1+1' } as PromQueryRequest;
  514. return this.performInstantQuery(query, now / 1000).then((response: any) => {
  515. if (response.data.status === 'success') {
  516. return { status: 'success', message: 'Data source is working' };
  517. } else {
  518. return { status: 'error', message: response.error };
  519. }
  520. });
  521. }
  522. getExploreState(queries: PromQuery[]): Partial<ExploreUrlState> {
  523. let state: Partial<ExploreUrlState> = { datasource: this.name };
  524. if (queries && queries.length > 0) {
  525. const expandedQueries = queries.map(query => ({
  526. ...query,
  527. expr: this.templateSrv.replace(query.expr, {}, this.interpolateQueryExpr),
  528. context: 'explore',
  529. // null out values we don't support in Explore yet
  530. legendFormat: null,
  531. step: null,
  532. }));
  533. state = {
  534. ...state,
  535. queries: expandedQueries,
  536. };
  537. }
  538. return state;
  539. }
  540. getQueryHints(query: PromQuery, result: any[]) {
  541. return getQueryHints(query.expr || '', result, this);
  542. }
  543. loadRules() {
  544. this.metadataRequest('/api/v1/rules')
  545. .then((res: any) => res.data || res.json())
  546. .then((body: any) => {
  547. const groups = _.get(body, ['data', 'groups']);
  548. if (groups) {
  549. this.ruleMappings = extractRuleMappingFromGroups(groups);
  550. }
  551. })
  552. .catch((e: any) => {
  553. console.log('Rules API is experimental. Ignore next error.');
  554. console.error(e);
  555. });
  556. }
  557. modifyQuery(query: PromQuery, action: any): PromQuery {
  558. let expression = query.expr || '';
  559. switch (action.type) {
  560. case 'ADD_FILTER': {
  561. expression = addLabelToQuery(expression, action.key, action.value);
  562. break;
  563. }
  564. case 'ADD_HISTOGRAM_QUANTILE': {
  565. expression = `histogram_quantile(0.95, sum(rate(${expression}[5m])) by (le))`;
  566. break;
  567. }
  568. case 'ADD_RATE': {
  569. expression = `rate(${expression}[5m])`;
  570. break;
  571. }
  572. case 'ADD_SUM': {
  573. expression = `sum(${expression.trim()}) by ($1)`;
  574. break;
  575. }
  576. case 'EXPAND_RULES': {
  577. if (action.mapping) {
  578. expression = expandRecordingRules(expression, action.mapping);
  579. }
  580. break;
  581. }
  582. default:
  583. break;
  584. }
  585. return { ...query, expr: expression };
  586. }
  587. getPrometheusTime(date: string | DateTime, roundUp: boolean) {
  588. if (_.isString(date)) {
  589. date = dateMath.parse(date, roundUp);
  590. }
  591. return Math.ceil(date.valueOf() / 1000);
  592. }
  593. getTimeRange(): { start: number; end: number } {
  594. const range = this.timeSrv.timeRange();
  595. return {
  596. start: this.getPrometheusTime(range.from, false),
  597. end: this.getPrometheusTime(range.to, true),
  598. };
  599. }
  600. getOriginalMetricName(labelData: { [key: string]: string }) {
  601. return this.resultTransformer.getOriginalMetricName(labelData);
  602. }
  603. }
  604. /**
  605. * Align query range to step.
  606. * Rounds start and end down to a multiple of step.
  607. * @param start Timestamp marking the beginning of the range.
  608. * @param end Timestamp marking the end of the range.
  609. * @param step Interval to align start and end with.
  610. * @param utcOffsetSec Number of seconds current timezone is offset from UTC
  611. */
  612. export function alignRange(
  613. start: number,
  614. end: number,
  615. step: number,
  616. utcOffsetSec: number
  617. ): { end: number; start: number } {
  618. const alignedEnd = Math.floor((end + utcOffsetSec) / step) * step - utcOffsetSec;
  619. const alignedStart = Math.floor((start + utcOffsetSec) / step) * step - utcOffsetSec;
  620. return {
  621. end: alignedEnd,
  622. start: alignedStart,
  623. };
  624. }
  625. export function extractRuleMappingFromGroups(groups: any[]) {
  626. return groups.reduce(
  627. (mapping, group) =>
  628. group.rules
  629. .filter((rule: any) => rule.type === 'recording')
  630. .reduce(
  631. (acc: { [key: string]: string }, rule: any) => ({
  632. ...acc,
  633. [rule.name]: rule.query,
  634. }),
  635. mapping
  636. ),
  637. {}
  638. );
  639. }
  640. export function prometheusRegularEscape(value: any) {
  641. if (typeof value === 'string') {
  642. return value.replace(/'/g, "\\\\'");
  643. }
  644. return value;
  645. }
  646. export function prometheusSpecialRegexEscape(value: any) {
  647. if (typeof value === 'string') {
  648. return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()|]/g, '\\\\$&'));
  649. }
  650. return value;
  651. }