refactor: resource table columns

This commit is contained in:
jialin
2025-09-16 11:26:17 +08:00
parent 84859d1b7c
commit 949eded4ee
44 changed files with 1390 additions and 1544 deletions
+1 -1
View File
@@ -2,6 +2,6 @@
border-radius: var(--border-radius-small); border-radius: var(--border-radius-small);
background-color: var(--color-white-1); background-color: var(--color-white-1);
box-shadow: none; box-shadow: none;
padding: 10px; padding: 10px 16px;
border: 1px solid var(--ant-color-border); border: 1px solid var(--ant-color-border);
} }
+1
View File
@@ -67,6 +67,7 @@ export default function useChartConfig() {
const legend = { const legend = {
itemWidth: 8, itemWidth: 8,
itemHeight: 8, itemHeight: 8,
itemGap: 12,
textStyle: { textStyle: {
color: chartColorMap.axislabelColor color: chartColorMap.axislabelColor
} }
+20 -3
View File
@@ -16,7 +16,10 @@ const LineChart: React.FC<ChartProps> = (props) => {
tooltipValueFormatter = null, tooltipValueFormatter = null,
legendData = [], legendData = [],
smooth, smooth,
title title,
legendOptions,
gridOptions,
titleOptions
} = props; } = props;
const { const {
grid, grid,
@@ -42,7 +45,10 @@ const LineChart: React.FC<ChartProps> = (props) => {
title: { title: {
text: '' text: ''
}, },
grid, grid: {
...grid,
...gridOptions
},
tooltip: { tooltip: {
...tooltip, ...tooltip,
formatter(params: any) { formatter(params: any) {
@@ -61,6 +67,7 @@ const LineChart: React.FC<ChartProps> = (props) => {
yAxis, yAxis,
legend: { legend: {
...legend, ...legend,
...legendOptions,
data: legendData.map((item: any) => { data: legendData.map((item: any) => {
return { return {
name: item, name: item,
@@ -93,6 +100,7 @@ const LineChart: React.FC<ChartProps> = (props) => {
animation: false, animation: false,
title: { title: {
...titleConfig, ...titleConfig,
...titleOptions,
text: title text: title
}, },
yAxis: { yAxis: {
@@ -109,7 +117,16 @@ const LineChart: React.FC<ChartProps> = (props) => {
}, },
series: data series: data
}; };
}, [seriesData, xAxisData, yAxisName, title, smooth, legendData, options]); }, [
seriesData,
xAxisData,
yAxisName,
title,
smooth,
titleOptions,
legendData,
options
]);
return ( return (
<> <>
+16 -1
View File
@@ -1,14 +1,29 @@
import type { LegendComponentOption } from 'echarts/components'; import type {
LegendComponentOption,
TitleComponentOption
} from 'echarts/components';
export interface ChartProps { export interface ChartProps {
seriesData: any[]; seriesData: any[];
showEmpty?: boolean; showEmpty?: boolean;
xAxisData: string[]; xAxisData: string[];
legendData?: LegendComponentOption['data']; legendData?: LegendComponentOption['data'];
legendOptions?: {
[K in keyof LegendComponentOption]?: LegendComponentOption[K];
};
gridOptions?: {
left?: string | number;
right?: string | number;
top?: string | number;
bottom?: string | number;
};
labelFormatter?: (val?: any, index?: number) => string; labelFormatter?: (val?: any, index?: number) => string;
tooltipValueFormatter?: (val: any) => string; tooltipValueFormatter?: (val: any) => string;
height: string | number; height: string | number;
width?: string | number; width?: string | number;
title?: string; title?: string;
titleOptions?: {
[K in keyof TitleComponentOption]?: TitleComponentOption[K];
};
value?: number; value?: number;
smooth?: boolean; smooth?: boolean;
color?: string; color?: string;
+9 -8
View File
@@ -93,8 +93,8 @@ export const FilterBar: React.FC<FilterBarProps> = (props) => {
actionType = 'button', actionType = 'button',
marginBottom = 10, marginBottom = 10,
marginTop = 10, marginTop = 10,
inputHolder = 'common.filter.name', inputHolder,
selectHolder = '', selectHolder,
showPrimaryButton = true, showPrimaryButton = true,
showDeleteButton = true, showDeleteButton = true,
width width
@@ -165,9 +165,12 @@ export const FilterBar: React.FC<FilterBarProps> = (props) => {
left={ left={
<Space> <Space>
<Input <Input
placeholder={intl.formatMessage({ placeholder={
id: inputHolder inputHolder ||
})} intl.formatMessage({
id: 'common.filter.name'
})
}
style={{ width: width?.input || 230 }} style={{ width: width?.input || 230 }}
allowClear allowClear
onChange={handleInputChange} onChange={handleInputChange}
@@ -176,9 +179,7 @@ export const FilterBar: React.FC<FilterBarProps> = (props) => {
<Select <Select
allowClear allowClear
showSearch={false} showSearch={false}
placeholder={intl.formatMessage({ placeholder={selectHolder}
id: selectHolder
})}
style={{ width: width?.select || 230 }} style={{ width: width?.select || 230 }}
size="large" size="large"
onChange={handleSelectChange} onChange={handleSelectChange}
@@ -41,11 +41,7 @@ const NoteInfo: React.FC<NoteInfoProps> = (props) => {
return ( return (
<span className="label-text"> <span className="label-text">
{description ? ( <Tooltip title={description || false}>{labelContent}</Tooltip>
<Tooltip title={description}>{labelContent}</Tooltip>
) : (
labelContent
)}
{labelExtra} {labelExtra}
</span> </span>
); );
+5 -4
View File
@@ -23,19 +23,20 @@ declare namespace Global {
source: string; source: string;
avatar_url?: string; avatar_url?: string;
} }
type EmptyObject = Record<never, never>;
type BaseListItem<T, U extends Record<string, any>> = { type BaseListItem<T, U extends object = EmptyObject> = {
key: string; key: string;
locale?: boolean; locale?: boolean;
value: T; value: T;
} & U; } & Partial<U>;
type BaseOption<T, U extends Record<string, any>> = { type BaseOption<T, U extends object = EmptyObject> = {
label: string; label: string;
locale?: boolean; locale?: boolean;
value: T; value: T;
meta?: Record<string, any>; meta?: Record<string, any>;
} & U; } & Partial<U>;
interface HintOptions { interface HintOptions {
label: string; label: string;
-2
View File
@@ -9,8 +9,6 @@ export default function useUserSettings() {
const { light, dark, colorPrimary } = themeConfig; const { light, dark, colorPrimary } = themeConfig;
const [userSettings, setUserSettings] = useAtom(userSettingsHelperAtom); const [userSettings, setUserSettings] = useAtom(userSettingsHelperAtom);
console.log('userSettings===', userSettings);
const getCurrentTheme = (mode: Theme): 'light' | 'realDark' => { const getCurrentTheme = (mode: Theme): 'light' | 'realDark' => {
if (mode === 'auto') { if (mode === 'auto') {
return window.matchMedia('(prefers-color-scheme: dark)').matches return window.matchMedia('(prefers-color-scheme: dark)').matches
+14
View File
@@ -0,0 +1,14 @@
export default {
'clusters.title': 'Cluster',
'clusters.table.provider': 'Provider',
'clusters.table.deployments': 'Deployments',
'clusters.button.add': 'Add Cluster',
'clusters.button.addCredential': 'Add Cloud Credential',
'clusters.button.editCredential': 'Edit Cloud Credential',
'clusters.filterBy.cluster': 'Filter by Cluster',
'clusters.add.cluster': 'Add {cluster} Cluster',
'clusters.edit.cluster': 'Edit {cluster}',
'clusters.provider.custom': 'Custom',
'clusters.button.register': 'Register Cluster',
'clusters.button.addNodePool': 'Add Node Pool'
};
+3 -1
View File
@@ -257,5 +257,7 @@ export default {
'common.login.password': 'Log in with Password', 'common.login.password': 'Log in with Password',
'common.external.login': 'Log in with {type}', 'common.external.login': 'Log in with {type}',
'common.sso.noConfig': 'common.sso.noConfig':
'Single sign-on is not enabled on this system. Please contact your administrator.' 'Single sign-on is not enabled on this system. Please contact your administrator.',
'common.button.edit.item': 'Edit {name}',
'common.button.terminal': 'Terminal'
}; };
+29
View File
@@ -0,0 +1,29 @@
export default {
'clusters.title': 'Cluster',
'clusters.table.provider': 'Provider',
'clusters.table.deployments': 'Deployments',
'clusters.button.add': 'Add Cluster',
'clusters.button.addCredential': 'Add Cloud Credential',
'clusters.button.editCredential': 'Edit Cloud Credential',
'clusters.filterBy.cluster': 'Filter by Cluster',
'clusters.add.cluster': 'Add {cluster} Cluster',
'clusters.edit.cluster': 'Edit {cluster}',
'clusters.provider.custom': 'Custom',
'clusters.button.register': 'Register Cluster',
'clusters.button.addNodePool': 'Add Node Pool'
};
// ========== To-Do: Translate Keys (Remove After Translation) ==========
// 1. 'clusters.title': 'Cluster',
// 2. 'clusters.table.provider': 'Provider',
// 3. 'clusters.table.deployments': 'Deployments',
// 4. 'clusters.button.add': 'Add Cluster',
// 5. 'clusters.button.addCredential': 'Add Cloud Credential',
// 6. 'clusters.button.editCredential': 'Edit Cloud Credential',
// 7. 'clusters.filterBy.cluster': 'Filter by Cluster',
// 8. 'clusters.add.cluster': 'Add {cluster} Cluster',
// 9. 'clusters.edit.cluster': 'Edit {cluster}',
// 10. 'clusters.provider.custom': 'Custom',
// 11. 'clusters.button.register': 'Register Cluster',
// 12. 'clusters.button.addNodePool': 'Add Node Pool'
// ========== End of To-Do List ==========
+5 -1
View File
@@ -257,7 +257,9 @@ export default {
'common.login.password': 'Log in with Password', 'common.login.password': 'Log in with Password',
'common.external.login': 'Log in with {type}', 'common.external.login': 'Log in with {type}',
'common.sso.noConfig': 'common.sso.noConfig':
'Single sign-on is not enabled on this system. Please contact your administrator.' 'Single sign-on is not enabled on this system. Please contact your administrator.',
'common.button.edit.item': 'Edit {name}',
'common.button.terminal': 'Terminal'
}; };
// ========== To-Do: Translate Keys (Remove After Translation) ========== // ========== To-Do: Translate Keys (Remove After Translation) ==========
@@ -281,4 +283,6 @@ export default {
// 18. 'common.external.login': 'Log in with {type}' // 18. 'common.external.login': 'Log in with {type}'
// 19. 'common.login.password': 'Log in with Password', // 19. 'common.login.password': 'Log in with Password',
// 20. 'common.sso.noConfig': 'Single sign-on is not enabled on this system. Please contact your administrator.' // 20. 'common.sso.noConfig': 'Single sign-on is not enabled on this system. Please contact your administrator.'
// 21. 'common.button.edit.item': 'Edit {name}',
// 22. 'common.button.terminal': 'Terminal'
// ========== End of To-Do List ========== // ========== End of To-Do List ==========
+29
View File
@@ -0,0 +1,29 @@
export default {
'clusters.title': 'Cluster',
'clusters.table.provider': 'Provider',
'clusters.table.deployments': 'Deployments',
'clusters.button.add': 'Add Cluster',
'clusters.button.addCredential': 'Add Cloud Credential',
'clusters.button.editCredential': 'Edit Cloud Credential',
'clusters.filterBy.cluster': 'Filter by Cluster',
'clusters.add.cluster': 'Add {cluster} Cluster',
'clusters.edit.cluster': 'Edit {cluster}',
'clusters.provider.custom': 'Custom',
'clusters.button.register': 'Register Cluster',
'clusters.button.addNodePool': 'Add Node Pool'
};
// ========== To-Do: Translate Keys (Remove After Translation) ==========
// 1. 'clusters.title': 'Cluster',
// 2. 'clusters.table.provider': 'Provider',
// 3. 'clusters.table.deployments': 'Deployments',
// 4. 'clusters.button.add': 'Add Cluster',
// 5. 'clusters.button.addCredential': 'Add Cloud Credential',
// 6. 'clusters.button.editCredential': 'Edit Cloud Credential',
// 7. 'clusters.filterBy.cluster': 'Filter by Cluster',
// 8. 'clusters.add.cluster': 'Add {cluster} Cluster',
// 9. 'clusters.edit.cluster': 'Edit {cluster}',
// 10. 'clusters.provider.custom': 'Custom',
// 11. 'clusters.button.register': 'Register Cluster',
// 12. 'clusters.button.addNodePool': 'Add Node Pool'
// ========== End of To-Do List ==========
+5 -1
View File
@@ -256,11 +256,15 @@ export default {
'common.login.password': 'Log in with Password', 'common.login.password': 'Log in with Password',
'common.external.login': 'Log in with {type}', 'common.external.login': 'Log in with {type}',
'common.sso.noConfig': 'common.sso.noConfig':
'Single sign-on is not enabled on this system. Please contact your administrator.' 'Single sign-on is not enabled on this system. Please contact your administrator.',
'common.button.edit.item': 'Edit {name}',
'common.button.terminal': 'Terminal'
}; };
// ========== To-Do: Translate Keys (Remove After Translation) ========== // ========== To-Do: Translate Keys (Remove After Translation) ==========
// 1. 'common.external.login': 'Log in with {type}' // 1. 'common.external.login': 'Log in with {type}'
// 2. 'common.login.password': 'Log in with Password' // 2. 'common.login.password': 'Log in with Password'
// 3. 'common.sso.noConfig': 'Single sign-on is not enabled on this system. Please contact your administrator.' // 3. 'common.sso.noConfig': 'Single sign-on is not enabled on this system. Please contact your administrator.'
// 4. 'common.button.edit.item': 'Edit {name}',
// 5. 'common.button.terminal': 'Terminal'
// ========== End of To-Do List ========== // ========== End of To-Do List ==========
+14
View File
@@ -0,0 +1,14 @@
export default {
'clusters.title': '集群',
'clusters.table.provider': '提供商',
'clusters.table.deployments': '部署',
'clusters.button.add': '添加集群',
'clusters.button.addCredential': '添加云凭证',
'clusters.button.editCredential': '编辑云凭证',
'clusters.filterBy.cluster': '按集群过滤',
'clusters.add.cluster': '添加 {cluster} 集群',
'clusters.edit.cluster': '编辑 {cluster}',
'clusters.provider.custom': '自定义',
'clusters.button.register': '注册集群',
'clusters.button.addNodePool': '添加节点池'
};
+3 -1
View File
@@ -249,5 +249,7 @@ export default {
'common.login.auth.failed': '认证失败', 'common.login.auth.failed': '认证失败',
'common.login.password': '使用密码登录', 'common.login.password': '使用密码登录',
'common.external.login': '使用 {type} 登录', 'common.external.login': '使用 {type} 登录',
'common.sso.noConfig': '该系统未启用单点登录,请联系管理员。' 'common.sso.noConfig': '该系统未启用单点登录,请联系管理员。',
'common.button.edit.item': '编辑 {name}',
'common.button.terminal': '终端'
}; };
+1 -1
View File
@@ -29,5 +29,5 @@ export default {
'menu.accessControl.users': '用户', 'menu.accessControl.users': '用户',
'menu.clusterManagement': '集群管理', 'menu.clusterManagement': '集群管理',
'menu.clusterManagement.clusters': '集群', 'menu.clusterManagement.clusters': '集群',
'menu.clusterManagement.credentials': '凭' 'menu.clusterManagement.credentials': '凭'
}; };
@@ -1,489 +0,0 @@
import AutoTooltip from '@/components/auto-tooltip';
import DeleteModal from '@/components/delete-modal';
import DropDownActions from '@/components/drop-down-actions';
import DropdownButtons from '@/components/drop-down-buttons';
import IconFont from '@/components/icon-font';
import PageTools from '@/components/page-tools';
import { PageAction } from '@/config';
import type { PageActionType } from '@/config/types';
import useTableFetch from '@/hooks/use-table-fetch';
import AddWorker from '@/pages/resources/components/add-worker';
import {
DeleteOutlined,
DownOutlined,
EditOutlined,
KubernetesOutlined,
ProfileOutlined,
SyncOutlined
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import {
Button,
ConfigProvider,
Empty,
Input,
Space,
Table,
message
} from 'antd';
import { useState } from 'react';
import styled from 'styled-components';
import {
createCredential,
deleteCredential,
queryCredentialList,
updateCredential
} from './apis';
import AddCluster from './components/add-cluster';
import AddPool from './components/add-pool';
import { ClusterDataList } from './config';
import {
ClusterFormData as FormData,
ClusterListItem as ListItem
} from './config/types';
const { Column } = Table;
const addActions = [
{
label: 'Custom',
locale: false,
value: 'custom',
key: 'custom',
icon: <IconFont type="icon-docker" className="size-16" />
},
{
label: 'Kubernetes',
locale: false,
value: 'kubernetes',
key: 'kubernetes',
icon: <KubernetesOutlined className="size-16" />
},
{
label: 'Digital Ocean',
locale: false,
value: 'digitalocean',
key: 'digitalocean',
icon: <IconFont type="icon-digitalocean" />
}
];
const WorkerWrapper = styled.div`
display: flex;
flex-direction: column;
gap: 4px;
align-items: flex-start;
.worker {
display: flex;
align-items: center;
gap: 5px;
.value {
line-height: 1em;
color: var(--ant-color-text-secondary);
}
}
.dot {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 4px;
&.ready {
background-color: var(--ant-color-success);
}
&.error {
background-color: var(--ant-color-error);
}
&.transition {
background-color: var(--ant-blue-5);
}
}
`;
const ActionList = [
{
key: 'edit',
label: 'common.button.edit',
icon: <EditOutlined></EditOutlined>
},
{
key: 'add',
label: 'Add Worker',
locale: false,
icon: <EditOutlined></EditOutlined>
},
{
key: 'terminal',
label: 'common.button.detail',
icon: <ProfileOutlined />
},
{
key: 'addPool',
label: 'Add Node Pool',
locale: false,
icon: <IconFont type="icon-catalog1" />
},
{
key: 'delete',
props: {
danger: true
},
label: 'common.button.delete',
icon: <DeleteOutlined></DeleteOutlined>
}
];
const Credentials: React.FC = () => {
const {
dataSource,
rowSelection,
queryParams,
sortOrder,
modalRef,
handleDelete,
handleDeleteBatch,
fetchData,
handlePageChange,
handleTableChange,
handleSearch,
handleNameChange
} = useTableFetch<ListItem>({
fetchAPI: queryCredentialList,
deleteAPI: deleteCredential,
contentForDelete: 'users.table.user'
});
const intl = useIntl();
const [open, setOpen] = useState(false);
const [openAddModal, setOpenAddModal] = useState(false);
const [provider, setProvider] = useState<string>('custom');
const [action, setAction] = useState<PageActionType>(PageAction.CREATE);
const [title, setTitle] = useState<string>('');
const [addPoolStatus, setAddPoolStatus] = useState<{
open: boolean;
action: PageActionType;
title: string;
provider: string;
}>({
open: false,
action: PageAction.CREATE,
title: '',
provider: 'digitalocean'
});
const [currentData, setCurrentData] = useState<ListItem | undefined>(
undefined
);
const setActions = (row: ListItem) => {
if (row.provider !== 'custom') {
return ActionList.filter((item) => item.key !== 'add');
}
return ActionList;
};
const handleAddCluster = (value: string) => {
setOpenAddModal(true);
setAction(PageAction.CREATE);
setProvider(value);
const label = addActions.find((item) => item.value === value)?.label;
setTitle(`Add ${label} Cluster`);
};
const handleAddPool = (value: string) => {
setAddPoolStatus({
open: true,
action: PageAction.CREATE,
title: `Add Node Pool`,
provider: value
});
};
const handleClickDropdown = (item: any) => {
handleAddCluster(item.key);
};
const handleModalOk = async (data: FormData) => {
const params = {
...data
};
try {
if (action === PageAction.EDIT) {
await updateCredential({
data: {
...params,
id: currentData?.id
}
});
} else {
await createCredential({ data: params });
}
fetchData();
setOpenAddModal(false);
message.success(intl.formatMessage({ id: 'common.message.success' }));
} catch (error) {
setOpenAddModal(false);
}
};
const handleModalCancel = () => {
console.log('handleModalCancel');
setOpenAddModal(false);
};
const handleEditUser = (row: ListItem) => {
setCurrentData(row);
setOpenAddModal(true);
setAction(PageAction.EDIT);
setTitle(`Edit ${row.name} Cluster`);
};
const handleSelect = (val: any, row: ListItem) => {
if (val === 'edit') {
handleEditUser(row);
} else if (val === 'delete') {
handleDelete({ ...row, name: row.name });
} else if (val === 'add') {
setOpen(true);
setCurrentData(row);
} else if (val === 'addPool') {
handleAddPool(row.provider);
}
};
const renderEmpty = (type?: string) => {
if (type !== 'Table') return;
if (
!dataSource.loading &&
dataSource.loadend &&
!dataSource.dataList.length
) {
return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>;
}
return <div></div>;
};
return (
<>
<PageContainer
ghost
header={{
title: intl.formatMessage({
id: 'menu.clusterManagement.clusters'
}),
style: {
paddingInline: 'var(--layout-content-header-inlinepadding)'
},
breadcrumb: {}
}}
extra={[]}
>
<PageTools
marginBottom={22}
left={
<Space>
<Input
placeholder={intl.formatMessage({ id: 'common.filter.name' })}
style={{ width: 300 }}
allowClear
onChange={handleNameChange}
></Input>
<Button
type="text"
style={{ color: 'var(--ant-color-text-tertiary)' }}
onClick={handleSearch}
icon={<SyncOutlined></SyncOutlined>}
></Button>
</Space>
}
right={
<Space size={20}>
<DropDownActions
menu={{
items: addActions,
onClick: handleClickDropdown
}}
trigger={['click']}
placement="bottomRight"
>
<Button
icon={<DownOutlined></DownOutlined>}
type="primary"
iconPosition="end"
>
Add Cluster
</Button>
</DropDownActions>
<Button
icon={<DeleteOutlined />}
danger
onClick={handleDeleteBatch}
disabled={!rowSelection.selectedRowKeys.length}
>
<span>
{intl?.formatMessage?.({ id: 'common.button.delete' })}
{rowSelection.selectedRowKeys.length > 0 && (
<span>({rowSelection.selectedRowKeys?.length})</span>
)}
</span>
</Button>
</Space>
}
></PageTools>
<ConfigProvider renderEmpty={renderEmpty}>
<Table
dataSource={ClusterDataList}
rowSelection={rowSelection}
loading={dataSource.loading}
rowKey="id"
onChange={handleTableChange}
pagination={{
showSizeChanger: true,
pageSize: queryParams.perPage,
current: queryParams.page,
total: dataSource.total,
hideOnSinglePage: queryParams.perPage === 10,
onChange: handlePageChange
}}
>
<Column
title="Name"
dataIndex="name"
key="name"
ellipsis={{
showTitle: false
}}
render={(text, record) => {
return (
<AutoTooltip ghost minWidth={20}>
{text}
</AutoTooltip>
);
}}
/>
<Column
title="Provider"
dataIndex="provider"
key="provider"
ellipsis={{
showTitle: false
}}
render={(text, record) => {
return (
<AutoTooltip ghost minWidth={20}>
{addActions.find((item) => item.value === record.provider)
?.label || 'N/A'}
</AutoTooltip>
);
}}
/>
<Column
title="Workers"
dataIndex="workers"
key="workers"
ellipsis={{
showTitle: false
}}
render={(text, record) => {
return (
<WorkerWrapper>
<span className="worker">
<span className="dot ready"></span>
<span className="value">3</span>
</span>
<span className="worker">
<span className="dot error"></span>
<span className="value">1</span>
</span>
</WorkerWrapper>
);
}}
/>
<Column
title="GPUs"
dataIndex="gpus"
key="gpus"
ellipsis={{
showTitle: false
}}
render={(text, record) => {
return (
<AutoTooltip ghost minWidth={20}>
{text}
</AutoTooltip>
);
}}
/>
<Column
title="Deployments"
dataIndex="deployments"
key="deployments"
ellipsis={{
showTitle: false
}}
render={(text, record) => {
return (
<AutoTooltip ghost minWidth={20}>
{text}
</AutoTooltip>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'common.table.operation' })}
key="operation"
ellipsis={{
showTitle: false
}}
render={(text, record: ListItem) => {
return (
<DropdownButtons
items={setActions(record)}
onSelect={(val) => handleSelect(val, record)}
></DropdownButtons>
);
}}
/>
</Table>
</ConfigProvider>
</PageContainer>
<AddCluster
provider={provider}
open={openAddModal}
action={action}
title={title}
data={currentData}
onCancel={handleModalCancel}
onOk={handleModalOk}
></AddCluster>
<AddPool
provider={addPoolStatus.provider}
open={addPoolStatus.open}
action={addPoolStatus.action}
title={addPoolStatus.title}
onCancel={() => {
setAddPoolStatus({
open: false,
action: PageAction.CREATE,
title: '',
provider: 'digitalocean'
});
}}
onOk={() => {
setAddPoolStatus({
open: false,
action: PageAction.CREATE,
title: '',
provider: 'digitalocean'
});
}}
></AddPool>
<AddWorker open={open} onCancel={() => setOpen(false)}></AddWorker>
<DeleteModal ref={modalRef}></DeleteModal>
</>
);
};
export default Credentials;
+17 -7
View File
@@ -6,6 +6,7 @@ import useTableFetch from '@/hooks/use-table-fetch';
import AddWorker from '@/pages/resources/components/add-worker'; import AddWorker from '@/pages/resources/components/add-worker';
import { PageContainer } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max'; import { useIntl } from '@umijs/max';
import { useMemoizedFn } from 'ahooks';
import { Table, message } from 'antd'; import { Table, message } from 'antd';
import { useState } from 'react'; import { useState } from 'react';
import { import {
@@ -23,7 +24,7 @@ import {
ClusterFormData as FormData, ClusterFormData as FormData,
ClusterListItem as ListItem ClusterListItem as ListItem
} from './config/types'; } from './config/types';
import useClusterColumns from './config/use-cluster-columns'; import useClusterColumns from './hooks/use-cluster-columns';
const Credentials: React.FC = () => { const Credentials: React.FC = () => {
const { const {
@@ -112,12 +113,19 @@ const Credentials: React.FC = () => {
const handleAddCluster = (value: string) => { const handleAddCluster = (value: string) => {
const label = ProviderLabelMap[value]; const label = ProviderLabelMap[value];
const clusterLabel =
value === ProviderValueMap.Custom
? intl.formatMessage({ id: 'clusters.provider.custom' })
: label;
setOpenAddModal({ setOpenAddModal({
open: true, open: true,
action: PageAction.CREATE, action: PageAction.CREATE,
currentData: undefined, currentData: undefined,
title: `Add ${label} Cluster`, title: intl.formatMessage(
{ id: 'clusters.add.cluster' },
{ cluster: clusterLabel }
),
provider: value provider: value
}); });
}; };
@@ -184,7 +192,10 @@ const Credentials: React.FC = () => {
open: true, open: true,
action: PageAction.EDIT, action: PageAction.EDIT,
currentData: row, currentData: row,
title: `Edit ${row.name} Cluster`, title: intl.formatMessage(
{ id: 'clusters.edit.cluster' },
{ cluster: row.name }
),
provider: row.provider provider: row.provider
}); });
}; };
@@ -214,7 +225,7 @@ const Credentials: React.FC = () => {
} catch (error) {} } catch (error) {}
}; };
const handleSelect = (val: any, row: ListItem) => { const handleSelect = useMemoizedFn((val: any, row: ListItem) => {
if (val === 'edit') { if (val === 'edit') {
handleEditCluster(row); handleEditCluster(row);
} else if (val === 'delete') { } else if (val === 'delete') {
@@ -231,7 +242,7 @@ const Credentials: React.FC = () => {
} else if (val === 'register_cluster') { } else if (val === 'register_cluster') {
handleRegisterCluster(row); handleRegisterCluster(row);
} }
}; });
const columns = useClusterColumns(handleSelect); const columns = useClusterColumns(handleSelect);
@@ -254,11 +265,10 @@ const Credentials: React.FC = () => {
showSelect={false} showSelect={false}
showPrimaryButton={true} showPrimaryButton={true}
showDeleteButton={true} showDeleteButton={true}
selectHolder="Filter by name"
marginBottom={22} marginBottom={22}
marginTop={30} marginTop={30}
width={{ input: 300 }} width={{ input: 300 }}
buttonText="Add Cluster" buttonText={intl.formatMessage({ id: 'clusters.button.add' })}
actionType="dropdown" actionType="dropdown"
actionItems={addActions} actionItems={addActions}
rowSelection={rowSelection} rowSelection={rowSelection}
@@ -1,17 +1,47 @@
import GaugeChart from '@/components/echarts/gauge'; import GaugeChart from '@/components/echarts/gauge';
import Card from '@/components/templates/card';
import { PageAction } from '@/config'; import { PageAction } from '@/config';
import { Col, Row } from 'antd'; import { Col, Row } from 'antd';
import _ from 'lodash';
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import styled from 'styled-components'; import styled from 'styled-components';
import { queryClusterDetail } from '../apis'; import { queryClusterDetail } from '../apis';
import { ProviderValueMap } from '../config'; import { ProviderValueMap } from '../config';
import { ClusterListItem, NodePoolListItem } from '../config/types'; import { ClusterListItem, NodePoolListItem } from '../config/types';
import AddPool from './add-pool'; import AddPool from './add-pool';
import TrendChart from './trend-chart';
import WorkerPools from './worker-pools'; import WorkerPools from './worker-pools';
const metricsMap = {
cpu: {
label: 'CPU',
type: 'CPU',
intl: false,
color: 'rgba(250, 173, 20,.8)'
},
ram: {
label: 'Used',
type: 'Used',
intl: false,
color: 'rgba(114, 46, 209,.8)'
},
gpu: {
label: 'GPU',
type: 'GPU',
intl: false,
color: 'rgba(84, 204, 152,.8)'
},
vram: {
label: 'Used',
type: 'Used',
intl: false,
color: 'rgba(255, 107, 179, 80%)'
}
};
const SubTitle = styled.div` const SubTitle = styled.div`
font-size: var(--font-size-middle); font-size: var(--font-size-middle);
font-weight: 500; font-weight: 700;
color: var(--ant-color-text); color: var(--ant-color-text);
margin-block: 24px 16px; margin-block: 24px 16px;
`; `;
@@ -40,6 +70,12 @@ const gaugeConfig = {
} }
}; };
const formatValue = (value: number) => {
return _.round(value || 0, 1);
};
const CardHeight = 336;
const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => { const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
const chartHeight = 160; const chartHeight = 160;
const [show, setShow] = React.useState(false); const [show, setShow] = React.useState(false);
@@ -49,7 +85,23 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
title: '', title: '',
provider: ProviderValueMap.DigitalOcean provider: ProviderValueMap.DigitalOcean
}); });
const [detailContent, setDetailContent] = useState<Record<string, any>>({}); const [detailContent, setDetailContent] = useState<{
current: {
cpu: number;
ram: number;
gpu: number;
vram: number;
};
history: Record<string, { timestamp: number; value: number }[]>;
}>({
current: {
cpu: 0,
ram: 0,
gpu: 0,
vram: 0
},
history: {}
});
// pool action handler // pool action handler
const handleOnAction = (action: string, record: NodePoolListItem) => { const handleOnAction = (action: string, record: NodePoolListItem) => {
@@ -71,10 +123,21 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
const response = await queryClusterDetail({ const response = await queryClusterDetail({
cluster_id: data!.id cluster_id: data!.id
}); });
setDetailContent(response); setDetailContent({
current: response.system_load?.current,
history: response.system_load?.history
});
// handle response // handle response
} catch (error) { } catch (error) {
setDetailContent({}); setDetailContent({
current: {
cpu: 0,
ram: 0,
gpu: 0,
vram: 0
},
history: {}
});
} }
}; };
@@ -91,7 +154,7 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
<Col span={6}> <Col span={6}>
<GaugeChart <GaugeChart
title="GPU Utilization" title="GPU Utilization"
value={85} value={formatValue(detailContent.current.gpu)}
height={chartHeight} height={chartHeight}
gaugeConfig={gaugeConfig} gaugeConfig={gaugeConfig}
/> />
@@ -99,7 +162,7 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
<Col span={6}> <Col span={6}>
<GaugeChart <GaugeChart
title="CPU Utilization" title="CPU Utilization"
value={50} value={formatValue(detailContent.current.cpu)}
height={chartHeight} height={chartHeight}
gaugeConfig={gaugeConfig} gaugeConfig={gaugeConfig}
/> />
@@ -107,7 +170,7 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
<Col span={6}> <Col span={6}>
<GaugeChart <GaugeChart
title="RAM Utilization" title="RAM Utilization"
value={70} value={formatValue(detailContent.current.ram)}
height={chartHeight} height={chartHeight}
gaugeConfig={gaugeConfig} gaugeConfig={gaugeConfig}
/> />
@@ -115,13 +178,44 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
<Col span={6}> <Col span={6}>
<GaugeChart <GaugeChart
title="VRAM Utilization" title="VRAM Utilization"
value={60} value={formatValue(detailContent.current.vram)}
height={chartHeight} height={chartHeight}
gaugeConfig={gaugeConfig} gaugeConfig={gaugeConfig}
/> />
</Col> </Col>
</Row> </Row>
</div> </div>
<SubTitle>System Load</SubTitle>
<Row style={{ marginBottom: 20 }} gutter={20}>
<Col span={12}>
<Card height={CardHeight} clickable={false} ghost>
<TrendChart
data={detailContent?.history}
metrics={['vram', 'allocated']}
metricsMap={metricsMap}
title="VRAM"
></TrendChart>
</Card>
</Col>
<Col span={12}>
<Card height={CardHeight} clickable={false} ghost>
<TrendChart
data={detailContent?.history}
metrics={['ram', 'allocated']}
metricsMap={metricsMap}
title="RAM"
></TrendChart>
</Card>
</Col>
</Row>
<Card height={CardHeight} clickable={false} ghost>
<TrendChart
data={detailContent?.history}
metrics={['cpu', 'gpu']}
metricsMap={metricsMap}
title="CPU & GPU"
></TrendChart>
</Card>
{data?.provider === ProviderValueMap.DigitalOcean && ( {data?.provider === ProviderValueMap.DigitalOcean && (
<> <>
<SubTitle>Worker Pools</SubTitle> <SubTitle>Worker Pools</SubTitle>
@@ -143,7 +237,7 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
open: false, open: false,
action: PageAction.CREATE, action: PageAction.CREATE,
title: '', title: '',
provider: 'digitalocean' provider: ProviderValueMap.DigitalOcean
}); });
}} }}
onOk={() => { onOk={() => {
@@ -151,7 +245,7 @@ const ClusterDetail: React.FC<ClusterDetailProps> = ({ data }) => {
open: false, open: false,
action: addPoolStatus.action, action: addPoolStatus.action,
title: '', title: '',
provider: 'digitalocean' provider: ProviderValueMap.DigitalOcean
}); });
}} }}
></AddPool> ></AddPool>
@@ -20,8 +20,8 @@ const ClusterDetailModal: React.FC<ClusterDetailModalProps> = ({
return ( return (
<GSDrawer <GSDrawer
width={'80vw'} width={'calc(100vw - 200px)'}
title={`Cluster Detail - ${currentData?.name}`} title={`${currentData?.name}`}
open={open} open={open}
onClose={handleOnClose} onClose={handleOnClose}
> >
@@ -0,0 +1,78 @@
import LineChart from '@/components/echarts/line-chart';
import { useIntl } from '@umijs/max';
import dayjs from 'dayjs';
import _ from 'lodash';
import { useMemo } from 'react';
interface TrendChartProps {
data: any;
metrics: string[];
metricsMap: Record<string, any>;
title: string;
}
const titleOptions = {
left: 0
};
const TrendChart: React.FC<TrendChartProps> = ({
data,
metrics,
metricsMap,
title
}) => {
const intl = useIntl();
const tooltipValueFormatter = (value: any) => {
return !value ? value : `${value}%`;
};
const generateData = useMemo(() => {
const legendData: string[] = [];
const xAxisData: string[] = [];
let seriesData: { value: number; time: string; type: string }[] = [];
seriesData = _.map(metrics, (item: string) => {
const itemConfig = _.get(metricsMap, item, {});
const name = itemConfig.intl
? intl.formatMessage({ id: itemConfig.label })
: itemConfig.label;
legendData.push(name);
const itemDataList = _.get(data, item, []);
return {
name: name,
color: itemConfig.color,
data: _.map(itemDataList, (item: any) => {
xAxisData.push(dayjs(item.timestamp * 1000).format('HH:mm:ss'));
return {
time: dayjs(item.timestamp * 1000).format('HH:mm:ss'),
value: _.round(_.get(item, 'value', 0), 1)
};
})
};
});
return {
seriesData,
legendData,
xAxisData: _.uniq(xAxisData)
};
}, [data, intl]);
return (
<>
<LineChart
height={320}
title={title}
seriesData={generateData.seriesData}
legendData={generateData.legendData}
xAxisData={generateData.xAxisData}
tooltipValueFormatter={tooltipValueFormatter}
smooth={true}
width="100%"
yAxisName="(%)"
titleOptions={titleOptions}
></LineChart>
</>
);
};
export default TrendChart;
+8 -8
View File
@@ -43,8 +43,8 @@ export const generateRegisterCommand = (params: {
export const addActions = [ export const addActions = [
{ {
label: 'Custom', label: 'clusters.provider.custom',
locale: false, locale: true,
value: ProviderValueMap.Custom, value: ProviderValueMap.Custom,
key: ProviderValueMap.Custom, key: ProviderValueMap.Custom,
icon: icons.Docker icon: icons.Docker
@@ -78,23 +78,23 @@ export const clusterActionList = [
}, },
{ {
key: 'add_worker', key: 'add_worker',
label: 'Add Worker', label: 'resources.button.create',
provider: ProviderValueMap.Custom, provider: ProviderValueMap.Custom,
locale: false, locale: true,
icon: icons.Docker icon: icons.Docker
}, },
{ {
key: 'register_cluster', key: 'register_cluster',
label: 'Register Cluster', label: 'clusters.button.register',
provider: ProviderValueMap.Kubernetes, provider: ProviderValueMap.Kubernetes,
locale: false, locale: true,
icon: icons.KubernetesOutlined icon: icons.KubernetesOutlined
}, },
{ {
key: 'addPool', key: 'addPool',
label: 'Add Node Pool', label: 'clusters.button.addNodePool',
provider: ProviderValueMap.DigitalOcean, provider: ProviderValueMap.DigitalOcean,
locale: false, locale: true,
icon: icons.Catalog icon: icons.Catalog
}, },
{ {
+11 -6
View File
@@ -103,7 +103,7 @@ const Credentials: React.FC = () => {
provider: ProviderValueMap.DigitalOcean, provider: ProviderValueMap.DigitalOcean,
open: true, open: true,
action: PageAction.CREATE, action: PageAction.CREATE,
title: 'Add Cloud Credential', title: intl.formatMessage({ id: 'clusters.button.addCredential' }),
currentData: undefined currentData: undefined
}); });
}; };
@@ -141,7 +141,10 @@ const Credentials: React.FC = () => {
provider: row.provider, provider: row.provider,
open: true, open: true,
action: PageAction.EDIT, action: PageAction.EDIT,
title: `Edit ${row.name} Credential`, title: intl.formatMessage(
{ id: 'common.buton.edit.item' },
{ name: row.name }
),
currentData: row currentData: row
}); });
}; };
@@ -186,7 +189,9 @@ const Credentials: React.FC = () => {
showPrimaryButton={true} showPrimaryButton={true}
marginBottom={22} marginBottom={22}
marginTop={30} marginTop={30}
buttonText={'Add Cloud Credential'} buttonText={intl.formatMessage({
id: 'clusters.button.addCredential'
})}
handleDeleteByBatch={handleDeleteBatch} handleDeleteByBatch={handleDeleteBatch}
handleSearch={handleSearch} handleSearch={handleSearch}
handleInputChange={handleNameChange} handleInputChange={handleNameChange}
@@ -212,7 +217,7 @@ const Credentials: React.FC = () => {
}} }}
> >
<Column <Column
title="Name" title={intl.formatMessage({ id: 'common.table.name' })}
dataIndex="name" dataIndex="name"
key="name" key="name"
ellipsis={{ ellipsis={{
@@ -227,7 +232,7 @@ const Credentials: React.FC = () => {
}} }}
/> />
<Column <Column
title="Provider" title={intl.formatMessage({ id: 'clusters.table.provider' })}
dataIndex="provider" dataIndex="provider"
key="provider" key="provider"
ellipsis={{ ellipsis={{
@@ -261,7 +266,7 @@ const Credentials: React.FC = () => {
}} }}
/> />
<Column <Column
title="Description" title={intl.formatMessage({ id: 'common.table.description' })}
dataIndex="description" dataIndex="description"
key="description" key="description"
ellipsis={{ ellipsis={{
@@ -2,6 +2,7 @@
import AutoTooltip from '@/components/auto-tooltip'; import AutoTooltip from '@/components/auto-tooltip';
import DropdownButtons from '@/components/drop-down-buttons'; import DropdownButtons from '@/components/drop-down-buttons';
import StatusTag from '@/components/status-tag'; import StatusTag from '@/components/status-tag';
import { useIntl } from '@umijs/max';
import { ColumnsType } from 'antd/es/table'; import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { useMemo } from 'react'; import { useMemo } from 'react';
@@ -10,12 +11,13 @@ import {
ClusterStatusLabelMap, ClusterStatusLabelMap,
ProviderLabelMap, ProviderLabelMap,
clusterActionList clusterActionList
} from '.'; } from '../config';
import { ClusterListItem } from './types'; import { ClusterListItem } from '../config/types';
const useClusterColumns = ( const useClusterColumns = (
handleSelect: (val: string, record: ClusterListItem) => void handleSelect: (val: string, record: ClusterListItem) => void
): ColumnsType<ClusterListItem> => { ): ColumnsType<ClusterListItem> => {
const intl = useIntl();
const setActionsItems = (row: ClusterListItem) => { const setActionsItems = (row: ClusterListItem) => {
return clusterActionList.filter((item) => { return clusterActionList.filter((item) => {
if (item.provider) { if (item.provider) {
@@ -28,17 +30,17 @@ const useClusterColumns = (
return useMemo(() => { return useMemo(() => {
return [ return [
{ {
title: 'Name', title: intl.formatMessage({ id: 'common.table.name' }),
dataIndex: 'name', dataIndex: 'name',
render: (text: string) => <AutoTooltip ghost>{text}</AutoTooltip> render: (text: string) => <AutoTooltip ghost>{text}</AutoTooltip>
}, },
{ {
title: 'Provider', title: intl.formatMessage({ id: 'clusters.table.provider' }),
dataIndex: 'provider', dataIndex: 'provider',
render: (value: string) => <span>{ProviderLabelMap[value]}</span> render: (value: string) => <span>{ProviderLabelMap[value]}</span>
}, },
{ {
title: 'Status', title: intl.formatMessage({ id: 'common.table.status' }),
dataIndex: 'state', dataIndex: 'state',
render: (value: number) => ( render: (value: number) => (
<StatusTag <StatusTag
@@ -52,7 +54,11 @@ const useClusterColumns = (
{ {
title: 'Workers', title: 'Workers',
dataIndex: 'workers', dataIndex: 'workers',
render: (value: number) => <span>{value}</span> render: (value: number, record: ClusterListItem) => (
<span>
{record.ready_workers} / {record.workers}
</span>
)
}, },
{ {
title: 'GPUs', title: 'GPUs',
@@ -60,12 +66,12 @@ const useClusterColumns = (
render: (value: number) => <span>{value}</span> render: (value: number) => <span>{value}</span>
}, },
{ {
title: 'Deployments', title: intl.formatMessage({ id: 'clusters.table.deployments' }),
dataIndex: 'models', dataIndex: 'models',
render: (value: number) => <span>{value}</span> render: (value: number) => <span>{value}</span>
}, },
{ {
title: 'Created', title: intl.formatMessage({ id: 'common.table.createTime' }),
dataIndex: 'created_at', dataIndex: 'created_at',
width: 180, width: 180,
render: (value: string) => ( render: (value: string) => (
@@ -73,7 +79,7 @@ const useClusterColumns = (
) )
}, },
{ {
title: 'Operations', title: intl.formatMessage({ id: 'common.table.operation' }),
dataIndex: 'operations', dataIndex: 'operations',
render: (value: string, record: ClusterListItem) => ( render: (value: string, record: ClusterListItem) => (
<DropdownButtons <DropdownButtons
+10 -31
View File
@@ -1,24 +1,20 @@
import CardWrapper from '@/components/card-wrapper'; import CardWrapper from '@/components/card-wrapper';
import GaugeChart from '@/components/echarts/gauge'; import GaugeChart from '@/components/echarts/gauge';
import PageTools from '@/components/page-tools'; import PageTools from '@/components/page-tools';
import breakpoints from '@/config/breakpoints';
import useWindowResize from '@/hooks/use-window-resize';
import { useIntl } from '@umijs/max'; import { useIntl } from '@umijs/max';
import { Col, Row } from 'antd'; import { Col, Row } from 'antd';
import _ from 'lodash'; import _ from 'lodash';
import { memo, useContext, useEffect, useMemo, useState } from 'react'; import { memo, useContext, useMemo } from 'react';
import { DashboardContext } from '../config/dashboard-context'; import { DashboardContext } from '../config/dashboard-context';
import ResourceUtilization from './resource-utilization'; import ResourceUtilization from './resource-utilization';
const smallChartHeight = 190;
const largeChartHeight = 400;
const resourceChartHeight = 400;
const SystemLoad = () => { const SystemLoad = () => {
const intl = useIntl(); const intl = useIntl();
const data = useContext(DashboardContext)?.system_load?.current || {}; const data = useContext(DashboardContext)?.system_load?.current || {};
const { size } = useWindowResize();
const [paddingRight, setPaddingRight] = useState<string>('20px');
const [smallChartHeight, setSmallChartHeight] = useState<number>(190);
const [largeChartHeight, setLargeChartHeight] = useState<number>(400);
const height = 400;
const chartData = useMemo(() => { const chartData = useMemo(() => {
return { return {
@@ -37,16 +33,6 @@ const SystemLoad = () => {
}; };
}, [data]); }, [data]);
console.log('SystemLoad data:', chartData);
useEffect(() => {
if (size.width < breakpoints.xl) {
setPaddingRight('0');
} else {
setPaddingRight('20px');
}
}, [size.width]);
return ( return (
<div> <div>
<div className="system-load"> <div className="system-load">
@@ -58,22 +44,15 @@ const SystemLoad = () => {
</span> </span>
} }
/> />
<Row style={{ width: '100%' }} gutter={[0, 20]}> <Row gutter={[20, 20]}>
<Col <Col xs={24} sm={24} md={24} lg={24} xl={16}>
xs={24} <CardWrapper style={{ height: resourceChartHeight }}>
sm={24}
md={24}
lg={24}
xl={16}
style={{ paddingRight: paddingRight }}
>
<CardWrapper style={{ height: height, width: '100%' }}>
<ResourceUtilization /> <ResourceUtilization />
</CardWrapper> </CardWrapper>
</Col> </Col>
<Col xs={24} sm={24} md={24} lg={24} xl={8}> <Col xs={24} sm={24} md={24} lg={24} xl={8}>
<CardWrapper style={{ height: largeChartHeight, width: '100%' }}> <CardWrapper style={{ height: largeChartHeight }}>
<Row style={{ height: largeChartHeight, width: '100%' }}> <Row style={{ height: largeChartHeight }}>
<Col span={12} style={{ height: smallChartHeight }}> <Col span={12} style={{ height: smallChartHeight }}>
<GaugeChart <GaugeChart
height={smallChartHeight} height={smallChartHeight}
@@ -91,20 +91,8 @@ const UsageInner: FC<{ maxWidth: number }> = ({ maxWidth }) => {
return ( return (
<div> <div>
<Row <Row gutter={maxWidth < breakpoints.xl ? [0, 0] : [20, 20]}>
style={{ width: '100%' }} <Col xs={24} sm={24} md={24} lg={24} xl={16}>
gutter={maxWidth < breakpoints.xl ? [0, 0] : [0, 20]}
>
<Col
xs={24}
sm={24}
md={24}
lg={24}
xl={16}
style={{
paddingRight: maxWidth < breakpoints.xl ? 0 : 20
}}
>
<div <div
style={{ style={{
display: 'flex', display: 'flex',
@@ -2,7 +2,6 @@ import IconFont from '@/components/icon-font';
import LabelSelector from '@/components/label-selector'; import LabelSelector from '@/components/label-selector';
import ListInput from '@/components/list-input'; import ListInput from '@/components/list-input';
import CheckboxField from '@/components/seal-form/checkbox-field'; import CheckboxField from '@/components/seal-form/checkbox-field';
import SealCascader from '@/components/seal-form/seal-cascader';
import SealInput from '@/components/seal-form/seal-input'; import SealInput from '@/components/seal-form/seal-input';
import SealSelect from '@/components/seal-form/seal-select'; import SealSelect from '@/components/seal-form/seal-select';
import TooltipList from '@/components/tooltip-list'; import TooltipList from '@/components/tooltip-list';
@@ -28,7 +27,6 @@ import mindieConfig from '../config/mindie-config';
import { FormData } from '../config/types'; import { FormData } from '../config/types';
import vllmConfig from '../config/vllm-config'; import vllmConfig from '../config/vllm-config';
import dataformStyles from '../style/data-form.less'; import dataformStyles from '../style/data-form.less';
import GPUCard from './gpu-card';
import Performance from './performance'; import Performance from './performance';
interface AdvanceConfigProps { interface AdvanceConfigProps {
@@ -265,7 +263,7 @@ const AdvanceConfig: React.FC<AdvanceConfigProps> = (props) => {
</Form.Item> </Form.Item>
</> </>
)} )}
{scheduleType === 'manual' && ( {/* {scheduleType === 'manual' && (
<> <>
<Form.Item <Form.Item
name={['gpu_selector', 'gpu_ids']} name={['gpu_selector', 'gpu_ids']}
@@ -293,7 +291,7 @@ const AdvanceConfig: React.FC<AdvanceConfigProps> = (props) => {
></SealCascader> ></SealCascader>
</Form.Item> </Form.Item>
</> </>
)} )} */}
<Form.Item name="backend_version"> <Form.Item name="backend_version">
<SealInput.Input <SealInput.Input
@@ -3,7 +3,6 @@ import GSDrawer from '@/components/scroller-modal/gs-drawer';
import { PageActionType } from '@/config/types'; import { PageActionType } from '@/config/types';
import { createAxiosToken } from '@/hooks/use-chunk-request'; import { createAxiosToken } from '@/hooks/use-chunk-request';
import { ProviderValueMap } from '@/pages/cluster-management/config'; import { ProviderValueMap } from '@/pages/cluster-management/config';
import { CloseOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max'; import { useIntl } from '@umijs/max';
import { Button } from 'antd'; import { Button } from 'antd';
import _ from 'lodash'; import _ from 'lodash';
@@ -506,22 +505,7 @@ const AddModal: React.FC<AddModalProps> = (props) => {
return ( return (
<GSDrawer <GSDrawer
title={ title={title}
<div className="flex-between flex-center">
<span
style={{
color: 'var(--ant-color-text)',
fontWeight: 'var(--font-weight-medium)',
fontSize: 'var(--font-size-middle)'
}}
>
{title}
</span>
<Button type="text" size="small" onClick={handleCancel}>
<CloseOutlined></CloseOutlined>
</Button>
</div>
}
open={open} open={open}
onClose={handleCancel} onClose={handleCancel}
destroyOnClose={true} destroyOnClose={true}
+14 -13
View File
@@ -246,21 +246,18 @@ const AddModal: FC<AddModalProps> = (props) => {
categories: getCategory(item) categories: getCategory(item)
}); });
setWarningStatus( let warningStatus: MessageStatus = {
{ show: true,
show: true, title: '',
title: '', type: 'transition',
type: 'transition', message: intl.formatMessage({ id: 'models.form.evaluating' })
message: intl.formatMessage({ id: 'models.form.evaluating' }) };
},
{
override: true
}
);
if (item.isGGUF) { if (item.isGGUF) {
fetchModelFiles(); warningStatus.type = 'danger';
warningStatus.message = 'GGUF model is not supported.';
} }
setWarningStatus(warningStatus, { override: true });
}; };
const handleOnSelectModelAfterEvaluate = (item: any, manual?: boolean) => { const handleOnSelectModelAfterEvaluate = (item: any, manual?: boolean) => {
@@ -531,7 +528,11 @@ const AddModal: FC<AddModalProps> = (props) => {
showOkBtn={!showExtraButton} showOkBtn={!showExtraButton}
extra={ extra={
showExtraButton && ( showExtraButton && (
<Button type="primary" onClick={handleSubmitAnyway}> <Button
type="primary"
onClick={handleSubmitAnyway}
disabled={isGGUF}
>
{intl.formatMessage({ {intl.formatMessage({
id: 'models.form.submit.anyway' id: 'models.form.submit.anyway'
})} })}
@@ -681,4 +681,4 @@ const InstanceItem: React.FC<InstanceItemProps> = ({
</> </>
); );
}; };
export default React.memo(InstanceItem); export default InstanceItem;
@@ -174,8 +174,6 @@ const ModelCard: React.FC<{
setModelData(null); setModelData(null);
setReadmeText(null); setReadmeText(null);
handleOnCollapse(null); handleOnCollapse(null);
// setIsGGUF(false);
// setIsGGUFModel(false);
} }
}; };
@@ -205,8 +203,6 @@ const ModelCard: React.FC<{
setModelData(null); setModelData(null);
setReadmeText(null); setReadmeText(null);
handleOnCollapse(null); handleOnCollapse(null);
// setIsGGUF(false);
// setIsGGUFModel(false);
} }
}; };
@@ -199,7 +199,7 @@ const SearchModel: React.FC<SearchInputProps> = (props) => {
try { try {
const params = { const params = {
Name: `${searchInputRef.current}`, Name: `${searchInputRef.current}`,
tags: ['gptq'], tags: [],
tasks: filterTaskRef.current tasks: filterTaskRef.current
? ([ModelscopeTaskMap[filterTaskRef.current]] as string[]) ? ([ModelscopeTaskMap[filterTaskRef.current]] as string[])
: [], : [],
+3 -1
View File
@@ -724,7 +724,9 @@ const Models: React.FC<ModelsProps> = ({
<Select <Select
allowClear allowClear
showSearch={false} showSearch={false}
placeholder="Filter by cluster" placeholder={intl.formatMessage({
id: 'clusters.filterBy.cluster'
})}
style={{ width: 160 }} style={{ width: 160 }}
size="large" size="large"
maxTagCount={1} maxTagCount={1}
+34 -29
View File
@@ -1,10 +1,11 @@
import ModalFooter from '@/components/modal-footer'; import ModalFooter from '@/components/modal-footer';
import GSDrawer from '@/components/scroller-modal/gs-drawer'; import GSDrawer from '@/components/scroller-modal/gs-drawer';
import { ProviderValueMap } from '@/pages/cluster-management/config';
import { useIntl } from '@umijs/max'; import { useIntl } from '@umijs/max';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
import React, { useCallback, useEffect, useRef, useState } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import ColumnWrapper from '../components/column-wrapper'; import ColumnWrapper from '../components/column-wrapper';
import HFModelFile from '../components/hf-model-file'; import CompatibilityAlert from '../components/compatible-alert';
import ModelCard from '../components/model-card'; import ModelCard from '../components/model-card';
import SearchModel from '../components/search-model'; import SearchModel from '../components/search-model';
import Separator from '../components/separator'; import Separator from '../components/separator';
@@ -19,7 +20,6 @@ type AddModalProps = {
source: string; source: string;
width?: string | number; width?: string | number;
hasLinuxWorker?: boolean; hasLinuxWorker?: boolean;
workersList: Global.BaseOption<number>[];
workerOptions: any[]; workerOptions: any[];
onOk: (values: FormData) => void; onOk: (values: FormData) => void;
onCancel: () => void; onCancel: () => void;
@@ -28,7 +28,6 @@ type AddModalProps = {
const DownloadModel: React.FC<AddModalProps> = (props) => { const DownloadModel: React.FC<AddModalProps> = (props) => {
const { const {
title, title,
workersList,
open, open,
onOk, onOk,
onCancel, onCancel,
@@ -47,14 +46,13 @@ const DownloadModel: React.FC<AddModalProps> = (props) => {
const [selectedModel, setSelectedModel] = useState<any>({}); const [selectedModel, setSelectedModel] = useState<any>({});
const [collapsed, setCollapsed] = useState<boolean>(false); const [collapsed, setCollapsed] = useState<boolean>(false);
const [isGGUF, setIsGGUF] = useState<boolean>(false); const [isGGUF, setIsGGUF] = useState<boolean>(false);
const [fileName, setFileName] = useState<string>('');
const modelFileRef = useRef<any>(null); const modelFileRef = useRef<any>(null);
const generateModelInfo = () => { const generateModelInfo = () => {
if (source === modelSourceMap.huggingface_value) { if (source === modelSourceMap.huggingface_value) {
const huggingFaceModel = { const huggingFaceModel = {
huggingface_repo_id: selectedModel.name, huggingface_repo_id: selectedModel.name,
huggingface_filename: fileName || null huggingface_filename: null
}; };
return huggingFaceModel; return huggingFaceModel;
} }
@@ -62,15 +60,12 @@ const DownloadModel: React.FC<AddModalProps> = (props) => {
if (source === modelSourceMap.modelscope_value) { if (source === modelSourceMap.modelscope_value) {
const modelScopeModel = { const modelScopeModel = {
model_scope_model_id: selectedModel.name, model_scope_model_id: selectedModel.name,
model_scope_file_path: fileName || null model_scope_file_path: null
}; };
return modelScopeModel; return modelScopeModel;
} }
return {}; return {};
}; };
const handleSelectModelFile = useCallback((item: any) => {
setFileName(item.fakeName);
}, []);
const handleOnSelectModel = (item: any) => { const handleOnSelectModel = (item: any) => {
setSelectedModel(item); setSelectedModel(item);
@@ -103,21 +98,30 @@ const DownloadModel: React.FC<AddModalProps> = (props) => {
onCancel?.(); onCancel?.();
}, [onCancel]); }, [onCancel]);
useEffect(() => { const initDefaultWorker = () => {
handleSelectModelFile({ fakeName: '' }); if (!workerOptions || workerOptions.length === 0) {
}, [selectedModel]); form.current?.form?.setFieldValue('worker_id', []);
return;
}
const getWorkerId = (worker: any) => [
worker?.value ?? '',
worker?.children?.[0]?.value ?? ''
];
const customWorker = workerOptions.find(
(item) => item.provider === ProviderValueMap.Custom
);
const worker_id = getWorkerId(customWorker || workerOptions[0]);
form.current?.form?.setFieldValue('worker_id', worker_id);
};
useEffect(() => { useEffect(() => {
if (!open) { if (!open) {
setIsGGUF(false); setIsGGUF(false);
} else if (source === modelSourceMap.ollama_library_value) {
setIsGGUF(true);
} }
if (open) { if (open) {
form.current?.form?.setFieldValue( initDefaultWorker();
'worker_id',
workersList[0]?.value || ''
);
} }
return () => { return () => {
@@ -183,16 +187,6 @@ const DownloadModel: React.FC<AddModalProps> = (props) => {
modelSource={props.source} modelSource={props.source}
setIsGGUF={handleSetIsGGUF} setIsGGUF={handleSetIsGGUF}
></ModelCard> ></ModelCard>
{isGGUF && (
<HFModelFile
ref={modelFileRef}
selectedModel={selectedModel}
modelSource={props.source}
onSelectFile={handleSelectModelFile}
collapsed={collapsed}
isDownload={true}
></HFModelFile>
)}
</ColumnWrapper> </ColumnWrapper>
<Separator></Separator> <Separator></Separator>
</div> </div>
@@ -203,9 +197,21 @@ const DownloadModel: React.FC<AddModalProps> = (props) => {
paddingBottom={50} paddingBottom={50}
footer={ footer={
<> <>
<CompatibilityAlert
showClose={false}
warningStatus={{
show: isGGUF,
type: 'danger',
message: 'GGUF is not supported'
}}
contentStyle={{ paddingInline: 0 }}
></CompatibilityAlert>
<ModalFooter <ModalFooter
onCancel={handleCancel} onCancel={handleCancel}
onOk={handleSumit} onOk={handleSumit}
okBtnProps={{
disabled: isGGUF
}}
style={{ style={{
padding: '16px 24px', padding: '16px 24px',
display: 'flex', display: 'flex',
@@ -228,7 +234,6 @@ const DownloadModel: React.FC<AddModalProps> = (props) => {
ref={form} ref={form}
onOk={handleOk} onOk={handleOk}
source={source} source={source}
workersList={workersList}
workerOptions={workerOptions} workerOptions={workerOptions}
></TargetForm> ></TargetForm>
</> </>
+12 -11
View File
@@ -1,3 +1,4 @@
import SealCascader from '@/components/seal-form/seal-cascader';
import SealInput from '@/components/seal-form/seal-input'; import SealInput from '@/components/seal-form/seal-input';
import SealSelect from '@/components/seal-form/seal-select'; import SealSelect from '@/components/seal-form/seal-select';
import TooltipList from '@/components/tooltip-list'; import TooltipList from '@/components/tooltip-list';
@@ -11,14 +12,13 @@ import { localPathTipsList, modelSourceMap, sourceOptions } from '../config';
interface TargetFormProps { interface TargetFormProps {
ref?: any; ref?: any;
workersList: Global.BaseOption<number>[];
source: string; source: string;
workerOptions: any[]; workerOptions: any[];
onOk: (values: any) => void; onOk: (values: any) => void;
} }
const TargetForm: React.FC<TargetFormProps> = forwardRef((props, ref) => { const TargetForm: React.FC<TargetFormProps> = forwardRef((props, ref) => {
const { onOk, source, workersList, workerOptions } = props; const { onOk, source, workerOptions } = props;
const { getRuleMessage } = useAppUtils(); const { getRuleMessage } = useAppUtils();
const intl = useIntl(); const intl = useIntl();
const [form] = Form.useForm(); const [form] = Form.useForm();
@@ -29,7 +29,14 @@ const TargetForm: React.FC<TargetFormProps> = forwardRef((props, ref) => {
const handleOk = (values: any) => { const handleOk = (values: any) => {
const data = _.pickBy(values, (val: string) => val); const data = _.pickBy(values, (val: string) => val);
onOk(data); onOk({
...data,
worker_id: data.worker_id?.[1]
});
console.log('Form Data: ', {
...data,
worker_id: data.worker_id?.[1]
});
}; };
const handleOnLocalPathBlur = (e: any) => { const handleOnLocalPathBlur = (e: any) => {
@@ -116,12 +123,7 @@ const TargetForm: React.FC<TargetFormProps> = forwardRef((props, ref) => {
} }
]} ]}
> >
<SealSelect <SealCascader
label="Worker"
options={workersList}
required
></SealSelect>
{/* <SealCascader
required required
showSearch showSearch
expandTrigger="hover" expandTrigger="hover"
@@ -131,9 +133,8 @@ const TargetForm: React.FC<TargetFormProps> = forwardRef((props, ref) => {
label="Worker" label="Worker"
options={workerOptions} options={workerOptions}
showCheckedStrategy="SHOW_CHILD" showCheckedStrategy="SHOW_CHILD"
value={form.getFieldValue(['gpu_selector', 'gpu_ids'])}
getPopupContainer={(triggerNode) => triggerNode.parentNode} getPopupContainer={(triggerNode) => triggerNode.parentNode}
></SealCascader> */} ></SealCascader>
</Form.Item> </Form.Item>
{source !== modelSourceMap.local_path_value && ( {source !== modelSourceMap.local_path_value && (
<Form.Item<FormData> <Form.Item<FormData>
@@ -12,14 +12,16 @@ import { queryGPUList } from '../apis';
import { backendOptionsMap, setSourceRepoConfigValue } from '../config'; import { backendOptionsMap, setSourceRepoConfigValue } from '../config';
import { GPUListItem, ListItem } from '../config/types'; import { GPUListItem, ListItem } from '../config/types';
interface CascaderOption { type EmptyObject = Record<never, never>;
type CascaderOption<T extends object = EmptyObject> = {
label: string; label: string;
value: string | number; value: string | number;
parent?: boolean; parent?: boolean;
disabled?: boolean; disabled?: boolean;
index?: number; index?: number;
children?: CascaderOption[]; children?: CascaderOption<T>[];
} } & Partial<T>;
export const useGenerateGPUOptions = () => { export const useGenerateGPUOptions = () => {
const [gpuOptions, setGpuOptions] = useState<CascaderOption[]>([]); const [gpuOptions, setGpuOptions] = useState<CascaderOption[]>([]);
@@ -102,7 +104,9 @@ export const useGenerateGPUOptions = () => {
}; };
export const useGenerateWorkerOptions = () => { export const useGenerateWorkerOptions = () => {
const [workerOptions, setWorkerOptions] = useState<CascaderOption[]>([]); const [workerOptions, setWorkerOptions] = useState<
CascaderOption<{ state: string }>[]
>([]);
const [clusterList, setClusterList] = useState< const [clusterList, setClusterList] = useState<
Global.BaseOption<number, { provider: string; state: string | number }>[] Global.BaseOption<number, { provider: string; state: string | number }>[]
>([]); >([]);
@@ -117,18 +121,21 @@ export const useGenerateWorkerOptions = () => {
workerList: WorkerListItem[], workerList: WorkerListItem[],
clusterList: ClusterListItem[] clusterList: ClusterListItem[]
) => { ) => {
const options = clusterList.map((cluster) => ({ const options = clusterList
label: cluster.name, .map((cluster) => ({
value: cluster.id, label: cluster.name,
parent: true, value: cluster.id,
children: workerList parent: true,
.filter((worker) => worker.cluster_id === cluster.id) children: workerList
.map((worker) => ({ .filter((worker) => worker.cluster_id === cluster.id)
disabled: WorkerStatusMap.ready !== worker.state, .map((worker) => ({
label: worker.name, disabled: WorkerStatusMap.ready !== worker.state,
value: worker.id state: worker.state,
})) label: worker.name,
})); value: worker.id
}))
}))
.filter((cluster) => cluster.children.length > 0); // Filter out clusters with no workers
setWorkerOptions(options); setWorkerOptions(options);
return options; return options;
}; };
+1 -1
View File
@@ -45,7 +45,7 @@ const Profile: React.FC = () => {
children: <Appearance /> children: <Appearance />
} }
]; ];
}, [initialState?.currentUser?.source]); }, [intl, initialState?.currentUser?.source]);
const handleChangeTab = useCallback((key: string) => { const handleChangeTab = useCallback((key: string) => {
setActiveKey(key); setActiveKey(key);
+36 -137
View File
@@ -1,44 +1,13 @@
import AutoTooltip from '@/components/auto-tooltip';
import { FilterBar } from '@/components/page-tools'; import { FilterBar } from '@/components/page-tools';
import ProgressBar from '@/components/progress-bar';
import InfoColumn from '@/components/simple-table/info-column';
import useTableFetch from '@/hooks/use-table-fetch'; import useTableFetch from '@/hooks/use-table-fetch';
import { convertFileSize } from '@/utils'; import { queryClusterList } from '@/pages/cluster-management/apis';
import { PageContainer } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max'; import { useIntl } from '@umijs/max';
import { ConfigProvider, Empty, Table } from 'antd'; import { ConfigProvider, Empty, Table } from 'antd';
import _ from 'lodash'; import React, { useEffect, useState } from 'react';
import React from 'react';
import { GPU_DEVICES_API, queryGpuDevicesList } from '../apis'; import { GPU_DEVICES_API, queryGpuDevicesList } from '../apis';
import { GPUDeviceItem } from '../config/types'; import { GPUDeviceItem } from '../config/types';
const { Column } = Table; import useGPUColumns from '../hooks/use-gpu-columns';
const fieldList = [
{
label: 'resources.table.total',
key: 'total',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
},
{
label: 'resources.table.used',
key: 'used',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
},
{
label: 'resources.table.allocated',
key: 'allocated',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
}
];
const GPUList: React.FC = () => { const GPUList: React.FC = () => {
const { const {
@@ -56,6 +25,22 @@ const GPUList: React.FC = () => {
}); });
const intl = useIntl(); const intl = useIntl();
const [clusterList, setClusterList] = useState<Global.BaseOption<number>[]>(
[]
);
const getClusterList = async () => {
try {
const res = await queryClusterList({ page: 1, perPage: 100 });
const list = res.items?.map((item) => ({
label: item.name,
value: item.id
}));
setClusterList(list || []);
} catch (error) {
setClusterList([]);
}
};
const renderEmpty = (type?: string) => { const renderEmpty = (type?: string) => {
if (type !== 'Table') return; if (type !== 'Table') return;
@@ -69,6 +54,20 @@ const GPUList: React.FC = () => {
return <div></div>; return <div></div>;
}; };
const columns = useGPUColumns({
clusterList,
loadend: dataSource.loadend,
firstLoad: extraStatus.firstLoad
});
useEffect(() => {
console.log('columns changed!');
}, [columns]);
useEffect(() => {
getClusterList();
}, []);
return ( return (
<> <>
<PageContainer <PageContainer
@@ -94,6 +93,8 @@ const GPUList: React.FC = () => {
></FilterBar> ></FilterBar>
<ConfigProvider renderEmpty={renderEmpty}> <ConfigProvider renderEmpty={renderEmpty}>
<Table <Table
columns={columns}
style={{ width: '100%' }}
tableLayout={dataSource.loadend ? 'auto' : 'fixed'} tableLayout={dataSource.loadend ? 'auto' : 'fixed'}
dataSource={dataSource.dataList} dataSource={dataSource.dataList}
loading={dataSource.loading} loading={dataSource.loading}
@@ -107,109 +108,7 @@ const GPUList: React.FC = () => {
hideOnSinglePage: queryParams.perPage === 10, hideOnSinglePage: queryParams.perPage === 10,
onChange: handlePageChange onChange: handlePageChange
}} }}
> ></Table>
<Column
title={intl.formatMessage({ id: 'common.table.name' })}
dataIndex="name"
key="name"
width={240}
render={(text, record) => {
return (
<AutoTooltip ghost maxWidth={240}>
{text}
</AutoTooltip>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'resources.table.index' })}
dataIndex="index"
key="index"
render={(text, record: GPUDeviceItem) => {
return <span>{record.index}</span>;
}}
/>
<Column
title={intl.formatMessage({ id: 'resources.table.workername' })}
dataIndex="worker_name"
key="worker_name"
width={200}
render={(text, record: GPUDeviceItem) => {
return (
<span style={{ display: 'flex', width: '100%' }}>
<AutoTooltip ghost maxWidth={340}>
{text}
</AutoTooltip>
</span>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'resources.table.vender' })}
dataIndex="vendor"
key="vendor"
/>
<Column
title={`${intl.formatMessage({ id: 'resources.table.temperature' })} (°C)`}
dataIndex="temperature"
key="Temperature"
render={(text, record: GPUDeviceItem) => {
return <span>{text ? _.round(text, 1) : '-'}</span>;
}}
/>
<Column
title={intl.formatMessage({
id: 'resources.table.gpuutilization'
})}
dataIndex="gpuUtil"
key="gpuUtil"
render={(text, record: GPUDeviceItem) => {
return (
<>
{record.core ? (
<ProgressBar
percent={_.round(record.core?.utilization_rate, 2)}
></ProgressBar>
) : (
'-'
)}
</>
);
}}
/>
<Column
title={intl.formatMessage({
id: 'resources.table.vramutilization'
})}
dataIndex="VRAM"
key="VRAM"
render={(text, record: GPUDeviceItem, index: number) => {
return (
<ProgressBar
defaultOpen={
index === 0 && dataSource.loadend && extraStatus.firstLoad
}
percent={
record.memory?.used
? _.round(record.memory?.utilization_rate, 0)
: _.round(
record.memory?.allocated / record.memory?.total,
0
) * 100
}
label={
<InfoColumn
fieldList={fieldList}
data={record.memory}
></InfoColumn>
}
></ProgressBar>
);
}}
/>
</Table>
</ConfigProvider> </ConfigProvider>
</PageContainer> </PageContainer>
</> </>
+21 -357
View File
@@ -1,10 +1,6 @@
import { modelsExpandKeysAtom } from '@/atoms/models'; import { modelsExpandKeysAtom } from '@/atoms/models';
import AutoTooltip from '@/components/auto-tooltip';
import DeleteModal from '@/components/delete-modal'; import DeleteModal from '@/components/delete-modal';
import DropdownButtons from '@/components/drop-down-buttons';
import { TooltipOverlayScroller } from '@/components/overlay-scroller';
import { FilterBar } from '@/components/page-tools'; import { FilterBar } from '@/components/page-tools';
import StatusTag from '@/components/status-tag';
import { PageAction } from '@/config'; import { PageAction } from '@/config';
import useAppUtils from '@/hooks/use-app-utils'; import useAppUtils from '@/hooks/use-app-utils';
import useBodyScroll from '@/hooks/use-body-scroll'; import useBodyScroll from '@/hooks/use-body-scroll';
@@ -15,26 +11,18 @@ import { backendOptionsMap, modelSourceMap } from '@/pages/llmodels/config';
import { identifyModelTask } from '@/pages/llmodels/config/audio-catalog'; import { identifyModelTask } from '@/pages/llmodels/config/audio-catalog';
import { import {
modalConfig, modalConfig,
modelFileActions,
onLineSourceOptions onLineSourceOptions
} from '@/pages/llmodels/config/button-actions'; } from '@/pages/llmodels/config/button-actions';
import { SourceType } from '@/pages/llmodels/config/types'; import { SourceType } from '@/pages/llmodels/config/types';
import DownloadModal from '@/pages/llmodels/download'; import DownloadModal from '@/pages/llmodels/download';
import { useGenerateWorkerOptions } from '@/pages/llmodels/hooks/use-form-initial-values'; import { useGenerateWorkerOptions } from '@/pages/llmodels/hooks/use-form-initial-values';
import { convertFileSize } from '@/utils';
import {
CheckCircleFilled,
CopyOutlined,
InfoCircleOutlined
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { useIntl, useNavigate } from '@umijs/max'; import { useIntl, useNavigate } from '@umijs/max';
import { ConfigProvider, Empty, Table, Tag, Typography, message } from 'antd'; import { useMemoizedFn } from 'ahooks';
import dayjs from 'dayjs'; import { ConfigProvider, Empty, Table, message } from 'antd';
import { useAtom } from 'jotai'; import { useAtom } from 'jotai';
import _ from 'lodash'; import _ from 'lodash';
import React, { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { checkCurrentbackend } from '../../llmodels/hooks'; import { checkCurrentbackend } from '../../llmodels/hooks';
import { import {
MODEL_FILES_API, MODEL_FILES_API,
@@ -43,242 +31,12 @@ import {
queryModelFilesList, queryModelFilesList,
retryDownloadModelFile retryDownloadModelFile
} from '../apis'; } from '../apis';
import { import { WorkerStatusMap } from '../config';
ModelfileState,
ModelfileStateMap,
ModelfileStateMapValue,
WorkerStatusMap
} from '../config';
import { ModelFile as ListItem } from '../config/types'; import { ModelFile as ListItem } from '../config/types';
import useFilesColumns from '../hooks/use-files-columns';
const { Paragraph } = Typography;
const filterPattern = /^(.*?)(?:-\d+-of-\d+)?(\.gguf)?$/; const filterPattern = /^(.*?)(?:-\d+-of-\d+)?(\.gguf)?$/;
const PathWrapper = styled.div`
display: flex;
align-items: center;
justify-content: flex-start;
height: 100%;
&::after {
content: '';
display: block;
width: 20px;
height: 100%;
position: absolute;
top: 0;
right: 0;
z-index: 1;
}
.btn-wrapper {
display: flex;
opacity: 0;
width: 0;
align-items: center;
}
&:hover {
.btn-wrapper {
width: auto;
opacity: 1;
}
}
`;
const ItemWrapper = styled.ul`
max-width: 300px;
margin: 0;
padding-inline: 13px 0;
word-break: break-word;
li {
line-height: 1.6;
}
`;
const FilesTag = styled(Tag)`
cursor: pointer;
display: flex;
align-items: center;
margin-inline: 4px 0;
height: 22px;
border-radius: var(--border-radius-base);
`;
const TextWrapper = styled.div`
display: flex;
align-items: center;
cursor: pointer;
height: 100%;
`;
const TypographyPara = styled(Paragraph)`
background: transparent;
color: inherit;
margin-bottom: 0;
font-size: 13px;
`;
const TooltipTitle: React.FC<{ path: string }> = ({ path }) => {
const intl = useIntl();
return (
<TypographyPara
style={{ margin: 0 }}
copyable={{
icon: [
<CopyOutlined key="copy-icon" />,
<CheckCircleFilled key="copied-icon" />
],
text: path,
tooltips: [
intl.formatMessage({ id: 'common.button.copy' }),
intl.formatMessage({ id: 'common.button.copied' })
]
}}
>
{path}
</TypographyPara>
);
};
const getWorkerName = (
id: number,
workersList: Global.BaseOption<number>[]
) => {
const worker = workersList.find((item) => item.value === id);
return worker?.label || '';
};
const getModelInfo = (record: ListItem) => {
const source = _.get(modelSourceMap, record.source, '');
if (record.source === modelSourceMap.huggingface_value) {
return {
source: `${source}/${record.huggingface_repo_id}`,
repo_id: record.huggingface_repo_id,
title: `${record.huggingface_repo_id}/${record.huggingface_filename}`,
filename: record.huggingface_filename || record.huggingface_repo_id
};
}
if (record.source === modelSourceMap.modelscope_value) {
return {
source: `${source}/${record.model_scope_model_id}`,
repo_id: record.model_scope_model_id,
title: `${record.model_scope_model_id}/${record.model_scope_file_path}`,
filename: record.model_scope_file_path || record.model_scope_model_id
};
}
if (record.source === modelSourceMap.ollama_library_value) {
return {
source: `${source}/${record.ollama_library_model_name}`,
repo_id: record.ollama_library_model_name,
title: record.ollama_library_model_name,
filename: record.ollama_library_model_name
};
}
return {
source: `${source}${record.local_path}`,
repo_id: record.local_path,
title: record.local_path,
filename: _.split(record.local_path, /[\\/]/).pop()
};
};
const getResolvedPath = (pathList: string[]) => {
return _.split(pathList?.[0], /[\\/]/).pop();
};
const InstanceStatusTag = (props: { data: ListItem }) => {
const { data } = props;
if (!data.state) {
return null;
}
return (
<StatusTag
download={
data.state === ModelfileStateMap.Downloading
? { percent: data.download_progress }
: undefined
}
statusValue={{
status:
data.state === ModelfileStateMap.Downloading &&
data.download_progress === 100
? ModelfileState[ModelfileStateMap.Ready]
: ModelfileState[data.state],
text: ModelfileStateMapValue[data.state],
message:
data.state === ModelfileStateMap.Downloading &&
data.download_progress === 100
? ''
: data.state_message
}}
/>
);
};
const RenderParts = (props: { record: ListItem }) => {
const { record } = props;
const intl = useIntl();
const parts = record.resolved_paths || [];
if (parts.length <= 1) {
return null;
}
const renderItem = () => {
return (
<ItemWrapper>
{parts.map((item: string, index: number) => {
return <li key={index}>{_.split(item, /[\\/]/).pop()}</li>;
})}
</ItemWrapper>
);
};
return (
<TooltipOverlayScroller title={renderItem()}>
<FilesTag color="purple" icon={<InfoCircleOutlined />}>
<span style={{ opacity: 1 }}>
{record.resolved_paths?.length}{' '}
{intl.formatMessage({ id: 'models.form.files' })}
</span>
</FilesTag>
</TooltipOverlayScroller>
);
};
const ResolvedPathColumn = (props: { record: ListItem }) => {
const { record } = props;
const intl = useIntl();
if (
!record.resolved_paths.length &&
record.state === ModelfileStateMap.Downloading
) {
return (
<span>
{intl.formatMessage({
id: 'resources.modelfiles.storagePath.holder'
})}
</span>
);
}
return (
record.resolved_paths?.length > 0 && (
<PathWrapper>
<TextWrapper>
<AutoTooltip
ghost
showTitle
title={
<TooltipTitle path={record.resolved_paths?.[0]}></TooltipTitle>
}
>
<span>{getResolvedPath(record.resolved_paths)}</span>
</AutoTooltip>
</TextWrapper>
<RenderParts record={record}></RenderParts>
</PathWrapper>
)
);
};
const ModelFiles = () => { const ModelFiles = () => {
const { getWorkerOptionList, workerOptions, clusterList, workersList } = const { getWorkerOptionList, workerOptions, clusterList, workersList } =
useGenerateWorkerOptions(); useGenerateWorkerOptions();
@@ -387,7 +145,7 @@ const ModelFiles = () => {
}; };
}; };
const handleSelect = async (val: any, record: ListItem) => { const handleSelect = useMemoizedFn(async (val: any, record: ListItem) => {
try { try {
if (val === 'delete') { if (val === 'delete') {
handleDelete( handleDelete(
@@ -419,7 +177,7 @@ const ModelFiles = () => {
} catch (error) { } catch (error) {
// console.log('error', error); // console.log('error', error);
} }
}; });
const renderEmpty = (type?: string) => { const renderEmpty = (type?: string) => {
if (type !== 'Table') return; if (type !== 'Table') return;
@@ -464,14 +222,6 @@ const ModelFiles = () => {
} }
}; };
const setActionList = (record: ListItem) => {
return _.filter(modelFileActions, (item: { key: string }) => {
if (item.key === 'deploy') {
return record.state === ModelfileStateMap.Ready;
}
return true;
});
};
const handleDeployModalCancel = () => { const handleDeployModalCancel = () => {
setOpenDeployModal({ setOpenDeployModal({
...openDeployModal, ...openDeployModal,
@@ -506,104 +256,19 @@ const ModelFiles = () => {
} }
}; };
const columns: any[] = [ const columns = useFilesColumns({
{ handleSelect,
title: intl.formatMessage({ id: 'models.form.source' }), workersList
dataIndex: 'source', });
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => {
const modelInfo = getModelInfo(record);
const { repo_id, source } = modelInfo;
return (
<TextWrapper style={{ paddingRight: 8 }}>
<AutoTooltip ghost title={source}>
{source}
</AutoTooltip>
</TextWrapper>
);
}
},
{
title: 'Worker',
dataIndex: 'worker_name',
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => {
return (
<AutoTooltip ghost>
<span>{getWorkerName(record.worker_id, workersList)}</span>
</AutoTooltip>
);
}
},
{
title: intl.formatMessage({ id: 'common.table.status' }),
dataIndex: 'state',
width: 132,
render: (text: string, record: ListItem) => {
return <InstanceStatusTag data={record} />;
}
},
{
title: intl.formatMessage({ id: 'resources.modelfiles.form.path' }),
dataIndex: 'resolved_paths',
width: '30%',
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => (
<ResolvedPathColumn record={record} />
)
},
{
title: intl.formatMessage({ id: 'resources.modelfiles.size' }),
dataIndex: 'size',
width: 110,
align: 'right',
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => {
return (
<AutoTooltip ghost>
<span>{convertFileSize(record.size, 1, true)}</span>
</AutoTooltip>
);
}
},
{
title: intl.formatMessage({ id: 'common.table.createTime' }),
dataIndex: 'created_at',
sorter: false,
width: 180,
ellipsis: {
showTitle: false
},
render: (text: number) => (
<AutoTooltip ghost minWidth={20}>
{dayjs(text).format('YYYY-MM-DD HH:mm:ss')}
</AutoTooltip>
)
},
{
title: intl.formatMessage({ id: 'common.table.operation' }),
dataIndex: 'operation',
width: 120,
render: (text: string, record: ListItem) => (
<DropdownButtons
items={setActionList(record)}
onSelect={(val) => handleSelect(val, record)}
></DropdownButtons>
)
}
];
const readyWorkers = useMemo(() => { const readyWorkers = useMemo(() => {
return workersList.filter((item) => item.state === WorkerStatusMap.ready); return workerOptions.map((item) => {
}, [workersList]); item.children = item.children?.filter(
(child) => child.state === WorkerStatusMap.ready
);
return item;
});
}, [workerOptions]);
return ( return (
<> <>
@@ -622,8 +287,8 @@ const ModelFiles = () => {
marginBottom={22} marginBottom={22}
marginTop={30} marginTop={30}
actionType="dropdown" actionType="dropdown"
selectHolder="resources.filter.worker" selectHolder={intl.formatMessage({ id: 'resources.filter.worker' })}
inputHolder="resources.filter.path" inputHolder={intl.formatMessage({ id: 'resources.filter.path' })}
buttonText={intl.formatMessage({ buttonText={intl.formatMessage({
id: 'resources.modelfiles.download' id: 'resources.modelfiles.download'
})} })}
@@ -666,8 +331,7 @@ const ModelFiles = () => {
source={downloadModalStatus.source} source={downloadModalStatus.source}
width={downloadModalStatus.width} width={downloadModalStatus.width}
hasLinuxWorker={downloadModalStatus.hasLinuxWorker} hasLinuxWorker={downloadModalStatus.hasLinuxWorker}
workersList={readyWorkers} workerOptions={readyWorkers}
workerOptions={workerOptions}
></DownloadModal> ></DownloadModal>
<DeployModal <DeployModal
deploymentType="modelFiles" deploymentType="modelFiles"
+16 -347
View File
@@ -1,24 +1,11 @@
import AutoTooltip from '@/components/auto-tooltip';
import DeleteModal from '@/components/delete-modal'; import DeleteModal from '@/components/delete-modal';
import DropdownButtons from '@/components/drop-down-buttons';
import IconFont from '@/components/icon-font';
import { FilterBar } from '@/components/page-tools'; import { FilterBar } from '@/components/page-tools';
import ProgressBar from '@/components/progress-bar';
import InfoColumn from '@/components/simple-table/info-column';
import StatusTag from '@/components/status-tag';
import useTableFetch from '@/hooks/use-table-fetch'; import useTableFetch from '@/hooks/use-table-fetch';
import { queryClusterList } from '@/pages/cluster-management/apis'; import { queryClusterList } from '@/pages/cluster-management/apis';
import { convertFileSize } from '@/utils';
import {
CodeOutlined,
DeleteOutlined,
EditOutlined,
InfoCircleOutlined
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max'; import { useIntl } from '@umijs/max';
import { ConfigProvider, Empty, Table, Tooltip, message } from 'antd'; import { useMemoizedFn } from 'ahooks';
import _ from 'lodash'; import { ConfigProvider, Empty, Table, message } from 'antd';
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { import {
WORKERS_API, WORKERS_API,
@@ -26,82 +13,10 @@ import {
queryWorkersList, queryWorkersList,
updateWorker updateWorker
} from '../apis'; } from '../apis';
import { WorkerStatusMapValue, status } from '../config'; import { ListItem } from '../config/types';
import { Filesystem, GPUDeviceItem, ListItem } from '../config/types'; import useWorkerColumns from '../hooks/use-worker-columns';
import UpdateLabels from './update-labels'; import UpdateLabels from './update-labels';
const { Column } = Table;
const fieldList = [
{
label: 'resources.table.total',
key: 'total',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
},
{
label: 'resources.table.used',
key: 'used',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
},
{
label: 'resources.table.allocated',
key: 'allocated',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
}
];
const ActionList = [
{
label: 'common.button.edit',
key: 'edit',
icon: <EditOutlined />
},
{
label: 'common.button.logs',
locale: false,
key: 'logs',
icon: <IconFont type="icon-logs" />
},
{
label: 'Terminal',
locale: false,
key: 'terminal',
icon: <CodeOutlined />
},
{
label: 'common.button.delete',
key: 'delete',
props: {
danger: true
},
icon: <DeleteOutlined />
}
];
const formateUtilazation = (val1: number, val2: number): number => {
if (!val2 || !val1) {
return 0;
}
return _.round((val1 / val2) * 100, 0);
};
const calcStorage = (files: Filesystem[]) => {
const mountRoot = _.find(
files,
(item: Filesystem) => item.mount_point === '/'
);
return mountRoot ? formateUtilazation(mountRoot.used, mountRoot.total) : 0;
};
const Workers: React.FC = () => { const Workers: React.FC = () => {
const { const {
dataSource, dataSource,
@@ -203,7 +118,7 @@ const Workers: React.FC = () => {
}); });
}; };
const handleSelect = (val: any, record: ListItem) => { const handleSelect = useMemoizedFn((val: any, record: ListItem) => {
if (val === 'edit') { if (val === 'edit') {
handleUpdateLabels(record); handleUpdateLabels(record);
return; return;
@@ -211,7 +126,7 @@ const Workers: React.FC = () => {
if (val === 'delete') { if (val === 'delete') {
handleDelete(record); handleDelete(record);
} }
}; });
const renderEmpty = (type?: string) => { const renderEmpty = (type?: string) => {
if (type !== 'Table') return; if (type !== 'Table') return;
@@ -225,21 +140,6 @@ const Workers: React.FC = () => {
return <div></div>; return <div></div>;
}; };
const renderStorageTooltip = (files: Filesystem[]) => {
const mountRoot = _.find(
files,
(item: Filesystem) => item.mount_point === '/'
);
return mountRoot ? (
<InfoColumn
fieldList={fieldList.filter((item) => item.key !== 'allocated')}
data={mountRoot}
></InfoColumn>
) : (
0
);
};
const handleClusterChange = (value: number) => { const handleClusterChange = (value: number) => {
handleQueryChange({ handleQueryChange({
page: 1, page: 1,
@@ -247,6 +147,13 @@ const Workers: React.FC = () => {
}); });
}; };
const columns = useWorkerColumns({
clusterData,
dataSource,
extraStatus,
handleSelect
});
useEffect(() => { useEffect(() => {
getClusterList(); getClusterList();
}, []); }, []);
@@ -267,7 +174,7 @@ const Workers: React.FC = () => {
<FilterBar <FilterBar
showSelect={true} showSelect={true}
showPrimaryButton={false} showPrimaryButton={false}
selectHolder="Filter by cluster" selectHolder={intl.formatMessage({ id: 'clusters.filterBy.cluster' })}
marginBottom={22} marginBottom={22}
marginTop={30} marginTop={30}
buttonText={intl.formatMessage({ id: 'resources.button.create' })} buttonText={intl.formatMessage({ id: 'resources.button.create' })}
@@ -281,6 +188,7 @@ const Workers: React.FC = () => {
></FilterBar> ></FilterBar>
<ConfigProvider renderEmpty={renderEmpty}> <ConfigProvider renderEmpty={renderEmpty}>
<Table <Table
columns={columns}
tableLayout={dataSource.loadend ? 'auto' : 'fixed'} tableLayout={dataSource.loadend ? 'auto' : 'fixed'}
style={{ width: '100%' }} style={{ width: '100%' }}
dataSource={dataSource.dataList} dataSource={dataSource.dataList}
@@ -296,246 +204,7 @@ const Workers: React.FC = () => {
hideOnSinglePage: queryParams.perPage === 10, hideOnSinglePage: queryParams.perPage === 10,
onChange: handlePageChange onChange: handlePageChange
}} }}
> ></Table>
<Column
title={intl.formatMessage({ id: 'common.table.name' })}
dataIndex="name"
key="name"
width={100}
render={(text, record: ListItem) => {
return (
<AutoTooltip ghost maxWidth={240}>
<span>{record.name}</span>
</AutoTooltip>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'resources.table.labels' })}
dataIndex="labels"
key="labels"
width={200}
render={(text, record: ListItem) => {
return (
<div
style={{
display: 'flex',
flexWrap: 'wrap',
gap: 6
}}
>
{_.map(record.labels, (value: any, key: string) => {
return (
<AutoTooltip
key={key}
className="m-r-0"
maxWidth={155}
style={{
paddingInline: 8,
borderRadius: 12
}}
>
<span>{key}</span>
<span>:{value}</span>
</AutoTooltip>
);
})}
</div>
);
}}
/>
<Column
title="Cluster"
dataIndex="cluster"
key="cluster"
render={(text, record: ListItem) => {
return (
<AutoTooltip ghost maxWidth={240}>
<span>{clusterData.data[record.cluster_id]}</span>
</AutoTooltip>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'common.table.status' })}
dataIndex="state"
key="state"
render={(text, record: ListItem) => {
return (
<StatusTag
maxTooltipWidth={400}
statusValue={{
status: status[record.state] as any,
text: WorkerStatusMapValue[record.state],
message: record.state_message
}}
></StatusTag>
);
}}
/>
<Column title="IP" dataIndex="ip" key="address" />
<Column
title="CPU"
dataIndex="CPU"
key="CPU"
render={(text, record: ListItem) => {
return (
<ProgressBar
percent={_.round(record?.status?.cpu?.utilization_rate, 0)}
></ProgressBar>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'resources.table.memory' })}
dataIndex="memory"
key="Memory"
render={(text, record: ListItem) => {
return (
<ProgressBar
percent={formateUtilazation(
record?.status?.memory?.used,
record?.status?.memory?.total
)}
label={
<InfoColumn
fieldList={fieldList}
data={record.status.memory}
></InfoColumn>
}
></ProgressBar>
);
}}
/>
<Column
title="GPU"
dataIndex="GPU"
key="GPU"
render={(text, record: ListItem) => {
return (
<span className="flex-column flex-gap-2">
{_.map(
_.sortBy(record?.status?.gpu_devices || [], ['index']),
(item: GPUDeviceItem, index: string) => {
return (
<span className="flex-center" key={index}>
<span
className="m-r-5"
style={{ display: 'flex', width: 25 }}
>
[{item.index}]
</span>
{item.core ? (
<ProgressBar
key={index}
percent={_.round(
item.core?.utilization_rate,
0
)}
></ProgressBar>
) : (
'-'
)}
</span>
);
}
)}
</span>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'resources.table.vram' })}
dataIndex="VRAM"
key="VRAM"
render={(text, record: ListItem, rIndex) => {
return (
<span className="flex-column flex-gap-2">
{_.map(
_.sortBy(record?.status?.gpu_devices || [], ['index']),
(item: GPUDeviceItem, index: number) => {
return (
<span key={index}>
<span className="flex-center">
<span
className="m-r-5"
style={{ display: 'flex', width: 25 }}
>
[{item.index}]
</span>
<ProgressBar
defaultOpen={
rIndex === 0 &&
index === 0 &&
dataSource.loadend &&
extraStatus.firstLoad
}
key={index}
percent={
item.memory?.used
? _.round(item.memory?.utilization_rate, 0)
: _.round(
(item.memory?.allocated /
item.memory?.total) *
100,
0
)
}
label={
<InfoColumn
fieldList={fieldList}
data={item.memory}
></InfoColumn>
}
></ProgressBar>
{item.memory.is_unified_memory && (
<Tooltip
title={intl.formatMessage({
id: 'resources.table.unified'
})}
>
<InfoCircleOutlined
className="m-l-5"
style={{ color: 'var(--ant-blue-5)' }}
/>
</Tooltip>
)}
</span>
</span>
);
}
)}
</span>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'resources.table.disk' })}
dataIndex="storage"
key="storage"
render={(text, record: ListItem, index) => {
return (
<ProgressBar
percent={calcStorage(record.status?.filesystem)}
label={renderStorageTooltip(record.status.filesystem)}
></ProgressBar>
);
}}
/>
<Column
title={intl.formatMessage({ id: 'common.table.operation' })}
key="operation"
render={(text, record: ListItem) => {
return (
<DropdownButtons
items={ActionList}
onSelect={(val) => handleSelect(val, record)}
></DropdownButtons>
);
}}
/>
</Table>
</ConfigProvider> </ConfigProvider>
<DeleteModal ref={modalRef}></DeleteModal> <DeleteModal ref={modalRef}></DeleteModal>
<UpdateLabels <UpdateLabels
@@ -0,0 +1,366 @@
import AutoTooltip from '@/components/auto-tooltip';
import DropdownButtons from '@/components/drop-down-buttons';
import { TooltipOverlayScroller } from '@/components/overlay-scroller';
import StatusTag from '@/components/status-tag';
import { modelSourceMap } from '@/pages/llmodels/config';
import { modelFileActions } from '@/pages/llmodels/config/button-actions';
import { convertFileSize } from '@/utils';
import {
CheckCircleFilled,
CopyOutlined,
InfoCircleOutlined
} from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Tag, Typography } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import dayjs from 'dayjs';
import _ from 'lodash';
import { useMemo } from 'react';
import styled from 'styled-components';
import {
ModelfileState,
ModelfileStateMap,
ModelfileStateMapValue
} from '../config';
import { ModelFile as ListItem } from '../config/types';
const { Paragraph } = Typography;
const TextWrapper = styled.div`
display: flex;
align-items: center;
cursor: pointer;
height: 100%;
`;
const PathWrapper = styled.div`
display: flex;
align-items: center;
justify-content: flex-start;
height: 100%;
&::after {
content: '';
display: block;
width: 20px;
height: 100%;
position: absolute;
top: 0;
right: 0;
z-index: 1;
}
.btn-wrapper {
display: flex;
opacity: 0;
width: 0;
align-items: center;
}
&:hover {
.btn-wrapper {
width: auto;
opacity: 1;
}
}
`;
const FilesTag = styled(Tag)`
cursor: pointer;
display: flex;
align-items: center;
margin-inline: 4px 0;
height: 22px;
border-radius: var(--border-radius-base);
`;
const TypographyPara = styled(Paragraph)`
background: transparent;
color: inherit;
margin-bottom: 0;
font-size: 13px;
`;
const ItemWrapper = styled.ul`
max-width: 300px;
margin: 0;
padding-inline: 13px 0;
word-break: break-word;
li {
line-height: 1.6;
}
`;
const getResolvedPath = (pathList: string[]) => {
return _.split(pathList?.[0], /[\\/]/).pop();
};
const setActionList = (record: ListItem) => {
return _.filter(modelFileActions, (item: { key: string }) => {
if (item.key === 'deploy') {
return record.state === ModelfileStateMap.Ready;
}
return true;
});
};
const TooltipTitle: React.FC<{ path: string }> = ({ path }) => {
const intl = useIntl();
return (
<TypographyPara
style={{ margin: 0 }}
copyable={{
icon: [
<CopyOutlined key="copy-icon" />,
<CheckCircleFilled key="copied-icon" />
],
text: path,
tooltips: [
intl.formatMessage({ id: 'common.button.copy' }),
intl.formatMessage({ id: 'common.button.copied' })
]
}}
>
{path}
</TypographyPara>
);
};
const InstanceStatusTag = (props: { data: ListItem }) => {
const { data } = props;
if (!data.state) {
return null;
}
return (
<StatusTag
download={
data.state === ModelfileStateMap.Downloading
? { percent: data.download_progress }
: undefined
}
statusValue={{
status:
data.state === ModelfileStateMap.Downloading &&
data.download_progress === 100
? ModelfileState[ModelfileStateMap.Ready]
: ModelfileState[data.state],
text: ModelfileStateMapValue[data.state],
message:
data.state === ModelfileStateMap.Downloading &&
data.download_progress === 100
? ''
: data.state_message
}}
/>
);
};
const getModelInfo = (record: ListItem) => {
const source = _.get(modelSourceMap, record.source, '');
if (record.source === modelSourceMap.huggingface_value) {
return {
source: `${source}/${record.huggingface_repo_id}`,
repo_id: record.huggingface_repo_id,
title: `${record.huggingface_repo_id}/${record.huggingface_filename}`,
filename: record.huggingface_filename || record.huggingface_repo_id
};
}
if (record.source === modelSourceMap.modelscope_value) {
return {
source: `${source}/${record.model_scope_model_id}`,
repo_id: record.model_scope_model_id,
title: `${record.model_scope_model_id}/${record.model_scope_file_path}`,
filename: record.model_scope_file_path || record.model_scope_model_id
};
}
if (record.source === modelSourceMap.ollama_library_value) {
return {
source: `${source}/${record.ollama_library_model_name}`,
repo_id: record.ollama_library_model_name,
title: record.ollama_library_model_name,
filename: record.ollama_library_model_name
};
}
return {
source: `${source}${record.local_path}`,
repo_id: record.local_path,
title: record.local_path,
filename: _.split(record.local_path, /[\\/]/).pop()
};
};
const RenderParts = (props: { record: ListItem }) => {
const { record } = props;
const intl = useIntl();
const parts = record.resolved_paths || [];
if (parts.length <= 1) {
return null;
}
const renderItem = () => {
return (
<ItemWrapper>
{parts.map((item: string, index: number) => {
return <li key={index}>{_.split(item, /[\\/]/).pop()}</li>;
})}
</ItemWrapper>
);
};
return (
<TooltipOverlayScroller title={renderItem()}>
<FilesTag color="purple" icon={<InfoCircleOutlined />}>
<span style={{ opacity: 1 }}>
{record.resolved_paths?.length}{' '}
{intl.formatMessage({ id: 'models.form.files' })}
</span>
</FilesTag>
</TooltipOverlayScroller>
);
};
const ResolvedPathColumn = (props: { record: ListItem }) => {
const { record } = props;
const intl = useIntl();
if (
!record.resolved_paths.length &&
record.state === ModelfileStateMap.Downloading
) {
return (
<span>
{intl.formatMessage({
id: 'resources.modelfiles.storagePath.holder'
})}
</span>
);
}
return (
record.resolved_paths?.length > 0 && (
<PathWrapper>
<TextWrapper>
<AutoTooltip
ghost
showTitle
title={
<TooltipTitle path={record.resolved_paths?.[0]}></TooltipTitle>
}
>
<span>{getResolvedPath(record.resolved_paths)}</span>
</AutoTooltip>
</TextWrapper>
<RenderParts record={record}></RenderParts>
</PathWrapper>
)
);
};
const getWorkerName = (
id: number,
workersList: Global.BaseOption<number>[]
) => {
const worker = workersList.find((item) => item.value === id);
return worker?.label || '';
};
const useFilesColumns = (props: {
handleSelect: (action: string, record: ListItem) => void;
workersList: Global.BaseOption<number>[];
}): ColumnsType<ListItem> => {
const { workersList, handleSelect } = props;
const intl = useIntl();
return useMemo(() => {
return [
{
title: intl.formatMessage({ id: 'models.form.source' }),
dataIndex: 'source',
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => {
const modelInfo = getModelInfo(record);
const { repo_id, source } = modelInfo;
return (
<TextWrapper style={{ paddingRight: 8 }}>
<AutoTooltip ghost title={source}>
{source}
</AutoTooltip>
</TextWrapper>
);
}
},
{
title: 'Worker',
dataIndex: 'worker_name',
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => {
return (
<AutoTooltip ghost>
<span>{getWorkerName(record.worker_id, workersList)}</span>
</AutoTooltip>
);
}
},
{
title: intl.formatMessage({ id: 'common.table.status' }),
dataIndex: 'state',
width: 132,
render: (text: string, record: ListItem) => {
return <InstanceStatusTag data={record} />;
}
},
{
title: intl.formatMessage({ id: 'resources.modelfiles.form.path' }),
dataIndex: 'resolved_paths',
width: '30%',
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => (
<ResolvedPathColumn record={record} />
)
},
{
title: intl.formatMessage({ id: 'resources.modelfiles.size' }),
dataIndex: 'size',
width: 110,
align: 'right',
ellipsis: {
showTitle: false
},
render: (text: string, record: ListItem) => {
return (
<AutoTooltip ghost>
<span>{convertFileSize(record.size, 1, true)}</span>
</AutoTooltip>
);
}
},
{
title: intl.formatMessage({ id: 'common.table.createTime' }),
dataIndex: 'created_at',
sorter: false,
width: 180,
ellipsis: {
showTitle: false
},
render: (text: number) => (
<AutoTooltip ghost minWidth={20}>
{dayjs(text).format('YYYY-MM-DD HH:mm:ss')}
</AutoTooltip>
)
},
{
title: intl.formatMessage({ id: 'common.table.operation' }),
dataIndex: 'operation',
width: 120,
render: (text: string, record: ListItem) => (
<DropdownButtons
items={setActionList(record)}
onSelect={(val) => handleSelect(val, record)}
></DropdownButtons>
)
}
];
}, [workersList, handleSelect]);
};
export default useFilesColumns;
@@ -0,0 +1,138 @@
import AutoTooltip from '@/components/auto-tooltip';
import ProgressBar from '@/components/progress-bar';
import InfoColumn from '@/components/simple-table/info-column';
import { convertFileSize } from '@/utils';
import { useIntl } from '@umijs/max';
import { ColumnsType } from 'antd/lib/table';
import _ from 'lodash';
import { useMemo } from 'react';
import { GPUDeviceItem } from '../config/types';
const fieldList = [
{
label: 'resources.table.total',
key: 'total',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
},
{
label: 'resources.table.used',
key: 'used',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
},
{
label: 'resources.table.allocated',
key: 'allocated',
locale: true,
render: (val: any) => {
return convertFileSize(val, 0);
}
}
];
const useGPUColumns = (props: {
loadend: boolean;
firstLoad: boolean;
clusterList: Global.BaseOption<number>[];
}): ColumnsType<GPUDeviceItem> => {
const { clusterList, loadend, firstLoad } = props;
const intl = useIntl();
return useMemo(() => {
return [
{
title: intl.formatMessage({ id: 'common.table.name' }),
dataIndex: 'name',
width: 240,
render: (text: string, record: GPUDeviceItem) => (
<AutoTooltip ghost maxWidth={240}>
{text}
</AutoTooltip>
)
},
{
title: intl.formatMessage({ id: 'resources.table.index' }),
dataIndex: 'index',
render: (text: string, record: GPUDeviceItem) => <span>{text}</span>
},
{
title: intl.formatMessage({ id: 'clusters.title' }),
dataIndex: 'cluster_id',
render: (text: number, record: GPUDeviceItem) => (
<AutoTooltip ghost>
{clusterList.find((item) => item.value === text)?.label}
</AutoTooltip>
)
},
{
title: intl.formatMessage({ id: 'resources.table.workername' }),
dataIndex: 'worker_name',
render: (text: string, record: GPUDeviceItem) => (
<AutoTooltip ghost>{text}</AutoTooltip>
)
},
{
title: intl.formatMessage({ id: 'resources.table.vender' }),
dataIndex: 'vendor'
},
{
title: `${intl.formatMessage({ id: 'resources.table.temperature' })} (°C)`,
dataIndex: 'temperature',
render: (text: number, record: GPUDeviceItem) => (
<span>{text ? _.round(text, 1) : '-'}</span>
)
},
{
title: `${intl.formatMessage({ id: 'resources.table.utilization' })}`,
dataIndex: 'gpuUtil',
key: 'gpuUtil',
render: (text: number, record: GPUDeviceItem) => {
return (
<>
{record.core ? (
<ProgressBar
percent={_.round(record.core?.utilization_rate, 2)}
></ProgressBar>
) : (
'-'
)}
</>
);
}
},
{
title: intl.formatMessage({ id: 'resources.table.vramutilization' }),
dataIndex: 'VRAM',
key: 'VRAM',
render: (text: number, record: GPUDeviceItem, index: number) => {
return (
<ProgressBar
defaultOpen={index === 0 && loadend && firstLoad}
percent={
record.memory?.used
? _.round(record.memory?.utilization_rate, 0)
: _.round(
record.memory?.allocated / record.memory?.total,
0
) * 100
}
label={
<InfoColumn
fieldList={fieldList}
data={record.memory}
></InfoColumn>
}
></ProgressBar>
);
}
}
];
}, [clusterList, loadend, firstLoad]);
};
export default useGPUColumns;
@@ -0,0 +1,318 @@
import AutoTooltip from '@/components/auto-tooltip';
import DropdownButtons from '@/components/drop-down-buttons';
import IconFont from '@/components/icon-font';
import ProgressBar from '@/components/progress-bar';
import InfoColumn from '@/components/simple-table/info-column';
import StatusTag from '@/components/status-tag';
import { convertFileSize } from '@/utils';
import {
CodeOutlined,
DeleteOutlined,
EditOutlined,
InfoCircleOutlined
} from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Tooltip } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import _ from 'lodash';
import { useMemo } from 'react';
import styled from 'styled-components';
import { WorkerStatusMapValue, status } from '../config';
import { Filesystem, GPUDeviceItem, ListItem } from '../config/types';
const LabelsWrapper = styled.div`
display: flex;
flex-wrap: wrap;
gap: 6px;
`;
const ActionList = [
{ label: 'common.button.edit', key: 'edit', icon: <EditOutlined /> },
{
label: 'common.button.logs',
locale: false,
key: 'logs',
icon: <IconFont type="icon-logs" />
},
{ label: 'Terminal', locale: false, key: 'terminal', icon: <CodeOutlined /> },
{
label: 'common.button.delete',
key: 'delete',
props: { danger: true },
icon: <DeleteOutlined />
}
];
const fieldList = [
{
label: 'resources.table.total',
key: 'total',
locale: true,
render: (val: any) => convertFileSize(val, 0)
},
{
label: 'resources.table.used',
key: 'used',
locale: true,
render: (val: any) => convertFileSize(val, 0)
},
{
label: 'resources.table.allocated',
key: 'allocated',
locale: true,
render: (val: any) => convertFileSize(val, 0)
}
];
const formateUtilization = (val1: number, val2: number): number =>
val1 && val2 ? _.round((val1 / val2) * 100, 0) : 0;
const calcStorage = (files: Filesystem[]) => {
const mountRoot = _.find(
files,
(item: Filesystem) => item.mount_point === '/'
);
return mountRoot ? formateUtilization(mountRoot.used, mountRoot.total) : 0;
};
const LabelsCell = ({ labels }: { labels: Record<string, any> }) => (
<LabelsWrapper>
{_.map(labels, (value: string, key: string) => (
<AutoTooltip
key={key}
className="m-r-0"
maxWidth={155}
style={{ paddingInline: 8, borderRadius: 12 }}
>
<span>{key}</span>
<span>:{value}</span>
</AutoTooltip>
))}
</LabelsWrapper>
);
const GPUCell = ({ devices }: { devices: GPUDeviceItem[] }) => (
<span className="flex-column flex-gap-2">
{_.map(
_.sortBy(devices || [], ['index']),
(item: GPUDeviceItem, index: number) => (
<span className="flex-center" key={index}>
<span className="m-r-5" style={{ display: 'flex', width: 25 }}>
[{item.index}]
</span>
{item.core ? (
<ProgressBar percent={_.round(item.core?.utilization_rate, 0)} />
) : (
'-'
)}
</span>
)
)}
</span>
);
const VRAMCell = ({
devices,
intl,
rIndex,
dataSource,
extraStatus
}: {
devices: GPUDeviceItem[];
intl: any;
rIndex: number;
dataSource: any;
extraStatus: any;
}) => (
<span className="flex-column flex-gap-2">
{_.map(
_.sortBy(devices || [], ['index']),
(item: GPUDeviceItem, index: number) => (
<span key={index} className="flex-center">
<span className="m-r-5" style={{ display: 'flex', width: 25 }}>
[{item.index}]
</span>
<ProgressBar
defaultOpen={
rIndex === 0 &&
index === 0 &&
dataSource.loadend &&
extraStatus.firstLoad
}
percent={
item.memory?.used
? _.round(item.memory?.utilization_rate, 0)
: _.round(
(item.memory?.allocated / item.memory?.total) * 100,
0
)
}
label={<InfoColumn fieldList={fieldList} data={item.memory} />}
/>
{item.memory.is_unified_memory && (
<Tooltip
title={intl.formatMessage({ id: 'resources.table.unified' })}
>
<InfoCircleOutlined
className="m-l-5"
style={{ color: 'var(--ant-blue-5)' }}
/>
</Tooltip>
)}
</span>
)
)}
</span>
);
const StorageCell = ({ files }: { files: Filesystem[] }) => {
const mountRoot = _.find(
files,
(item: Filesystem) => item.mount_point === '/'
);
return (
<ProgressBar
percent={calcStorage(files)}
label={
mountRoot ? (
<InfoColumn
fieldList={fieldList.filter((f) => f.key !== 'allocated')}
data={mountRoot}
/>
) : (
0
)
}
/>
);
};
const useWorkerColumns = ({
clusterData,
dataSource,
extraStatus,
handleSelect
}: {
clusterData: {
list: Global.BaseOption<number>[];
data: Record<number, string>;
};
dataSource: any;
extraStatus: any;
handleSelect: (action: string, record: ListItem) => void;
}): ColumnsType<ListItem> => {
const intl = useIntl();
return useMemo<ColumnsType<ListItem>>(
() => [
{
title: intl.formatMessage({ id: 'common.table.name' }),
dataIndex: 'name',
width: 100,
render: (text: string) => (
<AutoTooltip ghost maxWidth={240}>
{text}
</AutoTooltip>
)
},
{
title: intl.formatMessage({ id: 'resources.table.labels' }),
dataIndex: 'labels',
width: 200,
render: (_, record) => <LabelsCell labels={record.labels} />
},
{
title: intl.formatMessage({ id: 'clusters.title' }),
dataIndex: 'cluster_id',
render: (id: number) => (
<AutoTooltip ghost maxWidth={240}>
{_.get(clusterData.data, id, '')}
</AutoTooltip>
)
},
{
title: intl.formatMessage({ id: 'common.table.status' }),
dataIndex: 'state',
render: (_, record) => (
<StatusTag
maxTooltipWidth={400}
statusValue={{
status: status[record.state] as any,
text: WorkerStatusMapValue[record.state],
message: record.state_message
}}
/>
)
},
{
title: 'IP',
dataIndex: 'ip',
render: (text: string) => (
<AutoTooltip ghost maxWidth={240}>
{text}
</AutoTooltip>
)
},
{
title: 'CPU',
dataIndex: 'cpu',
render: (text: string, record) => (
<ProgressBar
percent={_.round(record?.status?.cpu?.utilization_rate, 0)}
/>
)
},
{
title: intl.formatMessage({ id: 'resources.table.memory' }),
dataIndex: 'memory',
render: (_, record) => (
<ProgressBar
percent={formateUtilization(
record?.status?.memory?.used,
record?.status?.memory?.total
)}
label={
<InfoColumn fieldList={fieldList} data={record.status.memory} />
}
/>
)
},
{
title: 'GPU',
dataIndex: 'gpu',
render: (_, record) => <GPUCell devices={record?.status?.gpu_devices} />
},
{
title: intl.formatMessage({ id: 'resources.table.vram' }),
dataIndex: 'vram',
render: (_, record, rIndex) => (
<VRAMCell
devices={record?.status?.gpu_devices}
intl={intl}
rIndex={rIndex}
dataSource={dataSource}
extraStatus={extraStatus}
/>
)
},
{
title: intl.formatMessage({ id: 'resources.table.disk' }),
dataIndex: 'storage',
render: (_, record) => <StorageCell files={record.status?.filesystem} />
},
{
title: intl.formatMessage({ id: 'common.table.operation' }),
key: 'operation',
render: (_, record) => (
<DropdownButtons
items={ActionList}
onSelect={(val) => handleSelect(val, record)}
/>
)
}
],
[intl, clusterData, dataSource, extraStatus, handleSelect]
);
};
export default useWorkerColumns;