mirror of
https://github.com/MengMengCode/CLICD.git
synced 2026-12-06 05:15:59 +08:00
feat: add Podman application management
This commit is contained in:
@@ -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"})
|
||||
|
||||
@@ -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, "")
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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","<none>:<none>"],"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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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))))
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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://<host-address>: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.
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
容器管理是 CLICD 的核心模块,覆盖创建、生命周期控制、资源限制、网络映射、流量统计、密码重置和控制台访问。
|
||||
|
||||
使用 OCI 镜像部署应用时,请打开 [Podman 容器](./podman)。
|
||||
|
||||
## 容器列表
|
||||
|
||||
列表页用于扫描所有容器状态。管理员可以查看全部容器,子用户只能看到授权范围内的容器。
|
||||
|
||||
@@ -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 卷在停止和重启期间保留数据。删除容器会一并删除其匿名卷。删除前请先备份需要保留的应用数据。
|
||||
@@ -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 <Dashboard />
|
||||
}
|
||||
|
||||
function PodmanRoute() {
|
||||
const { isSubUser } = useAuth()
|
||||
return isSubUser ? <Navigate to="/containers" replace /> : <PodmanContainers />
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Routes>
|
||||
@@ -59,6 +65,7 @@ function App() {
|
||||
>
|
||||
<Route index element={<HomeRoute />} />
|
||||
<Route path="containers" element={<Containers />} />
|
||||
<Route path="podman" element={<PodmanRoute />} />
|
||||
<Route path="images" element={<ImageManagement />} />
|
||||
<Route path="container/:id" element={<ContainerDetail />} />
|
||||
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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<string, string> = {
|
||||
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<AbortController | null>(null)
|
||||
const imageRequest = useRef<AbortController | null>(null)
|
||||
const [status, setStatus] = useState<PodmanStatus | null>(null)
|
||||
const [containers, setContainers] = useState<PodmanContainer[]>([])
|
||||
const [images, setImages] = useState<PodmanImage[]>([])
|
||||
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 (
|
||||
<div className="mx-auto max-w-7xl space-y-5">
|
||||
<header className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight">
|
||||
<Container className="size-5 shrink-0" aria-hidden="true" />
|
||||
{t('Podman 容器')}
|
||||
</h1>
|
||||
{engineAvailable && status?.version && <Badge variant="outline">Podman {status.version}</Badge>}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t('从 OCI 镜像运行和管理应用容器。')}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" disabled={isRefreshing} onClick={refreshPage}>
|
||||
<RefreshCw className={isRefreshing ? 'size-4 animate-spin' : 'size-4'} />{t('刷新')}
|
||||
</Button>
|
||||
<Button disabled={!engineAvailable || isRefreshing} onClick={() => tab === 'apps' ? setCreate({ image: '' }) : setPullOpen(true)}>
|
||||
{tab === 'apps' ? <Plus className="size-4" /> : <ArrowDownToLine className="size-4" />}
|
||||
{t(tab === 'apps' ? '创建容器' : '拉取镜像')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{error && <ErrorAlert message={t(error)} />}
|
||||
{actionError && !detail && <ErrorAlert message={t(actionError)} />}
|
||||
{status && !engineAvailable && (
|
||||
<Alert>
|
||||
<AlertCircle className="size-4" />
|
||||
<AlertTitle>{t('Podman 不可用')}</AlertTitle>
|
||||
<AlertDescription className="space-y-1 break-words">
|
||||
<p>{t('请在宿主机安装 Podman,确认面板服务可以运行 Podman 后点击刷新。')}</p>
|
||||
{status.message && <p data-no-translate>{status.message}</p>}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{loading && !status && <ListLoading />}
|
||||
|
||||
{engineAvailable && <>
|
||||
<div className="grid grid-cols-3 gap-2 sm:gap-3">
|
||||
<CountCard icon={<Box />} label={t('全部容器')} count={containers.length} />
|
||||
<CountCard icon={<Activity />} label={t('运行中')} count={containers.filter(item => item.status === 'running').length} />
|
||||
<CountCard icon={<CircleStop />} label={t('已停止')} count={containers.filter(item => item.status === 'stopped').length} />
|
||||
</div>
|
||||
|
||||
<SectionTabs label={t('Podman 工作区')} current={tab} options={[
|
||||
{ value: 'apps', label: t('应用容器'), icon: <Container className="size-4" /> },
|
||||
{ value: 'images', label: t('本地镜像'), icon: <Package className="size-4" /> },
|
||||
]} onChange={setTab} />
|
||||
|
||||
{tab === 'apps' ? (
|
||||
<Card className="min-w-0 overflow-hidden p-0" aria-busy={loading}>
|
||||
<div className="flex flex-wrap items-center gap-2 border-b p-3 sm:px-4">
|
||||
<SearchField label={t('搜索容器名称、镜像或端口')} value={query} onChange={setQuery} />
|
||||
<NativeSelect aria-label={t('筛选运行状态')} value={filter} onChange={event => setFilter(event.target.value)}>
|
||||
<NativeSelectOption value="all">{t('全部状态')}</NativeSelectOption>
|
||||
{Object.entries(statuses).map(([value, label]) => <NativeSelectOption value={value} key={value}>{t(label)}</NativeSelectOption>)}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
{loading && containers.length === 0 ? <ListLoading /> : visible.length ? <>
|
||||
<div className={'hidden gap-3 border-b bg-muted/30 px-4 py-2.5 text-xs text-muted-foreground md:grid ' + listColumns}>
|
||||
<span>{t('容器 / 镜像')}</span><span>{t('状态')}</span><span>{t('端口映射')}</span><span className="w-36 text-right">{t('操作')}</span>
|
||||
</div>
|
||||
<ul className="divide-y">
|
||||
{visible.map(item => (
|
||||
<li key={item.id} className={'grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 px-4 py-3 ' + listColumns}>
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<div className="hidden shrink-0 rounded-lg border bg-muted/30 p-2 sm:block"><Box className="size-4 text-muted-foreground" /></div>
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<button type="button" onClick={() => { setActionError(''); setDetail({ id: item.id, tab: 'overview' }) }} className="block max-w-full truncate text-left text-sm font-medium hover:underline focus-visible:outline-ring" title={item.name} data-no-translate>{item.name}</button>
|
||||
<p className="truncate font-mono text-xs text-muted-foreground" title={item.image} data-no-translate>{item.image}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="justify-self-end md:justify-self-start">{pendingId === item.id ? (
|
||||
<Badge variant="outline" role="status"><Loader2 className="size-3 animate-spin" />{t('处理中...')}</Badge>
|
||||
) : <StatusBadge status={item.status} />}</div>
|
||||
<div className="min-w-0"><PortLabels ports={item.ports} compact /></div>
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button size="icon" className="size-8" variant="ghost" aria-label={t('查看详情')} title={t('查看详情')} onClick={() => { setActionError(''); setDetail({ id: item.id, tab: 'overview' }) }}><Activity /></Button>
|
||||
<Button size="icon" className="size-8" variant="ghost" aria-label={t('日志')} title={t('日志')} onClick={() => { setActionError(''); setDetail({ id: item.id, tab: 'logs' }) }}><FileText /></Button>
|
||||
<PowerButton item={item} disabled={!!pendingId} onAction={performAction} compact />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</> : !error && (
|
||||
<EmptyState icon={<Box />} title={t(containers.length ? '没有匹配的容器' : '还没有 Podman 容器。')}>
|
||||
{containers.length > 0 && (
|
||||
<Button size="sm" variant="outline" onClick={() => { setQuery(''); setFilter('all') }}>{t('清除筛选')}</Button>
|
||||
)}
|
||||
</EmptyState>
|
||||
)}
|
||||
</Card>
|
||||
) : (
|
||||
<ImageList images={images} query={imageQuery} onQueryChange={setImageQuery} loading={imagesLoading} error={imageError}
|
||||
onUse={image => setCreate({ image })} />
|
||||
)}
|
||||
</>}
|
||||
|
||||
{create && <CreateModal initialImage={create.image} onClose={() => setCreate(null)} onCreated={() => {
|
||||
setCreate(null); setTab('apps'); setQuery(''); setFilter('all'); void refresh()
|
||||
}} />}
|
||||
{pullOpen && <PullImageModal onClose={() => setPullOpen(false)} onPulled={() => { setPullOpen(false); setImageQuery(''); void refreshImages() }} />}
|
||||
{detailItem && detail && <DetailsModal key={detailItem.id} container={detailItem} tab={detail.tab} onTab={next => setDetail({ id: detail.id, tab: next })}
|
||||
pending={!!pendingId} refreshing={loading} error={actionError || error} onRefresh={refresh} onClose={() => setDetail(null)} onAction={performAction} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CountCard({ icon, label, count }: { icon: ReactNode; label: string; count: number }) {
|
||||
return (
|
||||
<Card className="flex min-w-0 flex-row items-start justify-between gap-1 p-3 sm:p-4">
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className="text-2xl font-semibold tabular-nums">{count}</p>
|
||||
</div>
|
||||
<span className="hidden shrink-0 rounded-md bg-muted p-2 text-muted-foreground [&>svg]:size-4 sm:block">{icon}</span>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function SectionTabs<T extends string>({ label, current, options, onChange }: {
|
||||
label: string
|
||||
current: T
|
||||
options: { value: T; label: string; icon: ReactNode }[]
|
||||
onChange: (value: T) => void
|
||||
}) {
|
||||
return (
|
||||
<div role="group" aria-label={label} className="inline-flex max-w-full flex-wrap items-center gap-1 rounded-lg bg-muted p-1">
|
||||
{options.map(option => (
|
||||
<Button key={option.value} type="button" variant="ghost" size="sm" aria-pressed={current === option.value} onClick={() => onChange(option.value)}
|
||||
className="gap-2 text-muted-foreground aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-sm">
|
||||
{option.icon}{option.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SearchField({ label, value, onChange }: { label: string; value: string; onChange: (value: string) => void }) {
|
||||
return (
|
||||
<div className="relative flex-1 sm:max-w-80">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input aria-label={label} placeholder={label} type="search" className="pl-9" value={value} onChange={event => onChange(event.target.value)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyState({ icon, title, children }: { icon: ReactNode; title: string; children?: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-44 flex-col items-center justify-center gap-3 px-4 py-8 text-center">
|
||||
<span className="rounded-full bg-muted p-3 text-muted-foreground [&>svg]:size-5">{icon}</span>
|
||||
<p className="text-sm font-medium">{title}</p>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ListLoading() {
|
||||
const { t } = useLanguage()
|
||||
return <div role="status" className="flex items-center justify-center gap-2 px-4 py-10 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />{t('加载中...')}</div>
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
const { t } = useLanguage()
|
||||
const color = status === 'running' ? 'bg-emerald-500' : status === 'paused' ? 'bg-amber-500' : 'bg-muted-foreground'
|
||||
return <Badge variant="outline" className="gap-1.5"><span aria-hidden className={'size-1.5 rounded-full ' + color} />{t(statuses[status] || '未知')}</Badge>
|
||||
}
|
||||
|
||||
function PortLabels({ ports, compact = false }: { ports?: PodmanPort[]; compact?: boolean }) {
|
||||
const { t } = useLanguage()
|
||||
if (!ports?.length) return <span className="text-xs text-muted-foreground">{compact ? '—' : t('未发布端口')}</span>
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{(compact ? ports.slice(0, 2) : ports).map(port => (
|
||||
<Badge key={port.host_port + '/' + port.protocol} variant="secondary" className="font-mono font-normal" data-no-translate>
|
||||
{port.host_port} → {port.container_port}/{port.protocol}
|
||||
</Badge>
|
||||
))}
|
||||
{compact && ports.length > 2 && <Badge variant="outline">+{ports.length - 2}</Badge>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PowerButton({ item, disabled, onAction, compact = false }: {
|
||||
item: PodmanContainer; disabled: boolean; onAction: (item: PodmanContainer, action: PodmanAction) => Promise<void>; 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 (
|
||||
<Button size={compact ? 'icon' : 'sm'} className={compact ? 'size-8' : undefined} variant={compact ? 'ghost' : 'outline'} disabled={disabled} onClick={() => void onAction(item, canStop ? 'stop' : 'start')} aria-label={label} title={label}>
|
||||
{canStop ? <Square /> : <Play />}{!compact && label}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
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<PortDraft[]>([])
|
||||
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<Omit<PortDraft, 'id'>>) => {
|
||||
setPorts(items => items.map(item => item.id === id ? { ...item, ...patch } : item))
|
||||
}
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
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<string>()
|
||||
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 (
|
||||
<Modal title={t('创建 Podman 容器')} size="3xl" onClose={onClose} dismissible={!submitting}
|
||||
footer={<>
|
||||
<Button variant="outline" disabled={submitting} onClick={onClose}>{t('取消')}</Button>
|
||||
<Button type="submit" form={formId} disabled={submitting}>
|
||||
{submitting && <Loader2 className="size-4 animate-spin" />}
|
||||
{t(submitting ? '正在拉取镜像并创建容器...' : '创建容器')}
|
||||
</Button>
|
||||
</>}>
|
||||
<form id={formId} onSubmit={submit} className="space-y-4" aria-busy={submitting}>
|
||||
{error && <ErrorAlert message={t(error)} />}
|
||||
<fieldset disabled={submitting} className="min-w-0 space-y-5">
|
||||
<section className="space-y-3 rounded-lg border p-3 sm:p-4">
|
||||
<h2 className="text-sm font-medium">{t('基础设置')}</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-name'}>{t('容器名称')}</Label>
|
||||
<Input id={formId + '-name'} value={name} onChange={event => setName(event.target.value)} placeholder="web-demo" maxLength={64} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-image'}>{t('OCI 镜像')}</Label>
|
||||
<Input id={formId + '-image'} value={image} onChange={event => setImage(event.target.value)} placeholder="docker.io/library/nginx:alpine" spellCheck={false} required />
|
||||
<p className="text-xs text-muted-foreground">{t('填写包含仓库域名的完整镜像名称。')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section className="space-y-3 rounded-lg border p-3 sm:p-4">
|
||||
<h2 className="text-sm font-medium">{t('资源限制')}</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-cpus'}>{t('CPU 上限(核)')}</Label>
|
||||
<Input id={formId + '-cpus'} type="number" min="0.01" max="256" step="0.01" value={cpus} onChange={event => setCpus(event.target.value)} placeholder={t('可选')} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-memory'}>{t('内存上限(MiB)')}</Label>
|
||||
<Input id={formId + '-memory'} type="number" min="16" max="1048576" step="1" value={memory} onChange={event => setMemory(event.target.value)} placeholder={t('可选')} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section className="space-y-2 rounded-lg border p-3 sm:p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="text-sm font-medium">{t('端口映射')}</h2>
|
||||
<Button size="sm" type="button" variant="outline" onClick={() => {
|
||||
const id = nextPortId.current++
|
||||
setPorts(items => [...items, { id, host_port: '', container_port: '', protocol: 'tcp' }])
|
||||
}}><Plus className="size-3.5" />{t('添加端口')}</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('服务可通过宿主机地址和已发布的端口访问。')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('请选择 CLICD IPv4 NAT 配置范围(默认 20000–65535)之外的宿主机端口,避免冲突。')}</p>
|
||||
{ports.map((port) => {
|
||||
const id = formId + '-port-' + port.id
|
||||
return (
|
||||
<div key={port.id} className="grid min-w-0 grid-cols-2 items-end gap-2 rounded-md border p-2 sm:grid-cols-[1fr_1fr_1fr_auto]">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<Label className="text-xs leading-tight" htmlFor={id + '-host'}>{t('宿主机端口')}</Label>
|
||||
<Input id={id + '-host'} type="number" min={1} max={65535} value={port.host_port} onChange={event => changePort(port.id, { host_port: event.target.value })} placeholder="8080" required />
|
||||
</div>
|
||||
<div className="min-w-0 space-y-1">
|
||||
<Label className="text-xs leading-tight" htmlFor={id + '-container'}>{t('容器端口')}</Label>
|
||||
<Input id={id + '-container'} type="number" min={1} max={65535} value={port.container_port} onChange={event => changePort(port.id, { container_port: event.target.value })} placeholder="80" required />
|
||||
</div>
|
||||
<div className="min-w-0 space-y-1">
|
||||
<Label className="text-xs" htmlFor={id + '-protocol'}>{t('协议')}</Label>
|
||||
<NativeSelect id={id + '-protocol'} wrapperClassName="w-full" value={port.protocol} onChange={event => changePort(port.id, { protocol: event.target.value as PodmanPort['protocol'] })}>
|
||||
<NativeSelectOption value="tcp">TCP</NativeSelectOption>
|
||||
<NativeSelectOption value="udp">UDP</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
</div>
|
||||
<Button size="icon" type="button" variant="ghost" className="justify-self-end" aria-label={t('移除此端口映射')} title={t('移除此端口映射')} onClick={() => setPorts(items => items.filter(item => item.id !== port.id))}><Trash2 className="size-4" /></Button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
<details className="rounded-lg border p-3">
|
||||
<summary className="cursor-pointer text-sm font-medium">{t('高级选项')}</summary>
|
||||
<div className="mt-4 space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-command'}>{t('启动参数')}</Label>
|
||||
<Textarea id={formId + '-command'} className="font-mono text-xs" value={command} onChange={event => setCommand(event.target.value)} placeholder={'["sh", "-c", "sleep 3600"]'} rows={2} spellCheck={false} />
|
||||
<p className="text-xs text-muted-foreground">{t('填写 JSON 字符串数组。留空时使用镜像默认参数。')}</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-env'}>{t('环境变量')}</Label>
|
||||
<Textarea id={formId + '-env'} className="font-mono text-xs" value={env} onChange={event => setEnv(event.target.value)} placeholder="TZ=Asia/Singapore" rows={2} spellCheck={false} />
|
||||
<p className="text-xs text-muted-foreground">{t('每行一条 KEY=value。')}</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-volumes'}>{t('持久卷')}</Label>
|
||||
<Textarea id={formId + '-volumes'} className="font-mono text-xs" value={volumes} onChange={event => setVolumes(event.target.value)} placeholder="/app/data" rows={2} spellCheck={false} />
|
||||
<p className="text-xs text-muted-foreground">{t('每行填写一个容器内绝对路径。数据在容器停止后保留,删除容器时移除。')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</fieldset>
|
||||
</form>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function ImageList({ images, query, onQueryChange, loading, error, onUse }: {
|
||||
images: PodmanImage[]; query: string; onQueryChange: (query: string) => void
|
||||
loading: boolean; error: string; onUse: (image: string) => void
|
||||
}) {
|
||||
const { t, language } = useLanguage()
|
||||
const search = query.trim().toLowerCase()
|
||||
const matches = images.filter(image => image.id.toLowerCase().includes(search) || image.tags?.some(tag => tag.toLowerCase().includes(search)))
|
||||
return (
|
||||
<Card className="min-w-0 overflow-hidden p-0" aria-busy={loading}>
|
||||
<div className="flex flex-wrap items-center gap-2 border-b p-3 sm:px-4">
|
||||
<SearchField label={t('搜索镜像名称或 ID')} value={query} onChange={onQueryChange} />
|
||||
{!loading && !error && <span className="ml-auto text-xs tabular-nums text-muted-foreground">{matches.length} / {images.length}</span>}
|
||||
</div>
|
||||
{error && <div className="p-4"><ErrorAlert message={t(error)} /></div>}
|
||||
{loading && images.length === 0 ? <ListLoading /> : matches.length ? (
|
||||
<ul className="divide-y">
|
||||
{matches.map(image => (
|
||||
<li key={image.id} className="p-4">
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<span className="shrink-0 rounded-lg border bg-muted/30 p-2"><Package className="size-4 text-muted-foreground" /></span>
|
||||
<div className="min-w-0 space-y-1.5">
|
||||
<p className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
|
||||
<span className="font-mono" title={image.id} data-no-translate>{image.id.replace(/^sha256:/, '').slice(0, 12)}</span>
|
||||
<span>{formatBytes(image.size_bytes)}</span>
|
||||
<span>{formatDate(image.created_at, language)}</span>
|
||||
</p>
|
||||
{image.tags?.length ? (
|
||||
<ul className="space-y-1.5">
|
||||
{image.tags.map(tag => (
|
||||
<li key={tag} className="flex min-w-0 flex-wrap items-center gap-1.5">
|
||||
<span className="break-all font-mono text-xs font-medium" data-no-translate>{tag}</span>
|
||||
<Button type="button" variant="outline" className="h-6 px-2 text-xs" onClick={() => onUse(tag)}>{t('使用镜像')}</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="text-sm text-muted-foreground">{t('无标签')}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : !error && (
|
||||
<EmptyState icon={<Package />} title={t(images.length ? '没有匹配的镜像' : '还没有本地 OCI 镜像。')}>
|
||||
{images.length > 0 && <Button size="sm" variant="outline" onClick={() => onQueryChange('')}>{t('清除筛选')}</Button>}
|
||||
</EmptyState>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function PullImageModal({ onClose, onPulled }: { onClose: () => void; onPulled: () => void }) {
|
||||
const { t } = useLanguage()
|
||||
const formId = useId()
|
||||
const [image, setImage] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
if (!image.trim() || busy) return
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
await pullPodmanImage(image.trim())
|
||||
onPulled()
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, '拉取镜像失败'))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal title={t('拉取镜像')} onClose={onClose} dismissible={!busy} footer={<>
|
||||
<Button variant="outline" onClick={onClose} disabled={busy}>{t('取消')}</Button>
|
||||
<Button type="submit" form={formId} disabled={busy}>{busy && <Loader2 className="size-4 animate-spin" />}{t(busy ? '正在拉取镜像…' : '拉取镜像')}</Button>
|
||||
</>}>
|
||||
<form className="space-y-3" id={formId} onSubmit={submit} aria-busy={busy}>
|
||||
{error && <ErrorAlert message={t(error)} />}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={formId + '-image'}>{t('OCI 镜像')}</Label>
|
||||
<Input id={formId + '-image'} value={image} onChange={event => setImage(event.target.value)} placeholder="docker.io/library/nginx:alpine" spellCheck={false} disabled={busy} required />
|
||||
<p className="text-xs text-muted-foreground">{t('填写包含仓库域名的完整镜像名称。')}</p>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function DetailsModal({ container, tab, onTab, pending, refreshing, error, onRefresh, onClose, onAction }: {
|
||||
container: PodmanContainer
|
||||
tab: 'overview' | 'logs'
|
||||
onTab: (tab: 'overview' | 'logs') => void
|
||||
pending: boolean
|
||||
refreshing: boolean
|
||||
error: string
|
||||
onRefresh: () => Promise<void>
|
||||
onClose: () => void
|
||||
onAction: (item: PodmanContainer, action: PodmanAction) => Promise<void>
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
const active = container.status === 'running' || container.status === 'paused'
|
||||
return (
|
||||
<Modal title={<span data-no-translate>{container.name}</span>} description={t('容器详情')} extra={<StatusBadge status={container.status} />} size="4xl" onClose={onClose}
|
||||
footer={<>
|
||||
<Button variant="ghost" className="text-destructive sm:mr-auto" disabled={pending} onClick={() => void onAction(container, 'delete')}><Trash2 className="size-4" />{t('删除')}</Button>
|
||||
<PowerButton item={container} disabled={pending} onAction={onAction} />
|
||||
{active && <Button variant="outline" disabled={pending} onClick={() => void onAction(container, 'restart')}><RotateCw className="size-4" />{t('重启')}</Button>}
|
||||
<Button onClick={onClose}>{t('关闭')}</Button>
|
||||
</>}>
|
||||
<div className="space-y-4" aria-busy={pending}>
|
||||
{error && <ErrorAlert message={t(error)} />}
|
||||
{pending && <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />{t('处理中...')}</p>}
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<SectionTabs label={t('容器详情')} current={tab} options={[
|
||||
{ value: 'overview', label: t('概览'), icon: <Activity className="size-4" /> },
|
||||
{ value: 'logs', label: t('日志'), icon: <FileText className="size-4" /> },
|
||||
]} onChange={onTab} />
|
||||
{tab === 'overview' && <Button size="sm" variant="outline" disabled={pending || refreshing} onClick={() => void onRefresh()}>
|
||||
<RefreshCw className={refreshing ? 'size-4 animate-spin' : 'size-4'} />{t('刷新')}
|
||||
</Button>}
|
||||
</div>
|
||||
{tab === 'overview' ? <ContainerOverview container={container} /> : <ContainerLogs container={container} />}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContainerOverview({ container }: { container: PodmanContainer }) {
|
||||
const { t, language } = useLanguage()
|
||||
const fields = [
|
||||
[t('OCI 镜像'), container.image, 'font-mono'],
|
||||
['ID', container.id, 'font-mono'],
|
||||
[t('创建时间'), formatDate(container.created_at, language), ''],
|
||||
[t('最近启动'), formatDate(container.started_at, language), ''],
|
||||
...(container.health ? [[t('健康检查'), t(({ healthy: '健康', unhealthy: '异常', starting: '正在启动' } as Record<string, string>)[container.health] || container.health), '']] : []),
|
||||
...(container.status === 'stopped' && container.exit_code != null ? [[t('退出码'), String(container.exit_code), 'font-mono']] : []),
|
||||
...(container.status === 'stopped' && container.finished_at ? [[t('最近退出'), formatDate(container.finished_at, language), '']] : []),
|
||||
[t('CPU 上限'), container.cpus ? String(container.cpus) : t('未限制'), ''],
|
||||
[t('内存上限'), container.memory_mb ? container.memory_mb + ' MiB' : t('未限制'), ''],
|
||||
]
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<dl className="grid gap-3 rounded-lg border p-3 sm:grid-cols-2 sm:p-4">
|
||||
{fields.map(([label, value, className]) => (
|
||||
<div key={label} className="min-w-0 space-y-1">
|
||||
<dt className="text-xs text-muted-foreground">{label}</dt>
|
||||
<dd className={'text-sm [overflow-wrap:anywhere] ' + className} data-no-translate>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="min-w-0 space-y-2 rounded-lg border p-3 sm:p-4">
|
||||
<h3 className="text-sm font-medium">{t('端口映射')}</h3>
|
||||
<PortLabels ports={container.ports} />
|
||||
</div>
|
||||
<div className="min-w-0 space-y-2 rounded-lg border p-3 sm:p-4">
|
||||
<h3 className="text-sm font-medium">{t('持久卷')}</h3>
|
||||
{container.volumes?.length ? <ul className="flex flex-wrap gap-1.5">{container.volumes.map(volume => (
|
||||
<li key={volume} className="max-w-full break-all rounded bg-muted px-2 py-1 font-mono text-xs" data-no-translate>{volume}</li>
|
||||
))}</ul> : <p className="text-xs text-muted-foreground">{t('未配置持久卷')}</p>}
|
||||
</div>
|
||||
</div>
|
||||
{container.status === 'running' ? <LiveStats key={container.id} id={container.id} /> : (
|
||||
<div className="rounded-lg border p-3 sm:p-4"><h3 className="text-sm font-medium">{t('实时资源')}</h3><p className="mt-2 text-xs text-muted-foreground">{t('容器运行后显示实时资源。')}</p></div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function usePollingResource<T>(load: (signal: AbortSignal) => Promise<T>, fallback: string, interval = 0) {
|
||||
const [data, setData] = useState<T>()
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [revision, setRevision] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let timer: number | undefined
|
||||
const controller = new AbortController()
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const value = await load(controller.signal)
|
||||
if (!controller.signal.aborted) {
|
||||
setData(value)
|
||||
setError('')
|
||||
}
|
||||
} catch (err) {
|
||||
if (!controller.signal.aborted) setError(errorMessage(err, fallback))
|
||||
} finally {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false)
|
||||
if (interval) timer = window.setTimeout(() => void refresh(), interval)
|
||||
}
|
||||
}
|
||||
}
|
||||
setLoading(true)
|
||||
void refresh()
|
||||
return () => {
|
||||
controller.abort()
|
||||
window.clearTimeout(timer)
|
||||
}
|
||||
}, [load, fallback, interval, revision])
|
||||
|
||||
return { data, loading, error, refresh: () => setRevision(current => current + 1) }
|
||||
}
|
||||
|
||||
function LiveStats({ id }: { id: string }) {
|
||||
const { t } = useLanguage()
|
||||
const load = useCallback(async (signal: AbortSignal) => (await getPodmanStats(id, signal)).data.data, [id])
|
||||
const { data, loading, error } = usePollingResource(load, '无法读取容器资源', 5000)
|
||||
const metrics = data ? statsMetrics(data, t) : []
|
||||
return (
|
||||
<div className="space-y-3 rounded-lg border p-3 sm:p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h3 className="flex items-center gap-2 text-sm font-medium"><Activity className="size-4 text-muted-foreground" />{t('实时资源')}</h3>
|
||||
<span className="text-xs text-muted-foreground">{t('每 5 秒刷新')}</span>
|
||||
</div>
|
||||
{error && <ErrorAlert message={t(error)} />}
|
||||
{metrics.length ? <dl className="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
||||
{metrics.map(([label, value]) => (
|
||||
<div key={label} className="min-w-0 space-y-1 rounded-md bg-muted/50 px-3 py-2">
|
||||
<dt className="text-xs text-muted-foreground">{label}</dt>
|
||||
<dd className="break-words text-sm font-medium tabular-nums" data-no-translate>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl> : !error && <p role="status" className="text-sm text-muted-foreground">{t(loading ? '加载中...' : '暂无资源数据')}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function statsMetrics(metrics: PodmanStats, t: (text: string) => string) {
|
||||
const usage = metrics.memory_used_bytes == null ? '—' : formatBytes(metrics.memory_used_bytes)
|
||||
const memory = metrics.memory_limit_bytes ? usage + ' / ' + formatBytes(metrics.memory_limit_bytes) : usage
|
||||
const bytes = (value: number | null) => value == null ? '—' : formatBytes(value)
|
||||
return [
|
||||
['CPU', metrics.cpu_percent == null ? '—' : metrics.cpu_percent.toFixed(1) + '%'],
|
||||
[t('内存'), memory],
|
||||
[t('进程数'), String(metrics.pids ?? '—')],
|
||||
[t('网络接收 / 发送'), bytes(metrics.network_rx_bytes) + ' / ' + bytes(metrics.network_tx_bytes)],
|
||||
[t('磁盘读取 / 写入'), bytes(metrics.block_read_bytes) + ' / ' + bytes(metrics.block_write_bytes)],
|
||||
]
|
||||
}
|
||||
|
||||
function ContainerLogs({ container }: { container: PodmanContainer }) {
|
||||
const { t } = useLanguage()
|
||||
const { alert } = useDialog()
|
||||
const [follow, setFollow] = useState(false)
|
||||
const sectionRef = useRef<HTMLElement | null>(null)
|
||||
const logRef = useRef<HTMLPreElement | null>(null)
|
||||
const load = useCallback(async (signal: AbortSignal) => (await getPodmanLogs(container.id, signal)).data.data?.logs || '', [container.id])
|
||||
const { data: logs = '', loading, error, refresh } = usePollingResource(load, '无法读取容器日志', follow ? 3000 : 0)
|
||||
|
||||
useEffect(() => {
|
||||
const element = logRef.current
|
||||
if (follow && element) element.scrollTop = element.scrollHeight
|
||||
}, [logs, follow])
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
if (await copyToClipboard(logs, sectionRef.current ?? undefined)) {
|
||||
await alert('复制成功', '日志已复制到剪贴板。')
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// The download action remains available when the browser blocks clipboard access.
|
||||
}
|
||||
await alert('复制失败', '可使用下载日志保存内容。')
|
||||
}
|
||||
|
||||
const download = () => {
|
||||
const url = URL.createObjectURL(new Blob([logs], { type: 'text/plain;charset=utf-8' }))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = container.name.replace(/[^A-Za-z0-9_.-]+/g, '-') + '.log'
|
||||
link.click()
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
|
||||
return (
|
||||
<section ref={sectionRef} className="min-w-0 space-y-3" aria-label={t('容器日志')} aria-busy={loading}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<label className="mr-auto flex items-center gap-2 text-xs text-muted-foreground"><Switch checked={follow} onCheckedChange={setFollow} />{t('自动刷新')}</label>
|
||||
<Button variant="outline" size="sm" disabled={loading} onClick={refresh}><RefreshCw className="size-4" />{t('刷新')}</Button>
|
||||
<Button variant="outline" size="sm" disabled={!logs} onClick={() => void copy()}><Copy className="size-4" />{t('复制日志')}</Button>
|
||||
<Button variant="outline" size="sm" disabled={!logs} onClick={download}><ArrowDownToLine className="size-4" />{t('下载日志')}</Button>
|
||||
</div>
|
||||
{error && <ErrorAlert message={t(error)} />}
|
||||
{logs ? <pre ref={logRef} className="max-h-[48dvh] min-h-32 overflow-auto whitespace-pre-wrap break-words rounded-md border bg-muted/40 p-3 font-mono text-xs leading-relaxed" tabIndex={0} data-no-translate>{logs}</pre>
|
||||
: <div role="status" className="min-h-28 rounded-md border bg-muted/30 px-3 py-6 text-center text-sm text-muted-foreground">{t(loading ? '加载中...' : '该容器暂无日志。')}</div>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function ErrorAlert({ message }: { message: string }) {
|
||||
return <Alert variant="destructive"><AlertCircle className="size-4" /><AlertDescription className="whitespace-pre-wrap break-words">{message}</AlertDescription></Alert>
|
||||
}
|
||||
@@ -1111,4 +1111,89 @@ export const updateLanguage = (language: PanelLanguage) =>
|
||||
export const getVersion = () =>
|
||||
api.get<APIResponse<{ version: string }>>('/version')
|
||||
|
||||
export interface PodmanStatus {
|
||||
available: boolean
|
||||
version?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface PodmanPort {
|
||||
host_port: number
|
||||
container_port: number
|
||||
protocol: 'tcp' | 'udp'
|
||||
}
|
||||
|
||||
export interface PodmanContainer {
|
||||
id: string
|
||||
name: string
|
||||
image: string
|
||||
status: string
|
||||
created_at?: string
|
||||
ports?: PodmanPort[]
|
||||
memory_mb?: number
|
||||
cpus?: number
|
||||
volumes?: string[]
|
||||
exit_code?: number
|
||||
started_at?: string
|
||||
finished_at?: string
|
||||
health?: string
|
||||
}
|
||||
|
||||
export interface PodmanImage {
|
||||
id: string
|
||||
tags: string[]
|
||||
size_bytes: number
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface PodmanStats {
|
||||
cpu_percent: number | null
|
||||
memory_used_bytes: number
|
||||
memory_limit_bytes: number
|
||||
network_rx_bytes: number
|
||||
network_tx_bytes: number
|
||||
block_read_bytes: number
|
||||
block_write_bytes: number
|
||||
pids: number
|
||||
}
|
||||
|
||||
export interface CreatePodmanContainerRequest {
|
||||
name: string
|
||||
image: string
|
||||
cpus?: number
|
||||
memory_mb?: number
|
||||
ports: PodmanPort[]
|
||||
env?: Record<string, string>
|
||||
command?: string[]
|
||||
volumes?: string[]
|
||||
}
|
||||
|
||||
export type PodmanAction = 'start' | 'stop' | 'restart' | 'delete'
|
||||
|
||||
export const getPodmanStatus = (signal: AbortSignal) =>
|
||||
api.get<APIResponse<PodmanStatus>>('/podman/status', { signal })
|
||||
|
||||
export const listPodmanContainers = (signal: AbortSignal) =>
|
||||
api.get<APIResponse<PodmanContainer[]>>('/podman/containers', { signal })
|
||||
|
||||
export const listPodmanImages = (signal: AbortSignal) =>
|
||||
api.get<APIResponse<PodmanImage[]>>('/podman/images', { signal })
|
||||
|
||||
export const pullPodmanImage = (image: string) =>
|
||||
api.post<APIResponse<{ id: string }>>('/podman/images', { image }, { timeout: 300000 })
|
||||
|
||||
export const createPodmanContainer = (request: CreatePodmanContainerRequest) =>
|
||||
api.post<APIResponse<PodmanContainer>>('/podman/containers', request, { timeout: 300000 })
|
||||
|
||||
export const runPodmanAction = (id: string, action: PodmanAction) => {
|
||||
const path = `/podman/containers/${encodeURIComponent(id)}`
|
||||
return action === 'delete' ? api.delete<APIResponse>(path) : api.post<APIResponse>(`${path}/${action}`)
|
||||
}
|
||||
|
||||
export const getPodmanLogs = (id: string, signal: AbortSignal) =>
|
||||
api.get<APIResponse<{ logs: string }>>(`/podman/containers/${encodeURIComponent(id)}/logs`, { signal })
|
||||
|
||||
export const getPodmanStats = (id: string, signal: AbortSignal) =>
|
||||
api.get<APIResponse<PodmanStats>>(`/podman/containers/${encodeURIComponent(id)}/stats`, { signal })
|
||||
|
||||
export default api
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
export async function copyToClipboard(text: string, container: HTMLElement = document.body): Promise<boolean> {
|
||||
if (!text) return false
|
||||
|
||||
if (navigator.clipboard?.writeText) {
|
||||
@@ -23,8 +23,9 @@ export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
|
||||
const selection = document.getSelection()
|
||||
const selectedRange = selection?.rangeCount ? selection.getRangeAt(0) : null
|
||||
const previousFocus = document.activeElement
|
||||
|
||||
document.body.appendChild(textarea)
|
||||
container.appendChild(textarea)
|
||||
textarea.focus({ preventScroll: true })
|
||||
textarea.select()
|
||||
textarea.setSelectionRange(0, textarea.value.length)
|
||||
@@ -33,11 +34,12 @@ export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
try {
|
||||
copied = document.execCommand('copy')
|
||||
} finally {
|
||||
document.body.removeChild(textarea)
|
||||
textarea.remove()
|
||||
if (selection && selectedRange) {
|
||||
selection.removeAllRanges()
|
||||
selection.addRange(selectedRange)
|
||||
}
|
||||
if (previousFocus instanceof HTMLElement && previousFocus.isConnected) previousFocus.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
return copied
|
||||
|
||||
@@ -615,6 +615,84 @@ const exact: Record<string, string> = {
|
||||
'面板资源状态与容器概览': 'Panel resource status and container overview',
|
||||
'宿主机资源状态与容器概览': 'Host resource status and container overview',
|
||||
'存储管理': 'Storage Management',
|
||||
'Podman 容器': 'Podman Containers',
|
||||
'从 OCI 镜像运行和管理应用容器。': 'Run and manage application containers from OCI images.',
|
||||
'无法读取 Podman 状态': 'Could not read Podman status',
|
||||
'无法加载 Podman 容器': 'Could not load Podman containers',
|
||||
'Podman 不可用': 'Podman is unavailable',
|
||||
'请在宿主机安装 Podman,确认面板服务可以运行 Podman 后点击刷新。': 'Install Podman on the host and ensure the panel service can run it, then refresh.',
|
||||
'还没有 Podman 容器。': 'No Podman containers yet.',
|
||||
'待启动': 'Ready to start',
|
||||
'已暂停': 'Paused',
|
||||
'正在停止': 'Stopping',
|
||||
'CPU 上限': 'CPU limit',
|
||||
'内存上限': 'Memory limit',
|
||||
'启动': 'Start',
|
||||
'停止': 'Stop',
|
||||
'日志': 'Logs',
|
||||
'删除容器会同时移除它的可写层和持久卷。': 'Deleting this container also removes its writable layer and persistent volumes.',
|
||||
'创建 Podman 容器': 'Create Podman container',
|
||||
'创建 Podman 容器失败': 'Failed to create Podman container',
|
||||
'正在拉取镜像并创建容器...': 'Pulling image and creating container...',
|
||||
'OCI 镜像': 'OCI image',
|
||||
'填写包含仓库域名的完整镜像名称。': 'Enter the full image name, including the registry domain.',
|
||||
'CPU 上限(核)': 'CPU limit (cores)',
|
||||
'内存上限(MiB)': 'Memory limit (MiB)',
|
||||
'添加端口': 'Add port',
|
||||
'服务可通过宿主机地址和已发布的端口访问。': 'Access services through the host address and the published port.',
|
||||
'请选择 CLICD IPv4 NAT 配置范围(默认 20000–65535)之外的宿主机端口,避免冲突。': 'To avoid conflicts, choose a host port outside the range configured for CLICD IPv4 NAT (20000–65535 by default).',
|
||||
'移除此端口映射': 'Remove this port mapping',
|
||||
'高级选项': 'Advanced options',
|
||||
'启动参数': 'Command and arguments',
|
||||
'填写 JSON 字符串数组。留空时使用镜像默认参数。': 'Enter a JSON array of strings. Leave blank to use the image default command.',
|
||||
'启动参数须填写为 JSON 字符串数组。': 'Enter the command and arguments as a JSON array of strings.',
|
||||
'环境变量': 'Environment variables',
|
||||
'每行一条 KEY=value。': 'Enter one KEY=value pair per line.',
|
||||
'环境变量每行须为 KEY=value,且变量名不能重复。': 'Use one KEY=value pair per line, with unique variable names.',
|
||||
'持久卷': 'Persistent volumes',
|
||||
'每行填写一个容器内绝对路径。数据在容器停止后保留,删除容器时移除。': 'Enter one absolute container path per line. Data survives stops and is removed when the container is deleted.',
|
||||
'无法读取容器日志': 'Could not read container logs',
|
||||
'容器日志': 'Container logs',
|
||||
'该容器暂无日志。': 'This container has no logs yet.',
|
||||
'Podman 工作区': 'Podman workspace',
|
||||
'应用容器': 'Applications',
|
||||
'本地镜像': 'Local images',
|
||||
'拉取镜像': 'Pull image',
|
||||
'正在拉取镜像…': 'Pulling image…',
|
||||
'拉取镜像失败': 'Could not pull image',
|
||||
'使用镜像': 'Use image',
|
||||
'无标签': 'Untagged image',
|
||||
'无法加载本地镜像': 'Could not load local images',
|
||||
'还没有本地 OCI 镜像。': 'No local OCI images yet.',
|
||||
'搜索容器名称、镜像或端口': 'Search container names, images or ports',
|
||||
'搜索镜像名称或 ID': 'Search image names or IDs',
|
||||
'筛选运行状态': 'Filter by status',
|
||||
'清除筛选': 'Clear filters',
|
||||
'容器 / 镜像': 'Container / Image',
|
||||
'查看详情': 'View details',
|
||||
'概览': 'Overview',
|
||||
'基础设置': 'Basic settings',
|
||||
'资源限制': 'Resource limits',
|
||||
'未限制': 'Unlimited',
|
||||
'健康检查': 'Health',
|
||||
'正在启动': 'Starting',
|
||||
'最近启动': 'Last started',
|
||||
'最近退出': 'Last exited',
|
||||
'退出码': 'Exit code',
|
||||
'未发布端口': 'No published ports',
|
||||
'未配置持久卷': 'No persistent volumes',
|
||||
'实时资源': 'Live resources',
|
||||
'容器运行后显示实时资源。': 'Live resource usage appears when the container is running.',
|
||||
'无法读取容器资源': 'Could not read container resources',
|
||||
'暂无资源数据': 'Resource data is unavailable',
|
||||
'每 5 秒刷新': 'Refreshes every 5 seconds',
|
||||
'进程数': 'Processes',
|
||||
'网络接收 / 发送': 'Network received / sent',
|
||||
'磁盘读取 / 写入': 'Disk read / written',
|
||||
'自动刷新': 'Auto-refresh',
|
||||
'复制日志': 'Copy logs',
|
||||
'日志已复制到剪贴板。': 'Logs copied to the clipboard.',
|
||||
'可使用下载日志保存内容。': 'Use Download logs to save a copy.',
|
||||
'显示已挂载的可写存储。勾选用途后,对应功能可以选择此位置保存数据。': 'Lists mounted, writable storage. Enable a content type to make this location available to the corresponding feature.',
|
||||
'空间分布': 'Space Distribution',
|
||||
'用于存储': 'Storage Usage',
|
||||
|
||||
Reference in New Issue
Block a user