AlertStatesWorker.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { from, Observable } from 'rxjs';
  2. import { catchError, map } from 'rxjs/operators';
  3. import { getBackendSrv } from '@grafana/runtime';
  4. import { DashboardQueryRunnerOptions, DashboardQueryRunnerWorker, DashboardQueryRunnerWorkerResult } from './types';
  5. import { emptyResult, handleDashboardQueryRunnerWorkerError } from './utils';
  6. export class AlertStatesWorker implements DashboardQueryRunnerWorker {
  7. canWork({ dashboard, range }: DashboardQueryRunnerOptions): boolean {
  8. if (!dashboard.id) {
  9. return false;
  10. }
  11. if (range.raw.to !== 'now') {
  12. return false;
  13. }
  14. // if dashboard has no alerts, no point to query alert states
  15. if (!dashboard.panels.find((panel) => !!panel.alert)) {
  16. return false;
  17. }
  18. return true;
  19. }
  20. work(options: DashboardQueryRunnerOptions): Observable<DashboardQueryRunnerWorkerResult> {
  21. if (!this.canWork(options)) {
  22. return emptyResult();
  23. }
  24. const { dashboard } = options;
  25. return from(
  26. getBackendSrv().get(
  27. '/api/alerts/states-for-dashboard',
  28. {
  29. dashboardId: dashboard.id,
  30. },
  31. `dashboard-query-runner-alert-states-${dashboard.id}`
  32. )
  33. ).pipe(
  34. map((alertStates) => {
  35. return { alertStates, annotations: [] };
  36. }),
  37. catchError(handleDashboardQueryRunnerWorkerError)
  38. );
  39. }
  40. }