useAlertManagerSourceName.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { useCallback } from 'react';
  2. import { useQueryParams } from 'app/core/hooks/useQueryParams';
  3. import store from 'app/core/store';
  4. import { ALERTMANAGER_NAME_LOCAL_STORAGE_KEY, ALERTMANAGER_NAME_QUERY_KEY } from '../utils/constants';
  5. import { AlertManagerDataSource, GRAFANA_RULES_SOURCE_NAME } from '../utils/datasource';
  6. function useIsAlertManagerAvailable(availableAlertManagers: AlertManagerDataSource[]) {
  7. return useCallback(
  8. (alertManagerName: string) => {
  9. const availableAlertManagersNames = availableAlertManagers.map((am) => am.name);
  10. return availableAlertManagersNames.includes(alertManagerName);
  11. },
  12. [availableAlertManagers]
  13. );
  14. }
  15. /* This will return am name either from query params or from local storage or a default (grafana).
  16. * Due to RBAC permissions Grafana Managed Alert manager or external alert managers may not be available
  17. * In the worst case neihter GMA nor external alert manager is available
  18. */
  19. export function useAlertManagerSourceName(
  20. availableAlertManagers: AlertManagerDataSource[]
  21. ): [string | undefined, (alertManagerSourceName: string) => void] {
  22. const [queryParams, updateQueryParams] = useQueryParams();
  23. const isAlertManagerAvailable = useIsAlertManagerAvailable(availableAlertManagers);
  24. const update = useCallback(
  25. (alertManagerSourceName: string) => {
  26. if (!isAlertManagerAvailable(alertManagerSourceName)) {
  27. return;
  28. }
  29. if (alertManagerSourceName === GRAFANA_RULES_SOURCE_NAME) {
  30. store.delete(ALERTMANAGER_NAME_LOCAL_STORAGE_KEY);
  31. updateQueryParams({ [ALERTMANAGER_NAME_QUERY_KEY]: null });
  32. } else {
  33. store.set(ALERTMANAGER_NAME_LOCAL_STORAGE_KEY, alertManagerSourceName);
  34. updateQueryParams({ [ALERTMANAGER_NAME_QUERY_KEY]: alertManagerSourceName });
  35. }
  36. },
  37. [updateQueryParams, isAlertManagerAvailable]
  38. );
  39. const querySource = queryParams[ALERTMANAGER_NAME_QUERY_KEY];
  40. if (querySource && typeof querySource === 'string') {
  41. if (isAlertManagerAvailable(querySource)) {
  42. return [querySource, update];
  43. } else {
  44. // non existing alertmanager
  45. return [undefined, update];
  46. }
  47. }
  48. const storeSource = store.get(ALERTMANAGER_NAME_LOCAL_STORAGE_KEY);
  49. if (storeSource && typeof storeSource === 'string' && isAlertManagerAvailable(storeSource)) {
  50. update(storeSource);
  51. return [storeSource, update];
  52. }
  53. if (isAlertManagerAvailable(GRAFANA_RULES_SOURCE_NAME)) {
  54. return [GRAFANA_RULES_SOURCE_NAME, update];
  55. }
  56. return [undefined, update];
  57. }