1
0
Fork 0
mirror of https://github.com/portainer/portainer.git synced 2025-08-04 21:35:23 +02:00

refactor(k8s): namespace core logic (#12142)

Co-authored-by: testA113 <aliharriss1995@gmail.com>
Co-authored-by: Anthony Lapenna <anthony.lapenna@portainer.io>
Co-authored-by: James Carppe <85850129+jamescarppe@users.noreply.github.com>
Co-authored-by: Ali <83188384+testA113@users.noreply.github.com>
This commit is contained in:
Steven Kang 2024-10-01 14:15:51 +13:00 committed by GitHub
parent da010f3d08
commit ea228c3d6d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
276 changed files with 9241 additions and 3361 deletions

View file

@ -0,0 +1,173 @@
import { Trash2, Link as LinkIcon } from 'lucide-react';
import { useRouter } from '@uirouter/react';
import { Row } from '@tanstack/react-table';
import clsx from 'clsx';
import { useMemo } from 'react';
import { useEnvironmentId } from '@/react/hooks/useEnvironmentId';
import { useAuthorizations, Authorized } from '@/react/hooks/useUser';
import { notifyError, notifySuccess } from '@/portainer/services/notifications';
import { SystemResourceDescription } from '@/react/kubernetes/datatables/SystemResourceDescription';
import { createStore } from '@/react/kubernetes/datatables/default-kube-datatable-store';
import { CreateFromManifestButton } from '@/react/kubernetes/components/CreateFromManifestButton';
import { confirmDelete } from '@@/modals/confirm';
import { Datatable, Table, TableSettingsMenu } from '@@/datatables';
import { LoadingButton } from '@@/buttons';
import { useTableState } from '@@/datatables/useTableState';
import { DefaultDatatableSettings } from '../../../datatables/DefaultDatatableSettings';
import { ClusterRoleBinding } from './types';
import { columns } from './columns';
import { useGetClusterRoleBindingsQuery } from './queries/useGetClusterRoleBindingsQuery';
import { useDeleteClusterRoleBindingsMutation } from './queries/useDeleteClusterRoleBindingsMutation';
const storageKey = 'clusterRoleBindings';
const settingsStore = createStore(storageKey);
export function ClusterRoleBindingsDatatable() {
const environmentId = useEnvironmentId();
const tableState = useTableState(settingsStore, storageKey);
const clusterRoleBindingsQuery = useGetClusterRoleBindingsQuery(
environmentId,
{
autoRefreshRate: tableState.autoRefreshRate * 1000,
}
);
const filteredClusterRoleBindings = useMemo(
() =>
clusterRoleBindingsQuery.data?.filter(
(crb) => tableState.showSystemResources || !crb.isSystem
),
[clusterRoleBindingsQuery.data, tableState.showSystemResources]
);
const { authorized: isAuthorizedToAddOrEdit } = useAuthorizations([
'K8sClusterRoleBindingsW',
]);
return (
<Datatable
dataset={filteredClusterRoleBindings || []}
columns={columns}
settingsManager={tableState}
isLoading={clusterRoleBindingsQuery.isLoading}
emptyContentLabel="No supported cluster role bindings found"
title="Cluster Role Bindings"
titleIcon={LinkIcon}
getRowId={(row) => row.uid}
isRowSelectable={(row) => !row.original.isSystem}
renderTableActions={(selectedRows) => (
<TableActions selectedItems={selectedRows} />
)}
renderTableSettings={() => (
<TableSettingsMenu>
<DefaultDatatableSettings settings={tableState} />
</TableSettingsMenu>
)}
description={
<SystemResourceDescription
showSystemResources={tableState.showSystemResources}
/>
}
disableSelect={!isAuthorizedToAddOrEdit}
renderRow={renderRow}
data-cy="k8s-cluster-role-bindings-datatable"
/>
);
}
// needed to apply custom styling to the row and not globally required in the AC's for this ticket.
function renderRow(row: Row<ClusterRoleBinding>, highlightedItemId?: string) {
return (
<Table.Row<ClusterRoleBinding>
cells={row.getVisibleCells()}
className={clsx('[&>td]:!py-4 [&>td]:!align-top', {
active: highlightedItemId === row.id,
})}
/>
);
}
interface SelectedRole {
name: string;
}
type TableActionsProps = {
selectedItems: ClusterRoleBinding[];
};
function TableActions({ selectedItems }: TableActionsProps) {
const environmentId = useEnvironmentId();
const deleteClusterRoleBindingsMutation =
useDeleteClusterRoleBindingsMutation(environmentId);
const router = useRouter();
async function handleRemoveClick(roles: SelectedRole[]) {
const confirmed = await confirmDelete(
<>
<p>
Are you sure you want to delete the selected cluster role binding(s)?
</p>
<ul className="mt-2 max-h-96 list-inside overflow-hidden overflow-y-auto text-sm">
{roles.map((s, index) => (
<li key={index}>{s.name}</li>
))}
</ul>
</>
);
if (!confirmed) {
return null;
}
const payload: string[] = [];
roles.forEach((r) => {
payload.push(r.name);
});
deleteClusterRoleBindingsMutation.mutate(
{ environmentId, data: payload },
{
onSuccess: () => {
notifySuccess(
'Roles successfully removed',
roles.map((r) => `${r.name}`).join(', ')
);
router.stateService.reload();
},
onError: (error) => {
notifyError(
'Unable to delete cluster role bindings',
error as Error,
roles.map((r) => `${r.name}`).join(', ')
);
},
}
);
return roles;
}
return (
<Authorized authorizations="K8sClusterRoleBindingsW">
<LoadingButton
className="btn-wrapper"
color="dangerlight"
disabled={selectedItems.length === 0}
onClick={() => handleRemoveClick(selectedItems)}
icon={Trash2}
isLoading={deleteClusterRoleBindingsMutation.isLoading}
loadingText="Removing cluster role bindings..."
data-cy="k8s-cluster-role-bindings-remove-button"
>
Remove
</LoadingButton>
<CreateFromManifestButton
params={{ tab: 'clusterRoleBindings' }}
data-cy="k8s-cluster-role-bindings-deploy-button"
/>
</Authorized>
);
}

View file

@ -0,0 +1,12 @@
import { formatDate } from '@/portainer/filters/filters';
import { columnHelper } from './helper';
export const created = columnHelper.accessor(
(row) => formatDate(row.creationDate),
{
header: 'Created',
id: 'created',
cell: ({ getValue }) => getValue(),
}
);

View file

@ -0,0 +1,5 @@
import { createColumnHelper } from '@tanstack/react-table';
import { ClusterRoleBinding } from '../types';
export const columnHelper = createColumnHelper<ClusterRoleBinding>();

View file

@ -0,0 +1,17 @@
import { name } from './name';
import { roleName } from './roleName';
import { kind } from './kind';
import { created } from './created';
import { subjectKind } from './subjectKind';
import { subjectName } from './subjectName';
import { subjectNamespace } from './subjectNamespace';
export const columns = [
name,
roleName,
kind,
subjectKind,
subjectName,
subjectNamespace,
created,
];

View file

@ -0,0 +1,6 @@
import { columnHelper } from './helper';
export const kind = columnHelper.accessor('roleRef.kind', {
header: 'Role Kind',
id: 'roleKind',
});

View file

@ -0,0 +1,22 @@
import { SystemBadge } from '@@/Badge/SystemBadge';
import { columnHelper } from './helper';
export const name = columnHelper.accessor(
(row) => {
if (row.isSystem) {
return `${row.name} system`;
}
return row.name;
},
{
header: 'Name',
id: 'name',
cell: ({ row }) => (
<div className="flex gap-2">
{row.original.name}
{row.original.isSystem && <SystemBadge />}
</div>
),
}
);

View file

@ -0,0 +1,6 @@
import { columnHelper } from './helper';
export const roleName = columnHelper.accessor('roleRef.name', {
header: 'Role Name',
id: 'roleName',
});

View file

@ -0,0 +1,13 @@
import { columnHelper } from './helper';
export const subjectKind = columnHelper.accessor(
(row) => row.subjects?.map((sub) => sub.kind).join(', '),
{
header: 'Subject Kind',
id: 'subjectKind',
cell: ({ row }) =>
row.original.subjects?.map((sub, index) => (
<div key={index}>{sub.kind}</div>
)) || '-',
}
);

View file

@ -0,0 +1,13 @@
import { columnHelper } from './helper';
export const subjectName = columnHelper.accessor(
(row) => row.subjects?.map((sub) => sub.name).join(' '),
{
header: 'Subject Name',
id: 'subjectName',
cell: ({ row }) =>
row.original.subjects?.map((sub, index) => (
<div key={index}>{sub.name}</div>
)) || '-',
}
);

View file

@ -0,0 +1,42 @@
import { Link } from '@@/Link';
import { filterHOC } from '@@/datatables/Filter';
import { filterFn, filterNamespaceOptionsTransformer } from '../../utils';
import { columnHelper } from './helper';
export const subjectNamespace = columnHelper.accessor(
(row) => row.subjects?.flatMap((sub) => sub.namespace || '-') || [],
{
header: 'Subject Namespace',
id: 'subjectNamespace',
cell: ({ row }) =>
row.original.subjects?.map((sub, index) => (
<div key={index}>
{sub.namespace ? (
<Link
to="kubernetes.resourcePools.resourcePool"
params={{
id: sub.namespace,
}}
title={sub.namespace}
data-cy={`subject-namespace-link-${row.original.name}_${index}`}
>
{sub.namespace}
</Link>
) : (
'-'
)}
</div>
)) || '-',
enableColumnFilter: true,
// use a custom filter, to remove empty namespace values
meta: {
filter: filterHOC(
'Filter by subject namespace',
filterNamespaceOptionsTransformer
),
},
filterFn,
}
);

View file

@ -0,0 +1,11 @@
import { EnvironmentId } from '@/react/portainer/environments/types';
export const queryKeys = {
list: (environmentId: EnvironmentId) =>
[
'environments',
environmentId,
'kubernetes',
'cluster_role_bindings',
] as const,
};

View file

@ -0,0 +1,34 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { withGlobalError, withInvalidate } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { queryKeys } from './query-keys';
export function useDeleteClusterRoleBindingsMutation(
environmentId: EnvironmentId
) {
const queryClient = useQueryClient();
return useMutation(deleteClusterRoleBindings, {
...withInvalidate(queryClient, [queryKeys.list(environmentId)]),
...withGlobalError('Unable to delete cluster role bindings'),
});
}
export async function deleteClusterRoleBindings({
environmentId,
data,
}: {
environmentId: EnvironmentId;
data: string[];
}) {
try {
return await axios.post(
`kubernetes/${environmentId}/cluster_role_bindings/delete`,
data
);
} catch (e) {
throw parseAxiosError(e, `Unable to delete cluster role bindings`);
}
}

View file

@ -0,0 +1,41 @@
import { compact } from 'lodash';
import { useQuery } from '@tanstack/react-query';
import { withGlobalError } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { ClusterRoleBinding } from '../types';
import { queryKeys } from './query-keys';
export function useGetClusterRoleBindingsQuery(
environmentId: EnvironmentId,
options?: { autoRefreshRate?: number }
) {
return useQuery(
queryKeys.list(environmentId),
async () => {
const cluerRoleBindings = await getClusterRoleBindings(environmentId);
return compact(cluerRoleBindings);
},
{
...withGlobalError('Unable to get cluster role bindings'),
refetchInterval() {
return options?.autoRefreshRate ?? false;
},
}
);
}
async function getClusterRoleBindings(environmentId: EnvironmentId) {
try {
const { data: roles } = await axios.get<ClusterRoleBinding[]>(
`kubernetes/${environmentId}/cluster_role_bindings`
);
return roles;
} catch (e) {
throw parseAxiosError(e, 'Unable to get cluster role bindings');
}
}

View file

@ -0,0 +1,26 @@
export type ClusterRoleRef = {
name: string;
kind: string;
apiGroup?: string;
};
export type ClusterRoleSubject = {
name: string;
kind: string;
apiGroup?: string;
namespace?: string;
};
export type ClusterRoleBinding = {
name: string;
uid: string;
namespace: string;
resourceVersion: string;
creationDate: string;
annotations: Record<string, string> | null;
roleRef: ClusterRoleRef;
subjects: ClusterRoleSubject[] | null;
isSystem: boolean;
};

View file

@ -0,0 +1,152 @@
import { Trash2, UserCheck } from 'lucide-react';
import { useRouter } from '@uirouter/react';
import { useMemo } from 'react';
import { useEnvironmentId } from '@/react/hooks/useEnvironmentId';
import { useAuthorizations, Authorized } from '@/react/hooks/useUser';
import { notifyError, notifySuccess } from '@/portainer/services/notifications';
import { SystemResourceDescription } from '@/react/kubernetes/datatables/SystemResourceDescription';
import { createStore } from '@/react/kubernetes/datatables/default-kube-datatable-store';
import { CreateFromManifestButton } from '@/react/kubernetes/components/CreateFromManifestButton';
import { confirmDelete } from '@@/modals/confirm';
import { Datatable, TableSettingsMenu } from '@@/datatables';
import { LoadingButton } from '@@/buttons';
import { useTableState } from '@@/datatables/useTableState';
import { DefaultDatatableSettings } from '../../../datatables/DefaultDatatableSettings';
import { ClusterRole } from './types';
import { columns } from './columns';
import { useGetClusterRolesQuery } from './queries/useGetClusterRolesQuery';
import { useDeleteClusterRolesMutation } from './queries/useDeleteClusterRolesMutation';
const storageKey = 'clusterRoles';
const settingsStore = createStore(storageKey);
export function ClusterRolesDatatable() {
const environmentId = useEnvironmentId();
const tableState = useTableState(settingsStore, storageKey);
const clusterRolesQuery = useGetClusterRolesQuery(environmentId, {
autoRefreshRate: tableState.autoRefreshRate * 1000,
});
const { authorized: isAuthorizedToAddEdit } = useAuthorizations([
'K8sClusterRolesW',
]);
const filteredClusterRoles = useMemo(
() =>
clusterRolesQuery.data?.filter(
(cr) => tableState.showSystemResources || !cr.isSystem
),
[clusterRolesQuery.data, tableState.showSystemResources]
);
return (
<Datatable
dataset={filteredClusterRoles || []}
columns={columns}
isLoading={clusterRolesQuery.isLoading}
settingsManager={tableState}
emptyContentLabel="No supported cluster roles found"
title="Cluster Roles"
titleIcon={UserCheck}
getRowId={(row) => row.uid}
isRowSelectable={(row) => !row.original.isSystem}
renderTableActions={(selectedRows) => (
<TableActions selectedItems={selectedRows} />
)}
renderTableSettings={() => (
<TableSettingsMenu>
<DefaultDatatableSettings settings={tableState} />
</TableSettingsMenu>
)}
description={
<SystemResourceDescription
showSystemResources={tableState.showSystemResources}
/>
}
disableSelect={!isAuthorizedToAddEdit}
data-cy="k8s-clusterroles-datatable"
/>
);
}
interface SelectedRole {
name: string;
}
type TableActionsProps = {
selectedItems: ClusterRole[];
};
function TableActions({ selectedItems }: TableActionsProps) {
const environmentId = useEnvironmentId();
const deleteClusterRolesMutation =
useDeleteClusterRolesMutation(environmentId);
const router = useRouter();
async function handleRemoveClick(roles: SelectedRole[]) {
const confirmed = await confirmDelete(
<>
<p>Are you sure you want to delete the selected cluster role(s)?</p>
<ul className="mt-2 max-h-96 list-inside overflow-hidden overflow-y-auto text-sm">
{roles.map((s, index) => (
<li key={index}>{s.name}</li>
))}
</ul>
</>
);
if (!confirmed) {
return null;
}
const payload: string[] = [];
roles.forEach((r) => {
payload.push(r.name);
});
deleteClusterRolesMutation.mutate(
{ environmentId, data: payload },
{
onSuccess: () => {
notifySuccess(
'Roles successfully removed',
roles.map((r) => `${r.name}`).join(', ')
);
router.stateService.reload();
},
onError: (error) => {
notifyError(
'Unable to delete cluster roles',
error as Error,
roles.map((r) => `${r.name}`).join(', ')
);
},
}
);
return roles;
}
return (
<Authorized authorizations="K8sClusterRolesW">
<LoadingButton
className="btn-wrapper"
color="dangerlight"
disabled={selectedItems.length === 0}
onClick={() => handleRemoveClick(selectedItems)}
icon={Trash2}
isLoading={deleteClusterRolesMutation.isLoading}
loadingText="Removing cluster roles..."
data-cy="k8sClusterRoles-removeRoleButton"
>
Remove
</LoadingButton>
<CreateFromManifestButton
params={{ tab: 'clusterRoles' }}
data-cy="k8s-cluster-roles-deploy-button"
/>
</Authorized>
);
}

View file

@ -0,0 +1,12 @@
import { formatDate } from '@/portainer/filters/filters';
import { columnHelper } from './helper';
export const created = columnHelper.accessor(
(row) => formatDate(row.creationDate),
{
header: 'Created',
id: 'created',
cell: ({ getValue }) => getValue(),
}
);

View file

@ -0,0 +1,5 @@
import { createColumnHelper } from '@tanstack/react-table';
import { ClusterRole } from '../types';
export const columnHelper = createColumnHelper<ClusterRole>();

View file

@ -0,0 +1,4 @@
import { name } from './name';
import { created } from './created';
export const columns = [name, created];

View file

@ -0,0 +1,28 @@
import { SystemBadge } from '@@/Badge/SystemBadge';
import { UnusedBadge } from '@@/Badge/UnusedBadge';
import { columnHelper } from './helper';
export const name = columnHelper.accessor(
(row) => {
let result = row.name;
if (row.isSystem) {
result += ' system';
}
if (row.isUnused) {
result += ' unused';
}
return result;
},
{
header: 'Name',
id: 'name',
cell: ({ row }) => (
<div className="flex gap-2">
{row.original.name}
{row.original.isSystem && <SystemBadge />}
{row.original.isUnused && <UnusedBadge />}
</div>
),
}
);

View file

@ -0,0 +1,6 @@
import { EnvironmentId } from '@/react/portainer/environments/types';
export const queryKeys = {
list: (environmentId: EnvironmentId) =>
['environments', environmentId, 'kubernetes', 'cluster_roles'] as const,
};

View file

@ -0,0 +1,33 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { withGlobalError } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { queryKeys } from './query-keys';
export function useDeleteClusterRolesMutation(environmentId: EnvironmentId) {
const queryClient = useQueryClient();
return useMutation(deleteClusterRoles, {
onSuccess: () =>
queryClient.invalidateQueries(queryKeys.list(environmentId)),
...withGlobalError('Unable to delete cluster roles'),
});
}
export async function deleteClusterRoles({
environmentId,
data,
}: {
environmentId: EnvironmentId;
data: string[];
}) {
try {
return await axios.post(
`kubernetes/${environmentId}/cluster_roles/delete`,
data
);
} catch (e) {
throw parseAxiosError(e, `Unable to delete cluster roles`);
}
}

View file

@ -0,0 +1,39 @@
import { compact } from 'lodash';
import { useQuery } from '@tanstack/react-query';
import { withGlobalError } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { ClusterRole } from '../types';
import { queryKeys } from './query-keys';
export function useGetClusterRolesQuery(
environmentId: EnvironmentId,
options?: { autoRefreshRate?: number }
) {
return useQuery(
queryKeys.list(environmentId),
async () => {
const clusterRoles = await getClusterRoles(environmentId);
return compact(clusterRoles);
},
{
...withGlobalError('Unable to get cluster roles'),
...options,
}
);
}
async function getClusterRoles(environmentId: EnvironmentId) {
try {
const { data: roles } = await axios.get<ClusterRole[]>(
`kubernetes/${environmentId}/cluster_roles`
);
return roles;
} catch (e) {
throw parseAxiosError(e, 'Unable to get cluster roles');
}
}

View file

@ -0,0 +1,23 @@
export type Rule = {
verbs: string[];
apiGroups: string[];
resources: string[];
};
export type ClusterRole = {
name: string;
uid: string;
namespace: string;
resourceVersion: string;
creationDate: string;
annotations?: Record<string, string>;
rules: Rule[];
isUnused: boolean;
isSystem: boolean;
};
export type DeleteRequestPayload = {
clusterRoles: string[];
};

View file

@ -0,0 +1,51 @@
import { UserCheck, Link } from 'lucide-react';
import { useCurrentStateAndParams } from '@uirouter/react';
import { useUnauthorizedRedirect } from '@/react/hooks/useUnauthorizedRedirect';
import { PageHeader } from '@@/PageHeader';
import { Tab, WidgetTabs, findSelectedTabIndex } from '@@/Widget/WidgetTabs';
import { ClusterRolesDatatable } from './ClusterRolesDatatable/ClusterRolesDatatable';
import { ClusterRoleBindingsDatatable } from './ClusterRoleBindingsDatatable/ClusterRoleBindingsDatatable';
export function ClusterRolesView() {
useUnauthorizedRedirect(
{ authorizations: ['K8sClusterRoleBindingsW', 'K8sClusterRolesW'] },
{ to: 'kubernetes.dashboard' }
);
const tabs: Tab[] = [
{
name: 'Cluster Roles',
icon: UserCheck,
widget: <ClusterRolesDatatable />,
selectedTabParam: 'clusterRoles',
},
{
name: 'Cluster Role Bindings',
icon: Link,
widget: <ClusterRoleBindingsDatatable />,
selectedTabParam: 'clusterRoleBindings',
},
];
const currentTabIndex = findSelectedTabIndex(
useCurrentStateAndParams(),
tabs
);
return (
<>
<PageHeader
title="Cluster Role list"
breadcrumbs="Cluster Roles"
reload
/>
<>
<WidgetTabs tabs={tabs} currentTabIndex={currentTabIndex} />
<div className="content">{tabs[currentTabIndex].widget}</div>
</>
</>
);
}

View file

@ -0,0 +1 @@
export { ClusterRolesView } from './ClusterRolesView';

View file

@ -0,0 +1,52 @@
import { Row } from '@tanstack/react-table';
import { RoleBinding } from '../RolesView/RoleBindingsDatatable/types';
import { ClusterRoleBinding } from './ClusterRoleBindingsDatatable/types';
/**
* Transforms the rows of a table to get a unique list of namespaces to use as filter options.
* One row can have multiple subject namespaces.
* @param rows - The rows of the table.
* @param id - The ID of the column containing the subject namespaces.
* @returns An array of unique subject namespace options.
*/
export function filterNamespaceOptionsTransformer<
TData extends ClusterRoleBinding | RoleBinding,
>(rows: Row<TData>[], id: string) {
const options = new Set<string>();
rows.forEach(({ getValue }) => {
const value = getValue<string[]>(id);
if (!value) {
return;
}
value.forEach((v) => {
if (v && v !== '-') {
options.add(v);
}
});
});
return Array.from(options);
}
/**
* Filters the rows of a table based on the selected namespaces.
* @param row - The row to filter.
* @param _columnId - The ID of the column being filtered.
* @param filterValue - The selected namespaces to filter by.
* @returns True if the row should be shown, false otherwise.
*/
export function filterFn(
row: Row<ClusterRoleBinding | RoleBinding>,
_columnId: string,
filterValue: string[]
) {
// when no filter is set, show all rows
if (filterValue.length === 0) {
return true;
}
const subjectNamespaces = row.original.subjects?.flatMap(
(sub) => sub.namespace ?? []
);
return filterValue.some((v) => subjectNamespaces?.includes(v));
}

View file

@ -0,0 +1,175 @@
import { Trash2, Link as LinkIcon } from 'lucide-react';
import { useRouter } from '@uirouter/react';
import { Row } from '@tanstack/react-table';
import clsx from 'clsx';
import { useEnvironmentId } from '@/react/hooks/useEnvironmentId';
import { useAuthorizations, Authorized } from '@/react/hooks/useUser';
import { notifyError, notifySuccess } from '@/portainer/services/notifications';
import { SystemResourceDescription } from '@/react/kubernetes/datatables/SystemResourceDescription';
import { createStore } from '@/react/kubernetes/datatables/default-kube-datatable-store';
import { useNamespacesQuery } from '@/react/kubernetes/namespaces/queries/useNamespacesQuery';
import { CreateFromManifestButton } from '@/react/kubernetes/components/CreateFromManifestButton';
import { isSystemNamespace } from '@/react/kubernetes/namespaces/queries/useIsSystemNamespace';
import { confirmDelete } from '@@/modals/confirm';
import { Datatable, Table, TableSettingsMenu } from '@@/datatables';
import { LoadingButton } from '@@/buttons';
import { useTableState } from '@@/datatables/useTableState';
import { DefaultDatatableSettings } from '../../../datatables/DefaultDatatableSettings';
import { RoleBinding } from './types';
import { columns } from './columns';
import { useGetAllRoleBindingsQuery } from './queries/useGetAllRoleBindingsQuery';
import { useDeleteRoleBindingsMutation } from './queries/useDeleteRoleBindingsMutation';
const storageKey = 'roleBindings';
const settingsStore = createStore(storageKey);
export function RoleBindingsDatatable() {
const environmentId = useEnvironmentId();
const tableState = useTableState(settingsStore, storageKey);
const namespacesQuery = useNamespacesQuery(environmentId);
const roleBindingsQuery = useGetAllRoleBindingsQuery(environmentId, {
autoRefreshRate: tableState.autoRefreshRate * 1000,
enabled: namespacesQuery.isSuccess,
});
const filteredRoleBindings = tableState.showSystemResources
? roleBindingsQuery.data
: roleBindingsQuery.data?.filter(
(rb) => !isSystemNamespace(rb.namespace, namespacesQuery.data)
);
const { authorized: isAuthorisedToAddEdit } = useAuthorizations([
'K8sRoleBindingsW',
]);
return (
<Datatable
dataset={filteredRoleBindings || []}
columns={columns}
settingsManager={tableState}
isLoading={roleBindingsQuery.isLoading}
emptyContentLabel="No role bindings found"
title="Role Bindings"
titleIcon={LinkIcon}
getRowId={(row) => row.uid}
isRowSelectable={(row) => !row.original.isSystem}
renderTableActions={(selectedRows) => (
<TableActions selectedItems={selectedRows} />
)}
renderTableSettings={() => (
<TableSettingsMenu>
<DefaultDatatableSettings settings={tableState} />
</TableSettingsMenu>
)}
description={
<SystemResourceDescription
showSystemResources={tableState.showSystemResources}
/>
}
disableSelect={!isAuthorisedToAddEdit}
renderRow={renderRow}
data-cy="k8s-role-bindings-datatable"
/>
);
}
// needed to apply custom styling to the row and not globally required in the AC's for this ticket.
function renderRow(row: Row<RoleBinding>, highlightedItemId?: string) {
return (
<Table.Row<RoleBinding>
cells={row.getVisibleCells()}
className={clsx('[&>td]:!py-4 [&>td]:!align-top', {
active: highlightedItemId === row.id,
})}
/>
);
}
interface SelectedRole {
namespace: string;
name: string;
}
type TableActionsProps = {
selectedItems: RoleBinding[];
};
function TableActions({ selectedItems }: TableActionsProps) {
const environmentId = useEnvironmentId();
const deleteRoleBindingsMutation =
useDeleteRoleBindingsMutation(environmentId);
const router = useRouter();
async function handleRemoveClick(roles: SelectedRole[]) {
const confirmed = await confirmDelete(
<>
<p>Are you sure you want to delete the selected role binding(s)?</p>
<ul className="mt-2 max-h-96 list-inside overflow-hidden overflow-y-auto text-sm">
{roles.map((r, index) => (
<li key={index}>
{r.namespace}/{r.name}
</li>
))}
</ul>
</>
);
if (!confirmed) {
return null;
}
const payload: Record<string, string[]> = {};
roles.forEach((r) => {
payload[r.namespace] = payload[r.namespace] || [];
payload[r.namespace].push(r.name);
});
deleteRoleBindingsMutation.mutate(
{ environmentId, data: payload },
{
onSuccess: () => {
notifySuccess(
'Role binding(s) successfully removed',
roles.map((r) => `${r.namespace}/${r.name}`).join(', ')
);
router.stateService.reload();
},
onError: (error) => {
notifyError(
'Unable to delete role bindings(s)',
error as Error,
roles.map((r) => `${r.namespace}/${r.name}`).join(', ')
);
},
}
);
return roles;
}
return (
<Authorized authorizations="K8sRoleBindingsW">
<LoadingButton
className="btn-wrapper"
color="dangerlight"
disabled={selectedItems.length === 0}
onClick={() => handleRemoveClick(selectedItems)}
icon={Trash2}
isLoading={deleteRoleBindingsMutation.isLoading}
loadingText="Removing role bindings..."
data-cy="k8s-role-bindings-remove-button"
>
Remove
</LoadingButton>
<CreateFromManifestButton
params={{
tab: 'roleBindings',
}}
data-cy="k8s-role-bindings-deploy-button"
/>
</Authorized>
);
}

View file

@ -0,0 +1,12 @@
import { formatDate } from '@/portainer/filters/filters';
import { columnHelper } from './helper';
export const created = columnHelper.accessor(
(row) => formatDate(row.creationDate),
{
header: 'Created',
id: 'created',
cell: ({ getValue }) => getValue(),
}
);

View file

@ -0,0 +1,5 @@
import { createColumnHelper } from '@tanstack/react-table';
import { RoleBinding } from '../types';
export const columnHelper = createColumnHelper<RoleBinding>();

View file

@ -0,0 +1,17 @@
import { name } from './name';
import { roleKind } from './roleKind';
import { roleName } from './roleName';
import { subjectKind } from './subjectKind';
import { subjectName } from './subjectName';
import { subjectNamespace } from './subjectNamespace';
import { created } from './created';
export const columns = [
name,
roleKind,
roleName,
subjectKind,
subjectName,
subjectNamespace,
created,
];

View file

@ -0,0 +1,22 @@
import { SystemBadge } from '@@/Badge/SystemBadge';
import { columnHelper } from './helper';
export const name = columnHelper.accessor(
(row) => {
if (row.isSystem) {
return `${row.name} system`;
}
return row.name;
},
{
header: 'Name',
id: 'name',
cell: ({ row }) => (
<div className="flex gap-2">
{row.original.name}
{row.original.isSystem && <SystemBadge />}
</div>
),
}
);

View file

@ -0,0 +1,6 @@
import { columnHelper } from './helper';
export const roleKind = columnHelper.accessor('roleRef.kind', {
header: 'Role Kind',
id: 'roleKind',
});

View file

@ -0,0 +1,6 @@
import { columnHelper } from './helper';
export const roleName = columnHelper.accessor('roleRef.name', {
header: 'Role Name',
id: 'roleName',
});

View file

@ -0,0 +1,13 @@
import { columnHelper } from './helper';
export const subjectKind = columnHelper.accessor(
(row) => row.subjects?.map((sub) => sub.kind).join(', '),
{
header: 'Subject Kind',
id: 'subjectKind',
cell: ({ row }) =>
row.original.subjects?.map((sub, index) => (
<div key={index}>{sub.kind}</div>
)) || '-',
}
);

View file

@ -0,0 +1,13 @@
import { columnHelper } from './helper';
export const subjectName = columnHelper.accessor(
(row) => row.subjects?.map((sub) => sub.name).join(', '),
{
header: 'Subject Name',
id: 'subjectName',
cell: ({ row }) =>
row.original.subjects?.map((sub, index) => (
<div key={index}>{sub.name}</div>
)) || '-',
}
);

View file

@ -0,0 +1,45 @@
import { Link } from '@@/Link';
import { filterHOC } from '@@/datatables/Filter';
import {
filterFn,
filterNamespaceOptionsTransformer,
} from '../../../ClusterRolesView/utils';
import { columnHelper } from './helper';
export const subjectNamespace = columnHelper.accessor(
(row) => row.subjects?.flatMap((sub) => sub.namespace || '-') || [],
{
header: 'Subject Namespace',
id: 'subjectNamespace',
cell: ({ row }) =>
row.original.subjects?.map((sub, index) => (
<div key={index}>
{sub.namespace ? (
<Link
to="kubernetes.resourcePools.resourcePool"
params={{
id: sub.namespace,
}}
title={sub.namespace}
data-cy={`subject-namespace-link-${row.original.name}_${index}`}
>
{sub.namespace}
</Link>
) : (
'-'
)}
</div>
)) || '-',
enableColumnFilter: true,
// use a custom filter, to remove empty namespace values
meta: {
filter: filterHOC(
'Filter by subject namespace',
filterNamespaceOptionsTransformer
),
},
filterFn,
}
);

View file

@ -0,0 +1 @@
export { RoleBindingsDatatable } from './RoleBindingsDatatable';

View file

@ -0,0 +1,6 @@
import { EnvironmentId } from '@/react/portainer/environments/types';
export const queryKeys = {
list: (environmentId: EnvironmentId) =>
['environments', environmentId, 'kubernetes', 'role_bindings'] as const,
};

View file

@ -0,0 +1,32 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { withGlobalError, withInvalidate } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { queryKeys } from './query-keys';
export function useDeleteRoleBindingsMutation(environmentId: EnvironmentId) {
const queryClient = useQueryClient();
return useMutation(deleteRoleBindings, {
...withInvalidate(queryClient, [queryKeys.list(environmentId)]),
...withGlobalError('Unable to delete role bindings'),
});
}
export async function deleteRoleBindings({
environmentId,
data,
}: {
environmentId: EnvironmentId;
data: Record<string, string[]>;
}) {
try {
return await axios.post(
`kubernetes/${environmentId}/role_bindings/delete`,
data
);
} catch (e) {
throw parseAxiosError(e, `Unable to delete role bindings`);
}
}

View file

@ -0,0 +1,38 @@
import { useQuery } from '@tanstack/react-query';
import { withGlobalError } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { RoleBinding } from '../types';
import { queryKeys } from './query-keys';
export function useGetAllRoleBindingsQuery(
environmentId: EnvironmentId,
options?: { autoRefreshRate?: number; enabled?: boolean }
) {
return useQuery(
queryKeys.list(environmentId),
async () => getAllRoleBindings(environmentId),
{
...withGlobalError('Unable to get role bindings'),
refetchInterval() {
return options?.autoRefreshRate ?? false;
},
enabled: options?.enabled,
}
);
}
async function getAllRoleBindings(environmentId: EnvironmentId) {
try {
const { data: roleBinding } = await axios.get<RoleBinding[]>(
`kubernetes/${environmentId}/role_bindings`
);
return roleBinding;
} catch (e) {
throw parseAxiosError(e, 'Unable to get role bindings');
}
}

View file

@ -0,0 +1,26 @@
export type RoleRef = {
name: string;
kind: string;
apiGroup?: string;
};
export type RoleSubject = {
name: string;
kind: string;
apiGroup?: string;
namespace?: string;
};
export type RoleBinding = {
name: string;
uid: string;
namespace: string;
resourceVersion: string;
creationDate: string;
annotations: Record<string, string> | null;
roleRef: RoleRef;
subjects: RoleSubject[] | null;
isSystem: boolean;
};

View file

@ -0,0 +1,157 @@
import { Trash2, UserCheck } from 'lucide-react';
import { useRouter } from '@uirouter/react';
import { useEnvironmentId } from '@/react/hooks/useEnvironmentId';
import { Authorized } from '@/react/hooks/useUser';
import { notifyError, notifySuccess } from '@/portainer/services/notifications';
import { SystemResourceDescription } from '@/react/kubernetes/datatables/SystemResourceDescription';
import { createStore } from '@/react/kubernetes/datatables/default-kube-datatable-store';
import { useNamespacesQuery } from '@/react/kubernetes/namespaces/queries/useNamespacesQuery';
import { CreateFromManifestButton } from '@/react/kubernetes/components/CreateFromManifestButton';
import { useUnauthorizedRedirect } from '@/react/hooks/useUnauthorizedRedirect';
import { isSystemNamespace } from '@/react/kubernetes/namespaces/queries/useIsSystemNamespace';
import { confirmDelete } from '@@/modals/confirm';
import { Datatable, TableSettingsMenu } from '@@/datatables';
import { LoadingButton } from '@@/buttons';
import { useTableState } from '@@/datatables/useTableState';
import { DefaultDatatableSettings } from '../../../datatables/DefaultDatatableSettings';
import { columns } from './columns';
import { Role } from './types';
import { useGetAllRolesQuery } from './queries/useGetAllRolesQuery';
import { useDeleteRolesMutation } from './queries/useDeleteRolesMutation';
const storageKey = 'roles';
const settingsStore = createStore(storageKey);
export function RolesDatatable() {
const environmentId = useEnvironmentId();
const tableState = useTableState(settingsStore, storageKey);
const namespacesQuery = useNamespacesQuery(environmentId);
const rolesQuery = useGetAllRolesQuery(environmentId, {
autoRefreshRate: tableState.autoRefreshRate * 1000,
enabled: namespacesQuery.isSuccess,
});
useUnauthorizedRedirect(
{ authorizations: ['K8sRolesW'] },
{ to: 'kubernetes.dashboard' }
);
const filteredRoles = tableState.showSystemResources
? rolesQuery.data
: rolesQuery.data?.filter(
(role) => !isSystemNamespace(role.namespace, namespacesQuery.data)
);
return (
<Datatable
dataset={filteredRoles || []}
columns={columns}
settingsManager={tableState}
isLoading={rolesQuery.isLoading}
emptyContentLabel="No roles found"
title="Roles"
titleIcon={UserCheck}
getRowId={(row) => row.uid}
isRowSelectable={(row) => !row.original.isSystem}
renderTableActions={(selectedRows) => (
<TableActions selectedItems={selectedRows} />
)}
renderTableSettings={() => (
<TableSettingsMenu>
<DefaultDatatableSettings settings={tableState} />
</TableSettingsMenu>
)}
description={
<SystemResourceDescription
showSystemResources={tableState.showSystemResources}
/>
}
data-cy="k8s-roles-datatable"
/>
);
}
interface SelectedRole {
namespace: string;
name: string;
}
type TableActionsProps = {
selectedItems: Role[];
};
function TableActions({ selectedItems }: TableActionsProps) {
const environmentId = useEnvironmentId();
const deleteRolesMutation = useDeleteRolesMutation(environmentId);
const router = useRouter();
return (
<Authorized authorizations="K8sRolesW">
<LoadingButton
className="btn-wrapper"
color="dangerlight"
disabled={selectedItems.length === 0}
onClick={() => handleRemoveClick(selectedItems)}
icon={Trash2}
isLoading={deleteRolesMutation.isLoading}
loadingText="Removing roles..."
data-cy="k8s-roles-removeRoleButton"
>
Remove
</LoadingButton>
<CreateFromManifestButton
params={{ tab: 'roles' }}
data-cy="k8s-roles-deploy-button"
/>
</Authorized>
);
async function handleRemoveClick(roles: SelectedRole[]) {
const confirmed = await confirmDelete(
<>
<p>Are you sure you want to delete the selected role(s)?</p>
<ul className="mt-2 max-h-96 list-inside overflow-hidden overflow-y-auto text-sm">
{roles.map((s, index) => (
<li key={index}>
{s.namespace}/{s.name}
</li>
))}
</ul>
</>
);
if (!confirmed) {
return null;
}
const payload: Record<string, string[]> = {};
roles.forEach((r) => {
payload[r.namespace] = payload[r.namespace] || [];
payload[r.namespace].push(r.name);
});
deleteRolesMutation.mutate(
{ environmentId, data: payload },
{
onSuccess: () => {
notifySuccess(
'Roles successfully removed',
roles.map((r) => `${r.namespace}/${r.name}`).join(', ')
);
router.stateService.reload();
},
onError: (error) => {
notifyError(
'Unable to delete roles',
error as Error,
roles.map((r) => `${r.namespace}/${r.name}`).join(', ')
);
},
}
);
return roles;
}
}

View file

@ -0,0 +1,12 @@
import { formatDate } from '@/portainer/filters/filters';
import { columnHelper } from './helper';
export const created = columnHelper.accessor(
(row) => formatDate(row.creationDate),
{
header: 'Created',
id: 'created',
cell: ({ getValue }) => getValue(),
}
);

View file

@ -0,0 +1,5 @@
import { createColumnHelper } from '@tanstack/react-table';
import { Role } from '../types';
export const columnHelper = createColumnHelper<Role>();

View file

@ -0,0 +1,5 @@
import { name } from './name';
import { created } from './created';
import { namespace } from './namespace';
export const columns = [name, namespace, created];

View file

@ -0,0 +1,28 @@
import { SystemBadge } from '@@/Badge/SystemBadge';
import { UnusedBadge } from '@@/Badge/UnusedBadge';
import { columnHelper } from './helper';
export const name = columnHelper.accessor(
(row) => {
let result = row.name;
if (row.isSystem) {
result += ' system';
}
if (row.isUnused) {
result += ' unused';
}
return result;
},
{
header: 'Name',
id: 'name',
cell: ({ row }) => (
<div className="flex gap-2">
{row.original.name}
{row.original.isSystem && <SystemBadge />}
{row.original.isUnused && <UnusedBadge />}
</div>
),
}
);

View file

@ -0,0 +1,32 @@
import { Row } from '@tanstack/react-table';
import { filterHOC } from '@@/datatables/Filter';
import { Link } from '@@/Link';
import { Role } from '../types';
import { columnHelper } from './helper';
export const namespace = columnHelper.accessor((row) => row.namespace, {
header: 'Namespace',
id: 'namespace',
cell: ({ getValue, row }) => (
<Link
to="kubernetes.resourcePools.resourcePool"
params={{
id: getValue(),
}}
title={getValue()}
data-cy={`role-namespace-link-${row.original.name}`}
>
{getValue()}
</Link>
),
meta: {
filter: filterHOC('Filter by namespace'),
},
enableColumnFilter: true,
filterFn: (row: Row<Role>, _columnId: string, filterValue: string[]) =>
filterValue.length === 0 ||
filterValue.includes(row.original.namespace ?? ''),
});

View file

@ -0,0 +1 @@
export { RolesDatatable } from './RolesDatatable';

View file

@ -0,0 +1,6 @@
import { EnvironmentId } from '@/react/portainer/environments/types';
export const queryKeys = {
list: (environmentId: EnvironmentId) =>
['environments', environmentId, 'kubernetes', 'roles'] as const,
};

View file

@ -0,0 +1,29 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { withGlobalError, withInvalidate } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { queryKeys } from './query-keys';
export function useDeleteRolesMutation(environmentId: EnvironmentId) {
const queryClient = useQueryClient();
return useMutation(deleteRole, {
...withInvalidate(queryClient, [queryKeys.list(environmentId)]),
...withGlobalError('Unable to delete roles'),
});
}
export async function deleteRole({
environmentId,
data,
}: {
environmentId: EnvironmentId;
data: Record<string, string[]>;
}) {
try {
return await axios.post(`kubernetes/${environmentId}/roles/delete`, data);
} catch (e) {
throw parseAxiosError(e, `Unable to delete roles`);
}
}

View file

@ -0,0 +1,41 @@
import { useQuery } from '@tanstack/react-query';
import { withGlobalError } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { Role } from '../types';
const queryKeys = {
list: (environmentId: EnvironmentId) =>
['environments', environmentId, 'kubernetes', 'roles'] as const,
};
export function useGetAllRolesQuery(
environmentId: EnvironmentId,
options?: { autoRefreshRate?: number; enabled?: boolean }
) {
return useQuery(
queryKeys.list(environmentId),
async () => getAllRoles(environmentId),
{
...withGlobalError('Unable to get roles'),
refetchInterval() {
return options?.autoRefreshRate ?? false;
},
enabled: options?.enabled,
}
);
}
async function getAllRoles(environmentId: EnvironmentId) {
try {
const { data: roles } = await axios.get<Role[]>(
`kubernetes/${environmentId}/roles`
);
return roles;
} catch (e) {
throw parseAxiosError(e, 'Unable to get roles');
}
}

View file

@ -0,0 +1,19 @@
export type Rule = {
verbs: string[];
apiGroups: string[];
resources: string[];
};
export type Role = {
name: string;
uid: string;
namespace: string;
resourceVersion: string;
creationDate: string;
annotations?: Record<string, string>;
rules: Rule[];
isSystem: boolean;
isUnused: boolean;
};

View file

@ -0,0 +1,47 @@
import { useCurrentStateAndParams } from '@uirouter/react';
import { UserCheck, Link } from 'lucide-react';
import { useUnauthorizedRedirect } from '@/react/hooks/useUnauthorizedRedirect';
import { PageHeader } from '@@/PageHeader';
import { WidgetTabs, Tab, findSelectedTabIndex } from '@@/Widget/WidgetTabs';
import { RolesDatatable } from './RolesDatatable';
import { RoleBindingsDatatable } from './RoleBindingsDatatable';
export function RolesView() {
useUnauthorizedRedirect(
{ authorizations: ['K8sRoleBindingsW', 'K8sRolesW'] },
{ to: 'kubernetes.dashboard' }
);
const tabs: Tab[] = [
{
name: 'Roles',
icon: UserCheck,
widget: <RolesDatatable />,
selectedTabParam: 'roles',
},
{
name: 'Role Bindings',
icon: Link,
widget: <RoleBindingsDatatable />,
selectedTabParam: 'roleBindings',
},
];
const currentTabIndex = findSelectedTabIndex(
useCurrentStateAndParams(),
tabs
);
return (
<>
<PageHeader title="Role list" breadcrumbs="Roles" reload />
<>
<WidgetTabs tabs={tabs} currentTabIndex={currentTabIndex} />
<div className="content">{tabs[currentTabIndex].widget}</div>
</>
</>
);
}

View file

@ -0,0 +1 @@
export { RolesView } from './RolesView';

View file

@ -0,0 +1,147 @@
import { User } from 'lucide-react';
import { useRouter } from '@uirouter/react';
import { useEnvironmentId } from '@/react/hooks/useEnvironmentId';
import { Authorized } from '@/react/hooks/useUser';
import { notifyError, notifySuccess } from '@/portainer/services/notifications';
import { SystemResourceDescription } from '@/react/kubernetes/datatables/SystemResourceDescription';
import { useNamespacesQuery } from '@/react/kubernetes/namespaces/queries/useNamespacesQuery';
import { createStore } from '@/react/kubernetes/datatables/default-kube-datatable-store';
import { CreateFromManifestButton } from '@/react/kubernetes/components/CreateFromManifestButton';
import { useUnauthorizedRedirect } from '@/react/hooks/useUnauthorizedRedirect';
import { isSystemNamespace } from '@/react/kubernetes/namespaces/queries/useIsSystemNamespace';
import { Datatable, TableSettingsMenu } from '@@/datatables';
import { useTableState } from '@@/datatables/useTableState';
import { DeleteButton } from '@@/buttons/DeleteButton';
import { ServiceAccount } from '../types';
import { DefaultDatatableSettings } from '../../../datatables/DefaultDatatableSettings';
import { useColumns } from './columns';
import { useDeleteServiceAccountsMutation } from './queries/useDeleteServiceAccountsMutation';
import { useGetAllServiceAccountsQuery } from './queries/useGetAllServiceAccountsQuery';
const storageKey = 'serviceAccounts';
const settingsStore = createStore(storageKey);
export function ServiceAccountsDatatable() {
useUnauthorizedRedirect(
{ authorizations: ['K8sServiceAccountsW'] },
{ to: 'kubernetes.dashboard' }
);
const environmentId = useEnvironmentId();
const tableState = useTableState(settingsStore, storageKey);
const namespacesQuery = useNamespacesQuery(environmentId);
const serviceAccountsQuery = useGetAllServiceAccountsQuery(environmentId, {
refetchInterval: tableState.autoRefreshRate * 1000,
enabled: namespacesQuery.isSuccess,
});
const columns = useColumns();
const filteredServiceAccounts = tableState.showSystemResources
? serviceAccountsQuery.data
: serviceAccountsQuery.data?.filter(
(sa) => !isSystemNamespace(sa.namespace, namespacesQuery.data)
);
return (
<Datatable
dataset={filteredServiceAccounts || []}
columns={columns}
settingsManager={tableState}
isLoading={serviceAccountsQuery.isLoading}
emptyContentLabel="No service accounts found"
title="Service Accounts"
titleIcon={User}
getRowId={(row) => row.uid}
isRowSelectable={(row) => !row.original.isSystem}
renderTableActions={(selectedRows) => (
<TableActions selectedItems={selectedRows} />
)}
renderTableSettings={() => (
<TableSettingsMenu>
<DefaultDatatableSettings settings={tableState} />
</TableSettingsMenu>
)}
description={
<SystemResourceDescription
showSystemResources={tableState.showSystemResources}
/>
}
data-cy="k8s-service-accounts-datatable"
/>
);
}
interface SelectedServiceAccount {
namespace: string;
name: string;
}
type TableActionsProps = {
selectedItems: ServiceAccount[];
};
function TableActions({ selectedItems }: TableActionsProps) {
const environmentId = useEnvironmentId();
const deleteServiceAccountsMutation =
useDeleteServiceAccountsMutation(environmentId);
const router = useRouter();
return (
<Authorized authorizations="K8sServiceAccountsW">
<DeleteButton
disabled={selectedItems.length === 0}
onConfirmed={() => handleRemoveClick(selectedItems)}
confirmMessage={
<>
<p>
Are you sure you want to delete the selected service account(s)?
</p>
<ul className="mt-2 max-h-96 list-inside overflow-hidden overflow-y-auto text-sm">
{selectedItems.map((s, index) => (
<li key={index}>
{s.namespace}/{s.name}
</li>
))}
</ul>
</>
}
data-cy="k8s-service-accounts-datatable-remove-button"
/>
<CreateFromManifestButton data-cy="k8s-service-accounts-datatable-create-button" />
</Authorized>
);
async function handleRemoveClick(serviceAccounts: SelectedServiceAccount[]) {
const payload: Record<string, string[]> = {};
serviceAccounts.forEach((sa) => {
payload[sa.namespace] = payload[sa.namespace] || [];
payload[sa.namespace].push(sa.name);
});
deleteServiceAccountsMutation.mutate(
{ environmentId, data: payload },
{
onSuccess: () => {
notifySuccess(
'Service account(s) successfully removed',
serviceAccounts.map((sa) => `${sa.namespace}/${sa.name}`).join(', ')
);
router.stateService.reload();
},
onError: (error) => {
notifyError(
'Unable to delete service account(s)',
error as Error,
serviceAccounts.map((sa) => `${sa.namespace}/${sa.name}`).join(', ')
);
},
}
);
}
}

View file

@ -0,0 +1,12 @@
import { formatDate } from '@/portainer/filters/filters';
import { columnHelper } from './helper';
export const created = columnHelper.accessor(
(row) => formatDate(row.creationDate),
{
header: 'Created',
id: 'created',
cell: ({ getValue }) => getValue(),
}
);

View file

@ -0,0 +1,5 @@
import { createColumnHelper } from '@tanstack/react-table';
import { ServiceAccount } from '../../types';
export const columnHelper = createColumnHelper<ServiceAccount>();

View file

@ -0,0 +1,7 @@
import { name } from './name';
import { namespace } from './namespace';
import { created } from './created';
export function useColumns() {
return [name, namespace, created];
}

View file

@ -0,0 +1,28 @@
import { SystemBadge } from '@@/Badge/SystemBadge';
import { UnusedBadge } from '@@/Badge/UnusedBadge';
import { columnHelper } from './helper';
export const name = columnHelper.accessor(
(row) => {
let result = row.name;
if (row.isSystem) {
result += ' system';
}
if (row.isUnused) {
result += ' unused';
}
return result;
},
{
header: 'Name',
id: 'name',
cell: ({ row }) => (
<div className="flex gap-2">
<div>{row.original.name}</div>
{row.original.isSystem && <SystemBadge />}
{!row.original.isSystem && row.original.isUnused && <UnusedBadge />}
</div>
),
}
);

View file

@ -0,0 +1,36 @@
import { Row } from '@tanstack/react-table';
import { Link } from '@@/Link';
import { filterHOC } from '@@/datatables/Filter';
import { ServiceAccount } from '../../types';
import { columnHelper } from './helper';
export const namespace = columnHelper.accessor('namespace', {
header: 'Namespace',
id: 'namespace',
cell: ({ row }) => (
<Link
to="kubernetes.resourcePools.resourcePool"
params={{
id: row.original.namespace,
}}
title={row.original.namespace}
data-cy={`service-account-namespace-link-${row.original.name}`}
>
{row.original.namespace}
</Link>
),
meta: {
filter: filterHOC('Filter by namespace'),
},
enableColumnFilter: true,
filterFn: (
row: Row<ServiceAccount>,
_columnId: string,
filterValue: string[]
) =>
filterValue.length === 0 ||
filterValue.includes(row.original.namespace ?? ''),
});

View file

@ -0,0 +1 @@
export { ServiceAccountsDatatable } from './ServiceAccountsDatatable';

View file

@ -0,0 +1,6 @@
import { EnvironmentId } from '@/react/portainer/environments/types';
export const queryKeys = {
list: (environmentId: EnvironmentId) =>
['environments', environmentId, 'kubernetes', 'serviceaccounts'] as const,
};

View file

@ -0,0 +1,33 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { withGlobalError } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { queryKeys } from './query-keys';
export function useDeleteServiceAccountsMutation(environmentId: EnvironmentId) {
const queryClient = useQueryClient();
return useMutation(deleteServices, {
onSuccess: () =>
queryClient.invalidateQueries(queryKeys.list(environmentId)),
...withGlobalError('Unable to delete service accounts'),
});
}
export async function deleteServices({
environmentId,
data,
}: {
environmentId: EnvironmentId;
data: Record<string, string[]>;
}) {
try {
return await axios.post(
`kubernetes/${environmentId}/service_accounts/delete`,
data
);
} catch (e) {
throw parseAxiosError(e, `Unable to delete service accounts`);
}
}

View file

@ -0,0 +1,38 @@
import { useQuery } from '@tanstack/react-query';
import { withGlobalError } from '@/react-tools/react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { ServiceAccount } from '../../types';
import { queryKeys } from './query-keys';
export function useGetAllServiceAccountsQuery(
environmentId: EnvironmentId,
options?: {
refetchInterval?: number;
enabled?: boolean;
}
) {
return useQuery(
queryKeys.list(environmentId),
async () => getAllServiceAccounts(environmentId),
{
...withGlobalError('Unable to get service accounts'),
...options,
}
);
}
async function getAllServiceAccounts(environmentId: EnvironmentId) {
try {
const { data: services } = await axios.get<ServiceAccount[]>(
`kubernetes/${environmentId}/service_accounts`
);
return services;
} catch (e) {
throw parseAxiosError(e, 'Unable to get service accounts');
}
}

View file

@ -0,0 +1,16 @@
import { PageHeader } from '@@/PageHeader';
import { ServiceAccountsDatatable } from './ServiceAccountsDatatable';
export function ServiceAccountsView() {
return (
<>
<PageHeader
title="Service Account list"
breadcrumbs="Service Accounts"
reload
/>
<ServiceAccountsDatatable />
</>
);
}

View file

@ -0,0 +1 @@
export { ServiceAccountsView } from './ServiceAccountsView';

View file

@ -0,0 +1,10 @@
export type ServiceAccount = {
name: string;
namespace: string;
resourceVersion: string;
uid: string;
creationDate: string;
isSystem: boolean;
isUnused: boolean;
};