datasource.ts 22 KB

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