MCPcopy
hub / github.com/dqzboy/Docker-Proxy / getContainersStatus

Function getContainersStatus

hubcmdui/services/dockerService.js:37–150  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

35
36// 修改其他Docker相关方法,添加更友好的错误处理
37async function getContainersStatus() {
38 const docker = await initDockerConnection();
39 if (!docker) {
40 logger.warn('[getContainersStatus] Cannot connect to Docker daemon, returning error indicator.');
41 // 返回带有特殊错误标记的数组,前端可以通过这个标记识别 Docker 不可用
42 return [{
43 id: 'n/a',
44 name: 'Docker 服务不可用',
45 image: 'n/a',
46 state: 'error',
47 status: 'Docker 服务未运行或无法连接',
48 error: 'DOCKER_UNAVAILABLE', // 特殊错误标记
49 cpu: 'N/A',
50 memory: 'N/A',
51 created: new Date().toLocaleString()
52 }];
53 }
54
55 let containers = [];
56 try {
57 containers = await docker.listContainers({ all: true });
58 logger.info(`[getContainersStatus] Found ${containers.length} containers.`);
59 } catch (listError) {
60 logger.error('[getContainersStatus] Error listing containers:', listError.message || listError);
61 // 使用同样的错误标记模式
62 return [{
63 id: 'n/a',
64 name: '容器列表获取失败',
65 image: 'n/a',
66 state: 'error',
67 status: `获取容器列表失败: ${listError.message}`,
68 error: 'CONTAINER_LIST_ERROR',
69 cpu: 'N/A',
70 memory: 'N/A',
71 created: new Date().toLocaleString()
72 }];
73 }
74
75 const containerPromises = containers.map(async (container) => {
76 try {
77 const containerInspectInfo = await docker.getContainer(container.Id).inspect();
78
79 let stats = {};
80 let cpuUsage = 'N/A';
81 let memoryUsage = 'N/A';
82
83 // 仅在容器运行时尝试获取 stats
84 if (containerInspectInfo.State.Running) {
85 try {
86 stats = await docker.getContainer(container.Id).stats({ stream: false });
87
88 // Safely calculate CPU usage
89 if (stats.precpu_stats && stats.cpu_stats && stats.cpu_stats.cpu_usage && stats.precpu_stats.cpu_usage && stats.cpu_stats.system_cpu_usage && stats.precpu_stats.system_cpu_usage) {
90 const cpuDelta = stats.cpu_stats.cpu_usage.total_usage - stats.precpu_stats.cpu_usage.total_usage;
91 const systemDelta = stats.cpu_stats.system_cpu_usage - stats.precpu_stats.system_cpu_usage;
92 if (systemDelta > 0 && stats.cpu_stats.online_cpus > 0) {
93 cpuUsage = ((cpuDelta / systemDelta) * stats.cpu_stats.online_cpus * 100.0).toFixed(2) + '%';
94 } else {

Callers

nothing calls this directly

Calls 2

initDockerConnectionFunction · 0.85
allMethod · 0.80

Tested by

no test coverage detected