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 != ":" { stats.ImageNames = append(stats.ImageNames, line) stats.ImageCount++ } } } return stats }