1.30 k8s管理

This commit is contained in:
dengqichen 2025-12-14 01:10:34 +08:00
parent e54d6834c3
commit 4e87fc1b98
6 changed files with 465 additions and 61 deletions

View File

@ -8,6 +8,29 @@ export const calculateLineNumberWidth = (totalLines: number): number => {
return Math.max(4, String(totalLines).length + 1);
};
/**
* ANSI转义序列
*
* ANSI转义序列包括
* - CSI序列\u001b[<参数>m \u001b[39m
* - OSC序列\u001b]<参数>;<文本>BEL/ST
* -
*
* 使ANSI转义序列
*
* @param text - ANSI转义码的原始文本
* @returns
*/
export const stripAnsiCodes = (text: string): string => {
if (!text) return '';
// 匹配所有ANSI转义序列的通用正则表达式
// \u001b\u009b - ESC字符两种编码
// [[()#;?]* - 可选的前缀字符
// (?:[0-9]{1,4}(?:;[0-9]{0,4})*)? - 参数(数字和分号)
// [0-9A-ORZcf-nqry=><] - 命令字符
return text.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
};
/**
* Monaco显示文本
* | | |
@ -30,10 +53,10 @@ export const formatStructuredLogs = (logs: StructuredLog[]): string => {
/**
*
*
* ANSI转义码
*/
export const formatPlainText = (content: string): string => {
return content || '';
return stripAnsiCodes(content || '');
};
/**

View File

@ -41,6 +41,7 @@ const LogViewer: React.FC<LogViewerProps> = ({
autoScroll = true,
className,
monacoLayout,
fontSize = 12,
}) => {
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
const isStructuredMode = !!logs;
@ -109,7 +110,7 @@ const LogViewer: React.FC<LogViewerProps> = ({
scrollBeyondLastLine: false,
wordWrap: 'on',
automaticLayout: true,
fontSize: 12,
fontSize,
fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace",
lineNumbers: showLineNumbers ? 'on' : 'off',
glyphMargin: layoutConfig.glyphMargin,

View File

@ -67,4 +67,7 @@ export interface LogViewerProps {
/** Monaco Editor布局配置 */
monacoLayout?: MonacoLayoutConfig;
/** 字体大小默认12 */
fontSize?: number;
}

View File

