mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-29 14:04:46 +03:00
feat(nodes): add remote Xray and panel restart actions (#6970)
An operator running a master with sub-nodes could probe or update a node from the Nodes page but had to log in to the node, or SSH into it, to restart Xray or the panel (#6937). Add Restart Xray and Restart panel to the node actions, behind a confirmation. Xray restarts through the node runtime; the panel restart is a new Remote call that the node accepts with node-admin credentials, the authority that already covers updatePanel. Both are refused for a disabled node.
This commit is contained in:
@@ -83,12 +83,29 @@ export function useNodeMutations() {
|
||||
},
|
||||
});
|
||||
|
||||
const restartMut = useMutation({
|
||||
mutationFn: ({ id, target }: { id: number; target: 'xray' | 'panel' }) =>
|
||||
HttpUtil.post(
|
||||
`/panel/api/nodes/${target === 'xray' ? 'restartXray' : 'restartPanel'}/${id}`,
|
||||
undefined,
|
||||
{
|
||||
silent: true,
|
||||
timeout: 12000,
|
||||
},
|
||||
),
|
||||
retry: false,
|
||||
onSuccess: (msg) => {
|
||||
if (msg?.success) queryClient.invalidateQueries({ queryKey: keys.nodes.root() });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
create: (payload: Partial<NodeRecord>) => createMut.mutateAsync(payload),
|
||||
update: (id: number, payload: Partial<NodeRecord>) => updateMut.mutateAsync({ id, payload }),
|
||||
remove: (id: number) => removeMut.mutateAsync(id),
|
||||
setEnable: (id: number, enable: boolean) => setEnableMut.mutateAsync({ id, enable }),
|
||||
probe: (id: number) => probeMut.mutateAsync(id),
|
||||
restart: (id: number, target: 'xray' | 'panel') => restartMut.mutateAsync({ id, target }),
|
||||
updatePanels: (ids: number[], dev: boolean): Promise<Msg<NodeUpdateResult[]>> =>
|
||||
updatePanelsMut.mutateAsync({ ids, dev }),
|
||||
testConnection: async (payload: Partial<NodeRecord>): Promise<Msg<ProbeResult>> => {
|
||||
|
||||
@@ -1853,6 +1853,20 @@ export const sections: readonly Section[] = [
|
||||
summary: 'Probe an existing node, updating its cached health state.',
|
||||
params: [{ name: 'id', in: 'path', type: 'number', desc: 'Node ID.' }],
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/nodes/restartXray/:id',
|
||||
summary:
|
||||
'Restart Xray on one enabled, directly configured node. Active Xray connections are interrupted. Uses the node runtime and accepts admin, node-admin or node-sync credentials on the node. A stale heartbeat does not prevent the request.',
|
||||
params: [{ name: 'id', in: 'path', type: 'number', desc: 'Node ID.' }],
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/nodes/restartPanel/:id',
|
||||
summary:
|
||||
'Request a restart of the panel and subscription services on one enabled, directly configured node. Requires admin or node-admin credentials on the node; mTLS requires an explicit node-admin bearer token. Success acknowledges scheduling, before the three-second restart delay. A stale heartbeat does not prevent the request. Older nodes may reject node-admin access until upgraded.',
|
||||
params: [{ name: 'id', in: 'path', type: 'number', desc: 'Node ID.' }],
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/nodes/updatePanel',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Badge, Button, Card, Dropdown, Modal, Space, Switch, Table, Tag, Tooltip } from 'antd';
|
||||
import type { BadgeProps } from 'antd';
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
InfoCircleOutlined,
|
||||
MoreOutlined,
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
RightOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
TeamOutlined,
|
||||
@@ -42,8 +43,12 @@ interface NodeListProps {
|
||||
onToggleEnable: (node: NodeRecord, next: boolean) => void;
|
||||
onUpdateNode: (node: NodeRecord) => void;
|
||||
onUpdateSelected: () => void;
|
||||
onRestart: (node: NodeRecord, target: 'xray' | 'panel') => void;
|
||||
restartingIds?: ReadonlySet<number>;
|
||||
}
|
||||
|
||||
const noRestarts: ReadonlySet<number> = new Set();
|
||||
|
||||
function isUpdateEligible(n: NodeRecord): boolean {
|
||||
return !!n.enable && n.status === 'online';
|
||||
}
|
||||
@@ -187,6 +192,8 @@ export default function NodeList({
|
||||
onToggleEnable,
|
||||
onUpdateNode,
|
||||
onUpdateSelected,
|
||||
onRestart,
|
||||
restartingIds = noRestarts,
|
||||
}: NodeListProps) {
|
||||
const { t } = useTranslation();
|
||||
const relativeTime = useRelativeTime();
|
||||
@@ -195,6 +202,18 @@ export default function NodeList({
|
||||
const [statsNode, setStatsNode] = useState<NodeRow | null>(null);
|
||||
const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
|
||||
|
||||
const restartItems = useCallback(
|
||||
(node: NodeRecord) =>
|
||||
(['xray', 'panel'] as const).map((target) => ({
|
||||
key: `restart-${target}`,
|
||||
icon: <ReloadOutlined aria-hidden />,
|
||||
label: t(`pages.nodes.${target === 'xray' ? 'restartXray' : 'restartPanel'}`),
|
||||
disabled: !node.enable || !!node.transitive || restartingIds.has(node.id),
|
||||
onClick: () => onRestart(node, target),
|
||||
})),
|
||||
[t, onRestart, restartingIds],
|
||||
);
|
||||
|
||||
// Map a direct node's GUID to its display name so a transitive sub-node can show
|
||||
// which parent it is reached through (#4983); the master walks one level only.
|
||||
const nameByGuid = useMemo(() => {
|
||||
@@ -299,6 +318,14 @@ export default function NodeList({
|
||||
onClick={() => onEdit(record)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Dropdown trigger={['click']} menu={{ items: restartItems(record) }}>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<MoreOutlined aria-hidden />}
|
||||
aria-label={t('more')}
|
||||
/>
|
||||
</Dropdown>
|
||||
<Tooltip title={t('delete')}>
|
||||
<Button
|
||||
type="text"
|
||||
@@ -543,6 +570,7 @@ export default function NodeList({
|
||||
onEdit,
|
||||
onDelete,
|
||||
onUpdateNode,
|
||||
restartItems,
|
||||
nameByGuid,
|
||||
],
|
||||
);
|
||||
@@ -673,6 +701,7 @@ export default function NodeList({
|
||||
placement="bottomRight"
|
||||
menu={{
|
||||
items: [
|
||||
...restartItems(record),
|
||||
{
|
||||
key: 'probe',
|
||||
label: (
|
||||
|
||||
@@ -88,6 +88,7 @@ export default function NodesPage() {
|
||||
fetchInbounds,
|
||||
probe,
|
||||
updatePanels,
|
||||
restart,
|
||||
} = useNodeMutations();
|
||||
|
||||
const { data: latestVersion = '' } = useQuery({
|
||||
@@ -103,6 +104,8 @@ export default function NodesPage() {
|
||||
const [formMode, setFormMode] = useState<'add' | 'edit'>('add');
|
||||
const [formNode, setFormNode] = useState<NodeRecord | null>(null);
|
||||
const [selectedIds, setSelectedIds] = useState<number[]>([]);
|
||||
const [restartingIds, setRestartingIds] = useState<ReadonlySet<number>>(new Set());
|
||||
const restartLocks = useRef(new Set<number>());
|
||||
const [mtlsOpen, setMtlsOpen] = useState(false);
|
||||
const [trustCa, setTrustCa] = useState('');
|
||||
const [copyingCa, setCopyingCa] = useState(false);
|
||||
@@ -199,6 +202,52 @@ export default function NodesPage() {
|
||||
[probe, t, messageApi, refetch],
|
||||
);
|
||||
|
||||
const onRestart = useCallback(
|
||||
(node: NodeRecord, target: 'xray' | 'panel') => {
|
||||
if (!node.enable || node.transitive || node.id <= 0 || restartLocks.current.has(node.id))
|
||||
return;
|
||||
restartLocks.current.add(node.id);
|
||||
const action = target === 'xray' ? 'restartXray' : 'restartPanel';
|
||||
let started = false;
|
||||
modal.confirm({
|
||||
title: t('pages.nodes.restartConfirmTitle', { name: node.name || String(node.id) }),
|
||||
content: t(`pages.nodes.${action}Content`),
|
||||
okText: t(`pages.nodes.${action}`),
|
||||
cancelText: t('cancel'),
|
||||
onCancel: () => {
|
||||
restartLocks.current.delete(node.id);
|
||||
},
|
||||
onOk: async () => {
|
||||
if (started) return;
|
||||
started = true;
|
||||
setRestartingIds((ids) => new Set(ids).add(node.id));
|
||||
try {
|
||||
const msg = await restart(node.id, target);
|
||||
if (msg?.success) {
|
||||
messageApi.success(
|
||||
t(
|
||||
`pages.nodes.toasts.${target === 'xray' ? 'xrayRestarted' : 'panelRestartAccepted'}`,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
messageApi.error(msg?.msg || t('somethingWentWrong'));
|
||||
}
|
||||
} catch (error) {
|
||||
messageApi.error(error instanceof Error ? error.message : t('somethingWentWrong'));
|
||||
} finally {
|
||||
restartLocks.current.delete(node.id);
|
||||
setRestartingIds((ids) => {
|
||||
const next = new Set(ids);
|
||||
next.delete(node.id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
[modal, t, restart, messageApi],
|
||||
);
|
||||
|
||||
const onToggleEnable = useCallback(
|
||||
async (node: NodeRecord, next: boolean) => {
|
||||
await setEnable(node.id, next);
|
||||
@@ -373,6 +422,8 @@ export default function NodesPage() {
|
||||
onToggleEnable={onToggleEnable}
|
||||
onUpdateNode={onUpdateNode}
|
||||
onUpdateSelected={onUpdateSelected}
|
||||
onRestart={onRestart}
|
||||
restartingIds={restartingIds}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
@@ -33,6 +33,7 @@ function renderList(isMobile: boolean) {
|
||||
onToggleEnable={noop}
|
||||
onUpdateNode={noop}
|
||||
onUpdateSelected={noop}
|
||||
onRestart={noop}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ describe('NodeList re-render', () => {
|
||||
onToggleEnable: noop,
|
||||
onUpdateNode: noop,
|
||||
onUpdateSelected: noop,
|
||||
onRestart: noop,
|
||||
};
|
||||
const view = render(<NodeList {...props} />, { wrapper });
|
||||
expect(updateChecks.count).toBeGreaterThan(0);
|
||||
|
||||
@@ -35,6 +35,7 @@ describe('NodeList desktop table row keys', () => {
|
||||
onToggleEnable={noop}
|
||||
onUpdateNode={noop}
|
||||
onUpdateSelected={noop}
|
||||
onRestart={noop}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ function renderSubNode(fields: Partial<NodeRecord>) {
|
||||
onToggleEnable={noop}
|
||||
onUpdateNode={noop}
|
||||
onUpdateSelected={noop}
|
||||
onRestart={noop}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ describe('node metric availability', () => {
|
||||
onToggleEnable={noop}
|
||||
onUpdateNode={noop}
|
||||
onUpdateSelected={noop}
|
||||
onRestart={noop}
|
||||
/>,
|
||||
);
|
||||
if (isMobile) fireEvent.click(screen.getByRole('button', { name: 'More Information' }));
|
||||
@@ -63,6 +64,7 @@ describe('node metric availability', () => {
|
||||
onToggleEnable={noop}
|
||||
onUpdateNode={noop}
|
||||
onUpdateSelected={noop}
|
||||
onRestart={noop}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('0.0%')).not.toBeNull();
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { ConfigProvider } from 'antd';
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import NodesPage from '@/pages/nodes/NodesPage';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import type { NodeRecord } from '@/schemas/node';
|
||||
import { renderWithProviders } from './test-utils';
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
isMobile: false,
|
||||
nodes: [] as NodeRecord[],
|
||||
refetch: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useMediaQuery', () => ({ useMediaQuery: () => ({ isMobile: state.isMobile }) }));
|
||||
vi.mock('@/api/queries/useNodesQuery', () => ({
|
||||
useNodesQuery: () => ({
|
||||
nodes: state.nodes,
|
||||
loading: false,
|
||||
fetched: true,
|
||||
fetchError: '',
|
||||
refetch: state.refetch,
|
||||
totals: {
|
||||
total: state.nodes.length,
|
||||
online: 0,
|
||||
offline: 1,
|
||||
avgLatency: 0,
|
||||
inbounds: 0,
|
||||
clients: 0,
|
||||
onlineClients: 0,
|
||||
depleted: 0,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock('@/pages/nodes/NodeFormModal', () => ({ default: () => null }));
|
||||
vi.mock('@/pages/nodes/NodeHistoryPanel', () => ({ default: () => null }));
|
||||
vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
|
||||
|
||||
beforeEach(() => {
|
||||
state.isMobile = false;
|
||||
state.nodes = [{ id: 7, name: 'edge-seven', guid: 'seven', enable: true, status: 'offline' }];
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', {}));
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
async function openRestart(label: string) {
|
||||
fireEvent.click(screen.getByRole('button', { name: /^more$/i }));
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: label }));
|
||||
return screen.findByRole('dialog');
|
||||
}
|
||||
|
||||
describe('remote node restart', () => {
|
||||
it.each([false, true])(
|
||||
'confirms each action and sends only the selected request (mobile=%s)',
|
||||
async (mobile) => {
|
||||
state.isMobile = mobile;
|
||||
const post = vi
|
||||
.spyOn(HttpUtil, 'post')
|
||||
.mockResolvedValue({ success: true, msg: '', obj: null });
|
||||
renderWithProviders(
|
||||
<ConfigProvider theme={{ token: { motion: false } }}>
|
||||
<NodesPage />
|
||||
</ConfigProvider>,
|
||||
);
|
||||
let dialog = await openRestart('Restart Xray');
|
||||
expect(dialog.textContent).toContain('edge-seven');
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
for (const [label, action, success] of [
|
||||
['Restart Xray', 'restartXray', 'Xray restarted on the node.'],
|
||||
[
|
||||
'Restart Panel',
|
||||
'restartPanel',
|
||||
'Panel restart request accepted. The node may be temporarily unavailable.',
|
||||
],
|
||||
]) {
|
||||
dialog = await openRestart(label);
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: label }));
|
||||
await screen.findByText(success);
|
||||
expect(post.mock.calls.at(-1)?.[0]).toBe(`/panel/api/nodes/${action}/7`);
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
}
|
||||
expect(post).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps both actions disabled while the request is pending and reports a node rejection without retrying', async () => {
|
||||
let finish!: (msg: Msg<never>) => void;
|
||||
const post = vi.spyOn(HttpUtil, 'post').mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
renderWithProviders(
|
||||
<ConfigProvider theme={{ token: { motion: false } }}>
|
||||
<NodesPage />
|
||||
</ConfigProvider>,
|
||||
);
|
||||
const dialog = await openRestart('Restart Panel');
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Restart Panel' }));
|
||||
await waitFor(() => expect(post).toHaveBeenCalledTimes(1));
|
||||
fireEvent.click(screen.getByRole('button', { name: /^more$/i }));
|
||||
for (const name of ['Restart Xray', 'Restart Panel']) {
|
||||
expect((await screen.findByRole('menuitem', { name })).getAttribute('aria-disabled')).toBe(
|
||||
'true',
|
||||
);
|
||||
}
|
||||
finish({ success: false, msg: 'remote permission denied', obj: null });
|
||||
await screen.findByText('remote permission denied');
|
||||
expect(post).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'does not offer restart for transitive nodes and disables it for disabled nodes (mobile=%s)',
|
||||
async (mobile) => {
|
||||
state.isMobile = mobile;
|
||||
state.nodes = [
|
||||
{ id: 0, name: 'child', guid: 'child', transitive: true, enable: true, status: 'online' },
|
||||
];
|
||||
const view = renderWithProviders(
|
||||
<ConfigProvider theme={{ token: { motion: false } }}>
|
||||
<NodesPage />
|
||||
</ConfigProvider>,
|
||||
);
|
||||
expect(screen.queryByRole('button', { name: /^more$/i })).toBeNull();
|
||||
view.unmount();
|
||||
state.nodes = [{ id: 7, name: 'disabled', enable: false }];
|
||||
renderWithProviders(
|
||||
<ConfigProvider theme={{ token: { motion: false } }}>
|
||||
<NodesPage />
|
||||
</ConfigProvider>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: /^more$/i }));
|
||||
for (const name of ['Restart Xray', 'Restart Panel']) {
|
||||
expect((await screen.findByRole('menuitem', { name })).getAttribute('aria-disabled')).toBe(
|
||||
'true',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user