variables.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { from, Observable, of } from 'rxjs';
  2. import { map } from 'rxjs/operators';
  3. import {
  4. DataQueryRequest,
  5. DataQueryResponse,
  6. rangeUtil,
  7. StandardVariableQuery,
  8. StandardVariableSupport,
  9. } from '@grafana/data';
  10. import { getTemplateSrv, TemplateSrv } from '@grafana/runtime';
  11. import { getTimeSrv, TimeSrv } from '../../../features/dashboard/services/TimeSrv';
  12. import { PrometheusDatasource } from './datasource';
  13. import PrometheusMetricFindQuery from './metric_find_query';
  14. import { PromQuery } from './types';
  15. export class PrometheusVariableSupport extends StandardVariableSupport<PrometheusDatasource> {
  16. constructor(
  17. private readonly datasource: PrometheusDatasource,
  18. private readonly templateSrv: TemplateSrv = getTemplateSrv(),
  19. private readonly timeSrv: TimeSrv = getTimeSrv()
  20. ) {
  21. super();
  22. this.query = this.query.bind(this);
  23. }
  24. query(request: DataQueryRequest<PromQuery>): Observable<DataQueryResponse> {
  25. const query = request.targets[0].expr;
  26. if (!query) {
  27. return of({ data: [] });
  28. }
  29. const scopedVars = {
  30. ...request.scopedVars,
  31. __interval: { text: this.datasource.interval, value: this.datasource.interval },
  32. __interval_ms: {
  33. text: rangeUtil.intervalToMs(this.datasource.interval),
  34. value: rangeUtil.intervalToMs(this.datasource.interval),
  35. },
  36. ...this.datasource.getRangeScopedVars(this.timeSrv.timeRange()),
  37. };
  38. const interpolated = this.templateSrv.replace(query, scopedVars, this.datasource.interpolateQueryExpr);
  39. const metricFindQuery = new PrometheusMetricFindQuery(this.datasource, interpolated);
  40. const metricFindStream = from(metricFindQuery.process());
  41. return metricFindStream.pipe(map((results) => ({ data: results })));
  42. }
  43. toDataQuery(query: StandardVariableQuery): PromQuery {
  44. return {
  45. refId: 'PrometheusDatasource-VariableQuery',
  46. expr: query.query,
  47. };
  48. }
  49. }