package docker import ( "encoding/json" "fmt" "strconv" "strings" ) // jsonLines parses one JSON object per line, skipping malformed rows. func jsonLines(text string) []map[string]any { out := make([]map[string]any, 0, 32) for _, line := range strings.Split(text, "\n") { line = strings.TrimSpace(line) if line == "" || !strings.HasPrefix(line, "{") { continue } var row map[string]any if err := json.Unmarshal([]byte(line), &row); err == nil { out = append(out, row) } } return out } func textField(row map[string]any, key string) string { if v, ok := row[key].(string); ok { return v } return "" } // parsePorts understands the `docker ps` Ports column, for example // "0.0.0.0:8080->80/tcp, :::8080->80/tcp" or "80/tcp". func parsePorts(raw string) []Port { out := make([]Port, 0, 8) seen := map[string]bool{} for _, part := range strings.Split(raw, ",") { part = strings.TrimSpace(part) if part == "" { continue } ports := parsePortEntry(part) for _, p := range ports { key := fmt.Sprintf("%d|%d|%s", p.HostPort, p.ContainerPort, p.Protocol) if seen[key] { continue } seen[key] = true out = append(out, p) } } return out } func parsePortEntry(part string) []Port { if idx := strings.Index(part, "->"); idx >= 0 { left := strings.TrimSpace(part[:idx]) right := strings.TrimSpace(part[idx+2:]) protocol := "tcp" if j := strings.LastIndex(right, "/"); j >= 0 { protocol = right[j+1:] right = right[:j] } hostIP, hostStart, hostEnd := splitPortRange(left) containerStart, containerEnd := splitRange(right) if hostStart == 0 { return []Port{{HostIP: hostIP, ContainerPort: containerStart, Protocol: protocol}} } if hostEnd > hostStart && containerEnd > containerStart && hostEnd-hostStart == containerEnd-containerStart && hostEnd-hostStart < 100 { out := make([]Port, 0, hostEnd-hostStart+1) for i := 0; i <= hostEnd-hostStart; i++ { out = append(out, Port{ HostIP: hostIP, HostPort: hostStart + i, ContainerPort: containerStart + i, Protocol: protocol, Published: true, }) } return out } return []Port{{ HostIP: hostIP, HostPort: hostStart, ContainerPort: containerStart, Protocol: protocol, Published: true, }} } // "8080/tcp" or "80/udp": exposed but not published to the host. containerPart := part protocol := "tcp" if j := strings.LastIndex(containerPart, "/"); j >= 0 { protocol = containerPart[j+1:] containerPart = containerPart[:j] } container, _ := splitRange(containerPart) return []Port{{ContainerPort: container, Protocol: protocol}} } func splitPortRange(raw string) (string, int, int) { raw = strings.TrimSpace(raw) if i := strings.LastIndex(raw, ":"); i >= 0 { host := raw[:i] raw = raw[i+1:] start, end := splitRange(raw) return host, start, end } start, end := splitRange(raw) return "", start, end } func splitRange(raw string) (int, int) { raw = strings.TrimSpace(strings.TrimPrefix(raw, ":")) if i := strings.Index(raw, "-"); i >= 0 { a, _ := strconv.Atoi(raw[:i]) b, _ := strconv.Atoi(raw[i+1:]) return a, b } p, _ := strconv.Atoi(raw) return p, p }