95 lines
2.6 KiB
Go
95 lines
2.6 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const defaultDockerSocket = "/var/run/docker.sock"
|
|
|
|
func socketCandidates() []string {
|
|
out := []string{defaultDockerSocket, "/run/docker.sock", "/run/podman/podman.sock", "/var/run/podman/podman.sock"}
|
|
if runtimeDir := strings.TrimSpace(os.Getenv("XDG_RUNTIME_DIR")); runtimeDir != "" {
|
|
out = append(out, filepath.Join(runtimeDir, "podman", "podman.sock"), filepath.Join(runtimeDir, "docker.sock"))
|
|
}
|
|
return out
|
|
}
|
|
|
|
func normalizeSocket(raw string) string {
|
|
raw = strings.TrimSpace(raw)
|
|
if strings.HasPrefix(raw, "unix://") {
|
|
raw = strings.TrimPrefix(raw, "unix://")
|
|
}
|
|
return raw
|
|
}
|
|
|
|
func resolveSocket(configured string) string {
|
|
configured = normalizeSocket(configured)
|
|
if configured != "" && !strings.EqualFold(configured, "auto") {
|
|
return configured
|
|
}
|
|
for _, candidate := range socketCandidates() {
|
|
if info, err := os.Stat(candidate); err == nil && info.Mode()&os.ModeSocket != 0 {
|
|
return candidate
|
|
}
|
|
}
|
|
return defaultDockerSocket
|
|
}
|
|
|
|
type engineInfo struct {
|
|
Containers uint64 `json:"Containers"`
|
|
ContainersRunning uint64 `json:"ContainersRunning"`
|
|
Images uint64 `json:"Images"`
|
|
ServerVersion string `json:"ServerVersion"`
|
|
OperatingSystem string `json:"OperatingSystem"`
|
|
KernelVersion string `json:"KernelVersion"`
|
|
Architecture string `json:"Architecture"`
|
|
NCPU uint32 `json:"NCPU"`
|
|
MemTotal uint64 `json:"MemTotal"`
|
|
DockerRootDir string `json:"DockerRootDir"`
|
|
}
|
|
|
|
type engineVersion struct {
|
|
Version string `json:"Version"`
|
|
Components []struct {
|
|
Name string `json:"Name"`
|
|
Version string `json:"Version"`
|
|
} `json:"Components"`
|
|
}
|
|
|
|
func engineGet(ctx context.Context, sock, path string, target any) error {
|
|
client := &http.Client{Transport: unixRoundTripper{sock: sock}, Timeout: 3 * time.Second}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://docker"+path, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("container API %s returned %s", path, resp.Status)
|
|
}
|
|
return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(target)
|
|
}
|
|
|
|
func runtimeName(version engineVersion, sock string) string {
|
|
for _, component := range version.Components {
|
|
if strings.Contains(strings.ToLower(component.Name), "podman") {
|
|
return "podman"
|
|
}
|
|
}
|
|
if strings.Contains(strings.ToLower(sock), "podman") {
|
|
return "podman"
|
|
}
|
|
return "docker"
|
|
}
|