Files
RustProxy/docker-agent/docker.go
T
2026-11-28 17:36:53 +01:00

185 lines
5.2 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
)
type unixRoundTripper struct{ sock string }
var unixTransports sync.Map
func unixTransport(sock string) *http.Transport {
if existing, ok := unixTransports.Load(sock); ok {
return existing.(*http.Transport)
}
transport := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "unix", sock)
},
MaxIdleConns: 16,
MaxIdleConnsPerHost: 16,
MaxConnsPerHost: 32,
IdleConnTimeout: 30 * time.Second,
}
actual, loaded := unixTransports.LoadOrStore(sock, transport)
if loaded {
transport.CloseIdleConnections()
}
return actual.(*http.Transport)
}
func (u unixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
clone := req.Clone(req.Context())
clone.URL.Scheme = "http"
clone.URL.Host = "docker"
return unixTransport(u.sock).RoundTrip(clone)
}
func dockerContainers(ctx context.Context, sock string) ([]dockerContainer, error) {
client := &http.Client{Transport: unixRoundTripper{sock: sock}, Timeout: 4 * time.Second}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://docker/containers/json?all=0", nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("docker API: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("docker API returned %s: %s", resp.Status, strings.TrimSpace(string(body)))
}
var items []dockerContainer
dec := json.NewDecoder(io.LimitReader(resp.Body, 4<<20))
if err := dec.Decode(&items); err != nil {
return nil, fmt.Errorf("decode Docker response: %w", err)
}
return items, nil
}
func cleanName(names []string) string {
if len(names) == 0 {
return ""
}
return strings.TrimPrefix(names[0], "/")
}
func dnsLabel(value string) string {
value = strings.ToLower(value)
var b strings.Builder
dash := false
for _, r := range value {
ok := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
if ok {
b.WriteRune(r)
dash = false
} else if b.Len() > 0 && !dash {
b.WriteByte('-')
dash = true
}
}
out := strings.Trim(b.String(), "-")
if len(out) > 48 {
out = strings.Trim(out[:48], "-")
}
return out
}
func firstLabel(labels map[string]string, names ...string) string {
for _, name := range names {
if value := strings.TrimSpace(labels[name]); value != "" {
return value
}
}
return ""
}
func serviceIdentity(c dockerContainer, p dockerPort) (key, technical string) {
name := cleanName(c.Names)
project := firstLabel(c.Labels, "com.docker.compose.project", "io.podman.compose.project")
composeService := firstLabel(c.Labels, "com.docker.compose.service", "io.podman.compose.service")
replica := firstLabel(c.Labels, "com.docker.compose.container-number", "io.podman.compose.container-number")
if project != "" && composeService != "" {
if replica == "" {
replica = name
}
key = fmt.Sprintf("compose:%s/%s/%s:%d/%s", project, composeService, replica, p.PrivatePort, p.Type)
} else {
key = fmt.Sprintf("container:%s:%d/%s", name, p.PrivatePort, p.Type)
}
return key, dnsLabel(name)
}
func servicesFrom(containers []dockerContainer) []service {
byKey := make(map[string]*service)
bindingSeen := make(map[string]map[string]struct{})
for _, c := range containers {
name := cleanName(c.Names)
if dnsLabel(name) == "" {
continue
}
for _, p := range c.Ports {
if p.PublicPort == 0 || p.Type != "tcp" {
continue
}
if bind := net.ParseIP(strings.TrimSpace(p.IP)); bind != nil && bind.IsLoopback() {
continue
}
key, technical := serviceIdentity(c, p)
item := byKey[key]
if item == nil {
id := c.ID
if len(id) > 12 {
id = id[:12]
}
item = &service{
Key: key, TechnicalName: technical, ContainerID: id, ContainerName: name,
Image: c.Image, PrivatePort: p.PrivatePort, Protocol: p.Type,
Labels: rustproxyLabels(c.Labels),
Container: &containerState{State: strings.ToLower(c.State), Health: healthFromStatus(c.Status)},
}
byKey[key] = item
bindingSeen[key] = make(map[string]struct{})
}
bindIP := strings.TrimSpace(p.IP)
dedupe := bindIP + "|" + strconv.Itoa(int(p.PublicPort))
if _, ok := bindingSeen[key][dedupe]; ok {
continue
}
bindingSeen[key][dedupe] = struct{}{}
item.Bindings = append(item.Bindings, binding{BindIP: bindIP, PublicPort: p.PublicPort})
}
}
out := make([]service, 0, len(byKey))
for _, item := range byKey {
sort.Slice(item.Bindings, func(i, j int) bool {
left := net.ParseIP(strings.TrimSpace(item.Bindings[i].BindIP))
right := net.ParseIP(strings.TrimSpace(item.Bindings[j].BindIP))
leftWildcard := left == nil || left.IsUnspecified()
rightWildcard := right == nil || right.IsUnspecified()
if leftWildcard != rightWildcard {
return !leftWildcard
}
if item.Bindings[i].BindIP != item.Bindings[j].BindIP {
return item.Bindings[i].BindIP < item.Bindings[j].BindIP
}
return item.Bindings[i].PublicPort < item.Bindings[j].PublicPort
})
out = append(out, *item)
}
sort.Slice(out, func(i, j int) bool { return out[i].Key < out[j].Key })
return out
}