@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useState, useRef } from 'react';
import {
Dialog,
DialogContent,
@ -9,11 +9,15 @@ import {
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FileText, RefreshCw, Download } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { FileText, RefreshCw, Download, ChevronUp, ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
import { getK8sPodLogs, getK8sPodDetail } from '../service';
import { getK8sPodLogs, getK8sPodsByDeployment } from '../service';
import { useToast } from '@/components/ui/use-toast';
import LogViewer from '@/components/LogViewer';
import type { K8sPodResponse, LogSelection } from '../types';
import { LOG_QUERY_CONSTANTS as LOG_CONSTANTS } from '../types';
interface PodLogDialogProps {
open: boolean;
@ -30,53 +34,156 @@ const PodLogDialog: React.FC<PodLogDialogProps> = ({
}) => {
const { toast } = useToast();
const [loading, setLoading] = useState(false);
const [loadingPod, setLoadingPod] = useState(false);
const [loadingPods, setLoadingPods] = useState(false);
const [logContent, setLogContent] = useState<string>('');
const [pods, setPods] = useState<K8sPodResponse[]>([]);
const [selectedPod, setSelectedPod] = useState<string>('');
const [selectedContainer, setSelectedContainer] = useState<string>('');
const [containers, setContainers] = useState<string[]>([]);
const [autoRefresh, setAutoRefresh] = useState(false);
const [refreshInterval, setRefreshInterval] = useState(5);
const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null);
const [autoScrollEnabled, setAutoScrollEnabled] = useState(true);
const [referenceForPrevious, setReferenceForPrevious] = useState<LogSelection | null>(null);
const [referenceForNext, setReferenceForNext] = useState<LogSelection | null>(null);
const [lastDisplayedTimestamp, setLastDisplayedTimestamp] = useState<string | null>(null);
const timerRef = useRef<NodeJS.Timeout | null>(null);
const referenceForNextRef = useRef<LogSelection | null>(null);
const lastDisplayedTimestampRef = useRef<string | null>(null);
// 打开对话框时获取Pod详情获取最新的容器列表
// 打开对话框时获取Deployment下的所有Pod
useEffect(() => {
if (open && deploymentId && podName) {
const fetchPodDetail = async () => {
setLoadingPod(true);
if (open && deploymentId) {
const fetchPods = async () => {
setLoadingPods(true);
try {
const pod = await getK8sPodDetail(deploymentId, podName);
const containerNames = pod.containers.map(c => c.name);
setContainers(containerNames);
if (containerNames.length > 0) {
setSelectedContainer(containerNames[0]);
const podList = await getK8sPodsByDeployment(deploymentId);
setPods(podList);
// 设置初始选中的Pod优先使用传入的podName
const initialPod = podList.find(p => p.name === podName) || podList[0];
if (initialPod) {
setSelectedPod(initialPod.name);
const containerNames = initialPod.containers.map(c => c.name);
setContainers(containerNames);
if (containerNames.length > 0) {
setSelectedContainer(containerNames[0]);
}
}
} catch (error: any) {
console.error('获取Pod详情失败:', error);
console.error('获取Pod列表失败:', error);
toast({
title: '获取Pod详情失败',
description: error.message || '无法获取Pod容器信息',
title: '获取Pod列表失败',
description: error.message || '无法获取Pod信息',
variant: 'destructive',
});
} finally {
setLoadingPod(false);
setLoadingPods(false);
}
};
fetchPodDetail();
fetchPods();
}
}, [open, deploymentId, podName]);
// 当选中的Pod变化时更新容器列表
useEffect(() => {
if (selectedPod && pods.length > 0) {
const pod = pods.find(p => p.name === selectedPod);
if (pod) {
const containerNames = pod.containers.map(c => c.name);
setContainers(containerNames);
if (containerNames.length > 0) {
setSelectedContainer(containerNames[0]);
}
}
}
}, [selectedPod, pods]);
const fetchLogs = async () => {
if (!deploymentId || !podName) return;
const fetchLogs = async (isManualRefresh: boolean = false) => {
if (!deploymentId || !selectedPod) return;
setLoading(true);
try {
// 如果有选中的容器,传递容器名;否则不传,让后端使用默认容器
const params: any = {
tail: 1000, // 获取最后1000行
container: selectedContainer,
};
if (selectedContainer) {
params.container = selectedContainer;
if (isManualRefresh || !referenceForNextRef.current) {
// 初始加载或手动刷新获取最新100行日志
params.referenceTimestamp = LOG_CONSTANTS.REFERENCE_NEWEST;
params.offsetFrom = LOG_CONSTANTS.INITIAL_OFFSET_FROM;
params.offsetTo = LOG_CONSTANTS.INITIAL_OFFSET_TO;
console.log('[初始加载] 请求参数:', params);
const response = await getK8sPodLogs(deploymentId, selectedPod, params);
console.log('[初始加载] 响应:', {
logsCount: response.logs.length,
referenceForPrevious: response.referenceForPrevious,
referenceForNext: response.referenceForNext,
});
// 格式化并显示初始日志
const formattedLogs = response.logs
.map(log => `${log.timestamp} ${log.content}`)
.join('\n');
setLogContent(formattedLogs || '暂无日志');
setReferenceForPrevious(response.referenceForPrevious);
setReferenceForNext(response.referenceForNext);
referenceForNextRef.current = response.referenceForNext;
// 记录最后显示的日志时间戳,用于去重
if (response.logs.length > 0) {
const lastTimestamp = response.logs[response.logs.length - 1].timestamp;
setLastDisplayedTimestamp(lastTimestamp);
lastDisplayedTimestampRef.current = lastTimestamp;
}
} else {
// 增量轮询使用referenceForNext获取新日志
const currentRef = referenceForNextRef.current;
if (!currentRef) return;
params.referenceTimestamp = currentRef.referenceTimestamp;
params.offsetFrom = currentRef.offsetFrom;
params.offsetTo = currentRef.offsetTo;
console.log('[轮询刷新] 请求参数:', params);
const response = await getK8sPodLogs(deploymentId, selectedPod, params);
console.log('[轮询刷新] 响应:', {
logsCount: response.logs.length,
referenceForNext: response.referenceForNext,
});
// 基于时间戳去重:只追加比最后显示时间戳更新的日志
if (response.logs && response.logs.length > 0) {
const uniqueLogs = lastDisplayedTimestampRef.current
? response.logs.filter(log => log.timestamp > lastDisplayedTimestampRef.current!)
: response.logs;
if (uniqueLogs.length > 0) {
const newLogs = uniqueLogs
.map(log => `${log.timestamp} ${log.content}`)
.join('\n');
setLogContent(prev => prev ? `${prev}\n${newLogs}` : newLogs);
// 更新最后显示的时间戳同时更新state和ref
const lastTimestamp = uniqueLogs[uniqueLogs.length - 1].timestamp;
setLastDisplayedTimestamp(lastTimestamp);
lastDisplayedTimestampRef.current = lastTimestamp;
}
}
// 无论是否有新日志都要更新referenceForNext用于下次轮询
setReferenceForNext(response.referenceForNext);
referenceForNextRef.current = response.referenceForNext;
}
const logs = await getK8sPodLogs(deploymentId, podName, params);
setLogContent(logs || '暂无日志');
setLastRefreshTime(new Date());
} catch (error: any) {
console.error('获取Pod日志失败:', error);
toast({
@ -84,19 +191,140 @@ const PodLogDialog: React.FC<PodLogDialogProps> = ({
description: error.message || '无法获取Pod日志',
variant: 'destructive',
});
setLogContent('获取日志失败');
if (isManualRefresh || !referenceForNextRef.current) {
setLogContent('获取日志失败');
}
} finally {
setLoading(false);
}
};
// 打开对话框或切换容器时加载日志
// 选中Pod或容器变化时加载日志
useEffect(() => {
if (open && selectedContainer) {
if (open && selectedPod && selectedContainer) {
setLogContent('');
setReferenceForPrevious(null);
setReferenceForNext(null);
setLastDisplayedTimestamp(null);
referenceForNextRef.current = null;
lastDisplayedTimestampRef.current = null;
fetchLogs();
}
}, [open, selectedContainer, deploymentId, podName]);
}, [open, selectedPod, selectedContainer, deploymentId]);
// 自动刷新轮询
useEffect(() => {
// 清理之前的定时器
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
// 启动新的定时器
if (autoRefresh && open && selectedPod && selectedContainer) {
timerRef.current = setInterval(() => {
fetchLogs();
}, refreshInterval * 1000);
}
// 清理函数
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
};
}, [autoRefresh, refreshInterval, open, selectedPod, selectedContainer]);
// 向前翻页(查看更早的日志)
const loadPreviousPage = async () => {
if (!referenceForPrevious || !deploymentId || !selectedPod) return;
setLoading(true);
try {
const params: any = {
container: selectedContainer,
referenceTimestamp: referenceForPrevious.referenceTimestamp,
offsetFrom: referenceForPrevious.offsetFrom,
offsetTo: referenceForPrevious.offsetTo,
};
console.log('[向前翻页] 请求参数:', params);
const response = await getK8sPodLogs(deploymentId, selectedPod, params);
console.log('[向前翻页] 响应:', {
logsCount: response.logs.length,
referenceForPrevious: response.referenceForPrevious,
});
if (response.logs && response.logs.length > 0) {
const newLogs = response.logs
.map(log => `${log.timestamp} ${log.content}`)
.join('\n');
// 在顶部插入日志
setLogContent(prev => prev ? `${newLogs}\n${prev}` : newLogs);
// 更新referenceForPrevious用于继续向前翻页
setReferenceForPrevious(response.referenceForPrevious);
}
} catch (error: any) {
console.error('加载历史日志失败:', error);
toast({
title: '加载失败',
description: error.message || '无法加载历史日志',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
// 向后翻页(手动获取更新的日志)
const loadNextPage = async () => {
if (!referenceForNext || !deploymentId || !selectedPod) return;
setLoading(true);
try {
const params: any = {
container: selectedContainer,
referenceTimestamp: referenceForNext.referenceTimestamp,
offsetFrom: referenceForNext.offsetFrom,
offsetTo: referenceForNext.offsetTo,
};
console.log('[向后翻页] 请求参数:', params);
const response = await getK8sPodLogs(deploymentId, selectedPod, params);
console.log('[向后翻页] 响应:', {
logsCount: response.logs.length,
referenceForNext: response.referenceForNext,
});
if (response.logs && response.logs.length > 0) {
const newLogs = response.logs
.map(log => `${log.timestamp} ${log.content}`)
.join('\n');
// 追加新日志
setLogContent(prev => prev ? `${prev}\n${newLogs}` : newLogs);
// 更新referenceForNext用于继续向后翻页
setReferenceForNext(response.referenceForNext);
}
setLastRefreshTime(new Date());
} catch (error: any) {
console.error('加载新日志失败:', error);
toast({
title: '加载失败',
description: error.message || '无法加载新日志',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
// 下载日志回调
const handleDownload = () => {
@ -112,12 +340,12 @@ const PodLogDialog: React.FC<PodLogDialogProps> = ({
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<FileText className="h-5 w-5 text-primary" />
Pod日志 - {podName}
: {selectedContainer || '加载中...'}
</DialogTitle>
</DialogHeader>
<DialogBody className="flex-1 flex flex-col min-h-0">
{loadingPod ? (
{loadingPods ? (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-2" />
@ -128,17 +356,19 @@ const PodLogDialog: React.FC<PodLogDialogProps> = ({
<LogViewer
content={logContent}
loading={loading && !logContent}
onRefresh={fetchLogs}
onRefresh={() => fetchLogs()}
onDownload={handleDownload}
theme="vs-dark"
autoScroll={true}
autoScroll={autoScrollEnabled}
showToolbar={true}
showLineNumbers={true}
fontSize={10}
customToolbar={
<div className="flex items-center justify-between">
{/* 左侧:容器选择器 */}
{/* 左侧:容器、Pod选择器和自动刷新控件 */}
<div className="flex items-center gap-4">
{containers.length > 1 ? (
{/* 容器选择器 */}
{containers.length > 1 && (
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">:</span>
<Select
@ -157,17 +387,105 @@ const PodLogDialog: React.FC<PodLogDialogProps> = ({
</SelectContent>
</Select>
</div>
) : containers.length === 1 ? (
<div className="flex items-center h-9">
<span className="text-sm text-muted-foreground">
: <span className="font-medium text-foreground">{containers[0]}</span>
</span>
)}
{/* Pod选择器 */}
{pods.length > 1 && (
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">Pod:</span>
<Select
value={selectedPod}
onValueChange={setSelectedPod}
>
<SelectTrigger className="w-64">
<SelectValue />
</SelectTrigger>
<SelectContent>
{pods.map((pod) => (
<SelectItem key={pod.name} value={pod.name}>
{pod.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : null}
)}
{/* 自动刷新开关 */}
<div className="flex items-center gap-2">
<Switch
id="auto-refresh"
checked={autoRefresh}
onCheckedChange={setAutoRefresh}
/>
<Label htmlFor="auto-refresh" className="text-sm text-muted-foreground cursor-pointer">
</Label>
</div>
{/* 自动滚动开关 */}
<div className="flex items-center gap-2">
<Switch
id="auto-scroll"
checked={autoScrollEnabled}
onCheckedChange={setAutoScrollEnabled}
/>
<Label htmlFor="auto-scroll" className="text-sm text-muted-foreground cursor-pointer">
</Label>
</div>
{/* 刷新间隔选择器 */}
{autoRefresh && (
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">:</span>
<Select
value={refreshInterval.toString()}
onValueChange={(value) => setRefreshInterval(Number(value))}
>
<SelectTrigger className="w-20 h-8 text-sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="3">3</SelectItem>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="30">30</SelectItem>
</SelectContent>
</Select>
</div>
)}
{/* 最后刷新时间 */}
{lastRefreshTime && (
<span className="text-xs text-muted-foreground">
: {lastRefreshTime.toLocaleTimeString()}
</span>
)}
</div>
{/* 右侧:操作按钮 */}
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={loadPreviousPage}
disabled={loading || !referenceForPrevious}
title="向前翻页(查看更早的日志)"
>
<ChevronUp className="h-4 w-4 mr-1" />
</Button>
<Button
variant="outline"
size="sm"
onClick={loadNextPage}
disabled={loading || !referenceForNext}
title="向后翻页(查看更新的日志)"
>
<ChevronDown className="h-4 w-4 mr-1" />
</Button>
<Button
variant="outline"
size="sm"
@ -180,7 +498,7 @@ const PodLogDialog: React.FC<PodLogDialogProps> = ({
<Button
variant="outline"
size="sm"
onClick={fetchLogs}
onClick={() => fetchLogs(true)}
disabled={loading}
>
<RefreshCw className={cn('h-4 w-4 mr-2', loading && 'animate-spin')} />

View File

@ -8,6 +8,8 @@ import type {
K8sSyncHistoryResponse,
K8sSyncHistoryQuery,
K8sPodResponse,
PodLogsQuery,
PodLogsResponse,
} from './types';
// ==================== K8S命名空间接口 ====================
@ -168,18 +170,13 @@ export const getK8sPodDetail = async (
// ==================== K8S日志接口 ====================
/**
* Pod日志
* Pod日志 -
*/
export const getK8sPodLogs = async (
deploymentId: number,
podName: string,
params?: {
container?: string;
tail?: number;
since?: string;
follow?: boolean;
}
): Promise<string> => {
params?: PodLogsQuery
): Promise<PodLogsResponse> => {
return request.get(`/api/v1/k8s-deployment/${deploymentId}/pods/${podName}/logs`, { params });
};

View File

@ -281,19 +281,81 @@ export interface K8sPodResponse {
// ==================== 日志相关 ====================
/**
* Pod日志查询参数
* -
*/
export interface LogSelection {
/** 引用点时间戳 */
referenceTimestamp: string;
/** 相对于引用点的起始偏移量(包含) */
offsetFrom: number;
/** 相对于引用点的结束偏移量(不包含) */
offsetTo: number;
}
/**
*
*/
export interface LogLine {
/** 日志时间戳RFC3339格式 */
timestamp: string;
/** 日志内容 */
content: string;
}
/**
* Pod日志响应
*/
export interface PodLogsResponse {
/** Pod名称 */
podName: string;
/** 容器名称 */
containerName: string;
/** 向前翻页的引用点 */
referenceForPrevious: LogSelection;
/** 向后翻页/轮询的引用点 */
referenceForNext: LogSelection;
/** 日志行数组 */
logs: LogLine[];
/** 是否被截断 */
truncated: boolean;
}
/**
* Pod日志查询参数 -
*/
export interface PodLogsQuery {
/** 容器名称 */
container?: string;
/** 显示最后N行 */
tail?: number;
/** 时间戳,显示此时间之后的日志 */
since?: string;
/** 是否实时跟踪 */
follow?: boolean;
/** 引用点时间戳("newest", "oldest", 或具体时间戳) */
referenceTimestamp?: string;
/** 相对于引用点的起始偏移量 */
offsetFrom?: number;
/** 相对于引用点的结束偏移量 */
offsetTo?: number;
}
/**
*
*/
export const LOG_QUERY_CONSTANTS = {
/** 引用点:最新日志 */
REFERENCE_NEWEST: 'newest' as const,
/** 引用点:最早日志 */
REFERENCE_OLDEST: 'oldest' as const,
/** 初始加载offsetFrom */
INITIAL_OFFSET_FROM: -100,
/** 初始加载offsetTo */
INITIAL_OFFSET_TO: 0,
/** 向前翻页offsetFrom */
PREVIOUS_OFFSET_FROM: -100,
/** 向前翻页offsetTo */
PREVIOUS_OFFSET_TO: 0,
/** 向后翻页/轮询offsetFrom */
NEXT_OFFSET_FROM: 1,
/** 向后翻页/轮询offsetTo */
NEXT_OFFSET_TO: 101,
} as const;
// ==================== 操作相关 ====================
/**