datasource.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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 } from '@grafana/data';
  7. import { Observable, from, of, merge } from 'rxjs';
  8. import { filter, map } 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. DataQueryResponseData,
  24. DataQueryResponse,
  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. import { LoadingState } from '@grafana/data/src/types/data';
  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. prepareTargets = (options: DataQueryRequest<PromQuery>, start: number, end: number) => {
  157. const queries: PromQueryRequest[] = [];
  158. const activeTargets: PromQuery[] = [];
  159. for (const target of options.targets) {
  160. if (!target.expr || target.hide) {
  161. continue;
  162. }
  163. target.requestId = options.panelId + target.refId;
  164. if (target.context !== PromContext.Explore) {
  165. activeTargets.push(target);
  166. queries.push(this.createQuery(target, options, start, end));
  167. continue;
  168. }
  169. if (target.showingTable) {
  170. // create instant target only if Table is showed in Explore
  171. const instantTarget: any = _.cloneDeep(target);
  172. instantTarget.format = 'table';
  173. instantTarget.instant = true;
  174. instantTarget.valueWithRefId = true;
  175. delete instantTarget.maxDataPoints;
  176. instantTarget.requestId += '_instant';
  177. activeTargets.push(instantTarget);
  178. queries.push(this.createQuery(instantTarget, options, start, end));
  179. }
  180. if (target.showingGraph) {
  181. // create time series target only if Graph is showed in Explore
  182. target.format = 'time_series';
  183. target.instant = false;
  184. activeTargets.push(target);
  185. queries.push(this.createQuery(target, options, start, end));
  186. }
  187. }
  188. return {
  189. queries,
  190. activeTargets,
  191. };
  192. };
  193. query(options: DataQueryRequest<PromQuery>): Observable<DataQueryResponse> {
  194. const start = this.getPrometheusTime(options.range.from, false);
  195. const end = this.getPrometheusTime(options.range.to, true);
  196. const { queries, activeTargets } = this.prepareTargets(options, start, end);
  197. // No valid targets, return the empty result to save a round trip.
  198. if (_.isEmpty(queries)) {
  199. return of({ data: [] });
  200. }
  201. const allInstant = queries.filter(query => query.instant).length === queries.length;
  202. const allTimeSeries = queries.filter(query => !query.instant).length === queries.length;
  203. const subQueries = queries.map((query, index) => {
  204. const target = activeTargets[index];
  205. let observable: Observable<any> = null;
  206. const state: LoadingState =
  207. allInstant || allTimeSeries ? LoadingState.Done : query.instant ? LoadingState.Loading : LoadingState.Done;
  208. if (query.instant) {
  209. observable = from(this.performInstantQuery(query, end));
  210. } else {
  211. observable = from(this.performTimeSeriesQuery(query, query.start, query.end));
  212. }
  213. return observable.pipe(
  214. filter((response: any) => (response.cancelled ? false : true)),
  215. map((response: any) => {
  216. const data = this.processResult(response, query, target, queries.length);
  217. return {
  218. data,
  219. key: query.requestId,
  220. state,
  221. } as DataQueryResponse;
  222. })
  223. );
  224. });
  225. return merge(...subQueries);
  226. }
  227. createQuery(target: PromQuery, options: DataQueryRequest<PromQuery>, start: number, end: number) {
  228. const query: PromQueryRequest = {
  229. hinting: target.hinting,
  230. instant: target.instant,
  231. step: 0,
  232. expr: '',
  233. requestId: target.requestId,
  234. refId: target.refId,
  235. start: 0,
  236. end: 0,
  237. };
  238. const range = Math.ceil(end - start);
  239. // options.interval is the dynamically calculated interval
  240. let interval = kbn.interval_to_seconds(options.interval);
  241. // Minimum interval ("Min step"), if specified for the query or datasource. or same as interval otherwise
  242. const minInterval = kbn.interval_to_seconds(
  243. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  244. );
  245. const intervalFactor = target.intervalFactor || 1;
  246. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  247. const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  248. let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars(options.range) };
  249. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  250. if (interval !== adjustedInterval) {
  251. interval = adjustedInterval;
  252. scopedVars = Object.assign({}, options.scopedVars, {
  253. __interval: { text: interval + 's', value: interval + 's' },
  254. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  255. ...this.getRangeScopedVars(options.range),
  256. });
  257. }
  258. query.step = interval;
  259. let expr = target.expr;
  260. // Apply adhoc filters
  261. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  262. expr = adhocFilters.reduce((acc: string, filter: { key?: any; operator?: any; value?: any }) => {
  263. const { key, operator } = filter;
  264. let { value } = filter;
  265. if (operator === '=~' || operator === '!~') {
  266. value = prometheusRegularEscape(value);
  267. }
  268. return addLabelToQuery(acc, key, value, operator);
  269. }, expr);
  270. // Only replace vars in expression after having (possibly) updated interval vars
  271. query.expr = this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr);
  272. // Align query interval with step to allow query caching and to ensure
  273. // that about-same-time query results look the same.
  274. const adjusted = alignRange(start, end, query.step, this.timeSrv.timeRange().to.utcOffset() * 60);
  275. query.start = adjusted.start;
  276. query.end = adjusted.end;
  277. this._addTracingHeaders(query, options);
  278. return query;
  279. }
  280. adjustInterval(interval: number, minInterval: number, range: number, intervalFactor: number) {
  281. // Prometheus will drop queries that might return more than 11000 data points.
  282. // Calibrate interval if it is too small.
  283. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  284. interval = Math.ceil(range / intervalFactor / 11000);
  285. }
  286. return Math.max(interval * intervalFactor, minInterval, 1);
  287. }
  288. performTimeSeriesQuery(query: PromQueryRequest, start: number, end: number) {
  289. if (start > end) {
  290. throw { message: 'Invalid time range' };
  291. }
  292. const url = '/api/v1/query_range';
  293. const data: any = {
  294. query: query.expr,
  295. start,
  296. end,
  297. step: query.step,
  298. };
  299. if (this.queryTimeout) {
  300. data['timeout'] = this.queryTimeout;
  301. }
  302. return this._request(url, data, { requestId: query.requestId, headers: query.headers }).catch((err: any) => {
  303. if (err.cancelled) {
  304. return err;
  305. }
  306. throw this.handleErrors(err, query);
  307. });
  308. }
  309. performInstantQuery(query: PromQueryRequest, time: number) {
  310. const url = '/api/v1/query';
  311. const data: any = {
  312. query: query.expr,
  313. time,
  314. };
  315. if (this.queryTimeout) {
  316. data['timeout'] = this.queryTimeout;
  317. }
  318. return this._request(url, data, { requestId: query.requestId, headers: query.headers }).catch((err: any) => {
  319. if (err.cancelled) {
  320. return err;
  321. }
  322. throw this.handleErrors(err, query);
  323. });
  324. }
  325. handleErrors = (err: any, target: PromQuery) => {
  326. const error: DataQueryError = {
  327. message: 'Unknown error during query transaction. Please check JS console logs.',
  328. refId: target.refId,
  329. };
  330. if (err.data) {
  331. if (typeof err.data === 'string') {
  332. error.message = err.data;
  333. } else if (err.data.error) {
  334. error.message = safeStringifyValue(err.data.error);
  335. }
  336. } else if (err.message) {
  337. error.message = err.message;
  338. } else if (typeof err === 'string') {
  339. error.message = err;
  340. }
  341. error.status = err.status;
  342. error.statusText = err.statusText;
  343. return error;
  344. };
  345. performSuggestQuery(query: string, cache = false) {
  346. const url = '/api/v1/label/__name__/values';
  347. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  348. return this.$q.when(
  349. _.filter(this.metricsNameCache.data, metricName => {
  350. return metricName.indexOf(query) !== 1;
  351. })
  352. );
  353. }
  354. return this.metadataRequest(url).then((result: PromDataQueryResponse) => {
  355. this.metricsNameCache = {
  356. data: result.data.data,
  357. expire: Date.now() + 60 * 1000,
  358. };
  359. return _.filter(result.data.data, metricName => {
  360. return metricName.indexOf(query) !== 1;
  361. });
  362. });
  363. }
  364. metricFindQuery(query: string) {
  365. if (!query) {
  366. return this.$q.when([]);
  367. }
  368. const scopedVars = {
  369. __interval: { text: this.interval, value: this.interval },
  370. __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
  371. ...this.getRangeScopedVars(this.timeSrv.timeRange()),
  372. };
  373. const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
  374. const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  375. return metricFindQuery.process();
  376. }
  377. getRangeScopedVars(range: TimeRange) {
  378. range = range || this.timeSrv.timeRange();
  379. const msRange = range.to.diff(range.from);
  380. const sRange = Math.round(msRange / 1000);
  381. const regularRange = kbn.secondsToHms(msRange / 1000);
  382. return {
  383. __range_ms: { text: msRange, value: msRange },
  384. __range_s: { text: sRange, value: sRange },
  385. __range: { text: regularRange, value: regularRange },
  386. };
  387. }
  388. annotationQuery(options: any) {
  389. const annotation = options.annotation;
  390. const expr = annotation.expr || '';
  391. let tagKeys = annotation.tagKeys || '';
  392. const titleFormat = annotation.titleFormat || '';
  393. const textFormat = annotation.textFormat || '';
  394. if (!expr) {
  395. return this.$q.when([]);
  396. }
  397. const step = annotation.step || '60s';
  398. const start = this.getPrometheusTime(options.range.from, false);
  399. const end = this.getPrometheusTime(options.range.to, true);
  400. const queryOptions = {
  401. ...options,
  402. interval: step,
  403. };
  404. // Unsetting min interval for accurate event resolution
  405. const minStep = '1s';
  406. const queryModel = {
  407. expr,
  408. interval: minStep,
  409. refId: 'X',
  410. requestId: `prom-query-${annotation.name}`,
  411. };
  412. const query = this.createQuery(queryModel, queryOptions, start, end);
  413. const self = this;
  414. return this.performTimeSeriesQuery(query, query.start, query.end).then((results: PromDataQueryResponse) => {
  415. const eventList: AnnotationEvent[] = [];
  416. tagKeys = tagKeys.split(',');
  417. if (results.cancelled) {
  418. return [];
  419. }
  420. _.each(results.data.data.result, series => {
  421. const tags = _.chain(series.metric)
  422. .filter((v, k) => {
  423. return _.includes(tagKeys, k);
  424. })
  425. .value();
  426. const dupCheck: { [key: number]: boolean } = {};
  427. for (const value of series.values) {
  428. const valueIsTrue = value[1] === '1'; // e.g. ALERTS
  429. if (valueIsTrue || annotation.useValueForTime) {
  430. const event: AnnotationEvent = {
  431. annotation: annotation,
  432. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  433. tags: tags,
  434. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  435. };
  436. if (annotation.useValueForTime) {
  437. const timestampValue = Math.floor(parseFloat(value[1]));
  438. if (dupCheck[timestampValue]) {
  439. continue;
  440. }
  441. dupCheck[timestampValue] = true;
  442. event.time = timestampValue;
  443. } else {
  444. event.time = Math.floor(parseFloat(value[0])) * 1000;
  445. }
  446. eventList.push(event);
  447. }
  448. }
  449. });
  450. return eventList;
  451. });
  452. }
  453. getTagKeys(options: any = {}) {
  454. const url = '/api/v1/labels';
  455. return this.metadataRequest(url).then((result: any) => {
  456. return _.map(result.data.data, value => {
  457. return { text: value };
  458. });
  459. });
  460. }
  461. getTagValues(options: any = {}) {
  462. const url = '/api/v1/label/' + options.key + '/values';
  463. return this.metadataRequest(url).then((result: any) => {
  464. return _.map(result.data.data, value => {
  465. return { text: value };
  466. });
  467. });
  468. }
  469. testDatasource() {
  470. const now = new Date().getTime();
  471. const query = { expr: '1+1' } as PromQueryRequest;
  472. return this.performInstantQuery(query, now / 1000).then((response: any) => {
  473. if (response.data.status === 'success') {
  474. return { status: 'success', message: 'Data source is working' };
  475. } else {
  476. return { status: 'error', message: response.error };
  477. }
  478. });
  479. }
  480. getExploreState(queries: PromQuery[]): Partial<ExploreUrlState> {
  481. let state: Partial<ExploreUrlState> = { datasource: this.name };
  482. if (queries && queries.length > 0) {
  483. const expandedQueries = queries.map(query => {
  484. const expandedQuery = {
  485. ...query,
  486. expr: this.templateSrv.replace(query.expr, {}, this.interpolateQueryExpr),
  487. context: 'explore',
  488. };
  489. return expandedQuery;
  490. });
  491. state = {
  492. ...state,
  493. queries: expandedQueries,
  494. };
  495. }
  496. return state;
  497. }
  498. getQueryHints(query: PromQuery, result: any[]) {
  499. return getQueryHints(query.expr || '', result, this);
  500. }
  501. loadRules() {
  502. this.metadataRequest('/api/v1/rules')
  503. .then((res: any) => res.data || res.json())
  504. .then((body: any) => {
  505. const groups = _.get(body, ['data', 'groups']);
  506. if (groups) {
  507. this.ruleMappings = extractRuleMappingFromGroups(groups);
  508. }
  509. })
  510. .catch((e: any) => {
  511. console.log('Rules API is experimental. Ignore next error.');
  512. console.error(e);
  513. });
  514. }
  515. modifyQuery(query: PromQuery, action: any): PromQuery {
  516. let expression = query.expr || '';
  517. switch (action.type) {
  518. case 'ADD_FILTER': {
  519. expression = addLabelToQuery(expression, action.key, action.value);
  520. break;
  521. }
  522. case 'ADD_HISTOGRAM_QUANTILE': {
  523. expression = `histogram_quantile(0.95, sum(rate(${expression}[5m])) by (le))`;
  524. break;
  525. }
  526. case 'ADD_RATE': {
  527. expression = `rate(${expression}[5m])`;
  528. break;
  529. }
  530. case 'ADD_SUM': {
  531. expression = `sum(${expression.trim()}) by ($1)`;
  532. break;
  533. }
  534. case 'EXPAND_RULES': {
  535. if (action.mapping) {
  536. expression = expandRecordingRules(expression, action.mapping);
  537. }
  538. break;
  539. }
  540. default:
  541. break;
  542. }
  543. return { ...query, expr: expression };
  544. }
  545. getPrometheusTime(date: string | DateTime, roundUp: boolean) {
  546. if (_.isString(date)) {
  547. date = dateMath.parse(date, roundUp);
  548. }
  549. return Math.ceil(date.valueOf() / 1000);
  550. }
  551. getTimeRange(): { start: number; end: number } {
  552. const range = this.timeSrv.timeRange();
  553. return {
  554. start: this.getPrometheusTime(range.from, false),
  555. end: this.getPrometheusTime(range.to, true),
  556. };
  557. }
  558. getOriginalMetricName(labelData: { [key: string]: string }) {
  559. return this.resultTransformer.getOriginalMetricName(labelData);
  560. }
  561. }
  562. /**
  563. * Align query range to step.
  564. * Rounds start and end down to a multiple of step.
  565. * @param start Timestamp marking the beginning of the range.
  566. * @param end Timestamp marking the end of the range.
  567. * @param step Interval to align start and end with.
  568. * @param utcOffsetSec Number of seconds current timezone is offset from UTC
  569. */
  570. export function alignRange(
  571. start: number,
  572. end: number,
  573. step: number,
  574. utcOffsetSec: number
  575. ): { end: number; start: number } {
  576. const alignedEnd = Math.floor((end + utcOffsetSec) / step) * step - utcOffsetSec;
  577. const alignedStart = Math.floor((start + utcOffsetSec) / step) * step - utcOffsetSec;
  578. return {
  579. end: alignedEnd,
  580. start: alignedStart,
  581. };
  582. }
  583. export function extractRuleMappingFromGroups(groups: any[]) {
  584. return groups.reduce(
  585. (mapping, group) =>
  586. group.rules
  587. .filter((rule: any) => rule.type === 'recording')
  588. .reduce(
  589. (acc: { [key: string]: string }, rule: any) => ({
  590. ...acc,
  591. [rule.name]: rule.query,
  592. }),
  593. mapping
  594. ),
  595. {}
  596. );
  597. }
  598. export function prometheusRegularEscape(value: any) {
  599. if (typeof value === 'string') {
  600. return value.replace(/'/g, "\\\\'");
  601. }
  602. return value;
  603. }
  604. export function prometheusSpecialRegexEscape(value: any) {
  605. if (typeof value === 'string') {
  606. return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()|]/g, '\\\\$&'));
  607. }
  608. return value;
  609. }