datasource.ts 22 KB

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