receivers.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { capitalize } from 'lodash';
  2. import { receiverTypeNames } from 'app/plugins/datasource/alertmanager/consts';
  3. import { GrafanaManagedReceiverConfig, Receiver } from 'app/plugins/datasource/alertmanager/types';
  4. import { NotifierDTO } from 'app/types';
  5. // extract notifier type name to count map, eg { Slack: 1, Email: 2 }
  6. type NotifierTypeCounts = Record<string, number>; // name : count
  7. export function extractNotifierTypeCounts(receiver: Receiver, grafanaNotifiers: NotifierDTO[]): NotifierTypeCounts {
  8. if (receiver['grafana_managed_receiver_configs']) {
  9. return getGrafanaNotifierTypeCounts(receiver.grafana_managed_receiver_configs ?? [], grafanaNotifiers);
  10. }
  11. return getCortexAlertManagerNotifierTypeCounts(receiver);
  12. }
  13. function getCortexAlertManagerNotifierTypeCounts(receiver: Receiver): NotifierTypeCounts {
  14. return Object.entries(receiver)
  15. .filter(([key]) => key !== 'grafana_managed_receiver_configs' && key.endsWith('_configs')) // filter out only properties that are alertmanager notifier
  16. .filter(([_, value]) => Array.isArray(value) && !!value.length) // check that there are actually notifiers of this type configured
  17. .reduce<NotifierTypeCounts>((acc, [key, value]) => {
  18. const type = key.replace('_configs', ''); // remove the `_config` part from the key, making it intto a notifier name
  19. const name = receiverTypeNames[type] ?? capitalize(type);
  20. return {
  21. ...acc,
  22. [name]: (acc[name] ?? 0) + (Array.isArray(value) ? value.length : 1),
  23. };
  24. }, {});
  25. }
  26. function getGrafanaNotifierTypeCounts(
  27. configs: GrafanaManagedReceiverConfig[],
  28. grafanaNotifiers: NotifierDTO[]
  29. ): NotifierTypeCounts {
  30. return configs
  31. .map((recv) => recv.type) // extract types from config
  32. .map((type) => grafanaNotifiers.find((r) => r.type === type)?.name ?? capitalize(type)) // get readable name from notifier cofnig, or if not available, just capitalize
  33. .reduce<NotifierTypeCounts>(
  34. (acc, type) => ({
  35. ...acc,
  36. [type]: (acc[type] ?? 0) + 1,
  37. }),
  38. {}
  39. );
  40. }