refactor(cluster): migrate nodes datatable to react [EE-4962] (#10459)

Co-authored-by: testa113 <testa113>
pull/10489/head
Ali 1 year ago committed by GitHub
parent b346fd7f39
commit 0e47f22c0a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -311,7 +311,7 @@ angular.module('portainer.kubernetes', ['portainer.app', registriesModule, custo
const node = {
name: 'kubernetes.cluster.node',
url: '/:name',
url: '/:nodeName',
views: {
'content@': {
component: 'kubernetesNodeView',

@ -1,190 +0,0 @@
<div class="datatable">
<rd-widget>
<rd-widget-body classes="no-padding">
<div class="toolBar">
<div class="toolBarTitle flex">
<div class="widget-icon space-right">
<pr-icon icon="$ctrl.titleIcon"></pr-icon>
</div>
<span class="vertical-center">
{{ $ctrl.titleText }}
</span>
</div>
<div class="searchBar vertical-center">
<pr-icon icon="'search'"></pr-icon>
<input
type="text"
class="searchInput"
ng-model="$ctrl.state.textFilter"
ng-change="$ctrl.onTextFilterChange()"
placeholder="Search for a node..."
auto-focus
ng-model-options="{ debounce: 300 }"
/>
</div>
<div class="settings">
<span
class="setting vertical-center"
ng-class="{ 'setting-active': $ctrl.settings.open }"
uib-dropdown
dropdown-append-to-body
auto-close="disabled"
is-open="$ctrl.settings.open"
>
<span uib-dropdown-toggle><pr-icon icon="'more-vertical'"></pr-icon></span>
<div class="dropdown-menu dropdown-menu-right" uib-dropdown-menu>
<div class="tableMenu">
<div class="menuHeader"> Table settings </div>
<div class="menuContent">
<div>
<div class="md-checkbox">
<input id="setting_auto_refresh" type="checkbox" ng-model="$ctrl.settings.repeater.autoRefresh" ng-change="$ctrl.onSettingsRepeaterChange()" />
<label for="setting_auto_refresh">Auto refresh</label>
</div>
<div ng-if="$ctrl.settings.repeater.autoRefresh">
<label for="settings_refresh_rate"> Refresh rate </label>
<select id="settings_refresh_rate" ng-model="$ctrl.settings.repeater.refreshRate" ng-change="$ctrl.onSettingsRepeaterChange()" class="small-select">
<option value="10">10s</option>
<option value="30">30s</option>
<option value="60">1min</option>
<option value="120">2min</option>
<option value="300">5min</option>
</select>
<span>
<pr-icon id="refreshRateChange" icon="'check'" mode="'success'" style="display: none"></pr-icon>
</span>
</div>
</div>
</div>
<div>
<a type="button" class="btn btn-default btn-sm" ng-click="$ctrl.settings.open = false;">Close</a>
</div>
</div>
</div>
</span>
</div>
</div>
<div class="table-responsive">
<table class="table-hover nowrap-cells table">
<thead>
<tr>
<th>
<table-column-header
col-title="'Name'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Name'"
is-sorted-desc="$ctrl.state.orderBy === 'Name' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Name')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Role'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Role'"
is-sorted-desc="$ctrl.state.orderBy === 'Role' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Role')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Status'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Status'"
is-sorted-desc="$ctrl.state.orderBy === 'Status' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Status')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'CPU'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'CPU'"
is-sorted-desc="$ctrl.state.orderBy === 'CPU' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('CPU')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Memory'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Memory'"
is-sorted-desc="$ctrl.state.orderBy === 'Memory' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Memory')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Version'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Version'"
is-sorted-desc="$ctrl.state.orderBy === 'Version' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Version')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'IP Address'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'IPAddress'"
is-sorted-desc="$ctrl.state.orderBy === 'IPAddress' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('IPAddress')"
></table-column-header>
</th>
<th ng-if="$ctrl.useServerMetrics">
<table-column-header col-title="'Actions'" can-sort="false"></table-column-header>
</th>
</tr>
</thead>
<tbody>
<tr
dir-paginate="item in ($ctrl.state.filteredDataSet = ($ctrl.dataset | filter:$ctrl.state.textFilter | orderBy:$ctrl.state.orderBy:$ctrl.state.reverseOrder | itemsPerPage: $ctrl.state.paginatedItemLimit))"
>
<td ng-if="$ctrl.isAdmin">
<a ui-sref="kubernetes.cluster.node({ name: item.Name })">
{{ item.Name }}
</a>
<span class="label label-primary image-tag" style="margin-left: 5px" ng-if="item.Api">api</span>
</td>
<td>{{ item.Role }}</td>
<td
><span class="label label-{{ item.Status | kubernetesNodeStatusColor }}">{{ item.Status }}</span></td
>
<td>{{ item.CPU }}</td>
<td>{{ item.Memory | humansize }}</td>
<td>{{ item.Version }}</td>
<td>{{ item.IPAddress }}</td>
<td ng-if="$ctrl.useServerMetrics">
<a ui-sref="kubernetes.cluster.node.stats({ name: item.Name })" class="vertical-center"> <pr-icon icon="'bar-chart'"></pr-icon> Stats </a>
</td>
</tr>
<tr ng-if="!$ctrl.dataset">
<td colspan="7" class="text-muted text-center">Loading...</td>
</tr>
<tr ng-if="$ctrl.state.filteredDataSet.length === 0">
<td colspan="7" class="text-muted text-center">No node available.</td>
</tr>
</tbody>
</table>
</div>
<div class="footer" ng-if="$ctrl.dataset">
<div class="infoBar" ng-if="$ctrl.state.selectedItemCount !== 0"> {{ $ctrl.state.selectedItemCount }} item(s) selected </div>
<div class="paginationControls">
<form class="form-inline">
<span class="limitSelector">
<span style="margin-right: 5px"> Items per page </span>
<select class="form-control" ng-model="$ctrl.state.paginatedItemLimit" ng-change="$ctrl.changePaginationLimit()" data-cy="component-paginationSelect">
<option value="0">All</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</span>
<dir-pagination-controls max-size="5"></dir-pagination-controls>
</form>
</div>
</div>
</rd-widget-body>
</rd-widget>
</div>

@ -1,14 +0,0 @@
angular.module('portainer.kubernetes').component('kubernetesNodesDatatable', {
templateUrl: './nodesDatatable.html',
controller: 'GenericDatatableController',
bindings: {
titleText: '@',
titleIcon: '@',
dataset: '<',
tableKey: '@',
orderBy: '@',
refreshCallback: '<',
isAdmin: '<',
useServerMetrics: '<',
},
});

@ -22,6 +22,7 @@ import { withFormValidation } from '@/react-tools/withFormValidation';
import { withCurrentUser } from '@/react-tools/withCurrentUser';
import { YAMLInspector } from '@/react/kubernetes/components/YAMLInspector';
import { ApplicationsStacksDatatable } from '@/react/kubernetes/applications/ListView/ApplicationsStacksDatatable';
import { NodesDatatable } from '@/react/kubernetes/cluster/HomeView/NodesDatatable';
import { StackName } from '@/react/kubernetes/DeployView/StackName/StackName';
export const ngModule = angular
@ -77,6 +78,10 @@ export const ngModule = angular
'createNamespaceRegistriesSelector',
r2a(RegistriesSelector, ['inputId', 'onChange', 'options', 'value'])
)
.component(
'kubeNodesDatatable',
r2a(withUIRouter(withReactQuery(withCurrentUser(NodesDatatable))), [])
)
.component(
'kubeApplicationAccessPolicySelector',
r2a(KubeApplicationAccessPolicySelector, [

@ -52,16 +52,7 @@
<div class="row">
<div class="col-sm-12">
<kubernetes-nodes-datatable
title-text="Nodes"
title-icon="hard-drive"
dataset="ctrl.nodes"
table-key="kubernetes.nodes"
order-by="Name"
refresh-callback="ctrl.getNodes"
is-admin="ctrl.isAdmin"
use-server-metrics="ctrl.state.useServerMetrics"
></kubernetes-nodes-datatable>
<kube-nodes-datatable></kube-nodes-datatable>
</div>
</div>
</div>

@ -277,7 +277,7 @@ class KubernetesNodeController {
async getNodesAsync() {
try {
this.state.dataLoading = true;
const nodeName = this.$transition$.params().name;
const nodeName = this.$transition$.params().nodeName;
this.nodes = await this.KubernetesNodeService.get();
this.node = _.find(this.nodes, { Name: nodeName });
this.state.isDrainOperation = _.find(this.nodes, { Availability: this.availabilities.DRAIN });
@ -298,7 +298,7 @@ class KubernetesNodeController {
async getNodeUsageAsync() {
try {
const nodeName = this.$transition$.params().name;
const nodeName = this.$transition$.params().nodeName;
const node = await getMetricsForNode(this.$state.params.endpointId, nodeName);
this.resourceUsage = new KubernetesResourceReservation();
this.resourceUsage.CPU = KubernetesResourceReservationHelper.parseCPU(node.usage.cpu);

@ -6,7 +6,7 @@
{
label:ctrl.state.transition.nodeName,
link: 'kubernetes.cluster.node',
linkParams:{name: ctrl.state.transition.nodeName}
linkParams:{nodeName: ctrl.state.transition.nodeName}
},
ctrl.state.transition.nodeName,
]"

@ -109,7 +109,7 @@ class KubernetesNodeStatsController {
refreshRate: '30',
viewReady: false,
transition: {
nodeName: this.$transition$.params().name,
nodeName: this.$transition$.params().nodeName,
},
getMetrics: true,
};

@ -0,0 +1,49 @@
import clsx from 'clsx';
import { AriaAttributes, PropsWithChildren } from 'react';
import { Icon, IconProps } from '@@/Icon';
export function StatusBadge({
className,
children,
color = 'default',
icon,
...aria
}: PropsWithChildren<
{
className?: string;
color?: 'success' | 'danger' | 'warning' | 'default';
icon?: IconProps['icon'];
} & AriaAttributes
>) {
return (
<span
className={clsx(
'flex items-center gap-1 rounded',
'w-fit px-1.5 py-0.5',
'text-sm font-medium text-white',
{
' bg-success-7 th-dark:bg-success-9': color === 'success',
' bg-warning-7 th-dark:bg-warning-9': color === 'warning',
' bg-error-7 th-dark:bg-error-9': color === 'danger',
},
className
)}
// eslint-disable-next-line react/jsx-props-no-spreading
{...aria}
>
{icon && (
<Icon
icon={icon}
className={clsx({
'!text-green-7': color === 'success',
'!text-warning-7': color === 'warning',
'!text-error-7': color === 'danger',
})}
/>
)}
{children}
</span>
);
}

@ -0,0 +1,107 @@
import { Node, Endpoints } from 'kubernetes-types/core/v1';
import { HardDrive } from 'lucide-react';
import { useMemo } from 'react';
import { useEnvironmentId } from '@/react/hooks/useEnvironmentId';
import { createStore } from '@/react/kubernetes/datatables/default-kube-datatable-store';
import { IndexOptional } from '@/react/kubernetes/configs/types';
import { useEnvironment } from '@/react/portainer/environments/queries';
import { Datatable, TableSettingsMenu } from '@@/datatables';
import { useTableState } from '@@/datatables/useTableState';
import { TableSettingsMenuAutoRefresh } from '@@/datatables/TableSettingsMenuAutoRefresh';
import { useNodesQuery } from '../nodes.service';
import { useKubernetesEndpointsQuery } from '../../kubernetesEndpoint.service';
import { getColumns } from './columns';
import { NodeRowData } from './types';
import { getInternalNodeIpAddress } from './utils';
const storageKey = 'k8sNodesDatatable';
const settingsStore = createStore(storageKey);
export function NodesDatatable() {
const tableState = useTableState(settingsStore, storageKey);
const environmentId = useEnvironmentId();
const { data: nodes, ...nodesQuery } = useNodesQuery(environmentId, {
autoRefreshRate: tableState.autoRefreshRate * 1000,
});
const { data: kubernetesEndpoints, ...kubernetesEndpointsQuery } =
useKubernetesEndpointsQuery(environmentId, {
autoRefreshRate: tableState.autoRefreshRate * 1000,
});
const { data: environment, ...environmentQuery } =
useEnvironment(environmentId);
const environmentUrl = environment?.URL;
const isServerMetricsEnabled =
!!environment?.Kubernetes?.Configuration.UseServerMetrics;
const nodeRowData = useNodeRowData(
nodes,
kubernetesEndpoints,
environmentUrl
);
return (
<Datatable<IndexOptional<NodeRowData>>
dataset={nodeRowData ?? []}
columns={getColumns(isServerMetricsEnabled)}
settingsManager={tableState}
isLoading={
nodesQuery.isLoading ||
kubernetesEndpointsQuery.isLoading ||
environmentQuery.isLoading
}
emptyContentLabel="No Nodes found"
title="Nodes"
titleIcon={HardDrive}
getRowId={(row) => row.metadata?.uid ?? ''}
renderTableSettings={() => (
<TableSettingsMenu>
<TableSettingsMenuAutoRefresh
value={tableState.autoRefreshRate}
onChange={(value) => tableState.setAutoRefreshRate(value)}
/>
</TableSettingsMenu>
)}
/>
);
}
/**
* This function is used to add the isApi property to the node row data.
*/
function useNodeRowData(
nodes?: Node[],
kubernetesEndpoints?: Endpoints[],
environmentUrl?: string
): NodeRowData[] {
return useMemo<NodeRowData[]>(() => {
if (!nodes || !kubernetesEndpoints) {
return [];
}
const subsetAddresses = kubernetesEndpoints?.flatMap(
(endpoint) =>
endpoint.subsets?.flatMap((subset) => subset.addresses ?? [])
);
const nodeRowData = nodes.map((node) => {
const nodeAddress = getInternalNodeIpAddress(node);
// if the node address is in the endpoints subset addresses, then it is an api node
const isApi = subsetAddresses?.some(
(subsetAddress) => subsetAddress?.ip === nodeAddress
);
// if the environment url includes the node address, then it is a published node
const isPublishedNode =
!!nodeAddress &&
!!environmentUrl &&
environmentUrl?.includes(nodeAddress);
return {
...node,
isApi,
isPublishedNode,
Name: `${node.metadata?.name}${isApi ? 'api' : ''}` ?? '',
};
});
return nodeRowData;
}, [nodes, kubernetesEndpoints, environmentUrl]);
}

@ -0,0 +1,47 @@
import { CellContext } from '@tanstack/react-table';
import { BarChart } from 'lucide-react';
import { Link } from '@@/Link';
import { Icon } from '@@/Icon';
import { NodeRowData } from '../types';
import { columnHelper } from './helper';
export function getActions(metricsEnabled: boolean) {
return columnHelper.accessor(() => '', {
header: 'Actions',
enableSorting: false,
cell: (props) => (
<ActionsCell
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
metricsEnabled={metricsEnabled}
/>
),
});
}
function ActionsCell({
row: { original: node },
metricsEnabled,
}: CellContext<NodeRowData, string> & {
metricsEnabled: boolean;
}) {
const nodeName = node.metadata?.name;
return (
<div className="flex gap-1.5">
{metricsEnabled && (
<Link
title="Stats"
to="kubernetes.cluster.node.stats"
params={{ nodeName }}
className="flex items-center p-1"
>
<Icon icon={BarChart} />
</Link>
)}
</div>
);
}

@ -0,0 +1,14 @@
import { parseCpu } from '@/react/kubernetes/utils';
import { NodeRowData } from '../types';
import { columnHelper } from './helper';
export const cpu = columnHelper.accessor((row) => getCPU(row), {
header: 'CPU',
cell: ({ row: { original: node } }) => getCPU(node),
});
function getCPU(node: NodeRowData) {
return parseCpu(node.status?.allocatable?.cpu ?? '');
}

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

@ -0,0 +1,25 @@
import { name } from './name';
import { role } from './role';
import { status } from './status';
import { cpu } from './cpu';
import { memory } from './memory';
import { version } from './version';
import { ip } from './ip';
import { getActions } from './actions';
export function getColumns(isServerMetricsEnabled: boolean) {
if (!isServerMetricsEnabled) {
return [name, role, status, cpu, memory, version, ip];
}
return [
name,
role,
status,
cpu,
memory,
version,
ip,
getActions(isServerMetricsEnabled),
];
}

@ -0,0 +1,11 @@
import { getInternalNodeIpAddress } from '../utils';
import { columnHelper } from './helper';
export const ip = columnHelper.accessor(
(row) => getInternalNodeIpAddress(row) ?? '-',
{
header: 'IP Address',
cell: ({ row }) => getInternalNodeIpAddress(row.original) ?? '-',
}
);

@ -0,0 +1,16 @@
import filesizeParser from 'filesize-parser';
import { humanize } from '@/portainer/filters/filters';
import { NodeRowData } from '../types';
import { columnHelper } from './helper';
export const memory = columnHelper.accessor((row) => getMemory(row), {
header: 'Memory',
cell: ({ row: { original: node } }) => getMemory(node),
});
function getMemory(node: NodeRowData) {
return humanize(filesizeParser(node.status?.allocatable?.memory ?? ''));
}

@ -0,0 +1,35 @@
import { CellContext } from '@tanstack/react-table';
import { Authorized } from '@/react/hooks/useUser';
import { Link } from '@@/Link';
import { Badge } from '@@/Badge';
import { NodeRowData } from '../types';
import { columnHelper } from './helper';
export const name = columnHelper.accessor('Name', {
header: 'Name',
cell: NameCell,
});
function NameCell({
row: { original: node },
}: CellContext<NodeRowData, string>) {
const nodeName = node.metadata?.name;
return (
<div className="flex gap-2 whitespace-nowrap">
<Authorized
authorizations="K8sClusterNodeR"
childrenUnauthorized={nodeName}
>
<Link to="kubernetes.cluster.node" params={{ nodeName }}>
{nodeName}
</Link>
</Authorized>
{node.isApi && <Badge type="info">api</Badge>}
{node.isPublishedNode && <Badge type="success">environment IP</Badge>}
</div>
);
}

@ -0,0 +1,8 @@
import { getRole } from '../utils';
import { columnHelper } from './helper';
export const role = columnHelper.accessor((row) => getRole(row), {
header: 'Role',
cell: ({ row: { original: node } }) => getRole(node),
});

@ -0,0 +1,44 @@
import { CellContext } from '@tanstack/react-table';
import { StatusBadge } from '@@/StatusBadge';
import { NodeRowData } from '../types';
import { columnHelper } from './helper';
export const status = columnHelper.accessor((row) => getStatus(row), {
header: 'Status',
cell: StatusCell,
});
function StatusCell({
row: { original: node },
}: CellContext<NodeRowData, string>) {
const status = getStatus(node);
const isDeleting =
node.metadata?.annotations?.['portainer.io/removing-node'] === 'true';
if (isDeleting) {
return <StatusBadge color="warning">Removing</StatusBadge>;
}
return (
<div className="whitespace-nowrap">
<StatusBadge color={status === 'Ready' ? 'success' : 'warning'}>
{status}
</StatusBadge>
{node.spec?.unschedulable && (
<StatusBadge color="warning" className="mt-2">
SchedulingDisabled
</StatusBadge>
)}
</div>
);
}
function getStatus(node: NodeRowData) {
return (
node.status?.conditions?.find((condition) => condition.status === 'True')
?.type ?? 'Not ready'
);
}

@ -0,0 +1,10 @@
import { columnHelper } from './helper';
export const version = columnHelper.accessor(
(row) => row.status?.nodeInfo?.kubeletVersion ?? '',
{
header: 'Version',
cell: ({ row: { original: node } }) =>
node.status?.nodeInfo?.kubeletVersion ?? '',
}
);

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

@ -0,0 +1,7 @@
import { Node } from 'kubernetes-types/core/v1';
export interface NodeRowData extends Node {
isApi: boolean;
isPublishedNode: boolean;
Name: string;
}

@ -0,0 +1,20 @@
import { Node } from 'kubernetes-types/core/v1';
export function getInternalNodeIpAddress(node?: Node) {
return node?.status?.addresses?.find(
(address) => address.type === 'InternalIP'
)?.address;
}
// most kube clusters set control-plane label, older clusters set master, microk8s doesn't have either but instead sets microk8s-controlplane
const masterLabels = [
'node-role.kubernetes.io/control-plane',
'node-role.kubernetes.io/master',
'node.kubernetes.io/microk8s-controlplane',
];
export function getRole(node: Node): 'Control plane' | 'Worker' {
return masterLabels.some((label) => node.metadata?.labels?.[label])
? 'Control plane'
: 'Worker';
}

@ -0,0 +1,29 @@
import { EndpointsList } from 'kubernetes-types/core/v1';
import { useQuery } from 'react-query';
import axios from '@/portainer/services/axios';
import { EnvironmentId } from '@/react/portainer/environments/types';
import { withError } from '@/react-tools/react-query';
async function getKubernetesEndpoints(environmentId: EnvironmentId) {
const { data: endpointsList } = await axios.get<EndpointsList>(
`/endpoints/${environmentId}/kubernetes/api/v1/endpoints`
);
return endpointsList.items;
}
export function useKubernetesEndpointsQuery(
environmentId: EnvironmentId,
options?: { autoRefreshRate?: number }
) {
return useQuery(
['environments', environmentId, 'kubernetes', 'endpoints'],
() => getKubernetesEndpoints(environmentId),
{
...withError('Unable to retrieve Kubernetes endpoints'),
refetchInterval() {
return options?.autoRefreshRate ?? false;
},
}
);
}

@ -0,0 +1,9 @@
export function parseCpu(cpu: string) {
let res = parseInt(cpu, 10);
if (cpu.endsWith('m')) {
res /= 1000;
} else if (cpu.endsWith('n')) {
res /= 1000000000;
}
return res;
}
Loading…
Cancel
Save