File size: 22,338 Bytes
8c7ba7b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 |
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useEffect, useRef } from 'react';
import {
Modal,
Button,
Typography,
Select,
Input,
Space,
Spin,
Card,
Tag,
Empty,
Switch,
Divider,
Tooltip,
Radio,
} from '@douyinfe/semi-ui';
import {
FaCopy,
FaSearch,
FaClock,
FaTerminal,
FaServer,
FaInfoCircle,
FaLink,
} from 'react-icons/fa';
import { IconRefresh, IconDownload } from '@douyinfe/semi-icons';
import { API, showError, showSuccess, copy, timestamp2string } from '../../../../helpers';
const { Text } = Typography;
const ALL_CONTAINERS = '__all__';
const ViewLogsModal = ({
visible,
onCancel,
deployment,
t
}) => {
const [logLines, setLogLines] = useState([]);
const [loading, setLoading] = useState(false);
const [autoRefresh, setAutoRefresh] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
const [following, setFollowing] = useState(false);
const [containers, setContainers] = useState([]);
const [containersLoading, setContainersLoading] = useState(false);
const [selectedContainerId, setSelectedContainerId] = useState(ALL_CONTAINERS);
const [containerDetails, setContainerDetails] = useState(null);
const [containerDetailsLoading, setContainerDetailsLoading] = useState(false);
const [streamFilter, setStreamFilter] = useState('stdout');
const [lastUpdatedAt, setLastUpdatedAt] = useState(null);
const logContainerRef = useRef(null);
const autoRefreshRef = useRef(null);
// Auto scroll to bottom when new logs arrive
const scrollToBottom = () => {
if (logContainerRef.current) {
logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
}
};
const resolveStreamValue = (value) => {
if (typeof value === 'string') {
return value;
}
if (value && typeof value.value === 'string') {
return value.value;
}
if (value && value.target && typeof value.target.value === 'string') {
return value.target.value;
}
return '';
};
const handleStreamChange = (value) => {
const next = resolveStreamValue(value) || 'stdout';
setStreamFilter(next);
};
const fetchLogs = async (containerIdOverride = undefined) => {
if (!deployment?.id) return;
const containerId = typeof containerIdOverride === 'string' ? containerIdOverride : selectedContainerId;
if (!containerId || containerId === ALL_CONTAINERS) {
setLogLines([]);
setLastUpdatedAt(null);
setLoading(false);
return;
}
setLoading(true);
try {
const params = new URLSearchParams();
params.append('container_id', containerId);
const streamValue = resolveStreamValue(streamFilter) || 'stdout';
if (streamValue && streamValue !== 'all') {
params.append('stream', streamValue);
}
if (following) params.append('follow', 'true');
const response = await API.get(`/api/deployments/${deployment.id}/logs?${params}`);
if (response.data.success) {
const rawContent = typeof response.data.data === 'string' ? response.data.data : '';
const normalized = rawContent.replace(/\r\n?/g, '\n');
const lines = normalized ? normalized.split('\n') : [];
setLogLines(lines);
setLastUpdatedAt(new Date());
setTimeout(scrollToBottom, 100);
}
} catch (error) {
showError(t('获取日志失败') + ': ' + (error.response?.data?.message || error.message));
} finally {
setLoading(false);
}
};
const fetchContainers = async () => {
if (!deployment?.id) return;
setContainersLoading(true);
try {
const response = await API.get(`/api/deployments/${deployment.id}/containers`);
if (response.data.success) {
const list = response.data.data?.containers || [];
setContainers(list);
setSelectedContainerId((current) => {
if (current !== ALL_CONTAINERS && list.some(item => item.container_id === current)) {
return current;
}
return list.length > 0 ? list[0].container_id : ALL_CONTAINERS;
});
if (list.length === 0) {
setContainerDetails(null);
}
}
} catch (error) {
showError(t('获取容器列表失败') + ': ' + (error.response?.data?.message || error.message));
} finally {
setContainersLoading(false);
}
};
const fetchContainerDetails = async (containerId) => {
if (!deployment?.id || !containerId || containerId === ALL_CONTAINERS) {
setContainerDetails(null);
return;
}
setContainerDetailsLoading(true);
try {
const response = await API.get(`/api/deployments/${deployment.id}/containers/${containerId}`);
if (response.data.success) {
setContainerDetails(response.data.data || null);
}
} catch (error) {
showError(t('获取容器详情失败') + ': ' + (error.response?.data?.message || error.message));
} finally {
setContainerDetailsLoading(false);
}
};
const handleContainerChange = (value) => {
const newValue = value || ALL_CONTAINERS;
setSelectedContainerId(newValue);
setLogLines([]);
setLastUpdatedAt(null);
};
const refreshContainerDetails = () => {
if (selectedContainerId && selectedContainerId !== ALL_CONTAINERS) {
fetchContainerDetails(selectedContainerId);
}
};
const renderContainerStatusTag = (status) => {
if (!status) {
return (
<Tag color="grey" size="small">
{t('未知状态')}
</Tag>
);
}
const normalized = typeof status === 'string' ? status.trim().toLowerCase() : '';
const statusMap = {
running: { color: 'green', label: '运行中' },
pending: { color: 'orange', label: '准备中' },
deployed: { color: 'blue', label: '已部署' },
failed: { color: 'red', label: '失败' },
destroyed: { color: 'red', label: '已销毁' },
stopping: { color: 'orange', label: '停止中' },
terminated: { color: 'grey', label: '已终止' },
};
const config = statusMap[normalized] || { color: 'grey', label: status };
return (
<Tag color={config.color} size="small">
{t(config.label)}
</Tag>
);
};
const currentContainer = selectedContainerId !== ALL_CONTAINERS
? containers.find((ctr) => ctr.container_id === selectedContainerId)
: null;
const refreshLogs = () => {
if (selectedContainerId && selectedContainerId !== ALL_CONTAINERS) {
fetchContainerDetails(selectedContainerId);
}
fetchLogs();
};
const downloadLogs = () => {
const sourceLogs = filteredLogs.length > 0 ? filteredLogs : logLines;
if (sourceLogs.length === 0) {
showError(t('暂无日志可下载'));
return;
}
const logText = sourceLogs.join('\n');
const blob = new Blob([logText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const safeContainerId = selectedContainerId && selectedContainerId !== ALL_CONTAINERS
? selectedContainerId.replace(/[^a-zA-Z0-9_-]/g, '-')
: '';
const fileName = safeContainerId
? `deployment-${deployment.id}-container-${safeContainerId}-logs.txt`
: `deployment-${deployment.id}-logs.txt`;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showSuccess(t('日志已下载'));
};
const copyAllLogs = async () => {
const sourceLogs = filteredLogs.length > 0 ? filteredLogs : logLines;
if (sourceLogs.length === 0) {
showError(t('暂无日志可复制'));
return;
}
const logText = sourceLogs.join('\n');
const copied = await copy(logText);
if (copied) {
showSuccess(t('日志已复制到剪贴板'));
} else {
showError(t('复制失败,请手动选择文本复制'));
}
};
// Auto refresh functionality
useEffect(() => {
if (autoRefresh && visible) {
autoRefreshRef.current = setInterval(() => {
fetchLogs();
}, 5000);
} else {
if (autoRefreshRef.current) {
clearInterval(autoRefreshRef.current);
autoRefreshRef.current = null;
}
}
return () => {
if (autoRefreshRef.current) {
clearInterval(autoRefreshRef.current);
}
};
}, [autoRefresh, visible, selectedContainerId, streamFilter, following]);
useEffect(() => {
if (visible && deployment?.id) {
fetchContainers();
} else if (!visible) {
setContainers([]);
setSelectedContainerId(ALL_CONTAINERS);
setContainerDetails(null);
setStreamFilter('stdout');
setLogLines([]);
setLastUpdatedAt(null);
}
}, [visible, deployment?.id]);
useEffect(() => {
if (visible) {
setStreamFilter('stdout');
}
}, [selectedContainerId, visible]);
useEffect(() => {
if (visible && deployment?.id) {
fetchContainerDetails(selectedContainerId);
}
}, [visible, deployment?.id, selectedContainerId]);
// Initial load and cleanup
useEffect(() => {
if (visible && deployment?.id) {
fetchLogs();
}
return () => {
if (autoRefreshRef.current) {
clearInterval(autoRefreshRef.current);
}
};
}, [visible, deployment?.id, streamFilter, selectedContainerId, following]);
// Filter logs based on search term
const filteredLogs = logLines
.map((line) => line ?? '')
.filter((line) =>
!searchTerm || line.toLowerCase().includes(searchTerm.toLowerCase()),
);
const renderLogEntry = (line, index) => (
<div
key={`${index}-${line.slice(0, 20)}`}
className="py-1 px-3 hover:bg-gray-50 font-mono text-sm border-b border-gray-100 whitespace-pre-wrap break-words"
>
{line}
</div>
);
return (
<Modal
title={
<div className="flex items-center gap-2">
<FaTerminal className="text-blue-500" />
<span>{t('容器日志')}</span>
<Text type="secondary" size="small">
- {deployment?.container_name || deployment?.id}
</Text>
</div>
}
visible={visible}
onCancel={onCancel}
footer={null}
width={1000}
height={700}
className="logs-modal"
style={{ top: 20 }}
>
<div className="flex flex-col h-full max-h-[600px]">
{/* Controls */}
<Card className="mb-4 border-0 shadow-sm">
<div className="flex items-center justify-between flex-wrap gap-3">
<Space wrap>
<Select
prefix={<FaServer />}
placeholder={t('选择容器')}
value={selectedContainerId}
onChange={handleContainerChange}
style={{ width: 240 }}
size="small"
loading={containersLoading}
dropdownStyle={{ maxHeight: 320, overflowY: 'auto' }}
>
<Select.Option value={ALL_CONTAINERS}>
{t('全部容器')}
</Select.Option>
{containers.map((ctr) => (
<Select.Option key={ctr.container_id} value={ctr.container_id}>
<div className="flex flex-col">
<span className="font-mono text-xs">{ctr.container_id}</span>
<span className="text-xs text-gray-500">
{ctr.brand_name || 'IO.NET'}
{ctr.hardware ? ` · ${ctr.hardware}` : ''}
</span>
</div>
</Select.Option>
))}
</Select>
<Input
prefix={<FaSearch />}
placeholder={t('搜索日志内容')}
value={searchTerm}
onChange={setSearchTerm}
style={{ width: 200 }}
size="small"
/>
<Space align="center" className="ml-2">
<Text size="small" type="secondary">
{t('日志流')}
</Text>
<Radio.Group
type="button"
size="small"
value={streamFilter}
onChange={handleStreamChange}
>
<Radio value="stdout">STDOUT</Radio>
<Radio value="stderr">STDERR</Radio>
</Radio.Group>
</Space>
<div className="flex items-center gap-2">
<Switch
checked={autoRefresh}
onChange={setAutoRefresh}
size="small"
/>
<Text size="small">{t('自动刷新')}</Text>
</div>
<div className="flex items-center gap-2">
<Switch
checked={following}
onChange={setFollowing}
size="small"
/>
<Text size="small">{t('跟随日志')}</Text>
</div>
</Space>
<Space>
<Tooltip content={t('刷新日志')}>
<Button
icon={<IconRefresh />}
onClick={refreshLogs}
loading={loading}
size="small"
theme="borderless"
/>
</Tooltip>
<Tooltip content={t('复制日志')}>
<Button
icon={<FaCopy />}
onClick={copyAllLogs}
size="small"
theme="borderless"
disabled={logLines.length === 0}
/>
</Tooltip>
<Tooltip content={t('下载日志')}>
<Button
icon={<IconDownload />}
onClick={downloadLogs}
size="small"
theme="borderless"
disabled={logLines.length === 0}
/>
</Tooltip>
</Space>
</div>
{/* Status Info */}
<Divider margin="12px" />
<div className="flex items-center justify-between">
<Space size="large">
<Text size="small" type="secondary">
{t('共 {{count}} 条日志', { count: logLines.length })}
</Text>
{searchTerm && (
<Text size="small" type="secondary">
{t('(筛选后显示 {{count}} 条)', { count: filteredLogs.length })}
</Text>
)}
{autoRefresh && (
<Tag color="green" size="small">
<FaClock className="mr-1" />
{t('自动刷新中')}
</Tag>
)}
</Space>
<Text size="small" type="secondary">
{t('状态')}: {deployment?.status || 'unknown'}
</Text>
</div>
{selectedContainerId !== ALL_CONTAINERS && (
<>
<Divider margin="12px" />
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between flex-wrap gap-2">
<Space>
<Tag color="blue" size="small">
{t('容器')}
</Tag>
<Text className="font-mono text-xs">
{selectedContainerId}
</Text>
{renderContainerStatusTag(containerDetails?.status || currentContainer?.status)}
</Space>
<Space>
{containerDetails?.public_url && (
<Tooltip content={containerDetails.public_url}>
<Button
icon={<FaLink />}
size="small"
theme="borderless"
onClick={() => window.open(containerDetails.public_url, '_blank')}
/>
</Tooltip>
)}
<Tooltip content={t('刷新容器信息')}>
<Button
icon={<IconRefresh />}
onClick={refreshContainerDetails}
size="small"
theme="borderless"
loading={containerDetailsLoading}
/>
</Tooltip>
</Space>
</div>
{containerDetailsLoading ? (
<div className="flex items-center justify-center py-6">
<Spin tip={t('加载容器详情中...')} />
</div>
) : containerDetails ? (
<div className="grid gap-4 md:grid-cols-2 text-sm">
<div className="flex items-center gap-2">
<FaInfoCircle className="text-blue-500" />
<Text type="secondary">{t('硬件')}</Text>
<Text>
{containerDetails?.brand_name || currentContainer?.brand_name || t('未知品牌')}
{(containerDetails?.hardware || currentContainer?.hardware) ? ` · ${containerDetails?.hardware || currentContainer?.hardware}` : ''}
</Text>
</div>
<div className="flex items-center gap-2">
<FaServer className="text-purple-500" />
<Text type="secondary">{t('GPU/容器')}</Text>
<Text>{containerDetails?.gpus_per_container ?? currentContainer?.gpus_per_container ?? 0}</Text>
</div>
<div className="flex items-center gap-2">
<FaClock className="text-orange-500" />
<Text type="secondary">{t('创建时间')}</Text>
<Text>
{containerDetails?.created_at
? timestamp2string(containerDetails.created_at)
: currentContainer?.created_at
? timestamp2string(currentContainer.created_at)
: t('未知')}
</Text>
</div>
<div className="flex items-center gap-2">
<FaInfoCircle className="text-green-500" />
<Text type="secondary">{t('运行时长')}</Text>
<Text>{containerDetails?.uptime_percent ?? currentContainer?.uptime_percent ?? 0}%</Text>
</div>
</div>
) : (
<Text size="small" type="secondary">
{t('暂无容器详情')}
</Text>
)}
{containerDetails?.events && containerDetails.events.length > 0 && (
<div className="bg-gray-50 rounded-lg p-3">
<Text size="small" type="secondary">
{t('最近事件')}
</Text>
<div className="mt-2 space-y-2 max-h-32 overflow-y-auto">
{containerDetails.events.slice(0, 5).map((event, index) => (
<div key={`${event.time}-${index}`} className="flex gap-3 text-xs font-mono">
<span className="text-gray-500">
{event.time ? timestamp2string(event.time) : '--'}
</span>
<span className="text-gray-700 break-all flex-1">
{event.message}
</span>
</div>
))}
</div>
</div>
)}
</div>
</>
)}
</Card>
{/* Log Content */}
<div className="flex-1 flex flex-col border rounded-lg bg-gray-50 overflow-hidden">
<div
ref={logContainerRef}
className="flex-1 overflow-y-auto bg-white"
style={{ maxHeight: '400px' }}
>
{loading && logLines.length === 0 ? (
<div className="flex items-center justify-center p-8">
<Spin tip={t('加载日志中...')} />
</div>
) : filteredLogs.length === 0 ? (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={
searchTerm ? t('没有匹配的日志条目') : t('暂无日志')
}
style={{ padding: '60px 20px' }}
/>
) : (
<div>
{filteredLogs.map((log, index) => renderLogEntry(log, index))}
</div>
)}
</div>
{/* Footer status */}
{logLines.length > 0 && (
<div className="flex items-center justify-between px-3 py-2 bg-gray-50 border-t text-xs text-gray-500">
<span>
{following ? t('正在跟随最新日志') : t('日志已加载')}
</span>
<span>
{t('最后更新')}: {lastUpdatedAt ? lastUpdatedAt.toLocaleTimeString() : '--'}
</span>
</div>
)}
</div>
</div>
</Modal>
);
};
export default ViewLogsModal;
|