Skip to content

Commit

Permalink
Chore: centralise getK8sNamespace (grafana#99767)
Browse files Browse the repository at this point in the history
* create new public/app/api folder, expose getK8sNamespace

* rename to getAPINamespace
  • Loading branch information
ashharrison90 authored Jan 29, 2025
1 parent 07601be commit 8f60308
Show file tree
Hide file tree
Showing 14 changed files with 52 additions and 49 deletions.
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,7 @@
playwright.config.ts @grafana/plugins-platform-frontend

# public folder
/public/app/api/ @grafana/grafana-frontend-platform
/public/app/core/ @grafana/grafana-frontend-platform
/public/app/core/components/TimePicker/ @grafana/grafana-frontend-platform
/public/app/core/components/Layers/ @grafana/dataviz-squad
Expand Down
3 changes: 3 additions & 0 deletions public/app/api/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { config } from '@grafana/runtime';

export const getAPINamespace = () => config.namespace;
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,14 @@ import { ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver } f
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
import { cloudNotifierTypes } from 'app/features/alerting/unified/utils/cloud-alertmanager-notifier-types';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import {
getK8sNamespace,
isK8sEntityProvisioned,
shouldUseK8sApi,
} from 'app/features/alerting/unified/utils/k8s/utils';
import { isK8sEntityProvisioned, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
import {
GrafanaManagedContactPoint,
GrafanaManagedReceiverConfig,
Receiver,
} from 'app/plugins/datasource/alertmanager/types';

import { getAPINamespace } from '../../../../../api/utils';
import { alertmanagerApi } from '../../api/alertmanagerApi';
import { onCallApi } from '../../api/onCallApi';
import { useAsync } from '../../hooks/useAsync';
Expand Down Expand Up @@ -117,7 +114,7 @@ const useK8sContactPoints = (...[hookParams, queryOptions]: Parameters<typeof us
* or the `/notifications/receivers` endpoint
*/
const useFetchGrafanaContactPoints = ({ skip }: Skippable = {}) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);

const grafanaResponse = useGetContactPointsListQuery(undefined, {
Expand Down Expand Up @@ -239,7 +236,7 @@ const useGetGrafanaContactPoint = (
{ name }: { name: string },
queryOptions?: Parameters<typeof useReadNamespacedReceiverQuery>[1]
) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);

const k8sResponse = useReadNamespacedReceiverQuery(
Expand Down Expand Up @@ -314,7 +311,7 @@ export function useDeleteContactPoint({ alertmanager }: BaseAlertmanagerArgs) {
const [deleteReceiver] = useDeleteNamespacedReceiverMutation();

const deleteFromK8sAPI = useAsync(async ({ name, resourceVersion }: DeleteContactPointArgs) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
await deleteReceiver({
name,
namespace,
Expand Down Expand Up @@ -407,7 +404,7 @@ export const useCreateContactPoint = ({ alertmanager }: BaseAlertmanagerArgs) =>
? await createOnCallIntegrations(contactPoint)
: contactPoint;

const namespace = getK8sNamespace();
const namespace = getAPINamespace();
const contactPointToUse = grafanaContactPointToK8sReceiver(contactPointWithMaybeOnCall);

return createGrafanaContactPoint({
Expand Down Expand Up @@ -455,7 +452,7 @@ export const useUpdateContactPoint = ({ alertmanager }: BaseAlertmanagerArgs) =>
? await createOnCallIntegrations(contactPoint)
: contactPoint;

const namespace = getK8sNamespace();
const namespace = getAPINamespace();
const contactPointToUse = grafanaContactPointToK8sReceiver(receiverWithPotentialOnCall, id, resourceVersion);

return replaceGrafanaContactPoint({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect } from 'react';
import { Validate } from 'react-hook-form';

import { getAPINamespace } from '../../../../../api/utils';
import { AlertManagerCortexConfig } from '../../../../../plugins/datasource/alertmanager/types';
import { alertmanagerApi } from '../../api/alertmanagerApi';
import { templatesApi } from '../../api/templateApi';
Expand All @@ -16,7 +17,7 @@ import {
updateNotificationTemplateAction,
} from '../../reducers/alertmanager/notificationTemplates';
import { K8sAnnotations, PROVENANCE_NONE } from '../../utils/k8s/constants';
import { getAnnotation, getK8sNamespace, shouldUseK8sApi } from '../../utils/k8s/utils';
import { getAnnotation, shouldUseK8sApi } from '../../utils/k8s/utils';
import { ensureDefine } from '../../utils/templates';
import { TemplateFormValues } from '../receivers/TemplateForm';

Expand Down Expand Up @@ -46,7 +47,7 @@ export function useNotificationTemplates({ alertmanager }: BaseAlertmanagerArgs)
const k8sApiSupported = shouldUseK8sApi(alertmanager);

const k8sApiTemplatesRequestState = useListNamespacedTemplateGroupQuery(
{ namespace: getK8sNamespace() },
{ namespace: getAPINamespace() },
{
skip: !k8sApiSupported,
selectFromResult: (state) => ({
Expand Down Expand Up @@ -131,7 +132,7 @@ export function useGetNotificationTemplate({ alertmanager, uid }: GetTemplatePar
// What are pros and cons of each?
useEffect(() => {
if (k8sApiSupported) {
fetchTemplate({ namespace: getK8sNamespace(), name: uid });
fetchTemplate({ namespace: getAPINamespace(), name: uid });
} else {
fetchAmConfig(alertmanager);
}
Expand Down Expand Up @@ -164,7 +165,7 @@ export function useCreateNotificationTemplate({ alertmanager }: BaseAlertmanager
const content = ensureDefine(templateValues.title, templateValues.content);

return createNamespacedTemplateGroup({
namespace: getK8sNamespace(),
namespace: getAPINamespace(),
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1TemplateGroup: {
spec: { title: templateValues.title, content },
metadata: {},
Expand Down Expand Up @@ -195,7 +196,7 @@ export function useUpdateNotificationTemplate({ alertmanager }: BaseAlertmanager
const content = ensureDefine(patch.title, patch.content);

return replaceNamespacedTemplateGroup({
namespace: getK8sNamespace(),
namespace: getAPINamespace(),
name: template.uid,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1TemplateGroup: {
spec: { title: patch.title, content },
Expand All @@ -218,7 +219,7 @@ export function useDeleteNotificationTemplate({ alertmanager }: BaseAlertmanager

const deleteUsingK8sApi = useAsync(({ uid }: { uid: string }) => {
return deleteNamespacedTemplateGroup({
namespace: getK8sNamespace(),
namespace: getAPINamespace(),
name: uid,
ioK8SApimachineryPkgApisMetaV1DeleteOptions: {},
}).unwrap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,10 @@ import {
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';
import {
getK8sNamespace,
isK8sEntityProvisioned,
shouldUseK8sApi,
} from 'app/features/alerting/unified/utils/k8s/utils';
import { isK8sEntityProvisioned, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';

import { getAPINamespace } from '../../../../../api/utils';
import { useAsync } from '../../hooks/useAsync';
import { useProduceNewAlertmanagerConfiguration } from '../../hooks/useProduceNewAlertmanagerConfig';
import {
Expand Down Expand Up @@ -114,7 +111,7 @@ export const useMuteTimings = ({ alertmanager, skip }: BaseAlertmanagerArgs & Sk
return;
}
if (useK8sApi) {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
getGrafanaTimeIntervals({ namespace });
} else {
getAlertmanagerTimeIntervals(alertmanager);
Expand All @@ -140,7 +137,7 @@ export const useCreateMuteTiming = ({ alertmanager }: BaseAlertmanagerArgs) => {
const [updateConfiguration] = useProduceNewAlertmanagerConfiguration();

const addToK8sAPI = useAsync(({ interval }: CreateUpdateMuteTimingArgs) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();

return createGrafanaTimeInterval({
namespace,
Expand Down Expand Up @@ -202,7 +199,7 @@ export const useGetMuteTiming = ({ alertmanager, name: nameToFind }: BaseAlertma

useEffect(() => {
if (useK8sApi) {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
getGrafanaTimeInterval({ namespace, fieldSelector: `spec.name=${nameToFind}` }, true);
} else {
getAlertmanagerTimeInterval(alertmanager, true);
Expand All @@ -228,7 +225,7 @@ export const useUpdateMuteTiming = ({ alertmanager }: BaseAlertmanagerArgs) => {

const updateToK8sAPI = useAsync(
async ({ interval, originalName }: CreateUpdateMuteTimingArgs & { originalName: string }) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();

return replaceGrafanaTimeInterval({
name: originalName,
Expand Down Expand Up @@ -267,7 +264,7 @@ export const useDeleteMuteTiming = ({ alertmanager }: BaseAlertmanagerArgs) => {
});

const deleteFromK8sAPI = useAsync(async ({ name }: DeleteMuteTimingArgs) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
await deleteGrafanaTimeInterval({
name,
namespace,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import memoize from 'micro-memoize';
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
import { MatcherOperator, ROUTES_META_SYMBOL, Route } from 'app/plugins/datasource/alertmanager/types';

import { getAPINamespace } from '../../../../../api/utils';
import { alertmanagerApi } from '../../api/alertmanagerApi';
import { useAsync } from '../../hooks/useAsync';
import { useProduceNewAlertmanagerConfiguration } from '../../hooks/useProduceNewAlertmanagerConfig';
Expand All @@ -21,7 +22,7 @@ import {
import { FormAmRoute } from '../../types/amroutes';
import { addUniqueIdentifierToRoute } from '../../utils/amroutes';
import { PROVENANCE_NONE, ROOT_ROUTE_NAME } from '../../utils/k8s/constants';
import { getK8sNamespace, isK8sEntityProvisioned, shouldUseK8sApi } from '../../utils/k8s/utils';
import { isK8sEntityProvisioned, shouldUseK8sApi } from '../../utils/k8s/utils';
import { INHERITABLE_KEYS, InheritableProperties } from '../../utils/notification-policies';
import {
InsertPosition,
Expand All @@ -45,7 +46,7 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg
const k8sApiSupported = shouldUseK8sApi(alertmanager);

const k8sRouteQuery = useListNamespacedRoutingTreeQuery(
{ namespace: getK8sNamespace() },
{ namespace: getAPINamespace() },
{
skip: skip || !k8sApiSupported,
selectFromResult: (result) => {
Expand Down Expand Up @@ -92,7 +93,7 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm
const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();

const updateUsingK8sApi = useAsync(async (update: Partial<FormAmRoute>) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
const result = await listNamespacedRoutingTree({ namespace });

const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
Expand Down Expand Up @@ -128,7 +129,7 @@ export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerAr
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();

const deleteFromK8sApi = useAsync(async (id: string) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
const result = await listNamespacedRoutingTree({ namespace });

const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
Expand Down Expand Up @@ -173,7 +174,7 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
referenceRouteIdentifier: string;
insertPosition: InsertPosition;
}) => {
const namespace = getK8sNamespace();
const namespace = getAPINamespace();
const result = await listNamespacedRoutingTree({ namespace });

const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
Expand Down
4 changes: 2 additions & 2 deletions public/app/features/alerting/unified/home/Insights.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
} from '@grafana/scenes';
import { Icon, Text, Tooltip } from '@grafana/ui';

import { config } from '../../../../core/config';
import { getAPINamespace } from '../../../../api/utils';
import { SectionFooter } from '../insights/SectionFooter';
import { SectionSubheader } from '../insights/SectionSubheader';
import { getActiveGrafanaAlertsScene } from '../insights/grafana/Active';
Expand Down Expand Up @@ -95,7 +95,7 @@ export const PANEL_STYLES = { minHeight: 300 };

const THIS_WEEK_TIME_RANGE = new SceneTimeRange({ from: 'now-1w', to: 'now' });

const namespace = config.namespace;
const namespace = getAPINamespace();

export const INSTANCE_ID = namespace.includes('stacks-') ? namespace.replace('stacks-', '') : undefined;

Expand Down
5 changes: 0 additions & 5 deletions public/app/features/alerting/unified/utils/k8s/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ import { IoK8SApimachineryPkgApisMetaV1ObjectMeta } from 'app/features/alerting/
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { K8sAnnotations, PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';

/**
* Get the correct namespace to use when using the K8S API.
*/
export const getK8sNamespace = () => config.namespace;

/**
* Should we call the kubernetes-style API for managing alertmanager entities?
*
Expand Down
4 changes: 3 additions & 1 deletion public/app/features/apiserver/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Observable, from, retry, catchError, filter, map, mergeMap } from 'rxjs
import { config, getBackendSrv } from '@grafana/runtime';
import { contextSrv } from 'app/core/core';

import { getAPINamespace } from '../../api/utils';

import {
ListOptions,
ListOptionsFieldSelector,
Expand All @@ -29,7 +31,7 @@ export class ScopedResourceClient<T = object, S = object, K = string> implements
readonly url: string;

constructor(gvr: GroupVersionResource, namespaced = true) {
const ns = namespaced ? `namespaces/${config.namespace}/` : '';
const ns = namespaced ? `namespaces/${getAPINamespace()}/` : '';

this.url = `/apis/${gvr.group}/${gvr.version}/${ns}${gvr.resource}`;
}
Expand Down
4 changes: 3 additions & 1 deletion public/app/features/dashboard/services/SnapshotSrv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { config, getBackendSrv, FetchResponse } from '@grafana/runtime';
import { contextSrv } from 'app/core/core';
import { DashboardDataDTO, DashboardDTO } from 'app/types';

import { getAPINamespace } from '../../../api/utils';

// Used in the snapshot list
export interface Snapshot {
key: string;
Expand Down Expand Up @@ -91,7 +93,7 @@ class K8sAPI implements DashboardSnapshotSrv {
readonly url: string;

constructor() {
this.url = `/apis/${this.apiVersion}/namespaces/${config.namespace}/dashboardsnapshots`;
this.url = `/apis/${this.apiVersion}/namespaces/${getAPINamespace()}/dashboardsnapshots`;
}

async create(cmd: SnapshotCreateCommand) {
Expand Down
7 changes: 3 additions & 4 deletions public/app/features/query-library/api/query.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { BaseQueryFn } from '@reduxjs/toolkit/query/react';
import { lastValueFrom } from 'rxjs';

import { config } from '@grafana/runtime';
import { BackendSrvRequest, getBackendSrv, isFetchError } from '@grafana/runtime/src/services/backendSrv';

import { getAPINamespace } from '../../../api/utils';

/**
* @alpha
*/
Expand All @@ -16,14 +17,12 @@ export enum QueryTemplateKinds {
QueryTemplate = 'QueryTemplate',
}

export const getK8sNamespace = () => config.namespace;

/**
* Query Library is an experimental feature. API (including the URL path) will likely change.
*
* @alpha
*/
export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getK8sNamespace()}`;
export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getAPINamespace()}`;

interface QueryLibraryBackendRequest extends BackendSrvRequest {
body?: BackendSrvRequest['data'];
Expand Down
5 changes: 3 additions & 2 deletions public/app/features/query-library/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getBackendSrv } from '@grafana/runtime';

import { getK8sNamespace } from './query';
import { getAPINamespace } from '../../../api/utils';

import { UserDataQueryResponse } from './types';

/**
Expand All @@ -11,7 +12,7 @@ export const API_VERSION = 'iam.grafana.app/v0alpha1';
/**
* @alpha
*/
const BASE_URL = `apis/${API_VERSION}/namespaces/${getK8sNamespace()}/display`;
const BASE_URL = `apis/${API_VERSION}/namespaces/${getAPINamespace()}/display`;

export async function getUserInfo(url?: string): Promise<UserDataQueryResponse> {
const userInfo = await getBackendSrv().get(`${BASE_URL}${url}`);
Expand Down
6 changes: 4 additions & 2 deletions public/app/features/scopes/internal/api.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Scope, ScopeDashboardBinding, ScopeNode, ScopeSpec } from '@grafana/data';
import { config, getBackendSrv } from '@grafana/runtime';
import { getBackendSrv } from '@grafana/runtime';
import { ScopedResourceClient } from 'app/features/apiserver/client';

import { getAPINamespace } from '../../../api/utils';

import { NodeReason, NodesMap, SelectedScope, TreeScope } from './types';
import { getBasicScope, mergeScopes } from './utils';

const group = 'scope.grafana.app';
const version = 'v0alpha1';
const namespace = config.namespace ?? 'default';
const namespace = getAPINamespace();

const nodesEndpoint = `/apis/${group}/${version}/namespaces/${namespace}/find/scope_node_children`;
const dashboardsEndpoint = `/apis/${group}/${version}/namespaces/${namespace}/find/scope_dashboard_bindings`;
Expand Down
Loading

0 comments on commit 8f60308

Please sign in to comment.