From caec4bd629b455e7110d347271be121f285aba56 Mon Sep 17 00:00:00 2001 From: MengMengCode <227010654+MengMengCode@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:31:14 +0800 Subject: [PATCH] feat: add Podman application management --- backend/internal/api/handlers.go | 4 + backend/internal/api/podman.go | 271 ++++++ backend/internal/api/podman_test.go | 56 ++ backend/internal/api/routing.go | 9 + backend/internal/api/taskqueue.go | 4 + backend/internal/podman/images.go | 99 +++ backend/internal/podman/manager.go | 495 +++++++++++ backend/internal/podman/manager_test.go | 85 ++ backend/internal/podman/observability_test.go | 64 ++ backend/internal/podman/request.go | 137 +++ backend/internal/podman/stats.go | 108 +++ backend/internal/server/server.go | 1 + docs/.vitepress/config.ts | 2 + docs/en/features/containers.md | 2 + docs/en/features/podman.md | 39 + docs/features/containers.md | 2 + docs/features/podman.md | 39 + frontend/src/App.tsx | 7 + frontend/src/components/Sidebar.tsx | 2 + frontend/src/pages/PodmanContainers.tsx | 827 ++++++++++++++++++ frontend/src/services/api.ts | 85 ++ frontend/src/utils/clipboard.ts | 8 +- frontend/src/utils/i18n.ts | 78 ++ 23 files changed, 2421 insertions(+), 3 deletions(-) create mode 100644 backend/internal/api/podman.go create mode 100644 backend/internal/api/podman_test.go create mode 100644 backend/internal/podman/images.go create mode 100644 backend/internal/podman/manager.go create mode 100644 backend/internal/podman/manager_test.go create mode 100644 backend/internal/podman/observability_test.go create mode 100644 backend/internal/podman/request.go create mode 100644 backend/internal/podman/stats.go create mode 100644 docs/en/features/podman.md create mode 100644 docs/features/podman.md create mode 100644 frontend/src/pages/PodmanContainers.tsx diff --git a/backend/internal/api/handlers.go b/backend/internal/api/handlers.go index ca66070..214b4db 100644 --- a/backend/internal/api/handlers.go +++ b/backend/internal/api/handlers.go @@ -328,6 +328,10 @@ func createContainer(w http.ResponseWriter, r *http.Request) { jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Container name is required"}) return } + if strings.EqualFold(strings.TrimSpace(cfg.Virtualization), "podman") { + jsonResponse(w, http.StatusBadRequest, APIResponse{Message: "Use the Podman container endpoint for OCI applications"}) + return + } cfg.Virtualization = runtimeFromRequest(cfg.Virtualization) if cfg.Virtualization != config.VirtualizationLXC && (cfg.Privileged || cfg.Nesting) { jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Privileged and nesting options are only supported for LXC containers"}) diff --git a/backend/internal/api/podman.go b/backend/internal/api/podman.go new file mode 100644 index 0000000..def0095 --- /dev/null +++ b/backend/internal/api/podman.go @@ -0,0 +1,271 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + + "clicd/internal/config" + "clicd/internal/lxc" + "clicd/internal/podman" +) + +var ( + podmanPortConfiguration sync.Mutex + errPodmanPortConflict = errors.New("Podman port conflict") +) + +func HandlePodman(w http.ResponseWriter, r *http.Request) { + auth, _ := authContextFromRequest(r) + if auth.Type != authTypeAdmin { + jsonResponse(w, http.StatusForbidden, APIResponse{Message: "Administrator login required"}) + return + } + + ctx := r.Context() + manager := podman.Manager{} + path := strings.TrimPrefix(r.URL.Path, "/api/podman/") + switch path { + case "status": + if r.Method != http.MethodGet { + podmanMethodNotAllowed(w, http.MethodGet) + return + } + info, err := manager.Info(ctx) + if err != nil { + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]any{ + "available": false, "message": err.Error(), + }}) + return + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]any{"available": true, "version": info.Version}}) + case "containers": + switch r.Method { + case http.MethodGet: + items, err := manager.List(ctx) + if err != nil { + podmanError(w, err) + return + } + if items == nil { + items = []podman.Container{} + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: items}) + case http.MethodPost: + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)) + decoder.DisallowUnknownFields() + var input podman.CreateRequest + if err := decoder.Decode(&input); err != nil || decoder.Decode(new(any)) != io.EOF { + jsonResponse(w, http.StatusBadRequest, APIResponse{Message: "Invalid Podman request body"}) + return + } + item, err := createPodmanApplication(r, manager, input) + if err != nil { + podmanError(w, err) + return + } + jsonResponse(w, http.StatusCreated, APIResponse{Success: true, Data: item}) + default: + podmanMethodNotAllowed(w, "GET, POST") + } + case "images": + handlePodmanImages(w, r, manager) + default: + handlePodmanContainer(w, r, manager, path) + } +} + +func handlePodmanImages(w http.ResponseWriter, r *http.Request, manager podman.Manager) { + switch r.Method { + case http.MethodGet: + images, err := manager.Images(r.Context()) + if err != nil { + podmanError(w, err) + return + } + if images == nil { + images = []podman.Image{} + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: images}) + case http.MethodPost: + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)) + decoder.DisallowUnknownFields() + var input struct { + Image string `json:"image"` + } + if err := decoder.Decode(&input); err != nil || decoder.Decode(new(any)) != io.EOF { + jsonResponse(w, http.StatusBadRequest, APIResponse{Message: "Invalid Podman image request body"}) + return + } + id, err := manager.PullImage(r.Context(), input.Image) + auditPodmanAction(r, "pull", input.Image, err) + if err != nil { + podmanError(w, err) + return + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]string{"id": id}}) + default: + podmanMethodNotAllowed(w, "GET, POST") + } +} + +func createPodmanApplication(r *http.Request, manager podman.Manager, input podman.CreateRequest) (podman.Container, error) { + podmanPortConfiguration.Lock() + defer podmanPortConfiguration.Unlock() + if err := checkPodmanPorts(input); err != nil { + return podman.Container{}, err + } + if len(input.Ports) > 0 { + apps, err := manager.List(r.Context()) + if err != nil { + return podman.Container{}, err + } + for _, app := range apps { + for _, used := range app.Ports { + for _, wanted := range input.Ports { + protocol := strings.ToLower(strings.TrimSpace(wanted.Protocol)) + if protocol == "" { + protocol = "tcp" + } + if used.HostPort == wanted.HostPort && used.Protocol == protocol { + return podman.Container{}, fmt.Errorf("%w: host port %d/%s is assigned to %s", errPodmanPortConflict, used.HostPort, used.Protocol, app.Name) + } + } + } + } + } + item, err := manager.Create(r.Context(), input) + auditPodmanAction(r, "create", input.Name, err) + return item, err +} + +func checkPodmanPorts(input podman.CreateRequest) error { + start, end := config.NATPortRange() + candidate := &config.Container{ID: -1} + for _, mapping := range input.Ports { + if mapping.HostPort < 1 || mapping.HostPort > 65535 { + continue // The Podman runtime reports invalid port numbers. + } + if mapping.HostPort >= start && mapping.HostPort <= end { + return fmt.Errorf("%w: host port %d overlaps the CLICD IPv4 NAT range (%d–%d)", errPodmanPortConflict, mapping.HostPort, start, end) + } + if !lxc.HostPortAvailable(candidate, "", mapping.HostPort, strings.ToLower(strings.TrimSpace(mapping.Protocol))) { + return fmt.Errorf("%w: host port %d is already mapped by a CLICD instance", errPodmanPortConflict, mapping.HostPort) + } + } + return nil +} + +func checkNATRangeAgainstPodman(ctx context.Context, start, end int) error { + apps, err := (podman.Manager{}).List(ctx) + if errors.Is(err, podman.ErrUnavailable) { + return nil + } + if err != nil { + return err + } + for _, app := range apps { + for _, mapping := range app.Ports { + if mapping.HostPort >= start && mapping.HostPort <= end { + return fmt.Errorf("%w: NAT range includes host port %d published by %s", errPodmanPortConflict, mapping.HostPort, app.Name) + } + } + } + return nil +} + +func handlePodmanContainer(w http.ResponseWriter, r *http.Request, manager podman.Manager, path string) { + tail, ok := strings.CutPrefix(path, "containers/") + if !ok || tail == "" { + jsonResponse(w, http.StatusNotFound, APIResponse{Message: "Podman endpoint not found"}) + return + } + ctx := r.Context() + id, action, subresource := strings.Cut(tail, "/") + expectedMethod := http.MethodPost + if !subresource { + action, expectedMethod = "delete", http.MethodDelete + } else if action == "logs" || action == "stats" { + expectedMethod = http.MethodGet + } else if action != "start" && action != "stop" && action != "restart" { + jsonResponse(w, http.StatusNotFound, APIResponse{Message: "Podman endpoint not found"}) + return + } + if r.Method != expectedMethod { + podmanMethodNotAllowed(w, expectedMethod) + return + } + if action == "logs" { + logs, err := manager.Logs(ctx, id) + if err != nil { + podmanError(w, err) + return + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]string{"logs": logs}}) + return + } + if action == "stats" { + stats, err := manager.Stats(ctx, id) + if err != nil { + podmanError(w, err) + return + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: stats}) + return + } + + var err error + switch action { + case "start": + err = manager.Start(ctx, id) + case "stop": + err = manager.Stop(ctx, id) + case "restart": + err = manager.Restart(ctx, id) + case "delete": + err = manager.Delete(ctx, id) + } + auditPodmanAction(r, action, id, err) + if err != nil { + podmanError(w, err) + return + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true}) +} + +func podmanMethodNotAllowed(w http.ResponseWriter, allow string) { + w.Header().Set("Allow", allow) + jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Message: "Method not allowed"}) +} + +func podmanError(w http.ResponseWriter, err error) { + status := http.StatusInternalServerError + switch { + case errors.Is(err, podman.ErrInvalid): + status = http.StatusBadRequest + case errors.Is(err, podman.ErrNotFound): + status = http.StatusNotFound + case errors.Is(err, podman.ErrUnavailable): + status = http.StatusServiceUnavailable + case errors.Is(err, errPodmanPortConflict), errors.Is(err, podman.ErrPortConflict), errors.Is(err, podman.ErrNotRunning): + status = http.StatusConflict + } + jsonResponse(w, status, APIResponse{Message: err.Error()}) +} + +func auditPodmanAction(r *http.Request, action, target string, err error) { + target = strings.TrimSpace(target) + if len(target) > 64 { + target = target[:64] + } + detail := "Succeeded" + if err != nil { + detail = "Failed" + } + auditRequest(r, "podman:"+action, target, detail, err == nil, "") +} diff --git a/backend/internal/api/podman_test.go b/backend/internal/api/podman_test.go new file mode 100644 index 0000000..9121693 --- /dev/null +++ b/backend/internal/api/podman_test.go @@ -0,0 +1,56 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "clicd/internal/config" +) + +func TestPodmanRequiresAdministratorSession(t *testing.T) { + for _, endpoint := range []struct { + method string + path string + }{ + {http.MethodGet, "/api/podman/status"}, + {http.MethodGet, "/api/podman/images"}, + {http.MethodPost, "/api/podman/images"}, + {http.MethodGet, "/api/podman/containers/" + strings.Repeat("a", 64) + "/stats"}, + } { + for _, auth := range []AuthContext{ + {Type: authTypeSubUser}, + {Type: authTypeAPIKey, Scopes: []string{"*"}}, + } { + req := httptest.NewRequest(endpoint.method, endpoint.path, nil) + rec := httptest.NewRecorder() + HandlePodman(rec, withAuthContext(req, auth)) + if rec.Code != http.StatusForbidden { + t.Fatalf("%s %s, auth type %s: status %d, want 403: %s", endpoint.method, endpoint.path, auth.Type, rec.Code, rec.Body.String()) + } + } + } +} + +func TestPodmanRejectsPortsReservedForOtherRuntimes(t *testing.T) { + previous := config.AppConfig + t.Cleanup(func() { config.AppConfig = previous }) + config.AppConfig = &config.ClicdConfig{ + NATPortStart: 20000, NATPortEnd: 65535, + Containers: []config.Container{{ID: 1, PortMappings: []config.PortMapping{ + {HostPort: 8080, Protocol: "tcp"}, + }}}, + } + for _, input := range []string{ + `{"name":"app","image":"docker.io/library/nginx:alpine","ports":[{"host_port":22000,"container_port":80,"protocol":"tcp"}]}`, + `{"name":"app","image":"docker.io/library/nginx:alpine","ports":[{"host_port":8080,"container_port":80,"protocol":"tcp"}]}`, + } { + req := httptest.NewRequest(http.MethodPost, "/api/podman/containers", strings.NewReader(input)) + rec := httptest.NewRecorder() + HandlePodman(rec, withAuthContext(req, AuthContext{Type: authTypeAdmin})) + if rec.Code != http.StatusConflict { + t.Fatalf("status %d, want 409: %s", rec.Code, rec.Body.String()) + } + } +} diff --git a/backend/internal/api/routing.go b/backend/internal/api/routing.go index ed80e02..18304e5 100644 --- a/backend/internal/api/routing.go +++ b/backend/internal/api/routing.go @@ -317,6 +317,15 @@ func handleRoutingPoolsUpdate(w http.ResponseWriter, r *http.Request) { jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()}) return } + podmanPortConfiguration.Lock() + defer podmanPortConfiguration.Unlock() + currentStart, currentEnd := config.NATPortRange() + if start != currentStart || end != currentEnd { + if err := checkNATRangeAgainstPodman(r.Context(), start, end); err != nil { + podmanError(w, err) + return + } + } config.AppConfig.NATPortStart = start config.AppConfig.NATPortEnd = end if config.AppConfig.NextSSHPort < start || config.AppConfig.NextSSHPort > end { diff --git a/backend/internal/api/taskqueue.go b/backend/internal/api/taskqueue.go index bd8cc38..07892e2 100644 --- a/backend/internal/api/taskqueue.go +++ b/backend/internal/api/taskqueue.go @@ -911,6 +911,10 @@ func HandleBatchCreate(w http.ResponseWriter, r *http.Request) { return } req.Containers[i].NormalizeResourceAliases() + if strings.EqualFold(strings.TrimSpace(req.Containers[i].Virtualization), "podman") { + jsonResponse(w, http.StatusBadRequest, APIResponse{Message: "Use the Podman container endpoint for OCI applications"}) + return + } req.Containers[i].Virtualization = runtimeFromRequest(req.Containers[i].Virtualization) if req.Containers[i].Virtualization != config.VirtualizationLXC && (req.Containers[i].Privileged || req.Containers[i].Nesting) { jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: name + ": privileged and nesting options are only supported for LXC containers"}) diff --git a/backend/internal/podman/images.go b/backend/internal/podman/images.go new file mode 100644 index 0000000..4c638bb --- /dev/null +++ b/backend/internal/podman/images.go @@ -0,0 +1,99 @@ +package podman + +import ( + "context" + "encoding/json" + "fmt" + "slices" + "sort" + "strings" + "time" +) + +type Image struct { + ID string `json:"id"` + Tags []string `json:"tags"` + SizeBytes int64 `json:"size_bytes"` + CreatedAt time.Time `json:"created_at"` +} + +func (Manager) Images(ctx context.Context) ([]Image, error) { + out, err := run(ctx, quickTimeout, "image", "list", "--no-trunc", "--format", "json") + if err != nil { + return nil, err + } + return parseImageList(out) +} + +func (Manager) PullImage(ctx context.Context, reference string) (string, error) { + reference = strings.TrimSpace(reference) + if !validImage(reference) { + return "", fmt.Errorf("%w: use a fully qualified image such as docker.io/library/nginx:alpine", ErrInvalid) + } + out, err := run(ctx, createTimeout, "pull", "--quiet", "--", reference) + if err != nil { + return "", err + } + id := imageID(strings.TrimSpace(string(out))) + if id == "" { + return "", fmt.Errorf("Podman did not return the pulled image's ID") + } + return id, nil +} + +func imageID(value string) string { + id := strings.TrimPrefix(value, "sha256:") + if fullID.MatchString(id) { + return id + } + return "" +} + +func parseImageList(data []byte) ([]Image, error) { + var rows []struct { + ID string `json:"Id"` + RepoTags []string `json:"RepoTags"` + Names []string `json:"Names"` + Size int64 `json:"Size"` + Created int64 `json:"Created"` + CreatedAt time.Time `json:"CreatedAt"` + } + if err := json.Unmarshal(data, &rows); err != nil { + return nil, fmt.Errorf("invalid Podman image list: %w", err) + } + + images := make([]Image, 0, len(rows)) + index := make(map[string]int, len(rows)) + for _, row := range rows { + id := imageID(row.ID) + if id == "" { + continue + } + i, found := index[id] + if !found { + i = len(images) + index[id] = i + created := row.CreatedAt + if created.IsZero() && row.Created > 0 { + created = time.Unix(row.Created, 0).UTC() + } + images = append(images, Image{ID: id, Tags: []string{}, SizeBytes: max(row.Size, 0), CreatedAt: created}) + } + for _, tag := range append(row.Names, row.RepoTags...) { + if validImage(tag) { + images[i].Tags = append(images[i].Tags, tag) + } + } + } + for i := range images { + sort.Strings(images[i].Tags) + images[i].Tags = slices.Compact(images[i].Tags) + } + sort.Slice(images, func(i, j int) bool { + if images[i].CreatedAt.Equal(images[j].CreatedAt) { + return images[i].ID < images[j].ID + } + return images[i].CreatedAt.After(images[j].CreatedAt) + }) + return images, nil +} diff --git a/backend/internal/podman/manager.go b/backend/internal/podman/manager.go new file mode 100644 index 0000000..a7b4977 --- /dev/null +++ b/backend/internal/podman/manager.go @@ -0,0 +1,495 @@ +package podman + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strconv" + "strings" + "time" +) + +const ( + managedLabel = "io.clicd.managed" + managedValue = "podman" + quickTimeout = 20 * time.Second + createTimeout = 3 * time.Minute + logLimit = 128 << 10 +) + +var ( + ErrInvalid = errors.New("invalid Podman application configuration") + ErrNotFound = errors.New("Podman application not found") + ErrNotRunning = errors.New("Podman application is not running") + ErrUnavailable = errors.New("Podman is unavailable") + ErrPortConflict = errors.New("Podman host port is already in use") +) + +// Manager controls the local Podman engine and its CLICD-managed applications. +type Manager struct{} + +type Info struct { + Version string `json:"version"` +} + +type PortMapping struct { + HostPort int `json:"host_port"` + ContainerPort int `json:"container_port"` + Protocol string `json:"protocol"` +} + +type CreateRequest struct { + Name string `json:"name"` + Image string `json:"image"` + CPUs float64 `json:"cpus"` + MemoryMB int `json:"memory_mb"` + Ports []PortMapping `json:"ports"` + Env map[string]string `json:"env"` + Command []string `json:"command"` + Volumes []string `json:"volumes"` +} + +type Container struct { + ID string `json:"id"` + Name string `json:"name"` + Image string `json:"image"` + Status string `json:"status"` + CreatedAt time.Time `json:"created_at"` + Ports []PortMapping `json:"ports,omitempty"` + MemoryMB int64 `json:"memory_mb,omitempty"` + CPUs float64 `json:"cpus,omitempty"` + Volumes []string `json:"volumes,omitempty"` + ExitCode *int `json:"exit_code,omitempty"` + StartedAt *time.Time `json:"started_at,omitempty"` + FinishedAt *time.Time `json:"finished_at,omitempty"` + Health string `json:"health,omitempty"` +} + +type inspectHealth struct { + Status string `json:"Status"` +} + +type inspectContainer struct { + ID string `json:"Id"` + Name string `json:"Name"` + Image string `json:"Image"` + ImageName string `json:"ImageName"` + Created time.Time `json:"Created"` + State struct { + Status string `json:"Status"` + ExitCode *int `json:"ExitCode"` + StartedAt time.Time `json:"StartedAt"` + FinishedAt time.Time `json:"FinishedAt"` + Healthcheck inspectHealth `json:"Healthcheck"` + Health inspectHealth `json:"Health"` + } `json:"State"` + Config struct { + Labels map[string]string `json:"Labels"` + } `json:"Config"` + HostConfig struct { + Memory int64 `json:"Memory"` + CPUQuota int64 `json:"CpuQuota"` + CPUPeriod int64 `json:"CpuPeriod"` + NanoCPUs int64 `json:"NanoCpus"` + PortBindings map[string][]struct { + HostPort string `json:"HostPort"` + } `json:"PortBindings"` + } `json:"HostConfig"` + Mounts []struct { + Type string `json:"Type"` + Destination string `json:"Destination"` + } `json:"Mounts"` +} + +func (c inspectContainer) managed() bool { + return fullID.MatchString(c.ID) && c.Config.Labels[managedLabel] == managedValue +} + +func (c inspectContainer) app() Container { + out := Container{ID: c.ID, Name: strings.TrimPrefix(c.Name, "/"), Image: c.ImageName, Status: c.State.Status, CreatedAt: c.Created} + if out.Image == "" { + out.Image = c.Image + } + switch out.Status { + case "configured", "initialized": + out.Status = "created" + case "exited": + out.Status = "stopped" + case "": + out.Status = "unknown" + } + if !c.State.StartedAt.IsZero() { + out.StartedAt = &c.State.StartedAt + } + if out.Status == "stopped" && !c.State.FinishedAt.IsZero() { + out.FinishedAt = &c.State.FinishedAt + out.ExitCode = c.State.ExitCode + } + if out.Status == "running" || out.Status == "paused" { + out.Health = c.State.Health.Status + if out.Health == "" { + out.Health = c.State.Healthcheck.Status + } + } + if c.HostConfig.Memory > 0 { + out.MemoryMB = c.HostConfig.Memory / (1 << 20) + } + if c.HostConfig.NanoCPUs > 0 { + out.CPUs = float64(c.HostConfig.NanoCPUs) / 1e9 + } else if c.HostConfig.CPUPeriod > 0 && c.HostConfig.CPUQuota > 0 { + out.CPUs = float64(c.HostConfig.CPUQuota) / float64(c.HostConfig.CPUPeriod) + } + for port, bindings := range c.HostConfig.PortBindings { + value, protocol, ok := strings.Cut(port, "/") + containerPort, err := strconv.Atoi(value) + if !ok || err != nil || !validPort(containerPort) || (protocol != "tcp" && protocol != "udp") { + continue + } + for _, binding := range bindings { + if hostPort, err := strconv.Atoi(binding.HostPort); err == nil && validPort(hostPort) { + out.Ports = append(out.Ports, PortMapping{hostPort, containerPort, protocol}) + } + } + } + sort.Slice(out.Ports, func(i, j int) bool { + a, b := out.Ports[i], out.Ports[j] + if a.HostPort != b.HostPort { + return a.HostPort < b.HostPort + } + if a.Protocol != b.Protocol { + return a.Protocol < b.Protocol + } + return a.ContainerPort < b.ContainerPort + }) + for _, mount := range c.Mounts { + if mount.Type == "volume" { + out.Volumes = append(out.Volumes, mount.Destination) + } + } + sort.Strings(out.Volumes) + return out +} + +func (Manager) Info(ctx context.Context) (Info, error) { + out, err := run(ctx, quickTimeout, "info", "--format", "{{.Version.Version}}") + if err != nil { + if errors.Is(err, ErrUnavailable) { + return Info{}, err + } + return Info{}, fmt.Errorf("%w: %v", ErrUnavailable, err) + } + version := strings.TrimSpace(string(out)) + if version == "" { + return Info{}, fmt.Errorf("%w: the engine did not report a version", ErrUnavailable) + } + return Info{Version: version}, nil +} + +func (m Manager) List(ctx context.Context) ([]Container, error) { + ctx, cancel := context.WithTimeout(ctx, quickTimeout) + defer cancel() + out, err := run(ctx, quickTimeout, "ps", "-a", "--filter", "label="+managedLabel+"="+managedValue, "--no-trunc", "--format", "{{.ID}}") + if err != nil { + return nil, err + } + ids := strings.Fields(string(out)) + for _, id := range ids { + if !fullID.MatchString(id) { + return nil, errors.New("Podman returned an invalid container ID") + } + } + apps := make([]Container, 0, len(ids)) + for offset := 0; offset < len(ids); offset += 32 { + group := ids[offset:min(offset+32, len(ids))] + inspected, err := inspect(ctx, group...) + if err != nil { + // A container may have been removed since the list was obtained. + for _, id := range group { + app, err := m.inspectOwned(ctx, id) + if errors.Is(err, ErrNotFound) { + continue + } + if err != nil { + return nil, err + } + apps = append(apps, app.app()) + } + continue + } + for _, container := range inspected { + if container.managed() { + apps = append(apps, container.app()) + } + } + } + return apps, nil +} + +func (m Manager) Create(ctx context.Context, req CreateRequest) (Container, error) { + if err := req.normalize(); err != nil { + return Container{}, err + } + dir, err := os.MkdirTemp("", "clicd-podman-") + if err != nil { + return Container{}, err + } + defer os.RemoveAll(dir) + cidFile := filepath.Join(dir, "cid") + args := []string{ + "create", "--cidfile", cidFile, "--name", req.Name, + "--label", managedLabel + "=" + managedValue, "--pull=missing", + "--security-opt=no-new-privileges", "--privileged=false", + "--network=bridge", "--pid=private", "--ipc=private", "--uts=private", + "--http-proxy=false", "--pids-limit=1024", "--log-driver=k8s-file", + "--log-opt=max-size=10mb", "--image-volume=ignore", + } + if req.CPUs > 0 { + args = append(args, "--cpus", strconv.FormatFloat(req.CPUs, 'f', 2, 64)) + } + if req.MemoryMB > 0 { + args = append(args, "--memory", strconv.Itoa(req.MemoryMB)+"m") + } + if len(req.Env) > 0 { + // Keep secrets out of argv and Podman's recorded creation command. + envFile := filepath.Join(dir, "environment") + if err := writeEnvFile(envFile, req.Env); err != nil { + return Container{}, err + } + args = append(args, "--env-file", envFile) + } + for _, p := range req.Ports { + args = append(args, "--publish", fmt.Sprintf("0.0.0.0:%d:%d/%s", p.HostPort, p.ContainerPort, p.Protocol)) + } + for _, destination := range req.Volumes { + args = append(args, "--volume", destination) + } + args = append(args, "--", req.Image) + args = append(args, req.Command...) + out, createErr := run(ctx, createTimeout, args...) + id := strings.TrimSpace(string(out)) + if file, err := os.ReadFile(cidFile); err == nil { + id = strings.TrimSpace(string(file)) + } + if !fullID.MatchString(id) { + if createErr != nil { + return Container{}, createErr + } + return Container{}, errors.New("Podman did not return the new application's ID") + } + if createErr != nil { + return Container{}, m.cleanupFailedCreate(id, createErr) + } + if err := m.Start(ctx, id); err != nil { + return Container{}, m.cleanupFailedCreate(id, err) + } + container, err := m.inspectOwned(ctx, id) + if err != nil { + return Container{}, m.cleanupFailedCreate(id, err) + } + return container.app(), nil +} + +func writeEnvFile(path string, env map[string]string) error { + keys := make([]string, 0, len(env)) + for key := range env { + keys = append(keys, key) + } + sort.Strings(keys) + var contents strings.Builder + for _, key := range keys { + fmt.Fprintf(&contents, "%s=%s\n", key, env[key]) + } + return os.WriteFile(path, []byte(contents.String()), 0600) +} + +func (m Manager) cleanupFailedCreate(id string, cause error) error { + if err := m.Delete(context.Background(), id); err != nil && !errors.Is(err, ErrNotFound) { + return fmt.Errorf("%w; cleanup failed: %v", cause, err) + } + return cause +} + +func (m Manager) Start(ctx context.Context, id string) error { + return m.action(ctx, id, "start") +} + +func (m Manager) Stop(ctx context.Context, id string) error { + return m.action(ctx, id, "stop", "--time", "10") +} + +func (m Manager) Restart(ctx context.Context, id string) error { + ctx, cancel := context.WithTimeout(ctx, 25*time.Second) + defer cancel() + container, err := m.inspectOwned(ctx, id) + if err != nil { + return err + } + switch container.State.Status { + case "running", "paused": + // Podman 3.4 may try to reserve the old container's published ports + // before its monitor releases them during a native restart. + if err := m.Stop(ctx, id); err != nil { + return err + } + default: + return m.Start(ctx, id) + } + for attempt := 0; ; attempt++ { + err := m.Start(ctx, id) + if !errors.Is(err, ErrPortConflict) || attempt == 2 { + return err + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Duration(attempt+1) * 250 * time.Millisecond): + } + } +} + +func (m Manager) Delete(ctx context.Context, id string) error { + return m.action(ctx, id, "rm", "--force", "--ignore", "--volumes") +} + +func (m Manager) action(ctx context.Context, id string, args ...string) error { + if _, err := m.inspectOwned(ctx, id); err != nil { + return err + } + _, err := run(ctx, quickTimeout, append(args, "--", id)...) + if args[0] == "start" && err != nil && strings.Contains(strings.ToLower(err.Error()), "address already in use") { + return fmt.Errorf("%w: %v", ErrPortConflict, err) + } + return err +} + +func (m Manager) Logs(ctx context.Context, id string) (string, error) { + if _, err := m.inspectOwned(ctx, id); err != nil { + return "", err + } + callCtx, cancel := context.WithTimeout(ctx, quickTimeout) + defer cancel() + cmd := command(callCtx, "logs", "--tail", "200", "--", id) + out := &outputBuffer{limit: logLimit, keepTail: true} + cmd.Stdout, cmd.Stderr = out, out + if err := cmd.Run(); err != nil { + return "", commandError(callCtx, err, out.String()) + } + if out.truncated { + return "[Earlier log output omitted]\n" + out.String(), nil + } + return out.String(), nil +} + +func (Manager) inspectOwned(ctx context.Context, id string) (inspectContainer, error) { + if !fullID.MatchString(id) { + return inspectContainer{}, fmt.Errorf("%w: a full container ID is required", ErrInvalid) + } + containers, err := inspect(ctx, id) + if err != nil { + if ctx.Err() != nil || errors.Is(err, ErrUnavailable) || errors.Is(err, context.DeadlineExceeded) { + return inspectContainer{}, err + } + _, existsErr := run(ctx, quickTimeout, "container", "exists", "--", id) + var exitErr *exec.ExitError + if errors.As(existsErr, &exitErr) && exitErr.ExitCode() == 1 { + return inspectContainer{}, ErrNotFound + } + return inspectContainer{}, err + } + for _, container := range containers { + if container.ID == id && container.managed() { + return container, nil + } + } + return inspectContainer{}, ErrNotFound +} + +func inspect(ctx context.Context, ids ...string) ([]inspectContainer, error) { + out, err := run(ctx, quickTimeout, append([]string{"container", "inspect", "--"}, ids...)...) + if err != nil { + return nil, err + } + var result []inspectContainer + if err := json.Unmarshal(out, &result); err != nil { + return nil, fmt.Errorf("invalid Podman inspection response: %w", err) + } + return result, nil +} + +func command(ctx context.Context, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, "podman", append([]string{"--remote=false"}, args...)...) + for _, value := range os.Environ() { + key, _, _ := strings.Cut(value, "=") + switch key { + case "CONTAINER_HOST", "CONTAINER_CONNECTION", "CONTAINER_SSHKEY": + // A service-wide remote connection must not redirect panel actions. + default: + cmd.Env = append(cmd.Env, value) + } + } + cmd.WaitDelay = 2 * time.Second + return cmd +} + +func run(ctx context.Context, timeout time.Duration, args ...string) ([]byte, error) { + callCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + cmd := command(callCtx, args...) + out := &outputBuffer{limit: 8 << 20} + stderr := &outputBuffer{limit: 8 << 10, keepTail: true} + cmd.Stdout, cmd.Stderr = out, stderr + if err := cmd.Run(); err != nil { + return out.Bytes(), commandError(callCtx, err, stderr.String()) + } + if out.truncated { + return nil, errors.New("Podman response exceeded the output limit") + } + return out.Bytes(), nil +} + +func commandError(ctx context.Context, err error, detail string) error { + if ctx.Err() != nil { + return fmt.Errorf("Podman command interrupted: %w", ctx.Err()) + } + if errors.Is(err, exec.ErrNotFound) { + return fmt.Errorf("%w: install Podman on the host", ErrUnavailable) + } + if detail = strings.TrimSpace(detail); detail != "" { + return fmt.Errorf("Podman command failed: %s (%w)", detail, err) + } + return fmt.Errorf("Podman command failed: %w", err) +} + +// outputBuffer drains the command's pipes without keeping unbounded output. +type outputBuffer struct { + buffer bytes.Buffer + limit int + keepTail bool + truncated bool +} + +func (b *outputBuffer) Bytes() []byte { return b.buffer.Bytes() } +func (b *outputBuffer) String() string { return b.buffer.String() } + +func (b *outputBuffer) Write(p []byte) (int, error) { + n := len(p) + if remaining := b.limit - b.buffer.Len(); n > remaining { + b.truncated = true + if !b.keepTail { + p = p[:remaining] + } else if n >= b.limit { + b.buffer.Reset() + p = p[n-b.limit:] + } else { + b.buffer.Next(n - remaining) + } + } + _, _ = b.buffer.Write(p) + return n, nil +} diff --git a/backend/internal/podman/manager_test.go b/backend/internal/podman/manager_test.go new file mode 100644 index 0000000..ec92337 --- /dev/null +++ b/backend/internal/podman/manager_test.go @@ -0,0 +1,85 @@ +package podman + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestCreateRequestRejectsUnexpectedInputs(t *testing.T) { + for _, test := range []struct { + name string + change func(*CreateRequest) + }{ + {"path image transport", func(r *CreateRequest) { r.Image = "dir:123/path" }}, + {"archive image transport", func(r *CreateRequest) { r.Image = "docker-archive:123/image" }}, + {"short image name", func(r *CreateRequest) { r.Image = "ubuntu:24.04" }}, + {"image option", func(r *CreateRequest) { r.Image = "--privileged" }}, + {"host bind", func(r *CreateRequest) { r.Volumes = []string{"/etc:/data"} }}, + {"kernel mount", func(r *CreateRequest) { r.Volumes = []string{"/sys/fs"} }}, + {"duplicate binding", func(r *CreateRequest) { r.Ports = append(r.Ports, PortMapping{8080, 81, "TCP"}) }}, + {"multiline environment", func(r *CreateRequest) { r.Env["TEST"] = "first\nsecond=value" }}, + {"invalid CPU precision", func(r *CreateRequest) { r.CPUs = 1.002 }}, + } { + t.Run(test.name, func(t *testing.T) { + req := CreateRequest{ + Name: "demo", Image: "docker.io/library/alpine:3.21", CPUs: 0.25, MemoryMB: 64, + Ports: []PortMapping{{8080, 80, ""}}, Volumes: []string{"/var/lib/app"}, + Env: map[string]string{"TEST": "a=b"}, Command: []string{"sh", "-c", "echo ok"}, + } + if err := req.normalize(); err != nil || req.Ports[0].Protocol != "tcp" { + t.Fatalf("valid request rejected: %v", err) + } + test.change(&req) + if err := req.normalize(); !errors.Is(err, ErrInvalid) { + t.Fatalf("invalid request accepted or wrong error: %v", err) + } + }) + } +} + +func TestInspectOlderPodmanDoesNotExposePrivateData(t *testing.T) { + id := strings.Repeat("3", 64) + input := `{ + "Id":"` + id + `", "Created":"2026-11-14T08:10:29.158833123Z", + "Name":"example","ImageName":"docker.io/library/alpine:3.21", + "State":{"Status":"exited"},"Config":{"Labels":{"io.clicd.managed":"podman"},"Env":["SECRET=private"]}, + "HostConfig":{"CpuPeriod":100000,"CpuQuota":25000,"Memory":67108864, + "PortBindings":{"80/tcp":[{"HostIp":"0.0.0.0","HostPort":"18895"}],"81/udp":[{"HostIp":"0.0.0.0","HostPort":"18894"}]}}, + "Mounts":[{"Type":"volume","Name":"private-name","Source":"/host/path","Destination":"/data"}] + }` + var inspected inspectContainer + if err := json.Unmarshal([]byte(input), &inspected); err != nil { + t.Fatal(err) + } + app := inspected.app() + if !inspected.managed() || app.ID != id || app.Status != "stopped" || app.CPUs != 0.25 || app.MemoryMB != 64 || + len(app.Ports) != 2 || app.Ports[0] != (PortMapping{18894, 81, "udp"}) || len(app.Volumes) != 1 || app.Volumes[0] != "/data" { + t.Fatalf("unexpected app: %+v", app) + } + serialized, err := json.Marshal(app) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(serialized), "private") || strings.Contains(string(serialized), "/host/path") { + t.Fatalf("private inspect data appeared in API output: %s", serialized) + } + inspected.Config.Labels = nil + if inspected.managed() { + t.Fatal("unmanaged container was accepted") + } +} + +func TestOutputBufferKeepsOnlyBoundedTail(t *testing.T) { + b := &outputBuffer{limit: 6, keepTail: true} + for _, piece := range []string{"12345", "678", "abcdefghij", "k"} { + n, err := b.Write([]byte(piece)) + if n != len(piece) || err != nil { + t.Fatalf("output writer did not drain the input: %d, %v", n, err) + } + } + if !b.truncated || b.String() != "fghijk" { + t.Fatalf("got %q, truncated=%v", b.String(), b.truncated) + } +} diff --git a/backend/internal/podman/observability_test.go b/backend/internal/podman/observability_test.go new file mode 100644 index 0000000..44d520c --- /dev/null +++ b/backend/internal/podman/observability_test.go @@ -0,0 +1,64 @@ +package podman + +import ( + "encoding/json" + "reflect" + "strings" + "testing" + "time" +) + +func TestImageListGroupsValidTagsByID(t *testing.T) { + busybox := strings.Repeat("a", 64) + alpine := strings.Repeat("b", 64) + data := `[ + {"Id":"sha256:BUSYBOX","Names":["docker.io/library/busybox:1.37","docker.io/library/busybox:stable"],"RepoTags":null,"Size":1428577,"CreatedAt":"2026-11-14T02:00:00Z"}, + {"Id":"BUSYBOX","Names":["docker.io/library/busybox:stable",":"],"RepoTags":["localhost/my-busybox:1.37"],"Size":1428577}, + {"Id":"ALPINE","Names":[],"Size":2100000,"Created":1794621500} + ]` + images, err := parseImageList([]byte(strings.NewReplacer("BUSYBOX", busybox, "ALPINE", alpine).Replace(data))) + if err != nil { + t.Fatal(err) + } + if len(images) != 2 || images[0].ID != busybox || images[1].ID != alpine { + t.Fatalf("unexpected images: %+v", images) + } + want := []string{"docker.io/library/busybox:1.37", "docker.io/library/busybox:stable", "localhost/my-busybox:1.37"} + if !reflect.DeepEqual(images[0].Tags, want) || images[0].SizeBytes != 1428577 { + t.Fatalf("unexpected BusyBox metadata: %+v", images[0]) + } + if images[1].Tags == nil || len(images[1].Tags) != 0 || images[1].CreatedAt.Unix() != 1794621500 { + t.Fatalf("unexpected untagged Alpine metadata: %+v", images[1]) + } +} + +func TestPodmanStatsUsesCounterDeltasAndCorrectNetworkDirections(t *testing.T) { + var legacy, current statsSample + if err := json.Unmarshal([]byte(`{"CPUNano":125000000,"SystemNano":1500000000,"MemUsage":339968,"MemLimit":67108864,"NetInput":132,"NetOutput":442,"BlockInput":4096,"BlockOutput":512,"PIDs":1}`), &legacy); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(`{"CPUNano":100,"SystemNano":2500000000,"Network":{"eth0":{"RxBytes":712,"TxBytes":134},"eth1":{"RxBytes":22,"TxBytes":31}}}`), ¤t); err != nil { + t.Fatal(err) + } + previous := statsSample{CPUNano: 0, SystemNano: uint64(time.Second)} + oldStats := legacy.since(previous) + if oldStats.CPUPercent == nil || *oldStats.CPUPercent != 25 || oldStats.NetworkRxBytes != 442 || oldStats.NetworkTxBytes != 132 || + oldStats.MemoryUsedBytes != 339968 || oldStats.MemoryLimitBytes != 67108864 || oldStats.BlockReadBytes != 4096 || oldStats.BlockWriteBytes != 512 || oldStats.PIDs != 1 { + t.Fatalf("incorrect legacy stats: %+v", oldStats) + } + newStats := current.since(legacy) + if newStats.CPUPercent != nil || newStats.NetworkRxBytes != 734 || newStats.NetworkTxBytes != 165 { + t.Fatalf("incorrect stats after restart: %+v", newStats) + } +} + +func TestInspectExitStatePreservesZeroExitCode(t *testing.T) { + var container inspectContainer + if err := json.Unmarshal([]byte(`{"State":{"Status":"exited","ExitCode":0,"StartedAt":"2026-11-14T02:00:00Z","FinishedAt":"2026-11-14T02:00:04Z"}}`), &container); err != nil { + t.Fatal(err) + } + app := container.app() + if app.Status != "stopped" || app.ExitCode == nil || *app.ExitCode != 0 || app.StartedAt == nil || app.FinishedAt == nil { + t.Fatalf("missing state of app that exited successfully: %+v", app) + } +} diff --git a/backend/internal/podman/request.go b/backend/internal/podman/request.go new file mode 100644 index 0000000..ff8d285 --- /dev/null +++ b/backend/internal/podman/request.go @@ -0,0 +1,137 @@ +package podman + +import ( + "fmt" + "math" + "path" + "regexp" + "strconv" + "strings" +) + +var ( + fullID = regexp.MustCompile(`^[a-f0-9]{64}$`) + containerName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$`) + registryHost = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$`) + repositoryPart = regexp.MustCompile(`^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$`) + imageTag = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$`) + imageDigest = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`) + environmentKey = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`) + volumeTarget = regexp.MustCompile(`^/[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$`) +) + +func (r *CreateRequest) normalize() error { + r.Name = strings.TrimSpace(r.Name) + r.Image = strings.TrimSpace(r.Image) + if !containerName.MatchString(r.Name) { + return fmt.Errorf("%w: name must start with a letter or number and contain at most 64 letters, numbers, periods, underscores or hyphens", ErrInvalid) + } + if !validImage(r.Image) { + return fmt.Errorf("%w: use a fully qualified image such as docker.io/library/nginx:alpine", ErrInvalid) + } + if math.IsNaN(r.CPUs) || r.CPUs < 0 || (r.CPUs != 0 && + (r.CPUs < 0.01 || r.CPUs > 256 || math.Abs(r.CPUs*100-math.Round(r.CPUs*100)) > 1e-6)) { + return fmt.Errorf("%w: CPU limit must be 0 or between 0.01 and 256 with at most two decimal places", ErrInvalid) + } + if r.MemoryMB != 0 && (r.MemoryMB < 16 || r.MemoryMB > 1048576) { + return fmt.Errorf("%w: memory limit must be 0 or between 16 and 1048576 MiB", ErrInvalid) + } + if len(r.Ports) > 64 || len(r.Volumes) > 16 || len(r.Env) > 64 || len(r.Command) > 64 { + return fmt.Errorf("%w: too many ports, volumes, environment variables or command arguments", ErrInvalid) + } + if err := r.normalizePorts(); err != nil { + return err + } + seenVolumes := make(map[string]bool, len(r.Volumes)) + for _, target := range r.Volumes { + if !validVolumeTarget(target) || seenVolumes[target] { + return fmt.Errorf("%w: volume targets must be unique, absolute guest data paths", ErrInvalid) + } + seenVolumes[target] = true + } + for key, value := range r.Env { + if !environmentKey.MatchString(key) || len(value) > 4096 || strings.ContainsAny(value, "\r\n\x00") { + return fmt.Errorf("%w: environment variables require valid names and single-line values up to 4096 bytes", ErrInvalid) + } + } + commandBytes := 0 + for _, arg := range r.Command { + commandBytes += len(arg) + if commandBytes > 32768 || strings.ContainsRune(arg, '\x00') { + return fmt.Errorf("%w: the command must be at most 32768 bytes and cannot contain NUL", ErrInvalid) + } + } + return nil +} + +func (r *CreateRequest) normalizePorts() error { + seenPorts := make(map[string]bool, len(r.Ports)) + for i := range r.Ports { + p := &r.Ports[i] + p.Protocol = strings.ToLower(strings.TrimSpace(p.Protocol)) + if p.Protocol == "" { + p.Protocol = "tcp" + } + if !validPort(p.HostPort) || !validPort(p.ContainerPort) || (p.Protocol != "tcp" && p.Protocol != "udp") { + return fmt.Errorf("%w: ports must be between 1 and 65535 and use TCP or UDP", ErrInvalid) + } + binding := strconv.Itoa(p.HostPort) + "/" + p.Protocol + if seenPorts[binding] { + return fmt.Errorf("%w: duplicate host port %s", ErrInvalid, binding) + } + seenPorts[binding] = true + } + return nil +} + +func validPort(port int) bool { + return port >= 1 && port <= 65535 +} + +func validImage(reference string) bool { + if len(reference) > 512 { + return false + } + name, digest, pinned := strings.Cut(reference, "@") + if pinned && !imageDigest.MatchString(digest) { + return false + } + registry, repository, qualified := strings.Cut(name, "/") + if !qualified { + return false + } + host, port, withPort := strings.Cut(registry, ":") + // Requiring a DNS name or localhost also prevents a colon from being + // interpreted as an image transport (for example, dir: or docker-archive:). + if !registryHost.MatchString(host) || (host != "localhost" && !strings.Contains(host, ".")) { + return false + } + if withPort { + n, err := strconv.Atoi(port) + if err != nil || !validPort(n) || strconv.Itoa(n) != port { + return false + } + } + repo, tag, tagged := strings.Cut(repository, ":") + if tagged && !imageTag.MatchString(tag) { + return false + } + for _, component := range strings.Split(repo, "/") { + if !repositoryPart.MatchString(component) { + return false + } + } + return true +} + +func validVolumeTarget(target string) bool { + if len(target) > 256 || !volumeTarget.MatchString(target) || path.Clean(target) != target { + return false + } + for _, restricted := range []string{"/proc", "/sys", "/dev", "/etc/hosts", "/etc/hostname", "/etc/resolv.conf", "/run/.containerenv"} { + if target == restricted || strings.HasPrefix(target, restricted+"/") || strings.HasPrefix(restricted, target+"/") { + return false + } + } + return true +} diff --git a/backend/internal/podman/stats.go b/backend/internal/podman/stats.go new file mode 100644 index 0000000..62a014b --- /dev/null +++ b/backend/internal/podman/stats.go @@ -0,0 +1,108 @@ +package podman + +import ( + "context" + "encoding/json" + "fmt" + "time" +) + +type Stats struct { + CPUPercent *float64 `json:"cpu_percent"` + MemoryUsedBytes uint64 `json:"memory_used_bytes"` + MemoryLimitBytes uint64 `json:"memory_limit_bytes"` + NetworkRxBytes uint64 `json:"network_rx_bytes"` + NetworkTxBytes uint64 `json:"network_tx_bytes"` + BlockReadBytes uint64 `json:"block_read_bytes"` + BlockWriteBytes uint64 `json:"block_write_bytes"` + PIDs uint64 `json:"pids"` +} + +type statsSample struct { + ContainerID string + CPUNano uint64 + SystemNano uint64 + MemUsage uint64 + MemLimit uint64 + NetInput uint64 + NetOutput uint64 + Network map[string]struct { + RxBytes uint64 + TxBytes uint64 + } + BlockInput uint64 + BlockOutput uint64 + PIDs uint64 +} + +func (m Manager) Stats(ctx context.Context, id string) (Stats, error) { + ctx, cancel := context.WithTimeout(ctx, quickTimeout) + defer cancel() + + container, err := m.inspectOwned(ctx, id) + if err != nil { + return Stats{}, err + } + if container.State.Status != "running" && container.State.Status != "paused" { + return Stats{}, ErrNotRunning + } + + first, err := readStatsSample(ctx, id) + if err != nil { + return Stats{}, err + } + // Podman 3.4 computes the first sample's CPU percentage against a zero + // timestamp. Use the deltas between snapshots to report current activity. + timer := time.NewTimer(250 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return Stats{}, ctx.Err() + case <-timer.C: + } + last, err := readStatsSample(ctx, id) + if err != nil { + return Stats{}, err + } + return last.since(first), nil +} + +func readStatsSample(ctx context.Context, id string) (statsSample, error) { + out, err := run(ctx, quickTimeout, "stats", "--no-stream", "--no-reset", "--format", "{{json .ContainerStats}}", "--", id) + if err != nil { + return statsSample{}, err + } + if len(out) == 0 { + return statsSample{}, ErrNotRunning + } + var sample statsSample + if err := json.Unmarshal(out, &sample); err != nil { + return statsSample{}, fmt.Errorf("invalid Podman statistics: %w", err) + } + if sample.ContainerID != id { + return statsSample{}, fmt.Errorf("Podman statistics returned an unexpected container ID") + } + return sample, nil +} + +func (sample statsSample) since(previous statsSample) Stats { + stats := Stats{ + MemoryUsedBytes: sample.MemUsage, MemoryLimitBytes: sample.MemLimit, + BlockReadBytes: sample.BlockInput, BlockWriteBytes: sample.BlockOutput, PIDs: sample.PIDs, + } + if sample.CPUNano >= previous.CPUNano && sample.SystemNano > previous.SystemNano { + pct := float64(sample.CPUNano-previous.CPUNano) / float64(sample.SystemNano-previous.SystemNano) * 100 + stats.CPUPercent = &pct + } + if sample.Network == nil { + // Podman 3.4 populates NetOutput with guest receives and NetInput with + // guest transmits. Newer releases expose guest counters per interface. + stats.NetworkRxBytes, stats.NetworkTxBytes = sample.NetOutput, sample.NetInput + } else { + for _, iface := range sample.Network { + stats.NetworkRxBytes += iface.RxBytes + stats.NetworkTxBytes += iface.TxBytes + } + } + return stats +} diff --git a/backend/internal/server/server.go b/backend/internal/server/server.go index 7e22bee..2103dbf 100644 --- a/backend/internal/server/server.go +++ b/backend/internal/server/server.go @@ -75,6 +75,7 @@ func setupRoutes(mux *http.ServeMux) { mux.HandleFunc("/api/routing/ipv4-scan", corsMiddleware(api.AdminMiddleware(api.HandleRoutingIPv4Scan))) mux.HandleFunc("/api/routing", corsMiddleware(api.AdminMiddleware(api.HandleRouting))) mux.HandleFunc("/api/storage", corsMiddleware(api.AdminMiddleware(api.HandleStorage))) + mux.HandleFunc("/api/podman/", corsMiddleware(api.AuthMiddleware(api.HandlePodman))) mux.HandleFunc("/api/ipv6/status", corsMiddleware(api.AdminMiddleware(api.HandleIPv6Status))) mux.HandleFunc("/api/ipv6/nat", corsMiddleware(api.AdminMiddleware(api.HandleIPv6NATSettings))) mux.HandleFunc("/api/tasks", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleTasks)))) diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index d39b186..cf9bb1c 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -30,6 +30,7 @@ const zhSidebar = [ items: [ { text: '控制面板', link: '/features/dashboard' }, { text: '容器管理', link: '/features/containers' }, + { text: 'Podman 容器', link: '/features/podman' }, { text: '镜像管理', link: '/features/images' }, { text: '网络与路由', link: '/features/networking' }, { text: '快照管理', link: '/features/snapshots' }, @@ -74,6 +75,7 @@ const enSidebar = [ items: [ { text: 'Dashboard', link: '/en/features/dashboard' }, { text: 'Containers', link: '/en/features/containers' }, + { text: 'Podman Containers', link: '/en/features/podman' }, { text: 'Images', link: '/en/features/images' }, { text: 'Networking & Routing', link: '/en/features/networking' }, { text: 'Snapshots', link: '/en/features/snapshots' }, diff --git a/docs/en/features/containers.md b/docs/en/features/containers.md index 2a70d39..c6cc13c 100644 --- a/docs/en/features/containers.md +++ b/docs/en/features/containers.md @@ -2,6 +2,8 @@ Container Management is the core CLICD module. It covers creation, lifecycle operations, resource limits, network mappings, traffic statistics, password resets, and console access. +To deploy an application from an OCI image, use [Podman Containers](./podman). + ## Container List The list page scans container status. Administrators can view all containers. Sub-users only see containers within their authorization scope. diff --git a/docs/en/features/podman.md b/docs/en/features/podman.md new file mode 100644 index 0000000..8724e22 --- /dev/null +++ b/docs/en/features/podman.md @@ -0,0 +1,39 @@ +# Podman Containers + +Use the Podman Containers page to deploy OCI applications such as Nginx. An application runs the process from its image and shares the host's Linux kernel. Use [LXC or KVM](./containers) for a full Linux environment, a system disk, or virtual hardware. + +## Prepare the Host + +Install Podman on the Linux host that runs CLICD, and verify that the CLICD service account can run it. With the default root installation, use `sudo podman info` on the host. On Debian or Ubuntu, install Podman from the distribution's package repository. + +```bash +sudo apt install podman +sudo podman info +``` + +Sign into the panel as an administrator and open **Podman Containers**. This page manages the application containers created through the panel. By default, CLICD runs local Podman as root. Use it for images you trust. Sub-users, snapshots, and backups for LXC and KVM are managed on their existing pages. + +## Deploy an Application + +1. Click **Create Container** and enter a name and an OCI image with its registry, such as `docker.io/library/nginx:alpine`. +2. To reach the application through the host, publish a TCP or UDP port. For example, publish host port `8080` to container port `80`. Where network rules allow, open `http://:8080` to reach Nginx. +3. Set CPU and memory limits as needed. Enter environment variables as one `KEY=value` per line. Supply command arguments as a JSON array of strings, such as `["nginx", "-g", "daemon off;"]`. The array replaces the image's default `CMD`. When the image defines an `ENTRYPOINT`, it receives the array as arguments. Check the image documentation for the expected arguments. +4. To persist data, enter one absolute path inside the container per line, such as `/var/cache/nginx`. Podman creates a volume for each path. + +Ports are published on the host's IPv4 interfaces. Select host ports outside CLICD's configured [NAT4 port range](./networking#nat4) to avoid conflicts with LXC and KVM forwarding rules. Use the host or upstream firewall to restrict access where needed. + +## Check Application Status + +In **Applications**, search by name or image and filter by status. Start, stop, or restart a container from the list. Open its details to find CPU and memory limits, published ports, and volume paths under **Overview**. Running containers also show CPU, memory, network, and disk I/O. After an application exits, check its exit code. + +## View Application Logs + +Open **Logs** in the container details to see the application's standard output and standard error. Turn on **Auto-refresh**, or copy or download the logs currently shown. If an application exits immediately after starting, check the exit code and logs against the image's expected arguments. + +## Manage Local Images + +**Local images** shows the Podman cache for the CLICD service account. Search by tag or select **Pull image** to download an image using its fully qualified OCI reference. Select **Use image** next to a local tag to open the creation form with that cached image selected. + +## Persistent Volumes + +Podman volumes keep data across stops and restarts. Deleting a container removes its anonymous volumes. Back up application data you want to keep before deleting the container. diff --git a/docs/features/containers.md b/docs/features/containers.md index 8132e30..ada3756 100644 --- a/docs/features/containers.md +++ b/docs/features/containers.md @@ -2,6 +2,8 @@ 容器管理是 CLICD 的核心模块,覆盖创建、生命周期控制、资源限制、网络映射、流量统计、密码重置和控制台访问。 +使用 OCI 镜像部署应用时,请打开 [Podman 容器](./podman)。 + ## 容器列表 列表页用于扫描所有容器状态。管理员可以查看全部容器,子用户只能看到授权范围内的容器。 diff --git a/docs/features/podman.md b/docs/features/podman.md new file mode 100644 index 0000000..c64ae09 --- /dev/null +++ b/docs/features/podman.md @@ -0,0 +1,39 @@ +# Podman 容器 + +在面板的「Podman 容器」页面可以部署 Nginx 等 OCI 应用。应用启动镜像内的进程,使用宿主机的 Linux 内核。需要完整 Linux 环境、系统盘或虚拟硬件时,请使用 [LXC 或 KVM](./containers)。 + +## 准备宿主机 + +先在 CLICD 所在的 Linux 宿主机安装 Podman,并确认 CLICD 服务账号能运行它。默认用 root 运行面板时,可在宿主机执行 `sudo podman info` 检查。以 Debian 或 Ubuntu 为例,可用各自的软件仓库安装。 + +```bash +sudo apt install podman +sudo podman info +``` + +用管理员账号登录并打开「Podman 容器」。这里管理通过面板创建的应用容器。CLICD 默认以 root 账号调用本机 Podman,适用于管理员部署自己信任的镜像。LXC/KVM 的子用户、快照和备份由各自的管理页面处理。 + +## 部署应用 + +1. 点击「创建容器」,填写名称和包含仓库地址的 OCI 镜像,例如 `docker.io/library/nginx:alpine`。 +2. 如需从宿主机访问应用,添加端口映射,选择 TCP 或 UDP。例如,映射宿主机端口 `8080` 到容器端口 `80`。端口发布后可在网络允许的情况下通过 `http://<宿主机地址>:8080` 访问 Nginx。 +3. 按应用需要设置 CPU 和内存上限。可填写环境变量,每行一个 `KEY=value`。若要传递启动参数,使用 JSON 字符串数组,例如 `["nginx", "-g", "daemon off;"]`。它会替换镜像默认的 `CMD`。镜像定义了 `ENTRYPOINT` 时,这些值将作为它的参数,具体写法以镜像说明为准。 +4. 如需持久化数据,每行填写一个容器内的绝对目录,例如 `/var/cache/nginx`。Podman 会为这些目录创建卷。 + +应用端口发布到宿主机的 IPv4 接口。填写宿主机端口时,需避开 CLICD 当前配置的 [NAT4 端口范围](./networking#nat4),以免与 LXC/KVM 的转发规则冲突。需要限制访问范围时,在宿主机或上游防火墙配置规则。 + +## 查看应用状态 + +在「应用」中按名称或镜像搜索,或按运行状态筛选。可从列表启动、停止或重启容器,也可打开详情,在「概览」中查看 CPU 和内存上限、已发布端口和持久卷路径。运行中的容器还显示 CPU、内存、网络和磁盘 I/O。应用退出后,可查看退出码。 + +## 查看应用日志 + +详情中的「日志」显示应用写入标准输出和标准错误的内容。可开启「自动刷新」,或复制、下载当前显示的日志。应用启动后立即退出时,可结合退出码、日志和镜像说明检查启动参数。 + +## 管理本地镜像 + +「本地镜像」显示当前 CLICD 服务账号的 Podman 本地缓存。可以搜索镜像标签,或点击「拉取镜像」并输入完整的 OCI 镜像名提前拉取。点击已有标签旁的「使用镜像」可直接打开创建容器表单,复用本地缓存。 + +## 持久卷 + +Podman 卷在停止和重启期间保留数据。删除容器会一并删除其匿名卷。删除前请先备份需要保留的应用数据。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 42a18fc..9f57861 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -17,6 +17,7 @@ import SubUserManagement from './pages/SubUserManagement' import Layout from './components/Layout' import PortableLibrary from './pages/PortableLibrary' import Tasks from './pages/Tasks' +import PodmanContainers from './pages/PodmanContainers' function ProtectedRoute({ children }: { children: React.ReactNode }) { const { isAuthenticated, isLoading } = useAuth() @@ -45,6 +46,11 @@ function HomeRoute() { return } +function PodmanRoute() { + const { isSubUser } = useAuth() + return isSubUser ? : +} + function App() { return ( @@ -59,6 +65,7 @@ function App() { > } /> } /> + } /> } /> } /> diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 2c16c8c..5ffc910 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -7,6 +7,7 @@ import { ChevronLeft, ChevronRight, Code2, + Container, Cpu, Camera, HardDrive, @@ -91,6 +92,7 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) { const navItems = [ { path: '/', label: '控制面板', icon: LayoutDashboard, active: location.pathname === '/', admin: true }, { path: '/containers', label: '容器管理', icon: Server, active: location.pathname.startsWith('/container'), admin: false }, + { path: '/podman', label: 'Podman 容器', icon: Container, active: location.pathname === '/podman', admin: true }, { path: '/images', label: '镜像管理', icon: Package, active: location.pathname.startsWith('/images'), admin: true }, { path: '/snapshots', label: '快照管理', icon: Camera, active: location.pathname.startsWith('/snapshots'), admin: true }, { path: '/backups', label: '备份与恢复', icon: Archive, active: location.pathname.startsWith('/backups'), admin: true }, diff --git a/frontend/src/pages/PodmanContainers.tsx b/frontend/src/pages/PodmanContainers.tsx new file mode 100644 index 0000000..c90c670 --- /dev/null +++ b/frontend/src/pages/PodmanContainers.tsx @@ -0,0 +1,827 @@ +import { useCallback, useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from 'react' +import { isAxiosError } from 'axios' +import { Activity, AlertCircle, ArrowDownToLine, Box, CircleStop, Container, Copy, FileText, Loader2, Package, Play, Plus, RefreshCw, RotateCw, Search, Square, Trash2 } from 'lucide-react' +import { useDialog } from '../components/Dialog' +import { Alert, AlertDescription, AlertTitle } from '../components/ui/alert' +import { Badge } from '../components/ui/badge' +import { Button } from '../components/ui/button' +import { Card } from '../components/ui/card' +import { Input } from '../components/ui/input' +import { Label } from '../components/ui/label' +import { Modal } from '../components/ui/modal' +import { NativeSelect, NativeSelectOption } from '../components/ui/native-select' +import { Switch } from '../components/ui/switch' +import { Textarea } from '../components/ui/textarea' +import { useLanguage } from '../contexts/LanguageContext' +import { + createPodmanContainer, + getPodmanLogs, + getPodmanStats, + getPodmanStatus, + listPodmanContainers, + listPodmanImages, + pullPodmanImage, + runPodmanAction, + type CreatePodmanContainerRequest, + type PodmanAction, + type PodmanContainer, + type PodmanImage, + type PodmanPort, + type PodmanStats, + type PodmanStatus, +} from '../services/api' +import { formatBytes } from '../services/operations' +import { copyToClipboard } from '../utils/clipboard' + +const statuses: Record = { + created: '待启动', + running: '运行中', + paused: '已暂停', + stopped: '已停止', + stopping: '正在停止', + restarting: '重启中', +} + +const listColumns = 'md:grid-cols-[minmax(0,1.25fr)_6.25rem_minmax(0,0.8fr)_auto]' + +function errorMessage(error: unknown, fallback: string) { + if (isAxiosError<{ message?: string }>(error)) return error.response?.data?.message || fallback + return error instanceof Error ? error.message : fallback +} + +function formatDate(value: string | undefined, language: string) { + if (!value || !Number.isFinite(Date.parse(value)) || value.startsWith('0001-')) return '—' + return new Date(value).toLocaleString(language === 'zh' ? 'zh-CN' : 'en-US') +} + +export default function PodmanContainers() { + const { t } = useLanguage() + const { confirm } = useDialog() + const request = useRef(null) + const imageRequest = useRef(null) + const [status, setStatus] = useState(null) + const [containers, setContainers] = useState([]) + const [images, setImages] = useState([]) + const [loading, setLoading] = useState(true) + const [imagesLoading, setImagesLoading] = useState(true) + const [error, setError] = useState('') + const [imageError, setImageError] = useState('') + const [actionError, setActionError] = useState('') + const [pendingId, setPendingId] = useState('') + const [create, setCreate] = useState<{ image: string } | null>(null) + const [pullOpen, setPullOpen] = useState(false) + const [detail, setDetail] = useState<{ id: string; tab: 'overview' | 'logs' } | null>(null) + const [tab, setTab] = useState<'apps' | 'images'>('apps') + const [query, setQuery] = useState('') + const [imageQuery, setImageQuery] = useState('') + const [filter, setFilter] = useState('all') + + const refresh = useCallback(async () => { + request.current?.abort() + const controller = new AbortController() + request.current = controller + setLoading(true) + setError('') + try { + const result = await getPodmanStatus(controller.signal) + const currentStatus = result.data.data + if (!currentStatus) throw new Error('无法读取 Podman 状态') + if (controller.signal.aborted) return + setStatus(currentStatus) + if (!currentStatus.available) { + setContainers([]) + return + } + const resultList = await listPodmanContainers(controller.signal) + if (!controller.signal.aborted) setContainers(resultList.data.data || []) + } catch (err) { + if (!controller.signal.aborted) setError(errorMessage(err, '无法加载 Podman 容器')) + } finally { + if (!controller.signal.aborted) setLoading(false) + } + }, []) + + const refreshImages = useCallback(async () => { + imageRequest.current?.abort() + const controller = new AbortController() + imageRequest.current = controller + setImagesLoading(true) + setImageError('') + try { + const result = await listPodmanImages(controller.signal) + if (!controller.signal.aborted) setImages(result.data.data || []) + } catch (err) { + if (!controller.signal.aborted) setImageError(errorMessage(err, '无法加载本地镜像')) + } finally { + if (!controller.signal.aborted) setImagesLoading(false) + } + }, []) + + useEffect(() => { + void refresh() + return () => request.current?.abort() + }, [refresh]) + + const engineAvailable = status?.available === true + useEffect(() => { + if (tab === 'images' && engineAvailable) void refreshImages() + return () => imageRequest.current?.abort() + }, [tab, engineAvailable, refreshImages]) + + const refreshPage = () => { + void refresh() + if (tab === 'images' && engineAvailable) void refreshImages() + } + + const performAction = async (item: PodmanContainer, action: PodmanAction) => { + if (action === 'delete') { + const accepted = await confirm('删除容器', item.name + '\n' + t('删除容器会同时移除它的可写层和持久卷。')) + if (!accepted) return + } + setPendingId(item.id) + setActionError('') + try { + await runPodmanAction(item.id, action) + if (action === 'delete') setDetail(current => current?.id === item.id ? null : current) + } catch (err) { + setActionError(errorMessage(err, '操作失败')) + } finally { + await refresh() + setPendingId('') + } + } + + const search = query.trim().toLowerCase() + const visible = containers.filter(item => + (filter === 'all' || filter === item.status) && + [item.name, item.image, item.id, ...(item.ports || []).map(port => String(port.host_port))].some(value => value.toLowerCase().includes(search)), + ) + const detailItem = detail && containers.find(item => item.id === detail.id) + const isRefreshing = loading || (tab === 'images' && imagesLoading) + + return ( +
+
+
+
+

+

+ {engineAvailable && status?.version && Podman {status.version}} +
+

{t('从 OCI 镜像运行和管理应用容器。')}

+
+
+ + +
+
+ + {error && } + {actionError && !detail && } + {status && !engineAvailable && ( + + + {t('Podman 不可用')} + +

{t('请在宿主机安装 Podman,确认面板服务可以运行 Podman 后点击刷新。')}

+ {status.message &&

{status.message}

} +
+
+ )} + {loading && !status && } + + {engineAvailable && <> +
+ } label={t('全部容器')} count={containers.length} /> + } label={t('运行中')} count={containers.filter(item => item.status === 'running').length} /> + } label={t('已停止')} count={containers.filter(item => item.status === 'stopped').length} /> +
+ + }, + { value: 'images', label: t('本地镜像'), icon: }, + ]} onChange={setTab} /> + + {tab === 'apps' ? ( + +
+ + setFilter(event.target.value)}> + {t('全部状态')} + {Object.entries(statuses).map(([value, label]) => {t(label)})} + +
+ {loading && containers.length === 0 ? : visible.length ? <> +
+ {t('容器 / 镜像')}{t('状态')}{t('端口映射')}{t('操作')} +
+
    + {visible.map(item => ( +
  • +
    +
    +
    + +

    {item.image}

    +
    +
    +
    {pendingId === item.id ? ( + {t('处理中...')} + ) : }
    +
    +
    + + + +
    +
  • + ))} +
+ : !error && ( + } title={t(containers.length ? '没有匹配的容器' : '还没有 Podman 容器。')}> + {containers.length > 0 && ( + + )} + + )} +
+ ) : ( + setCreate({ image })} /> + )} + } + + {create && setCreate(null)} onCreated={() => { + setCreate(null); setTab('apps'); setQuery(''); setFilter('all'); void refresh() + }} />} + {pullOpen && setPullOpen(false)} onPulled={() => { setPullOpen(false); setImageQuery(''); void refreshImages() }} />} + {detailItem && detail && setDetail({ id: detail.id, tab: next })} + pending={!!pendingId} refreshing={loading} error={actionError || error} onRefresh={refresh} onClose={() => setDetail(null)} onAction={performAction} />} +
+ ) +} + +function CountCard({ icon, label, count }: { icon: ReactNode; label: string; count: number }) { + return ( + +
+

{label}

+

{count}

+
+ {icon} +
+ ) +} + +function SectionTabs({ label, current, options, onChange }: { + label: string + current: T + options: { value: T; label: string; icon: ReactNode }[] + onChange: (value: T) => void +}) { + return ( +
+ {options.map(option => ( + + ))} +
+ ) +} + +function SearchField({ label, value, onChange }: { label: string; value: string; onChange: (value: string) => void }) { + return ( +
+ + onChange(event.target.value)} /> +
+ ) +} + +function EmptyState({ icon, title, children }: { icon: ReactNode; title: string; children?: ReactNode }) { + return ( +
+ {icon} +

{title}

+ {children} +
+ ) +} + +function ListLoading() { + const { t } = useLanguage() + return
{t('加载中...')}
+} + +function StatusBadge({ status }: { status: string }) { + const { t } = useLanguage() + const color = status === 'running' ? 'bg-emerald-500' : status === 'paused' ? 'bg-amber-500' : 'bg-muted-foreground' + return {t(statuses[status] || '未知')} +} + +function PortLabels({ ports, compact = false }: { ports?: PodmanPort[]; compact?: boolean }) { + const { t } = useLanguage() + if (!ports?.length) return {compact ? '—' : t('未发布端口')} + return ( +
+ {(compact ? ports.slice(0, 2) : ports).map(port => ( + + {port.host_port} → {port.container_port}/{port.protocol} + + ))} + {compact && ports.length > 2 && +{ports.length - 2}} +
+ ) +} + +function PowerButton({ item, disabled, onAction, compact = false }: { + item: PodmanContainer; disabled: boolean; onAction: (item: PodmanContainer, action: PodmanAction) => Promise; compact?: boolean +}) { + const { t } = useLanguage() + const canStop = item.status === 'running' || item.status === 'paused' + if (!canStop && item.status !== 'created' && item.status !== 'stopped') return null + const label = t(canStop ? '停止' : '启动') + return ( + + ) +} + +interface PortDraft { + id: number + host_port: string + container_port: string + protocol: PodmanPort['protocol'] +} + +function CreateModal({ initialImage, onClose, onCreated }: { initialImage: string; onClose: () => void; onCreated: () => void }) { + const { t } = useLanguage() + const formId = useId() + const nextPortId = useRef(0) + const [name, setName] = useState('') + const [image, setImage] = useState(initialImage) + const [cpus, setCpus] = useState('') + const [memory, setMemory] = useState('') + const [ports, setPorts] = useState([]) + const [command, setCommand] = useState('') + const [env, setEnv] = useState('') + const [volumes, setVolumes] = useState('') + const [submitting, setSubmitting] = useState(false) + const [error, setError] = useState('') + + const changePort = (id: number, patch: Partial>) => { + setPorts(items => items.map(item => item.id === id ? { ...item, ...patch } : item)) + } + + const submit = async (event: FormEvent) => { + event.preventDefault() + setError('') + let args: string[] | undefined + if (command.trim()) { + try { + const parsed: unknown = JSON.parse(command) + if (!Array.isArray(parsed) || !parsed.every(item => typeof item === 'string')) throw new Error() + args = parsed + } catch { + setError('启动参数须填写为 JSON 字符串数组。') + return + } + } + const envEntries: Array<[string, string]> = [] + const names = new Set() + for (const line of env.split(/\r?\n/)) { + if (!line.trim()) continue + const separator = line.indexOf('=') + const key = line.slice(0, separator) + if (separator < 1 || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key) || names.has(key)) { + setError('环境变量每行须为 KEY=value,且变量名不能重复。') + return + } + names.add(key) + envEntries.push([key, line.slice(separator + 1)]) + } + const request: CreatePodmanContainerRequest = { + name: name.trim(), + image: image.trim(), + cpus: cpus ? Number(cpus) : undefined, + memory_mb: memory ? Number(memory) : undefined, + ports: ports.map(port => ({ host_port: Number(port.host_port), container_port: Number(port.container_port), protocol: port.protocol })), + command: args, + env: envEntries.length ? Object.fromEntries(envEntries) : undefined, + volumes: volumes.split(/\r?\n/).map(path => path.trim()).filter(Boolean), + } + setSubmitting(true) + try { + await createPodmanContainer(request) + onCreated() + } catch (err) { + setError(errorMessage(err, '创建 Podman 容器失败')) + } finally { + setSubmitting(false) + } + } + + return ( + + + + }> +
+ {error && } +
+
+

{t('基础设置')}

+
+
+ + setName(event.target.value)} placeholder="web-demo" maxLength={64} required /> +
+
+ + setImage(event.target.value)} placeholder="docker.io/library/nginx:alpine" spellCheck={false} required /> +

{t('填写包含仓库域名的完整镜像名称。')}

+
+
+
+
+

{t('资源限制')}

+
+
+ + setCpus(event.target.value)} placeholder={t('可选')} /> +
+
+ + setMemory(event.target.value)} placeholder={t('可选')} /> +
+
+
+
+
+

{t('端口映射')}

+ +
+

{t('服务可通过宿主机地址和已发布的端口访问。')}

+

{t('请选择 CLICD IPv4 NAT 配置范围(默认 20000–65535)之外的宿主机端口,避免冲突。')}

+ {ports.map((port) => { + const id = formId + '-port-' + port.id + return ( +
+
+ + changePort(port.id, { host_port: event.target.value })} placeholder="8080" required /> +
+
+ + changePort(port.id, { container_port: event.target.value })} placeholder="80" required /> +
+
+ + changePort(port.id, { protocol: event.target.value as PodmanPort['protocol'] })}> + TCP + UDP + +
+ +
+ ) + })} +
+
+ {t('高级选项')} +
+
+ +