Files
2025-12-14 15:25:31 +08:00

79 lines
2.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
"os/exec"
"strings"
"time"
)
// readDockerStats 读取 Docker 统计信息(简化版)
func readDockerStats() DockerStats {
stats := DockerStats{
Available: false,
RunningNames: []string{},
StoppedNames: []string{},
ImageNames: []string{},
}
// 检查 docker 是否可用
if _, err := exec.LookPath("docker"); err != nil {
return stats
}
stats.Available = true
// 获取 Docker 版本
cmd := exec.Command("docker", "--version")
if out, err := cmd.Output(); err == nil {
stats.Version = strings.TrimSpace(string(out))
}
// 获取运行中的容器名
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd = exec.CommandContext(ctx, "docker", "ps", "--format", "{{.Names}}")
if out, err := cmd.Output(); err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
stats.RunningNames = append(stats.RunningNames, line)
stats.Running++
}
}
}
// 获取停止的容器名
ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd = exec.CommandContext(ctx, "docker", "ps", "-a", "--filter", "status=exited", "--format", "{{.Names}}")
if out, err := cmd.Output(); err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
stats.StoppedNames = append(stats.StoppedNames, line)
stats.Stopped++
}
}
}
// 获取镜像名只获取前20个避免数据过多
ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd = exec.CommandContext(ctx, "docker", "images", "--format", "{{.Repository}}:{{.Tag}}")
if out, err := cmd.Output(); err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" && line != "<none>:<none>" {
stats.ImageNames = append(stats.ImageNames, line)
stats.ImageCount++
}
}
}
return stats
}