query.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { DataQuery, DataSourceInstanceSettings } from '@grafana/data';
  2. import { LokiQuery } from 'app/plugins/datasource/loki/types';
  3. import { PromQuery } from 'app/plugins/datasource/prometheus/types';
  4. import { CombinedRule } from 'app/types/unified-alerting';
  5. import { AlertQuery } from 'app/types/unified-alerting-dto';
  6. import { isCloudRulesSource, isGrafanaRulesSource } from './datasource';
  7. import { isGrafanaRulerRule } from './rules';
  8. export function alertRuleToQueries(combinedRule: CombinedRule | undefined | null): AlertQuery[] {
  9. if (!combinedRule) {
  10. return [];
  11. }
  12. const { namespace, rulerRule } = combinedRule;
  13. const { rulesSource } = namespace;
  14. if (isGrafanaRulesSource(rulesSource)) {
  15. if (isGrafanaRulerRule(rulerRule)) {
  16. return rulerRule.grafana_alert.data;
  17. }
  18. }
  19. if (isCloudRulesSource(rulesSource)) {
  20. const model = cloudAlertRuleToModel(rulesSource, combinedRule);
  21. return [
  22. {
  23. refId: model.refId,
  24. datasourceUid: rulesSource.uid,
  25. queryType: '',
  26. model,
  27. relativeTimeRange: {
  28. from: 360,
  29. to: 0,
  30. },
  31. },
  32. ];
  33. }
  34. return [];
  35. }
  36. function cloudAlertRuleToModel(dsSettings: DataSourceInstanceSettings, rule: CombinedRule): DataQuery {
  37. const refId = 'A';
  38. switch (dsSettings.type) {
  39. case 'prometheus': {
  40. const query: PromQuery = {
  41. refId,
  42. expr: rule.query,
  43. };
  44. return query;
  45. }
  46. case 'loki': {
  47. const query: LokiQuery = {
  48. refId,
  49. expr: rule.query,
  50. };
  51. return query;
  52. }
  53. default:
  54. throw new Error(`Query for datasource type ${dsSettings.type} is currently not supported by cloud alert rules.`);
  55. }
  56. }