Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add native Podman support (#4514)
Kyle Mendellfd125ecc8169
diff --git a/backend/api/api.go b/backend/api/api.goindex 4722c625a..ddd54ddae 100644--- a/backend/api/api.go+++ b/backend/api/api.go@@ -43,6 +43,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/oidc""github.com/getarcaneapp/arcane/backend/v2/internal/passkey"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman""github.com/getarcaneapp/arcane/backend/v2/internal/port""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry"@@ -100,6 +101,7 @@ var dockerSchemaPrefixes = map[string]string{"network": "DockerNetwork","volume": "DockerVolume","swarm": "DockerSwarm",+ "podman": "Podman","mount": "DockerMount","filters": "DockerFilters","blkiodev": "DockerBlkiodev",@@ -201,6 +203,7 @@ type HandlerDeps struct {Network *network.NetworkServicePort *port.PortServiceSwarm *swarm.Module+ Podman *podman.ModuleImageUpdate *imageupdate.ModuleAuth *auth.ModulePasskey *passkey.PasskeyService@@ -302,6 +305,7 @@ func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlerutil.ActivityAppport.RegisterPorts(api, deps.Port)network.RegisterNetworks(api, deps.Network, deps.Docker, deps.Activity.Service(), appCtx)deps.Swarm.RegisterRoutes(api)+ deps.Podman.RegisterRoutes(api)deps.Notification.RegisterRoutes(api)deps.Apns.RegisterRoutes(api)deps.Updater.RegisterRoutes(api, appCtx)diff --git a/backend/go.mod b/backend/go.modindex 516f1b1d1..5a90dc16b 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -22,6 +22,7 @@ require (github.com/containerd/errdefs v1.0.0github.com/containerd/platforms v1.0.0-rc.5github.com/coreos/go-oidc/v3 v3.21.0+ github.com/coreos/go-systemd/v22 v22.7.0github.com/danielgtaylor/huma/v2 v2.39.1github.com/distribution/reference v0.6.0github.com/docker/cli v29.9.1+incompatible@@ -33,6 +34,7 @@ require (github.com/go-git/go-billy/v5 v5.9.2github.com/go-git/go-git/v5 v5.19.3github.com/go-webauthn/webauthn v0.18.2+ github.com/godbus/dbus/v5 v5.2.2github.com/gofrs/flock v0.13.1github.com/google/go-containerregistry v0.22.1github.com/hashicorp/yamux v0.1.2diff --git a/backend/go.sum b/backend/go.sumindex c4e5f4d92..28e0750a0 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -201,6 +201,8 @@ github.com/containerd/typeurl/v2 v2.3.0 h1:HZHPhRWo5XMy3QGQoPrUzbW/2ckwjfweHmOwlgithub.com/containerd/typeurl/v2 v2.3.0/go.mod h1:Qk+PAdUYArVj41TnGi6rJ+48RF0PkcTc4i/taoBcK0w=github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=+github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA=+github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w=github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=github.com/cpuguy83/go-docker v0.4.0 h1:q4HTRaVdiom8I8esE2bbOiqkukew6/ZLdlKfLzpWuSI=@@ -301,6 +303,8 @@ github.com/go-webauthn/webauthn v0.18.2 h1:0BeftmEHU7i3Dv0VFwBtidy/ba37Vcdjvqst9github.com/go-webauthn/webauthn v0.18.2/go.mod h1:hEXaOuLxvZ3zG9miZe3ehlyeVso9AtklXG+kTn36k+A=github.com/go-webauthn/x v0.3.1 h1:1ff37z3XfmTTomkhlURgGizLIDyOvPgTt2t9nlzKLRo=github.com/go-webauthn/x v0.3.1/go.mod h1:ZInxAynYXfBPvvm5gzKZ7geBlL23K71xASMgohHl/Rg=+github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=+github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=github.com/gofrs/flock v0.13.1 h1:jjREztyBeSKBZYAC+mgc1laB+xsgy4kYMf3FbKF2UBo=github.com/gofrs/flock v0.13.1/go.mod h1:sf4BFiHwnvgxa25DlQoDqXQnwRMEOwqxRq37P6MzzmE=github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex d5e5fce5d..79ec3e628 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -52,6 +52,7 @@ func Bootstrap(ctx context.Context) error {return fmt.Errorf("load .env: %w", err)}cfg := config.Load()+ cfg.DockerHost = startup.ResolveDockerHost(cfg.DockerHost, os.Stat)runtimeIdentityCfg := &startup.RuntimeIdentityConfig{PUID: cfg.PUID,PGID: cfg.PGID,diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 0ec41ebc5..83db1a5b8 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -98,9 +98,11 @@ var (ErrPatchScanReportUnavailable = Classify(ErrNotFound, errors.New("no stored scan report is available for this scan; re-scan the image or patch without a report"))ErrPatchScanImageMismatch = Classify(ErrBadRequest, errors.New("the selected scan does not belong to this image"))ErrContainerComposeManaged = Classify(ErrConflict, errors.New("container is managed by a compose project; edit it via the project editor"))+ ErrContainerQuadletManaged = Classify(ErrConflict, errors.New("container is managed by a Podman quadlet; manage it through its systemd unit"))ErrContainerNameTaken = Classify(ErrConflict, errors.New("a container with this name already exists"))ErrInvalidBackupSelection = Classify(ErrBadRequest, errors.New("invalid backup file selection"))ErrSwarmNotEnabled = Classify(ErrBadRequest, errors.New("Swarm mode is not enabled"))+ ErrPodmanNotDetected = Classify(ErrBadRequest, errors.New("Podman was not detected on this environment"))ErrSwarmManagerRequired = Classify(ErrForbidden, errors.New("Swarm manager access required"))ErrRoleNotFound = Classify(ErrNotFound, errors.New("Role not found"))ErrRoleBuiltIn = Classify(ErrForbidden, errors.New("Built-in role cannot be modified"))diff --git a/backend/internal/container/service.go b/backend/internal/container/service.goindex 3442cf0cb..0dc1f9e9f 100644--- a/backend/internal/container/service.go+++ b/backend/internal/container/service.go@@ -45,9 +45,11 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/kv"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"+ libpodman "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -76,6 +78,7 @@ type ContainerService struct {settingsService *settings.SettingsServiceprojectService *project.ProjectServicekvService *kv.KVService+ podmanService *podman.ServiceiconMetaCache *hot.HotCache[string, projects.ArcaneComposeMetadata]stats *stats.Service// opLock serializes mutating operations on the same container.@@ -118,6 +121,7 @@ func NewContainerService(settingsService *settings.SettingsService,projectService *project.ProjectService,kvService *kv.KVService,+ podmanService *podman.Service,) *ContainerService {return &ContainerService{eventService: eventService,@@ -126,6 +130,7 @@ func NewContainerService(settingsService: settingsService,projectService: projectService,kvService: kvService,+ podmanService: podmanService,iconMetaCache: hot.NewHotCache[string, projects.ArcaneComposeMetadata](hot.LRU, 1024).WithTTL(containerIconMetadataTTL).WithJanitor().@@ -409,6 +414,9 @@ func (s *ContainerService) StartContainer(ctx context.Context, containerID strinaction: "start",eventType: event.EventTypeContainerStart,runContainerAction: func(ctx context.Context) error {+ if handled, unitErr := s.podmanService.ContainerUnitAction(ctx, containerID, libpodman.Systemd.Start); handled {+ return unitErr+ }_, err := s.dockerService.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.ContainerStartResult, error) {return dockerClient.ContainerStart(ctx, containerID, client.ContainerStartOptions{})})@@ -422,6 +430,9 @@ func (s *ContainerService) StopContainer(ctx context.Context, containerID stringaction: "stop",eventType: event.EventTypeContainerStop,runContainerAction: func(ctx context.Context) error {+ if handled, unitErr := s.podmanService.ContainerUnitAction(ctx, containerID, libpodman.Systemd.Stop); handled {+ return unitErr+ }return s.stopContainer(ctx, containerID)},})@@ -432,6 +443,9 @@ func (s *ContainerService) RestartContainer(ctx context.Context, containerID straction: "restart",eventType: event.EventTypeContainerRestart,runContainerAction: func(ctx context.Context) error {+ if handled, unitErr := s.podmanService.ContainerUnitAction(ctx, containerID, libpodman.Systemd.Restart); handled {+ return unitErr+ }dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {return fmt.Errorf("failed to connect to Docker: %w", err)@@ -557,6 +571,9 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st})return "", fmt.Errorf("failed to redeploy container: %w", err)}+ if guardErr := s.podmanService.GuardQuadletManaged(ctx, containerInfo.Config.Labels); guardErr != nil {+ return "", guardErr+ }containerName := strings.TrimPrefix(containerInfo.Name, "/")apiVersion, _ := s.dockerService.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (string, error) {@@ -686,6 +703,20 @@ func (s *ContainerService) recreateContainer(if err != nil {return "", fmt.Errorf("preserve volumes of container %s: %w", containerName, err)}+ engine, err := s.dockerService.Engine(ctx)+ if err != nil {+ return "", fmt.Errorf("detect container engine for %s: %w", containerName, err)+ }+ engine.SanitizeRecreateHostConfig(&restoreHostConfig)+ if engine.SanitizeRecreateHostConfig(&createHostConfig) {+ slog.InfoContext(ctx, "Stripped unsupported host config field for recreate",+ "container", containerName,+ "containerId", containerInfo.ID,+ "engine", engine.Name,+ "cgroupVersion", engine.CgroupVersion,+ "field", "memorySwappiness",+ )+ }defer s.eventService.BeginDockerResourceSuppressionWindow("container", containerInfo.ID, containerName)()backupName := fmt.Sprintf("%s%s%d", cmp.Or(containerName, "arcane-redeploy-"+containerInfo.ID[:min(12, len(containerInfo.ID))]), redeployBackupInfix, time.Now().Unix())@@ -694,7 +725,7 @@ func (s *ContainerService) recreateContainer(// A returned error means the workload is down and is joined into the start error.restoreAutoRemoveOriginal := func(ctx context.Context) error {originalConfig := *containerInfo.Config- if len(containerInfo.ID) >= 12 && originalConfig.Hostname == containerInfo.ID[:12] {+ if originalConfig.Hostname == containerInfo.ID[:min(12, len(containerInfo.ID))] {originalConfig.Hostname = "" // keep: copying Docker's 24-field container.Config to clear one field is unreadable}@@ -752,7 +783,7 @@ func (s *ContainerService) recreateContainer(}}- if len(containerInfo.ID) >= 12 && newConfig.Hostname == containerInfo.ID[:12] {+ if newConfig.Hostname == containerInfo.ID[:min(12, len(containerInfo.ID))] {newConfig.Hostname = "" // keep: copying Docker's 24-field container.Config to clear one field is unreadable}@@ -1147,6 +1178,9 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID stringif localProject := docker.ComposeProjectLabel(containerInfo.Config.Labels); localProject != "" {return "", fmt.Errorf("compose project %s: %w", localProject, common.ErrContainerComposeManaged)}+ if guardErr := s.podmanService.GuardQuadletManaged(ctx, containerInfo.Config.Labels); guardErr != nil {+ return "", guardErr+ }currentContainerID, currentContainerErr := cgroup.CurrentContainerID()if labels.ShouldDisableArcaneServerRedeploy(containerInfo.Config.Labels, containerInfo.ID, currentContainerID, currentContainerErr) {@@ -1307,18 +1341,23 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri}defer unlock()+ containerJSON, inspectErr := s.dockerService.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.ContainerInspectResult, error) {+ return compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ })+ if inspectErr != nil {+ return fmt.Errorf("failed to inspect container before removal: %w", inspectErr)+ }+ if guardErr := s.podmanService.GuardQuadletManaged(ctx, kit.FromPtr(containerJSON.Container.Config).Labels); guardErr != nil {+ return guardErr+ }+// Get container mounts before deletion if we need to remove volumesvar volumesToRemove []stringif removeVolumes {- containerJSON, inspectErr := s.dockerService.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.ContainerInspectResult, error) {- return compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})- })- if inspectErr == nil {- for _, mount := range containerJSON.Container.Mounts {- // Only collect named volumes (not bind mounts or tmpfs)- if mount.Type == "volume" && mount.Name != "" {- volumesToRemove = append(volumesToRemove, mount.Name)- }+ for _, mount := range containerJSON.Container.Mounts {+ // Only collect named volumes (not bind mounts or tmpfs)+ if mount.Type == "volume" && mount.Name != "" {+ volumesToRemove = append(volumesToRemove, mount.Name)}}}diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.goindex e8905e3f4..962dd0f6d 100644--- a/backend/internal/container/service_test.go+++ b/backend/internal/container/service_test.go@@ -25,6 +25,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/base"containertypes "github.com/getarcaneapp/arcane/types/v2/container""github.com/getarcaneapp/arcane/types/v2/image"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman""github.com/getarcaneapp/arcane/types/v2/user""github.com/libtnb/sqlite""github.com/moby/moby/api/types/container"@@ -32,9 +33,11 @@ import ("github.com/moby/moby/api/types/network""github.com/moby/moby/client""github.com/stretchr/testify/require"+ "go.getarcane.app/docker/compat""go.getarcane.app/kit/pkg""gorm.io/gorm"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/container/children/stats""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -43,8 +46,10 @@ import (imagedomain "github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/kv"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ libpodman "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"@@ -146,7 +151,7 @@ func TestContainerSummaryIconsAppliedAfterGrouping(t *testing.T) {db := setupProjectTestDB(t)settingsService, err := settings.NewSettingsService(t.Context(), db, &config.Config{})require.NoError(t, err)- service := NewContainerService(nil, nil, nil, settingsService, project.NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, nil, nil, nil), nil)+ service := NewContainerService(nil, nil, nil, settingsService, project.NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, nil, nil, nil), nil, nil)dockerContainers := []container.Summary{{ID: "app", Names: []string{"/app"}, Labels: map[string]string{"com.docker.compose.project": "media",@@ -326,6 +331,7 @@ func TestContainerServiceCommitContainerCallsDockerAPI(t *testing.T) {nil,nil,nil,+ nil,)out, err := svc.CommitContainer(t.Context(), "container-1", containertypes.CommitRequest{@@ -374,6 +380,7 @@ func TestContainerServiceCommitContainerOmitsReferenceWhenRepositoryEmpty(t *tesnil,nil,nil,+ nil,)out, err := svc.CommitContainer(t.Context(), "container-1", containertypes.CommitRequest{@@ -648,6 +655,7 @@ func TestContainerServiceResizeExec(t *testing.T) {nil,nil,nil,+ nil,)require.NoError(t, svc.ResizeExec(t.Context(), "exec-1", 120, 40))@@ -662,6 +670,11 @@ func TestRecreateContainerDaemonCorrelation(t *testing.T) {observed := make(chan string, 8)server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {path := dockerTestPath(r.URL.Path)+ if path == "/version" || path == "/info" {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte("{}"))+ return+ }id, name := "old-id", "web"if path == "/containers/create" {id = ""@@ -688,7 +701,7 @@ func TestRecreateContainerDaemonCorrelation(t *testing.T) {}))t.Cleanup(server.Close)kvService := kv.NewKVService(db)- svc := NewContainerService(events, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, nil, nil, kvService)+ svc := NewContainerService(events, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, nil, nil, kvService, nil)info := container.InspectResponse{ID: "old-id",Name: "/web",@@ -743,6 +756,11 @@ func TestRecreateContainerRollsBackAfterRequestCancellation(t *testing.T) {var observed []stringserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {path := dockerTestPath(r.URL.Path)+ if path == "/version" || path == "/info" {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte("{}"))+ return+ }mu.Lock()observed = append(observed, r.Method+" "+path)mu.Unlock()@@ -762,7 +780,7 @@ func TestRecreateContainerRollsBackAfterRequestCancellation(t *testing.T) {}))t.Cleanup(server.Close)kvService := kv.NewKVService(db)- svc := NewContainerService(event.NewEventService(db, nil, nil), docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, nil, nil, kvService)+ svc := NewContainerService(event.NewEventService(db, nil, nil), docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, nil, nil, kvService, nil)info := container.InspectResponse{ID: "old-id",Name: "/web",@@ -877,7 +895,7 @@ func TestRecoverInterruptedRedeploys(t *testing.T) {w.WriteHeader(http.StatusNoContent)}))t.Cleanup(server.Close)- svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, nil, nil, kvService)+ svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, nil, nil, kvService, nil)require.NoError(t, svc.RecoverInterruptedRedeploys(t.Context()))@@ -894,7 +912,7 @@ func TestRecoverInterruptedRedeploys(t *testing.T) {func TestBuildSummariesUsesContainerTagPolicyUpdates(t *testing.T) {settingsService, err := settings.NewSettingsService(t.Context(), setupProjectTestDB(t), &config.Config{})require.NoError(t, err)- service := NewContainerService(nil, nil, nil, settingsService, nil, nil)+ service := NewContainerService(nil, nil, nil, settingsService, nil, nil, nil)strategyLabel := "com.getarcaneapp.arcane.updater.strategy"containers := []container.Summary{{ID: "first", Image: "app:3.1.0", ImageID: "shared-image"},@@ -1006,7 +1024,7 @@ func TestContainerServiceGetContainerProcesses(t *testing.T) {t.Cleanup(server.Close)settingsService, err := settings.NewSettingsService(t.Context(), setupProjectTestDB(t), &config.Config{})require.NoError(t, err)- svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, settingsService, nil, nil)+ svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, settingsService, nil, nil, nil)processes, err := svc.GetContainerProcesses(t.Context(), "container-1")wantArgs := []string{strings.Join(containerProcessesPsArgs[0], " ")}@@ -1034,7 +1052,7 @@ func TestContainerServiceGetContainerProcessesPropagatesContext(t *testing.T) {t.Cleanup(server.Close)settingsService, err := settings.NewSettingsService(t.Context(), setupProjectTestDB(t), &config.Config{})require.NoError(t, err)- svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, settingsService, nil, nil)+ svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, server)), nil, settingsService, nil, nil, nil)ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)defer cancel()@@ -1183,6 +1201,7 @@ func newResourceSortService(t *testing.T, fixture *resourceStatsServer) *ContainsettingsService,nil,nil,+ nil,)}@@ -1527,6 +1546,7 @@ func newLogsTestService(t *testing.T, tty bool, logsBody []byte, gotQuery *url.Vnil,nil,nil,+ nil,)}@@ -1699,3 +1719,137 @@ func TestAggregateContainersMergesEnvironments(t *testing.T) {require.Len(t, body.FailedEnvironments, 3)})}++type quadletTestSystemd struct {+ mu sync.Mutex+ calls []string+}++func (f *quadletTestSystemd) Availability(context.Context) podmantypes.SystemdAvailability {+ return podmantypes.SystemdAvailability{Available: true}+}++func (f *quadletTestSystemd) Start(_ context.Context, unit string) error {+ return f.record("start " + unit)+}++func (f *quadletTestSystemd) Stop(_ context.Context, unit string) error {+ return f.record("stop " + unit)+}++func (f *quadletTestSystemd) Restart(_ context.Context, unit string) error {+ return f.record("restart " + unit)+}++func (f *quadletTestSystemd) UnitStatus(_ context.Context, unit string) (podmantypes.UnitStatus, error) {+ return podmantypes.UnitStatus{Name: unit, ActiveState: "active"}, nil+}++func (f *quadletTestSystemd) record(call string) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.calls = append(f.calls, call)+ return nil+}++func newQuadletTestContainerService(t *testing.T) (*ContainerService, *quadletTestSystemd, func() []string) {+ t.Helper()++ var mu sync.Mutex+ var dockerCalls []string+ dockerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path := dockerTestPath(r.URL.Path)+ mu.Lock()+ dockerCalls = append(dockerCalls, r.Method+" "+path)+ mu.Unlock()+ if r.Method == http.MethodGet && path == "/containers/quadlet-id/json" {+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(container.InspectResponse{+ ID: "quadlet-id",+ Name: "/web",+ State: &container.State{Running: true},+ Config: &container.Config{Image: "nginx:latest", Labels: map[string]string{podmantypes.SystemdUnitLabel: "web.service"}},+ HostConfig: &container.HostConfig{},+ }); err != nil {+ t.Errorf("encode inspect response: %v", err)+ }+ return+ }+ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(dockerServer.Close)++ libpodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/v4.0.0/libpod/version":+ _, _ = w.Write([]byte(`{"Version":"6.1.0","ApiVersion":"6.1.0"}`))+ case "/v4.0.0/libpod/info":+ _, _ = w.Write([]byte(`{"host":{"security":{"rootless":false}}}`))+ case "/v4.0.0/libpod/containers/json":+ _, _ = w.Write([]byte(`[{"Id":"quadlet-id","Names":["web"],"Labels":{"PODMAN_SYSTEMD_UNIT":"web.service"}}]`))+ case "/v4.0.0/libpod/quadlets/json":+ _, _ = w.Write([]byte(`[{"Name":"web.container","UnitName":"web.service"}]`))+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(libpodServer.Close)++ systemd := &quadletTestSystemd{}+ svc := NewContainerService(+ event.NewEventService(setupProjectTestDB(t), nil, nil),+ docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClient(t, dockerServer)),+ nil,+ nil,+ nil,+ nil,+ podman.NewService(podman.Config{+ Engine: func(context.Context) (compat.EngineCompatibilityInfo, error) {+ return compat.EngineCompatibilityInfo{Name: "podman"}, nil+ },+ Host: libpodServer.URL,+ NewSystemd: func(bool) libpodman.Systemd {+ return systemd+ },+ }),+ )+ return svc, systemd, func() []string {+ mu.Lock()+ defer mu.Unlock()+ return slices.Clone(dockerCalls)+ }+}++func TestContainerLifecycleRoutesQuadletContainersThroughSystemd(t *testing.T) {+ svc, systemd, dockerCalls := newQuadletTestContainerService(t)+ actor := user.Actor{ID: "user-1", Username: "tester"}++ require.NoError(t, svc.StartContainer(t.Context(), "quadlet-id", actor))+ require.NoError(t, svc.StopContainer(t.Context(), "quadlet-id", actor))+ require.NoError(t, svc.RestartContainer(t.Context(), "quadlet-id", actor))+ require.Equal(t, []string{"start web.service", "stop web.service", "restart web.service"}, systemd.calls)+ require.Empty(t, dockerCalls())++ require.NoError(t, svc.StartContainer(t.Context(), "plain-id", actor))+ require.Equal(t, []string{"POST /containers/plain-id/start"}, dockerCalls())+ require.Len(t, systemd.calls, 3)+}++func TestContainerMutationsRefuseQuadletContainers(t *testing.T) {+ svc, systemd, dockerCalls := newQuadletTestContainerService(t)+ actor := user.Actor{ID: "user-1", Username: "tester"}++ _, err := svc.EditContainer(t.Context(), "quadlet-id", containertypes.Edit{}, actor)+ require.ErrorIs(t, err, common.ErrContainerQuadletManaged)+ _, err = svc.RedeployContainer(t.Context(), "quadlet-id", actor)+ require.ErrorIs(t, err, common.ErrContainerQuadletManaged)+ require.ErrorIs(t, svc.DeleteContainer(t.Context(), "quadlet-id", true, true, actor), common.ErrContainerQuadletManaged)++ require.Equal(t, []string{+ "GET /containers/quadlet-id/json",+ "GET /containers/quadlet-id/json",+ "GET /containers/quadlet-id/json",+ }, dockerCalls())+ require.Empty(t, systemd.calls)+}diff --git a/backend/internal/dashboard/service.go b/backend/internal/dashboard/service.goindex fb454d799..5cd15110e 100644--- a/backend/internal/dashboard/service.go+++ b/backend/internal/dashboard/service.go@@ -34,6 +34,7 @@ import (dockerInternal "github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/image"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/version"@@ -64,6 +65,7 @@ type DashboardService struct {environmentService *environment.EnvironmentServiceversionService *version.VersionServicevolumeService *volume.VolumeService+ podmanService *podman.Service// Shared, immutable snapshot builds indexed by [includeTables][debugAllGood][iconCatalog];// full snapshots resolve icons per catalog, so each catalog gets its own entry.@@ -91,6 +93,7 @@ func NewDashboardService(environmentService *environment.EnvironmentService,versionService *version.VersionService,volumeService *volume.VolumeService,+ podmanService *podman.Service,) *DashboardService {return &DashboardService{db: db,@@ -103,6 +106,7 @@ func NewDashboardService(environmentService: environmentService,versionService: versionService,volumeService: volumeService,+ podmanService: podmanService,}}@@ -258,6 +262,7 @@ func (s *DashboardService) buildSnapshot(ctx context.Context, options DashboardAActionItems: *actionItems,Settings: dashboard.SnapshotSettings{},VersionInfo: versionInfo,+ PodCount: s.podmanService.PodCount(ctx).ToPointer(),}, nil}@@ -373,12 +378,13 @@ func (s *DashboardService) getPendingContainerUpdatesCount(ctx context.Context,type inventoryGauges struct {containers, health, images, imageSize, volumes, networks, projects metric.Int64ObservableGaugeswarmNodes, swarmServices, swarmTasks metric.Int64ObservableGauge+ podmanPods metric.Int64ObservableGauge}// ObserveInventory reports the local Docker engine's inventory through arcane.docker.* and arcane.projects gauges.func (s *DashboardService) ObserveInventory(meter metric.Meter) error {var g inventoryGauges- var errs [10]error+ var errs [11]errorg.containers, errs[0] = meter.Int64ObservableGauge("arcane.docker.containers",metric.WithDescription("Containers on the local Docker engine by state"), metric.WithUnit("{container}"))g.health, errs[1] = meter.Int64ObservableGauge("arcane.docker.containers.health",@@ -399,6 +405,8 @@ func (s *DashboardService) ObserveInventory(meter metric.Meter) error {metric.WithDescription("Swarm services, reported by swarm managers"), metric.WithUnit("{service}"))g.swarmTasks, errs[9] = meter.Int64ObservableGauge("arcane.docker.swarm.service.tasks",metric.WithDescription("Running and desired tasks per swarm service, reported by swarm managers"), metric.WithUnit("{task}"))+ g.podmanPods, errs[10] = meter.Int64ObservableGauge("arcane.podman.pods",+ metric.WithDescription("Podman pods on the local engine, reported when Podman is detected"), metric.WithUnit("{pod}"))if err := errors.Join(errs[:]...); err != nil {return err}@@ -460,8 +468,11 @@ func (s *DashboardService) ObserveInventory(meter metric.Meter) error {}s.observeSwarm(ctx, o, &g)+ if pods, detected := s.podmanService.PodCount(ctx).Get(); detected {+ o.ObserveInt64(g.podmanPods, int64(pods))+ }return nil- }, g.containers, g.health, g.images, g.imageSize, g.volumes, g.networks, g.projects, g.swarmNodes, g.swarmServices, g.swarmTasks)+ }, g.containers, g.health, g.images, g.imageSize, g.volumes, g.networks, g.projects, g.swarmNodes, g.swarmServices, g.swarmTasks, g.podmanPods)return err}diff --git a/backend/internal/dashboard/service_test.go b/backend/internal/dashboard/service_test.goindex d5a73852e..a9246c55a 100644--- a/backend/internal/dashboard/service_test.go+++ b/backend/internal/dashboard/service_test.go@@ -22,7 +22,10 @@ import ("github.com/moby/moby/client""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ "go.getarcane.app/docker/compat""go.getarcane.app/updater/labels"+ "go.opentelemetry.io/otel/sdk/metric"+ "go.opentelemetry.io/otel/sdk/metric/metricdata""gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"@@ -33,9 +36,11 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/volume"+ libpodman "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref")@@ -204,7 +209,19 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {}).Error)imageSvc := image.NewImageService(db, nil, nil, nil, nil, nil, nil, nil)projectSvc := project.NewProjectService(db, settingsSvc, nil, imageSvc, testDockerService, nil, nil, nil, config.Load(), nil, nil)- svc := NewDashboardService(db, dockerSvc, nil, projectSvc, imageSvc, settingsSvc, nil, nil, nil, volume.NewVolumeService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil))+ svc := NewDashboardService(+ db,+ dockerSvc,+ nil,+ projectSvc,+ imageSvc,+ settingsSvc,+ nil,+ nil,+ nil,+ volume.NewVolumeService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil),+ podman.NewService(podman.Config{Engine: dockerSvc.Engine}),+ )snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)require.NoError(t, err)@@ -259,7 +276,7 @@ func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testicreateDashboardTestImageUpdateRecord(t, db, imageupdate.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)- svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil)+ svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil, podman.NewService(podman.Config{Engine: dockerSvc.Engine}))snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{DebugAllGood: true}, true)require.NoError(t, err)@@ -300,7 +317,7 @@ func TestDashboardService_GetSnapshot_EnrichesPinnedReferences(t *testing.T) {}dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)- svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil)+ svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil, podman.NewService(podman.Config{Engine: dockerSvc.Engine}))snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)require.NoError(t, err)@@ -344,7 +361,7 @@ func TestDashboardService_GetSnapshot_TrimmedOmitsTablesAndSharesBuilds(t *testi}dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)- svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil)+ svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil, podman.NewService(podman.Config{Engine: dockerSvc.Engine}))trimmed, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, false)require.NoError(t, err)@@ -394,8 +411,8 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testidockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "autoUpdateExcludedContainers", "running-app"))- containerSvc := container.NewContainerService(nil, dockerSvc, nil, settingsSvc, nil, nil)- svc := NewDashboardService(db, dockerSvc, containerSvc, nil, nil, settingsSvc, nil, nil, nil, nil)+ containerSvc := container.NewContainerService(nil, dockerSvc, nil, settingsSvc, nil, nil, nil)+ svc := NewDashboardService(db, dockerSvc, containerSvc, nil, nil, settingsSvc, nil, nil, nil, nil, podman.NewService(podman.Config{Engine: dockerSvc.Engine}))defaultSnapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)require.NoError(t, err)@@ -471,3 +488,72 @@ func TestPendingContainerCountUsesScopedTagRecords(t *testing.T) {require.NoError(t, err)require.Equal(t, 1, count, "a missing runtime image ID inherits no digest check")}++func TestDashboardService_ReportsPodmanPods(t *testing.T) {+ db, settingsSvc := setupDashboardServiceTestDB(t)+ dockerSvc := newDashboardTestDockerService(t, settingsSvc, nil, nil, nil)++ libpodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/v4.0.0/libpod/version":+ _, _ = w.Write([]byte(`{"Version":"6.1.0","ApiVersion":"6.1.0"}`))+ case "/v4.0.0/libpod/info":+ _, _ = w.Write([]byte(`{"host":{"security":{"rootless":false}}}`))+ case "/v4.0.0/libpod/pods/json":+ _, _ = w.Write([]byte(`[{"Id":"pod-a","Name":"web"},{"Id":"pod-b","Name":"db"}]`))+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(libpodServer.Close)++ svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil, podman.NewService(podman.Config{+ Engine: func(context.Context) (compat.EngineCompatibilityInfo, error) {+ return compat.EngineCompatibilityInfo{Name: "podman"}, nil+ },+ Host: libpodServer.URL,+ NewSystemd: func(rootless bool) libpodman.Systemd {+ return libpodman.NewSystemd("", rootless, func(string) string {+ return ""+ })+ },+ }))++ snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, false)+ require.NoError(t, err)+ require.NotNil(t, snapshot.PodCount)+ require.Equal(t, 2, *snapshot.PodCount)++ reader := metric.NewManualReader()+ provider := metric.NewMeterProvider(metric.WithReader(reader))+ t.Cleanup(func() { require.NoError(t, provider.Shutdown(context.WithoutCancel(t.Context()))) })+ require.NoError(t, svc.ObserveInventory(provider.Meter("dashboard-test")))++ var collected metricdata.ResourceMetrics+ require.NoError(t, reader.Collect(t.Context(), &collected))+ var pods []metricdata.DataPoint[int64]+ for _, scope := range collected.ScopeMetrics {+ for _, m := range scope.Metrics {+ if gauge, ok := m.Data.(metricdata.Gauge[int64]); ok && m.Name == "arcane.podman.pods" {+ pods = gauge.DataPoints+ }+ }+ }+ require.Len(t, pods, 1)+ require.Equal(t, int64(2), pods[0].Value)+}++func TestDashboardService_OmitsPodCountOnDocker(t *testing.T) {+ db, settingsSvc := setupDashboardServiceTestDB(t)+ dockerSvc := newDashboardTestDockerService(t, settingsSvc, nil, nil, nil)+ svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil, podman.NewService(podman.Config{+ Engine: func(context.Context) (compat.EngineCompatibilityInfo, error) {+ return compat.EngineCompatibilityInfo{Name: "docker"}, nil+ },+ }))++ snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, false)+ require.NoError(t, err)+ require.Nil(t, snapshot.PodCount)+}diff --git a/backend/internal/di/di.go b/backend/internal/di/di.goindex 7ef945d24..68d33c478 100644--- a/backend/internal/di/di.go+++ b/backend/internal/di/di.go@@ -5,6 +5,7 @@ import ("context""log/slog""net/http"+ "os""go.uber.org/fx"@@ -35,6 +36,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/oidc""github.com/getarcaneapp/arcane/backend/v2/internal/passkey"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman""github.com/getarcaneapp/arcane/backend/v2/internal/port""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry"@@ -55,6 +57,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability""github.com/getarcaneapp/arcane/backend/v2/internal/webhook"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"+ libpodman "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler""github.com/getarcaneapp/arcane/backend/v2/resources")@@ -164,6 +167,16 @@ var ServiceOptions = fx.Options(func(db *database.DB, localDocker *docker.DockerClientService, kvService *kv.KVService, settingsService *settings.SettingsService) *registry.ContainerRegistryService {return registry.NewContainerRegistryService(db, func(ctx context.Context) (registry.RegistryDaemonClient, error) { return localDocker.GetClient(ctx) }, kvService, settingsService)},+ func(localDocker *docker.DockerClientService, notificationService *notification.NotificationService) *podman.Service {+ return podman.NewService(podman.Config{+ Engine: localDocker.Engine,+ Host: localDocker.DockerHost(),+ NewSystemd: func(rootless bool) libpodman.Systemd {+ return libpodman.NewSystemd(localDocker.DockerHost(), rootless, os.Getenv)+ },+ NotifyUpdates: notificationService.SendBatchContainerUpdateNotification,+ })+ },provideUpdaterService,provideAuthMiddleware,),@@ -179,6 +192,7 @@ var ServiceOptions = fx.Options(container.New,dashboard.New,swarm.New,+ podman.New,system.New,volume.New,updater.New,diff --git a/backend/internal/di/di_test.go b/backend/internal/di/di_test.goindex 778136061..e26147322 100644--- a/backend/internal/di/di_test.go+++ b/backend/internal/di/di_test.go@@ -41,6 +41,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/network""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/oidc"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman""github.com/getarcaneapp/arcane/backend/v2/internal/port""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry"@@ -106,6 +107,7 @@ type graphParams struct {Webhook *webhook.ModuleVulnerability *vulnerability.VulnerabilityServiceDashboard *dashboard.Module+ Podman *podman.ModuleRole *role.RoleServiceVariable *variable.VariableServiceAuthMiddleware *auth.AuthMiddlewarediff --git a/backend/internal/docker/service.go b/backend/internal/docker/service.goindex 95730a52e..d28cc3e41 100644--- a/backend/internal/docker/service.go+++ b/backend/internal/docker/service.go@@ -47,6 +47,8 @@ type DockerClientService struct {settingsService *settings.SettingsServiceclientVersion stringclientLastProbe time.Time+ engine compat.EngineCompatibilityInfo+ engineClient *client.Clientmu sync.MutexeventBus *bus.DockerEventBus@@ -152,6 +154,7 @@ func (s *DockerClientService) RefreshClient(ctx context.Context) error {s.Client = clis.clientVersion = apiVersions.clientLastProbe = time.Now()+ s.engineClient = nils.mu.Unlock()closeDockerClient(ctx, oldClient, "replaced")@@ -159,6 +162,34 @@ func (s *DockerClientService) RefreshClient(ctx context.Context) error {return nil}+func (s *DockerClientService) Engine(ctx context.Context) (compat.EngineCompatibilityInfo, error) {+ s.mu.Lock()+ if s.engineClient != nil && s.engineClient == s.Client {+ engine := s.engine+ s.mu.Unlock()+ return engine, nil+ }+ s.mu.Unlock()++ return s.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (compat.EngineCompatibilityInfo, error) {+ version, err := dockerClient.ServerVersion(ctx, client.ServerVersionOptions{})+ if err != nil {+ return compat.EngineCompatibilityInfo{}, fmt.Errorf("failed to get Docker server version: %w", err)+ }+ info, err := dockerClient.Info(ctx, client.InfoOptions{})+ if err != nil {+ return compat.EngineCompatibilityInfo{}, fmt.Errorf("failed to get Docker info: %w", err)+ }++ engine := compat.DetectEngineCompatibility(version, info.Info)+ s.mu.Lock()+ s.engine = engine+ s.engineClient = dockerClient+ s.mu.Unlock()+ return engine, nil+ })+}+// DockerHost returns the configured DOCKER_HOST value.func (s *DockerClientService) DockerHost() string {if s == nil || s.config == nil {@@ -172,6 +203,7 @@ func (s *DockerClientService) Close() {s.mu.Lock()oldClient := s.Clients.Client = nil+ s.engineClient = nils.mu.Unlock()closeDockerClient(context.Background(), oldClient, "cached") //nolint:forbidigo // Shutdown close runs without a request context.diff --git a/backend/internal/docker/service_test.go b/backend/internal/docker/service_test.goindex 267a0df9a..7025949d8 100644--- a/backend/internal/docker/service_test.go+++ b/backend/internal/docker/service_test.go@@ -330,6 +330,48 @@ func TestDockerClientService_WatchEventsResumesFromLastEventAfterRefresh(t *test}}+func TestDockerClientService_EngineCachesUntilClientChanges(t *testing.T) {+ var versionCalls atomic.Int32+ server := newDockerPingTestServerWithHandler(t, func(w http.ResponseWriter, r *http.Request) {+ switch path.Base(r.URL.Path) {+ case "_ping":+ w.Header().Set("Api-Version", "1.41")+ w.WriteHeader(http.StatusOK)+ case "version":+ versionCalls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"Platform":{"Name":"Podman Engine"}}`))+ case "info":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"CgroupVersion":"2"}`))+ default:+ http.NotFound(w, r)+ }+ })+ svc := newDockerClientServiceForTest(t, server.URL)+ t.Cleanup(svc.Close)++ first, err := svc.Engine(t.Context())+ require.NoError(t, err)+ second, err := svc.Engine(t.Context())+ require.NoError(t, err)++ assert.Equal(t, "podman", first.Name)+ assert.Equal(t, "2", first.CgroupVersion)+ assert.Equal(t, first, second)+ assert.Equal(t, int32(1), versionCalls.Load())++ copied := svc.WithClient(svc.Client)+ _, err = copied.Engine(t.Context())+ require.NoError(t, err)+ assert.Equal(t, int32(2), versionCalls.Load())++ svc.Close()+ _, err = svc.Engine(t.Context())+ require.NoError(t, err)+ assert.Equal(t, int32(3), versionCalls.Load())+}+func TestCountImageUsage_UsesContainerImageIDs(t *testing.T) {images := []image.Summary{{ID: "sha256:image-a", Containers: -1, Size: 100},diff --git a/backend/internal/environment/service.go b/backend/internal/environment/service.goindex a689606f7..a28bb1eb0 100644--- a/backend/internal/environment/service.go+++ b/backend/internal/environment/service.go@@ -11,6 +11,7 @@ import ("maps""net/http""net/url"+ "os""slices""strings""sync"@@ -24,6 +25,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/environment""github.com/getarcaneapp/arcane/types/v2/scheduler"usertypes "github.com/getarcaneapp/arcane/types/v2/user"+ "github.com/moby/moby/client""github.com/samber/hot""github.com/samber/mo""go.getarcane.app/kit/normalization"@@ -62,6 +64,7 @@ import (type EnvironmentService struct {db *database.DB+ dockerService *docker.DockerClientServiceeventService *event.EventServicesettingsService *settings.SettingsServiceedgeTokens *edgeTokenCache@@ -87,6 +90,7 @@ const (// LocalEnvironmentID is the reserved ID of the environment Arcane manages directly.LocalEnvironmentID = "0"localEnvironmentFallbackName = "Local"+ legacyLocalEnvironmentName = "Local Docker"// SyncDeliveryExpiry bounds how long an accepted config push is trusted, so a// rebuilt agent that stayed online is resynced without operator action.@@ -153,6 +157,7 @@ func NewEnvironmentService(return &EnvironmentService{syncGate: syncGate,db: db,+ dockerService: dockerService,eventService: eventService,settingsService: settingsService,edgeTokens: &edgeTokenCache{@@ -318,17 +323,33 @@ func (s *EnvironmentService) ResolveEnvironmentName(ctx context.Context, environ}func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl string) error {+ hostName := func() string {+ info, _ := s.dockerService.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.SystemInfoResult, error) {+ return dockerClient.Info(ctx, client.InfoOptions{})+ })+ osHostName, _ := os.Hostname()+ return cmp.Or(strings.TrimSpace(info.Info.Name), strings.TrimSpace(osHostName), localEnvironmentFallbackName)+ }+var existingEnv Environmenterr := s.db.WithContext(ctx).Where("id = ?", LocalEnvironmentID).First(&existingEnv).Errorif err == nil {+ updates := map[string]any{}if existingEnv.ApiUrl != appUrl {- if updateLocalURLErr := s.db.WithContext(ctx).Model(&existingEnv).Update("api_url", appUrl).Error; updateLocalURLErr != nil {- return fmt.Errorf("failed to update local environment api url: %w", updateLocalURLErr)- }- s.invalidateEnvironmentCache(LocalEnvironmentID)- slog.InfoContext(ctx, "updated local environment api url", "id", LocalEnvironmentID, "url", appUrl)+ updates["api_url"] = appUrl+ }+ if existingEnv.Name == legacyLocalEnvironmentName {+ updates["name"] = hostName()+ }+ if len(updates) == 0 {+ return nil+ }+ if updateLocalErr := s.db.WithContext(ctx).Model(&existingEnv).Updates(updates).Error; updateLocalErr != nil {+ return fmt.Errorf("failed to update local environment: %w", updateLocalErr)}+ s.invalidateEnvironmentCache(LocalEnvironmentID)+ slog.InfoContext(ctx, "updated local environment", "id", LocalEnvironmentID, "updates", updates)return nil}@@ -341,7 +362,7 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrlID: LocalEnvironmentID,CreatedAt: now,UpdatedAt: new(now),- Name: "Local Docker",+ Name: hostName(),ApiUrl: appUrl,Status: string(EnvironmentStatusOnline),Enabled: true,diff --git a/backend/internal/podman/children/kube/handler.go b/backend/internal/podman/children/kube/handler.gonew file mode 100644index 000000000..59b58464a--- /dev/null+++ b/backend/internal/podman/children/kube/handler.go@@ -0,0 +1,65 @@+package kube++import (+ "context"++ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++type Handler struct {+ service *Service+ audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)+}++func NewHandler(service *Service, audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)) *Handler {+ return &Handler{service: service, audit: audit}+}++type PlayKubeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body podmantypes.KubePlayRequest+}++type DownKubeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body podmantypes.KubeDownRequest+}++type GenerateKubeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body podmantypes.KubeGenerateRequest+}++func (h *Handler) Play(ctx context.Context, input *PlayKubeInput) (*handlerutil.Out[podmantypes.KubePlayReport], error) {+ report, err := h.service.Play(ctx, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to play kube YAML: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "kube.play", "kube", "", map[string]any{"pods": len(report.Pods), "replace": input.Body.Replace})+ return &handlerutil.Out[podmantypes.KubePlayReport]{Body: base.ApiResponse[podmantypes.KubePlayReport]{Success: true, Data: report}}, nil+}++func (h *Handler) Down(ctx context.Context, input *DownKubeInput) (*handlerutil.Out[podmantypes.KubeDownReport], error) {+ report, err := h.service.Down(ctx, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to tear down kube YAML: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "kube.down", "kube", "", map[string]any{"pods": len(report.RmReport), "force": input.Body.Force})+ return &handlerutil.Out[podmantypes.KubeDownReport]{Body: base.ApiResponse[podmantypes.KubeDownReport]{Success: true, Data: report}}, nil+}++func (h *Handler) Generate(ctx context.Context, input *GenerateKubeInput) (*handlerutil.Out[podmantypes.KubeGenerateResponse], error) {+ generated, err := h.service.Generate(ctx, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to generate kube YAML: "+apiErr.Message)+ }+ return &handlerutil.Out[podmantypes.KubeGenerateResponse]{Body: base.ApiResponse[podmantypes.KubeGenerateResponse]{Success: true, Data: generated}}, nil+}diff --git a/backend/internal/podman/children/kube/module.go b/backend/internal/podman/children/kube/module.gonew file mode 100644index 000000000..f6f4eb0ae--- /dev/null+++ b/backend/internal/podman/children/kube/module.go@@ -0,0 +1,27 @@+package kube++import (+ "net/http"++ "github.com/danielgtaylor/huma/v2"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++const (+ kubePath = "/environments/{id}/podman/kube"+ kubeTag = "Podman"+)++func RegisterRoutes(api huma.API, h *Handler) {+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("play-podman-kube", http.MethodPost, kubePath+"/play", "Play kube YAML", "Create pods and containers from Kubernetes YAML", kubeTag),+ authz.PermPodmanKube, h.Play)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("down-podman-kube", http.MethodPost, kubePath+"/down", "Tear down kube YAML", "Remove pods and containers created from Kubernetes YAML", kubeTag),+ authz.PermPodmanKube, h.Down)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("generate-podman-kube", http.MethodPost, kubePath+"/generate", "Generate kube YAML", "Generate Kubernetes YAML from pods, containers, or volumes", kubeTag),+ authz.PermPodmanKube, h.Generate)+}diff --git a/backend/internal/podman/children/kube/service.go b/backend/internal/podman/children/kube/service.gonew file mode 100644index 000000000..2d4f8fe4e--- /dev/null+++ b/backend/internal/podman/children/kube/service.go@@ -0,0 +1,46 @@+package kube++import (+ "context"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+)++type Service struct {+ runtime func(context.Context) (podman.Runtime, error)+}++func NewService(runtime func(context.Context) (podman.Runtime, error)) *Service {+ return &Service{runtime: runtime}+}++func (s *Service) Play(ctx context.Context, req podmantypes.KubePlayRequest) (podmantypes.KubePlayReport, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.KubePlayReport{}, err+ }+ return rt.Client.KubePlay(ctx, req)+}++func (s *Service) Down(ctx context.Context, req podmantypes.KubeDownRequest) (podmantypes.KubeDownReport, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.KubeDownReport{}, err+ }+ return rt.Client.KubeDown(ctx, req)+}++func (s *Service) Generate(ctx context.Context, req podmantypes.KubeGenerateRequest) (podmantypes.KubeGenerateResponse, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.KubeGenerateResponse{}, err+ }++ yaml, err := rt.Client.KubeGenerate(ctx, req)+ if err != nil {+ return podmantypes.KubeGenerateResponse{}, err+ }+ return podmantypes.KubeGenerateResponse{YAML: yaml}, nil+}diff --git a/backend/internal/podman/children/pods/handler.go b/backend/internal/podman/children/pods/handler.gonew file mode 100644index 000000000..37059e75d--- /dev/null+++ b/backend/internal/podman/children/pods/handler.go@@ -0,0 +1,170 @@+package pods++import (+ "context"++ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+)++type Handler struct {+ service *Service+ audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)+}++func NewHandler(service *Service, audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)) *Handler {+ return &Handler{service: service, audit: audit}+}++type ListPodsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type GetPodInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ PodID string `path:"podId" doc:"Pod name or ID"`+}++type CreatePodInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body podmantypes.PodCreateRequest+}++type PodActionInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ PodID string `path:"podId" doc:"Pod name or ID"`+ Action string `path:"action" enum:"start,stop,restart,pause,unpause,kill" doc:"Lifecycle action"`+ Body *podmantypes.PodActionRequest+}++type DeletePodInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ PodID string `path:"podId" doc:"Pod name or ID"`+ Force bool `query:"force" doc:"Stop and remove running containers"`+}++type PrunePodsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type PodTopInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ PodID string `path:"podId" doc:"Pod name or ID"`+ PsArgs string `query:"psArgs" doc:"Arguments passed to ps"`+}++type PodStatsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Names []string `query:"names" doc:"Pod names or IDs; empty reports every pod"`+}++func (h *Handler) List(ctx context.Context, input *ListPodsInput) (*handlerutil.Page[podmantypes.Pod], error) {+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)+ if _, ok := httpx.EnvironmentScopeFromContext(ctx); ok {+ body, err := h.service.Aggregate(ctx, params)+ if err != nil {+ return nil, huma.Error500InternalServerError("Failed to list pods: " + err.Error())+ }+ return &handlerutil.Page[podmantypes.Pod]{Body: body}, nil+ }++ items, page, err := h.service.ListPaginated(ctx, params)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to list pods: "+apiErr.Message)+ }+ return &handlerutil.Page[podmantypes.Pod]{+ Body: base.Paginated[podmantypes.Pod]{+ Success: true,+ Data: kit.Ternary(items != nil, items, []podmantypes.Pod{}),+ Pagination: handlerutil.PaginationResponse(page),+ },+ }, nil+}++func (h *Handler) Get(ctx context.Context, input *GetPodInput) (*handlerutil.Out[podmantypes.PodInspect], error) {+ pod, err := h.service.Inspect(ctx, input.PodID)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to inspect pod: "+apiErr.Message)+ }+ return &handlerutil.Out[podmantypes.PodInspect]{Body: base.ApiResponse[podmantypes.PodInspect]{Success: true, Data: pod}}, nil+}++func (h *Handler) Create(ctx context.Context, input *CreatePodInput) (*handlerutil.Out[podmantypes.PodCreateResponse], error) {+ id, err := h.service.Create(ctx, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to create pod: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "pod.create", "pod", input.Body.Name, map[string]any{"podId": id})+ return &handlerutil.Out[podmantypes.PodCreateResponse]{Body: base.ApiResponse[podmantypes.PodCreateResponse]{Success: true, Data: podmantypes.PodCreateResponse{ID: id}}}, nil+}++func (h *Handler) Action(ctx context.Context, input *PodActionInput) (*handlerutil.Out[base.MessageResponse], error) {+ if err := h.service.Action(ctx, input.PodID, podman.PodAction(input.Action), kit.FromPtr(input.Body)); err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to "+input.Action+" pod: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "pod."+input.Action, "pod", input.PodID, nil)+ return handlerutil.MessageOutput("Pod "+input.Action+" completed", ""), nil+}++func (h *Handler) Delete(ctx context.Context, input *DeletePodInput) (*handlerutil.Out[base.MessageResponse], error) {+ if err := h.service.Remove(ctx, input.PodID, input.Force); err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to remove pod: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "pod.delete", "pod", input.PodID, map[string]any{"force": input.Force})+ return handlerutil.MessageOutput("Pod removed", ""), nil+}++func (h *Handler) Prune(ctx context.Context, input *PrunePodsInput) (*handlerutil.Out[[]podmantypes.PodPruneReport], error) {+ reports, err := h.service.Prune(ctx)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to prune pods: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "pod.prune", "pod", "", map[string]any{"removed": len(reports)})+ return &handlerutil.Out[[]podmantypes.PodPruneReport]{+ Body: base.ApiResponse[[]podmantypes.PodPruneReport]{+ Success: true,+ Data: kit.Ternary(reports != nil, reports, []podmantypes.PodPruneReport{}),+ },+ }, nil+}++func (h *Handler) Top(ctx context.Context, input *PodTopInput) (*handlerutil.Out[podmantypes.PodTop], error) {+ top, err := h.service.Top(ctx, input.PodID, input.PsArgs)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to list pod processes: "+apiErr.Message)+ }+ return &handlerutil.Out[podmantypes.PodTop]{Body: base.ApiResponse[podmantypes.PodTop]{Success: true, Data: top}}, nil+}++func (h *Handler) Stats(ctx context.Context, input *PodStatsInput) (*handlerutil.Out[[]podmantypes.PodStats], error) {+ stats, err := h.service.Stats(ctx, input.Names)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to read pod stats: "+apiErr.Message)+ }+ return &handlerutil.Out[[]podmantypes.PodStats]{+ Body: base.ApiResponse[[]podmantypes.PodStats]{+ Success: true,+ Data: kit.Ternary(stats != nil, stats, []podmantypes.PodStats{}),+ },+ }, nil+}diff --git a/backend/internal/podman/children/pods/helpers.go b/backend/internal/podman/children/pods/helpers.gonew file mode 100644index 000000000..798eab148--- /dev/null+++ b/backend/internal/podman/children/pods/helpers.go@@ -0,0 +1,57 @@+package pods++import (+ "fmt"+ "strconv"+ "strings"++ "github.com/docker/go-units"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+)++func namespace(value string) *podman.PodNamespace {+ mode, rest, _ := strings.Cut(strings.TrimSpace(value), ":")+ switch mode {+ case "":+ return nil+ case "ns":+ return &podman.PodNamespace{NSMode: "path", Value: rest}+ default:+ return &podman.PodNamespace{NSMode: mode, Value: rest}+ }+}++func byteSize(field, value string) (*int64, error) {+ switch value = strings.TrimSpace(value); value {+ case "":+ return nil, nil+ case "-1":+ return new(int64(-1)), nil+ }+ size, err := units.RAMInBytes(value)+ if err != nil {+ return nil, common.Classify(common.ErrBadRequest, fmt.Errorf("invalid %s %q: %w", field, value, err))+ }+ return &size, nil+}++func deviceLimits[T any](field string, limits []podmantypes.PodDeviceLimit, build func(major, minor int64, value string) (T, error)) ([]T, error) {+ out := make([]T, 0, len(limits))+ for _, limit := range limits {+ majorText, minorText, ok := strings.Cut(strings.TrimSpace(limit.Device), ":")+ major, majorErr := strconv.ParseInt(majorText, 10, 64)+ minor, minorErr := strconv.ParseInt(minorText, 10, 64)+ if !ok || majorErr != nil || minorErr != nil {+ return nil, common.Classify(common.ErrBadRequest, fmt.Errorf("invalid %s device %q: use MAJOR:MINOR", field, limit.Device))+ }+ item, err := build(major, minor, strings.TrimSpace(limit.Value))+ if err != nil {+ return nil, common.Classify(common.ErrBadRequest, fmt.Errorf("invalid %s value %q: %w", field, limit.Value, err))+ }+ out = append(out, item)+ }+ return out, nil+}diff --git a/backend/internal/podman/children/pods/module.go b/backend/internal/podman/children/pods/module.gonew file mode 100644index 000000000..bd61c1fa9--- /dev/null+++ b/backend/internal/podman/children/pods/module.go@@ -0,0 +1,48 @@+package pods++import (+ "net/http"++ "github.com/danielgtaylor/huma/v2"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++const (+ podsPath = "/environments/{id}/podman/pods"+ podsTag = "Podman"+)++func RegisterRoutes(api huma.API, h *Handler) {+ handlerutil.RegisterSecured(api, huma.Operation{+ OperationID: "list-podman-pods",+ Method: http.MethodGet,+ Path: podsPath,+ Summary: "List pods",+ Description: "List Podman pods with their member containers",+ Tags: []string{podsTag},+ Metadata: map[string]any{authz.MetaEnvironmentAggregate: true},+ }, authz.PermPodmanRead, h.List)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("create-podman-pod", http.MethodPost, podsPath, "Create pod", "", podsTag),+ authz.PermPodmanPods, h.Create)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("prune-podman-pods", http.MethodPost, podsPath+"/prune", "Prune pods", "Remove every stopped pod", podsTag),+ authz.PermPodmanPods, h.Prune)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-pod-stats", http.MethodGet, podsPath+"/stats", "Get pod stats", "", podsTag),+ authz.PermPodmanRead, h.Stats)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-pod", http.MethodGet, podsPath+"/{podId}", "Inspect pod", "", podsTag),+ authz.PermPodmanRead, h.Get)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-pod-top", http.MethodGet, podsPath+"/{podId}/top", "List pod processes", "", podsTag),+ authz.PermPodmanRead, h.Top)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("podman-pod-action", http.MethodPost, podsPath+"/{podId}/{action}", "Run pod lifecycle action", "Start, stop, restart, pause, unpause, or kill a pod", podsTag),+ authz.PermPodmanPods, h.Action)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("delete-podman-pod", http.MethodDelete, podsPath+"/{podId}", "Remove pod", "", podsTag),+ authz.PermPodmanPods, h.Delete)+}diff --git a/backend/internal/podman/children/pods/service.go b/backend/internal/podman/children/pods/service.gonew file mode 100644index 000000000..d8db776c9--- /dev/null+++ b/backend/internal/podman/children/pods/service.go@@ -0,0 +1,348 @@+package pods++import (+ "cmp"+ "context"+ "fmt"+ "net/url"+ "slices"+ "strconv"+ "strings"++ "github.com/docker/go-units"+ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+)++const cpuPeriod = 100000++type Service struct {+ runtime func(context.Context) (podman.Runtime, error)+}++func NewService(runtime func(context.Context) (podman.Runtime, error)) *Service {+ return &Service{runtime: runtime}+}++func (s *Service) List(ctx context.Context) ([]podmantypes.Pod, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return nil, err+ }+ return rt.Client.PodList(ctx, nil)+}++var podPagination = pagination.Config[podmantypes.Pod]{+ SearchAccessors: []pagination.SearchAccessor[podmantypes.Pod]{+ func(pod podmantypes.Pod) (string, error) {+ return pod.Name, nil+ },+ func(pod podmantypes.Pod) (string, error) {+ return pod.ID, nil+ },+ func(pod podmantypes.Pod) (string, error) {+ return pod.Status, nil+ },+ func(pod podmantypes.Pod) (string, error) {+ return strings.Join(pod.Networks, " "), nil+ },+ },+ SortBindings: []pagination.SortBinding[podmantypes.Pod]{+ {Key: "name", Fn: func(a, b podmantypes.Pod) int {+ return strings.Compare(a.Name, b.Name)+ }},+ {Key: "status", Fn: func(a, b podmantypes.Pod) int {+ return strings.Compare(a.Status, b.Status)+ }},+ {Key: "created", Fn: func(a, b podmantypes.Pod) int {+ return a.Created.Compare(b.Created)+ }},+ },+}++func (s *Service) ListPaginated(ctx context.Context, params pagination.QueryParams) ([]podmantypes.Pod, pagination.Response, error) {+ items, err := s.List(ctx)+ if err != nil {+ return nil, pagination.Response{}, err+ }+ result := podPagination.SearchOrderAndPaginate(items, params)+ return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params), nil+}++func (s *Service) Aggregate(ctx context.Context, params pagination.QueryParams) (base.Paginated[podmantypes.Pod], error) {+ collection, err := httpx.CollectEnvironments[base.Paginated[podmantypes.Pod]](ctx, url.Values{"start": {"0"}, "limit": {"-1"}})+ if err != nil {+ return base.Paginated[podmantypes.Pod]{}, err+ }++ pages := make([]pagination.EnvironmentPage[podmantypes.Pod], 0, len(collection.Results))+ for _, result := range collection.Results {+ pages = append(pages, pagination.EnvironmentPage[podmantypes.Pod]{+ Environment: result.Environment,+ Items: result.Value.Data,+ TotalAvailable: cmp.Or(result.Value.Pagination.GrandTotalItems, result.Value.Pagination.TotalItems),+ })+ }+ data, resp := pagination.MergeEnvironmentPages(podPagination, pages, params)++ return base.Paginated[podmantypes.Pod]{+ Success: true,+ Data: data,+ Pagination: handlerutil.PaginationResponse(resp),+ FailedEnvironments: collection.Failures,+ }, nil+}++func (s *Service) Inspect(ctx context.Context, nameOrID string) (podmantypes.PodInspect, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.PodInspect{}, err+ }+ return rt.Client.PodInspect(ctx, nameOrID)+}++func (s *Service) Create(ctx context.Context, req podmantypes.PodCreateRequest) (string, error) {+ memory, err := byteSize("memory", req.Memory)+ if err != nil {+ return "", err+ }+ memorySwap, err := byteSize("memory swap", req.MemorySwap)+ if err != nil {+ return "", err+ }+ shmSize, err := byteSize("shm size", req.ShmSize)+ if err != nil {+ return "", err+ }+ shmSizeSystemd, err := byteSize("systemd shm size", req.ShmSizeSystemd)+ if err != nil {+ return "", err+ }+ weightDevices, err := deviceLimits("blkio weight", req.BlkioWeightDevices, func(major, minor int64, value string) (podman.PodWeightDevice, error) {+ weight, parseErr := strconv.ParseUint(value, 10, 16)+ return podman.PodWeightDevice{+ Major: major,+ Minor: minor,+ Weight: new(uint16(weight)),+ }, parseErr+ })+ if err != nil {+ return "", err+ }+ throttle := func(major, minor int64, value string) (podman.PodThrottleDevice, error) {+ rate, parseErr := units.RAMInBytes(value)+ return podman.PodThrottleDevice{+ Major: major,+ Minor: minor,+ Rate: uint64(max(rate, 0)),+ }, parseErr+ }+ readBps, err := deviceLimits("read bps", req.DeviceReadBps, throttle)+ if err != nil {+ return "", err+ }+ writeBps, err := deviceLimits("write bps", req.DeviceWriteBps, throttle)+ if err != nil {+ return "", err+ }+ idMaps := [2][]podman.PodIDMap{}+ for i, entries := range [][]string{req.UIDMap, req.GIDMap} {+ for _, entry := range entries {+ var idMap podman.PodIDMap+ if _, scanErr := fmt.Sscanf(strings.TrimSpace(entry), "%d:%d:%d", &idMap.ContainerID, &idMap.HostID, &idMap.Size); scanErr != nil {+ return "", common.Classify(common.ErrBadRequest, fmt.Errorf("invalid ID mapping %q: use CONTAINER:HOST:SIZE", entry))+ }+ idMaps[i] = append(idMaps[i], idMap)+ }+ }++ var mounts []podman.PodMount+ var volumes []podman.PodNamedVolume+ for _, volume := range req.Volumes {+ if !strings.HasPrefix(volume.Source, "/") && strings.ContainsAny(volume.Source, `/\`) {+ return "", common.Classify(common.ErrBadRequest, fmt.Errorf("volume source %q must be an absolute host path or a named volume", volume.Source))+ }+ if strings.HasPrefix(volume.Source, "/") {+ mounts = append(mounts, podman.PodMount{+ Destination: volume.Destination,+ Type: "bind",+ Source: volume.Source,+ Options: volume.Options,+ })+ continue+ }+ volumes = append(volumes, podman.PodNamedVolume{+ Name: volume.Source,+ Dest: volume.Destination,+ Options: volume.Options,+ })+ }++ rt, err := s.runtime(ctx)+ if err != nil {+ return "", err+ }++ netNS := namespace(cmp.Or(req.NetworkMode, kit.Ternary(len(req.Networks) > 0, "bridge", "")))+ return rt.Client.PodCreate(ctx, podman.PodSpec{+ Name: strings.TrimSpace(req.Name),+ Hostname: strings.TrimSpace(req.Hostname),+ ExitPolicy: req.ExitPolicy,+ Labels: req.Labels,+ NoInfra: req.NoInfra,+ InfraConmonPidFile: req.InfraConmonPidFile,+ InfraCommand: req.InfraCommand,+ InfraImage: strings.TrimSpace(req.InfraImage),+ InfraName: strings.TrimSpace(req.InfraName),+ Ipc: namespace(req.Ipc),+ SharedNamespaces: req.SharedNamespaces,+ RestartPolicy: req.RestartPolicy,+ RestartRetries: req.RestartRetries,+ ShareParent: req.ShareParent,+ Pid: namespace(req.Pid),+ Userns: namespace(req.Userns),+ Uts: namespace(req.Uts),+ Devices: func() []string {+ devices := slices.Clone(req.Devices)+ for _, gpu := range req.GPUs {+ devices = append(devices, "nvidia.com/gpu="+gpu)+ }+ return devices+ }(),+ Sysctl: req.Sysctl,+ NetNS: netNS,+ PortMappings: func() []podman.PodPortMapping {+ out := make([]podman.PodPortMapping, 0, len(req.PortMappings))+ for _, mapping := range req.PortMappings {+ out = append(out, podman.PodPortMapping(mapping))+ }+ return out+ }(),+ Networks: func() map[string]podman.PodNetworkOptions {+ if len(req.Networks) == 0 {+ return nil+ }+ out := make(map[string]podman.PodNetworkOptions, len(req.Networks))+ for _, network := range req.Networks {+ out[strings.TrimSpace(network.Name)] = podman.PodNetworkOptions{+ StaticIPs: network.StaticIPs,+ Aliases: network.Aliases,+ StaticMAC: network.StaticMAC,+ InterfaceName: network.InterfaceName,+ }+ }+ return out+ }(),+ NoManageResolvConf: req.NoManageResolvConf,+ DNSServer: req.DNSServers,+ DNSSearch: req.DNSSearch,+ DNSOption: req.DNSOptions,+ NoManageHostname: req.NoHostname,+ NoManageHosts: req.NoHosts,+ HostAdd: req.AddHosts,+ HostsFile: req.HostsFile,+ NetworkOptions: func() map[string][]string {+ if len(req.NetworkOptions) == 0 || netNS == nil {+ return nil+ }+ return map[string][]string{netNS.NSMode: req.NetworkOptions}+ }(),+ CgroupParent: req.CgroupParent,+ ResourceLimits: &podman.PodResources{+ Memory: func() *podman.PodMemoryLimits {+ if memory == nil && memorySwap == nil {+ return nil+ }+ return &podman.PodMemoryLimits{Limit: memory, Swap: memorySwap}+ }(),+ CPU: func() *podman.PodCPULimits {+ if req.CPUs == 0 && req.CPUShares == 0 && req.CPUSetCPUs == "" && req.CPUSetMems == "" {+ return nil+ }+ return &podman.PodCPULimits{+ Shares: kit.Ternary(req.CPUShares > 0, new(req.CPUShares), nil),+ Quota: kit.Ternary(req.CPUs > 0, new(int64(req.CPUs*cpuPeriod)), nil),+ Period: kit.Ternary(req.CPUs > 0, new(uint64(cpuPeriod)), nil),+ Cpus: req.CPUSetCPUs,+ Mems: req.CPUSetMems,+ }+ }(),+ BlockIO: func() *podman.PodBlockIO {+ if req.BlkioWeight == 0 && len(weightDevices)+len(readBps)+len(writeBps) == 0 {+ return nil+ }+ return &podman.PodBlockIO{+ Weight: kit.Ternary(req.BlkioWeight > 0, new(req.BlkioWeight), nil),+ WeightDevice: weightDevices,+ ThrottleReadBpsDevice: readBps,+ ThrottleWriteBpsDevice: writeBps,+ }+ }(),+ },+ Mounts: mounts,+ Volumes: volumes,+ VolumesFrom: req.VolumesFrom,+ ShmSize: shmSize,+ ShmSizeSystemd: shmSizeSystemd,+ SecurityOpt: req.SecurityOpt,+ IDMappings: func() *podman.PodIDMappings {+ if len(idMaps[0])+len(idMaps[1]) == 0 {+ return nil+ }+ return &podman.PodIDMappings{+ UIDMap: kit.Ternary(len(idMaps[0]) > 0, idMaps[0], idMaps[1]),+ GIDMap: kit.Ternary(len(idMaps[1]) > 0, idMaps[1], idMaps[0]),+ }+ }(),+ })+}++func (s *Service) Action(ctx context.Context, nameOrID string, action podman.PodAction, req podmantypes.PodActionRequest) error {+ rt, err := s.runtime(ctx)+ if err != nil {+ return err+ }+ return rt.Client.PodAction(ctx, nameOrID, action, podman.PodActionOptions{+ Timeout: req.Timeout,+ Signal: req.Signal,+ })+}++func (s *Service) Remove(ctx context.Context, nameOrID string, force bool) error {+ rt, err := s.runtime(ctx)+ if err != nil {+ return err+ }+ return rt.Client.PodRemove(ctx, nameOrID, force)+}++func (s *Service) Prune(ctx context.Context) ([]podmantypes.PodPruneReport, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return nil, err+ }+ return rt.Client.PodPrune(ctx)+}++func (s *Service) Top(ctx context.Context, nameOrID, psArgs string) (podmantypes.PodTop, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.PodTop{}, err+ }+ return rt.Client.PodTop(ctx, nameOrID, psArgs)+}++func (s *Service) Stats(ctx context.Context, namesOrIDs []string) ([]podmantypes.PodStats, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return nil, err+ }+ return rt.Client.PodStats(ctx, namesOrIDs)+}diff --git a/backend/internal/podman/children/pods/service_test.go b/backend/internal/podman/children/pods/service_test.gonew file mode 100644index 000000000..24a5531b0--- /dev/null+++ b/backend/internal/podman/children/pods/service_test.go@@ -0,0 +1,279 @@+package pods++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+)++func TestCreateMapsRequestToPodSpec(t *testing.T) {+ tests := []struct {+ name string+ req podmantypes.PodCreateRequest+ want map[string]any+ }{+ {+ name: "named network with ports",+ req: podmantypes.PodCreateRequest{+ Name: " web ",+ Hostname: "web-host",+ Labels: map[string]string{"tier": "front"},+ Networks: []podmantypes.PodNetwork{{Name: "frontend"}},+ SharedNamespaces: []string{"net", "ipc"},+ PortMappings: []podmantypes.PodPortMapping{+ {+ ContainerPort: 80,+ HostPort: 8080,+ Protocol: "tcp",+ },+ },+ },+ want: map[string]any{+ "name": "web",+ "hostname": "web-host",+ "labels": map[string]any{"tier": "front"},+ "shared_namespaces": []any{"net", "ipc"},+ "portmappings": []any{+ map[string]any{+ "container_port": float64(80),+ "host_port": float64(8080),+ "protocol": "tcp",+ },+ },+ "netns": map[string]any{"nsmode": "bridge"},+ "Networks": map[string]any{"frontend": map[string]any{}},+ "resource_limits": map[string]any{},+ },+ },+ {+ name: "host network without infra",+ req: podmantypes.PodCreateRequest{+ Name: "host-pod",+ NetworkMode: "host",+ NoInfra: true,+ },+ want: map[string]any{+ "name": "host-pod",+ "no_infra": true,+ "netns": map[string]any{"nsmode": "host"},+ "resource_limits": map[string]any{},+ },+ },+ {+ name: "every option",+ req: podmantypes.PodCreateRequest{+ Name: "full",+ ExitPolicy: "stop",+ RestartPolicy: "on-failure",+ RestartRetries: new(uint(3)),+ InfraImage: "registry.k8s.io/pause:3.9",+ InfraCommand: []string{"/catatonit", "-P"},+ InfraName: "full-infra",+ InfraConmonPidFile: "/run/full.pid",+ ShareParent: new(false),+ Pid: "host",+ Ipc: "ns:/proc/1/ns/ipc",+ Uts: "private",+ Userns: "keep-id:uid=1000",+ UIDMap: []string{"0:100000:65536"},+ NetworkMode: "pasta",+ NetworkOptions: []string{"--ipv4-only"},+ Networks: []podmantypes.PodNetwork{{+ Name: "backend",+ Aliases: []string{"api"},+ StaticIPs: []string{"10.89.0.10"},+ StaticMAC: "92:d0:c6:0a:29:33",+ InterfaceName: "eth1",+ }},+ DNSServers: []string{"1.1.1.1"},+ DNSSearch: []string{"example.com"},+ DNSOptions: []string{"ndots:2"},+ NoManageResolvConf: true,+ AddHosts: []string{"db:10.0.0.5"},+ NoHosts: true,+ NoHostname: true,+ HostsFile: "image",+ CgroupParent: "machine.slice",+ CPUs: 1.5,+ CPUShares: 512,+ CPUSetCPUs: "0-3",+ CPUSetMems: "0",+ Memory: "512m",+ MemorySwap: "-1",+ BlkioWeight: 300,+ BlkioWeightDevices: []podmantypes.PodDeviceLimit{{Device: "8:0", Value: "200"}},+ DeviceReadBps: []podmantypes.PodDeviceLimit{{Device: "8:0", Value: "1mb"}},+ DeviceWriteBps: []podmantypes.PodDeviceLimit{{Device: "8:16", Value: "2mb"}},+ Devices: []string{"/dev/fuse"},+ GPUs: []string{"all"},+ Volumes: []podmantypes.PodVolume{+ {+ Source: "/srv/data",+ Destination: "/data",+ Options: []string{"ro", "Z"},+ },+ {Source: "cache", Destination: "/cache"},+ },+ VolumesFrom: []string{"seed:ro"},+ ShmSize: "64m",+ ShmSizeSystemd: "32m",+ SecurityOpt: []string{"label=disable"},+ Sysctl: map[string]string{"net.ipv4.ip_unprivileged_port_start": "80"},+ },+ want: map[string]any{+ "name": "full",+ "exit_policy": "stop",+ "restart_policy": "on-failure",+ "restart_tries": float64(3),+ "infra_image": "registry.k8s.io/pause:3.9",+ "infra_command": []any{"/catatonit", "-P"},+ "infra_name": "full-infra",+ "infra_conmon_pid_file": "/run/full.pid",+ "share_parent": false,+ "pidns": map[string]any{"nsmode": "host"},+ "ipcns": map[string]any{"nsmode": "path", "value": "/proc/1/ns/ipc"},+ "utsns": map[string]any{"nsmode": "private"},+ "userns": map[string]any{"nsmode": "keep-id", "value": "uid=1000"},+ "idmappings": map[string]any{+ "HostUIDMapping": false,+ "HostGIDMapping": false,+ "UIDMap": []any{+ map[string]any{+ "container_id": float64(0),+ "host_id": float64(100000),+ "size": float64(65536),+ },+ },+ "GIDMap": []any{+ map[string]any{+ "container_id": float64(0),+ "host_id": float64(100000),+ "size": float64(65536),+ },+ },+ },+ "netns": map[string]any{"nsmode": "pasta"},+ "network_options": map[string]any{"pasta": []any{"--ipv4-only"}},+ "Networks": map[string]any{"backend": map[string]any{+ "aliases": []any{"api"},+ "static_ips": []any{"10.89.0.10"},+ "static_mac": "92:d0:c6:0a:29:33",+ "interface_name": "eth1",+ }},+ "dns_server": []any{"1.1.1.1"},+ "dns_search": []any{"example.com"},+ "dns_option": []any{"ndots:2"},+ "no_manage_resolv_conf": true,+ "hostadd": []any{"db:10.0.0.5"},+ "no_manage_hosts": true,+ "no_manage_hostname": true,+ "hostsFile": "image",+ "cgroup_parent": "machine.slice",+ "resource_limits": map[string]any{+ "memory": map[string]any{"limit": float64(512 << 20), "swap": float64(-1)},+ "cpu": map[string]any{+ "shares": float64(512),+ "quota": float64(150000),+ "period": float64(100000),+ "cpus": "0-3",+ "mems": "0",+ },+ "blockIO": map[string]any{+ "weight": float64(300),+ "weightDevice": []any{+ map[string]any{+ "major": float64(8),+ "minor": float64(0),+ "weight": float64(200),+ },+ },+ "throttleReadBpsDevice": []any{+ map[string]any{+ "major": float64(8),+ "minor": float64(0),+ "rate": float64(1 << 20),+ },+ },+ "throttleWriteBpsDevice": []any{+ map[string]any{+ "major": float64(8),+ "minor": float64(16),+ "rate": float64(2 << 20),+ },+ },+ },+ },+ "pod_devices": []any{"/dev/fuse", "nvidia.com/gpu=all"},+ "mounts": []any{+ map[string]any{+ "destination": "/data",+ "type": "bind",+ "source": "/srv/data",+ "options": []any{"ro", "Z"},+ },+ },+ "volumes": []any{map[string]any{"Name": "cache", "Dest": "/cache"}},+ "volumes_from": []any{"seed:ro"},+ "shm_size": float64(64 << 20),+ "shm_size_systemd": float64(32 << 20),+ "security_opt": []any{"label=disable"},+ "sysctl": map[string]any{"net.ipv4.ip_unprivileged_port_start": "80"},+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ var got map[string]any+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, "/v4.0.0/libpod/pods/create", r.URL.Path)+ assert.NoError(t, json.NewDecoder(r.Body).Decode(&got))+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"Id":"pod-1"}`))+ }))+ t.Cleanup(server.Close)+ client, err := podman.NewClient(server.URL)+ require.NoError(t, err)++ svc := NewService(func(context.Context) (podman.Runtime, error) {+ return podman.Runtime{Client: client}, nil+ })+ id, err := svc.Create(t.Context(), tt.req)+ require.NoError(t, err)+ assert.Equal(t, "pod-1", id)+ assert.Equal(t, tt.want, got)+ })+ }+}++func TestCreateRejectsInvalidOptions(t *testing.T) {+ tests := []struct {+ name string+ req podmantypes.PodCreateRequest+ }{+ {name: "memory", req: podmantypes.PodCreateRequest{Name: "bad", Memory: "lots"}},+ {name: "device", req: podmantypes.PodCreateRequest{Name: "bad", DeviceReadBps: []podmantypes.PodDeviceLimit{{Device: "/dev/sda", Value: "1mb"}}}},+ {name: "weight", req: podmantypes.PodCreateRequest{Name: "bad", BlkioWeightDevices: []podmantypes.PodDeviceLimit{{Device: "8:0", Value: "heavy"}}}},+ {name: "id map", req: podmantypes.PodCreateRequest{Name: "bad", GIDMap: []string{"0:100000"}}},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ svc := NewService(func(context.Context) (podman.Runtime, error) {+ t.Error("runtime should not be requested")+ return podman.Runtime{}, nil+ })+ _, err := svc.Create(t.Context(), tt.req)+ require.ErrorIs(t, err, common.ErrBadRequest)+ })+ }+}diff --git a/backend/internal/podman/children/quadlets/handler.go b/backend/internal/podman/children/quadlets/handler.gonew file mode 100644index 000000000..d1229802f--- /dev/null+++ b/backend/internal/podman/children/quadlets/handler.go@@ -0,0 +1,147 @@+package quadlets++import (+ "context"++ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+)++type Handler struct {+ service *Service+ audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)+}++func NewHandler(service *Service, audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)) *Handler {+ return &Handler{service: service, audit: audit}+}++type ListQuadletsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name []string `query:"name,explode" doc:"Filter by quadlet name"`+ Pod []string `query:"pod,explode" doc:"Filter by pod (Podman 6.0+)"`+ Status []string `query:"status,explode" doc:"Filter by status (Podman 6.0+)"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type QuadletInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Quadlet file name"`+}++type InstallQuadletInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body podmantypes.QuadletInstallRequest+}++type UpdateQuadletInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Quadlet file name"`+ Body podmantypes.QuadletUpdateRequest+}++type QuadletActionInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Quadlet file name"`+ Action string `path:"action" enum:"start,stop,restart" doc:"systemd lifecycle action"`+}++func (h *Handler) List(ctx context.Context, input *ListQuadletsInput) (*handlerutil.Page[podmantypes.QuadletDetail], error) {+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)+ if _, ok := httpx.EnvironmentScopeFromContext(ctx); ok {+ body, err := h.service.Aggregate(ctx, params)+ if err != nil {+ return nil, huma.Error500InternalServerError("Failed to list quadlets: " + err.Error())+ }+ return &handlerutil.Page[podmantypes.QuadletDetail]{Body: body}, nil+ }++ items, page, err := h.service.ListPaginated(ctx, map[string][]string{+ "name": input.Name,+ "pod": input.Pod,+ "status": input.Status,+ }, params)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to list quadlets: "+apiErr.Message)+ }+ return &handlerutil.Page[podmantypes.QuadletDetail]{+ Body: base.Paginated[podmantypes.QuadletDetail]{+ Success: true,+ Data: items,+ Pagination: handlerutil.PaginationResponse(page),+ },+ }, nil+}++func (h *Handler) Get(ctx context.Context, input *QuadletInput) (*handlerutil.Out[podmantypes.QuadletDetail], error) {+ detail, err := h.service.Get(ctx, input.Name)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to get quadlet: "+apiErr.Message)+ }+ return &handlerutil.Out[podmantypes.QuadletDetail]{Body: base.ApiResponse[podmantypes.QuadletDetail]{Success: true, Data: detail}}, nil+}++func (h *Handler) File(ctx context.Context, input *QuadletInput) (*handlerutil.Out[podmantypes.QuadletFile], error) {+ file, err := h.service.File(ctx, input.Name)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to read quadlet file: "+apiErr.Message)+ }+ return &handlerutil.Out[podmantypes.QuadletFile]{Body: base.ApiResponse[podmantypes.QuadletFile]{Success: true, Data: file}}, nil+}++func (h *Handler) Install(ctx context.Context, input *InstallQuadletInput) (*handlerutil.Out[podmantypes.QuadletInstallReport], error) {+ report, err := h.service.Install(ctx, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to install quadlet: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "quadlet.install", "quadlet", input.Body.Name, map[string]any{"app": input.Body.App})+ return &handlerutil.Out[podmantypes.QuadletInstallReport]{Body: base.ApiResponse[podmantypes.QuadletInstallReport]{Success: true, Data: report}}, nil+}++func (h *Handler) Update(ctx context.Context, input *UpdateQuadletInput) (*handlerutil.Out[podmantypes.QuadletInstallReport], error) {+ report, err := h.service.Update(ctx, input.Name, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to update quadlet: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "quadlet.update", "quadlet", input.Name, nil)+ return &handlerutil.Out[podmantypes.QuadletInstallReport]{Body: base.ApiResponse[podmantypes.QuadletInstallReport]{Success: true, Data: report}}, nil+}++func (h *Handler) Delete(ctx context.Context, input *QuadletInput) (*handlerutil.Out[podmantypes.QuadletRemoveReport], error) {+ report, err := h.service.Delete(ctx, input.Name)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to remove quadlet: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "quadlet.delete", "quadlet", input.Name, nil)+ return &handlerutil.Out[podmantypes.QuadletRemoveReport]{Body: base.ApiResponse[podmantypes.QuadletRemoveReport]{Success: true, Data: report}}, nil+}++func (h *Handler) Action(ctx context.Context, input *QuadletActionInput) (*handlerutil.Out[podmantypes.UnitStatus], error) {+ status, err := h.service.Lifecycle(ctx, input.Name, map[string]func(podman.Systemd, context.Context, string) error{+ "start": podman.Systemd.Start,+ "stop": podman.Systemd.Stop,+ "restart": podman.Systemd.Restart,+ }[input.Action])+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to "+input.Action+" quadlet: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "quadlet."+input.Action, "quadlet", input.Name, map[string]any{"unit": status.Name})+ return &handlerutil.Out[podmantypes.UnitStatus]{Body: base.ApiResponse[podmantypes.UnitStatus]{Success: true, Data: status}}, nil+}diff --git a/backend/internal/podman/children/quadlets/module.go b/backend/internal/podman/children/quadlets/module.gonew file mode 100644index 000000000..3057c6592--- /dev/null+++ b/backend/internal/podman/children/quadlets/module.go@@ -0,0 +1,45 @@+package quadlets++import (+ "net/http"++ "github.com/danielgtaylor/huma/v2"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++const (+ quadletsPath = "/environments/{id}/podman/quadlets"+ quadletsTag = "Podman"+)++func RegisterRoutes(api huma.API, h *Handler) {+ handlerutil.RegisterSecured(api, huma.Operation{+ OperationID: "list-podman-quadlets",+ Method: http.MethodGet,+ Path: quadletsPath,+ Summary: "List quadlets",+ Description: "List installed Podman quadlets with their systemd units",+ Tags: []string{quadletsTag},+ Metadata: map[string]any{authz.MetaEnvironmentAggregate: true},+ }, authz.PermPodmanRead, h.List)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("install-podman-quadlet", http.MethodPost, quadletsPath, "Install quadlet", "", quadletsTag),+ authz.PermPodmanQuadlets, h.Install)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-quadlet", http.MethodGet, quadletsPath+"/{name}", "Get quadlet", "Get a quadlet with its unit status and backing containers", quadletsTag),+ authz.PermPodmanRead, h.Get)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-quadlet-file", http.MethodGet, quadletsPath+"/{name}/file", "Get quadlet file", "", quadletsTag),+ authz.PermPodmanRead, h.File)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("update-podman-quadlet", http.MethodPut, quadletsPath+"/{name}", "Update quadlet", "Replace a quadlet file, keeping its application", quadletsTag),+ authz.PermPodmanQuadlets, h.Update)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("delete-podman-quadlet", http.MethodDelete, quadletsPath+"/{name}", "Remove quadlet", "", quadletsTag),+ authz.PermPodmanQuadlets, h.Delete)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("podman-quadlet-action", http.MethodPost, quadletsPath+"/{name}/{action}", "Run quadlet lifecycle action", "Start, stop, or restart the quadlet's systemd unit", quadletsTag),+ authz.PermPodmanQuadletsLifecycle, h.Action)+}diff --git a/backend/internal/podman/children/quadlets/service.go b/backend/internal/podman/children/quadlets/service.gonew file mode 100644index 000000000..da93155f7--- /dev/null+++ b/backend/internal/podman/children/quadlets/service.go@@ -0,0 +1,313 @@+package quadlets++import (+ "cmp"+ "context"+ "errors"+ "fmt"+ "log/slog"+ "maps"+ "net/url"+ "path"+ "slices"+ "strings"++ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+)++var installableTypes = []podmantypes.QuadletType{+ podmantypes.QuadletTypeContainer,+ podmantypes.QuadletTypePod,+ podmantypes.QuadletTypeKube,+ podmantypes.QuadletTypeNetwork,+ podmantypes.QuadletTypeVolume,+ podmantypes.QuadletTypeImage,+ podmantypes.QuadletTypeBuild,+ podmantypes.QuadletTypeArtifact,+}++type Runtime struct {+ Client *podman.Client+ Systemd podman.Systemd+ AppsSupported bool+}++type Service struct {+ runtime func(context.Context) (Runtime, error)+}++func NewService(runtime func(context.Context) (Runtime, error)) *Service {+ return &Service{runtime: runtime}+}++func (s *Service) List(ctx context.Context, filters map[string][]string) ([]podmantypes.QuadletDetail, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return nil, err+ }++ entries, err := rt.Client.QuadletList(ctx, filters)+ if err != nil {+ return nil, err+ }++ out := make([]podmantypes.QuadletDetail, 0, len(entries))+ for _, entry := range entries {+ out = append(out, describe(entry))+ }+ return out, nil+}++var quadletPagination = pagination.Config[podmantypes.QuadletDetail]{+ SearchAccessors: []pagination.SearchAccessor[podmantypes.QuadletDetail]{+ func(quadlet podmantypes.QuadletDetail) (string, error) {+ return quadlet.Name, nil+ },+ func(quadlet podmantypes.QuadletDetail) (string, error) {+ return quadlet.UnitName, nil+ },+ func(quadlet podmantypes.QuadletDetail) (string, error) {+ return string(quadlet.Type), nil+ },+ func(quadlet podmantypes.QuadletDetail) (string, error) {+ return quadlet.Status, nil+ },+ func(quadlet podmantypes.QuadletDetail) (string, error) {+ return quadlet.App, nil+ },+ },+ SortBindings: []pagination.SortBinding[podmantypes.QuadletDetail]{+ {Key: "name", Fn: func(a, b podmantypes.QuadletDetail) int {+ return strings.Compare(a.Name, b.Name)+ }},+ {Key: "type", Fn: func(a, b podmantypes.QuadletDetail) int {+ return strings.Compare(string(a.Type), string(b.Type))+ }},+ {Key: "status", Fn: func(a, b podmantypes.QuadletDetail) int {+ return strings.Compare(a.Status, b.Status)+ }},+ {Key: "unitName", Fn: func(a, b podmantypes.QuadletDetail) int {+ return strings.Compare(a.UnitName, b.UnitName)+ }},+ {Key: "app", Fn: func(a, b podmantypes.QuadletDetail) int {+ return strings.Compare(a.App, b.App)+ }},+ },+}++func (s *Service) ListPaginated(ctx context.Context, filters map[string][]string, params pagination.QueryParams) ([]podmantypes.QuadletDetail, pagination.Response, error) {+ items, err := s.List(ctx, filters)+ if err != nil {+ return nil, pagination.Response{}, err+ }+ result := quadletPagination.SearchOrderAndPaginate(items, params)+ return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params), nil+}++func (s *Service) Aggregate(ctx context.Context, params pagination.QueryParams) (base.Paginated[podmantypes.QuadletDetail], error) {+ collection, err := httpx.CollectEnvironments[base.Paginated[podmantypes.QuadletDetail]](ctx, url.Values{"start": {"0"}, "limit": {"-1"}})+ if err != nil {+ return base.Paginated[podmantypes.QuadletDetail]{}, err+ }++ pages := make([]pagination.EnvironmentPage[podmantypes.QuadletDetail], 0, len(collection.Results))+ for _, result := range collection.Results {+ pages = append(pages, pagination.EnvironmentPage[podmantypes.QuadletDetail]{+ Environment: result.Environment,+ Items: result.Value.Data,+ TotalAvailable: cmp.Or(result.Value.Pagination.GrandTotalItems, result.Value.Pagination.TotalItems),+ })+ }+ data, resp := pagination.MergeEnvironmentPages(quadletPagination, pages, params)++ return base.Paginated[podmantypes.QuadletDetail]{+ Success: true,+ Data: data,+ Pagination: handlerutil.PaginationResponse(resp),+ FailedEnvironments: collection.Failures,+ }, nil+}++func (s *Service) Get(ctx context.Context, name string) (podmantypes.QuadletDetail, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.QuadletDetail{}, err+ }++ entry, err := find(ctx, rt.Client, name)+ if err != nil {+ return podmantypes.QuadletDetail{}, err+ }++ detail := describe(entry)+ containers, err := rt.Client.ContainerList(ctx, []string{podmantypes.SystemdUnitLabel + "=" + detail.UnitName}, nil)+ if err != nil {+ return podmantypes.QuadletDetail{}, err+ }+ unitStatus, unitErr := rt.Systemd.UnitStatus(ctx, detail.UnitName)+ if unitErr != nil {+ slog.DebugContext(ctx, "Quadlet unit status unavailable", "quadlet", name, "unit", detail.UnitName, "error", unitErr)+ }++ return podmantypes.QuadletDetail{+ Name: detail.Name,+ UnitName: detail.UnitName,+ Path: detail.Path,+ Status: detail.Status,+ App: detail.App,+ Type: detail.Type,+ Template: detail.Template,+ UnitStatus: kit.Ternary(unitErr == nil, &unitStatus, nil),+ Containers: containers,+ }, nil+}++func (s *Service) File(ctx context.Context, name string) (podmantypes.QuadletFile, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.QuadletFile{}, err+ }++ content, err := rt.Client.QuadletFile(ctx, name)+ if err != nil {+ return podmantypes.QuadletFile{}, err+ }+ return podmantypes.QuadletFile{Name: name, Content: content}, nil+}++func (s *Service) Install(ctx context.Context, req podmantypes.QuadletInstallRequest) (podmantypes.QuadletInstallReport, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.QuadletInstallReport{}, err+ }++ name := strings.TrimSpace(req.Name)+ quadletType := podmantypes.QuadletType(strings.TrimPrefix(path.Ext(name), "."))+ if strings.TrimSuffix(name, path.Ext(name)) == "" || !slices.Contains(installableTypes, quadletType) {+ return podmantypes.QuadletInstallReport{}, common.Classify(common.ErrBadRequest, fmt.Errorf("unsupported quadlet file %q", name))+ }+ if req.App != "" && !rt.AppsSupported {+ return podmantypes.QuadletInstallReport{}, common.Classify(common.ErrBadRequest, errors.New("quadlet applications require Podman 6.1 or later"))+ }++ return rt.Client.QuadletInstall(ctx, podman.QuadletInstallOptions{+ File: podmantypes.QuadletFile{+ Name: name,+ Content: req.Content,+ },+ ExtraFiles: req.ExtraFiles,+ Application: req.App,+ AppsSupported: rt.AppsSupported,+ })+}++func (s *Service) Update(ctx context.Context, name string, req podmantypes.QuadletUpdateRequest) (podmantypes.QuadletInstallReport, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.QuadletInstallReport{}, err+ }++ entry, err := find(ctx, rt.Client, name)+ if err != nil {+ return podmantypes.QuadletInstallReport{}, err+ }++ return rt.Client.QuadletInstall(ctx, podman.QuadletInstallOptions{+ File: podmantypes.QuadletFile{+ Name: entry.Name,+ Content: req.Content,+ },+ ExtraFiles: req.ExtraFiles,+ Replace: true,+ Application: entry.App,+ AppsSupported: rt.AppsSupported,+ })+}++func (s *Service) Delete(ctx context.Context, name string) (podmantypes.QuadletRemoveReport, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.QuadletRemoveReport{}, err+ }+ report, err := rt.Client.QuadletRemove(ctx, name, podman.QuadletRemoveOptions{Force: true})+ if err != nil {+ return podmantypes.QuadletRemoveReport{}, err+ }+ if len(report.Errors) > 0 {+ failures := make([]string, 0, len(report.Errors))+ for _, quadlet := range slices.Sorted(maps.Keys(report.Errors)) {+ failures = append(failures, quadlet+": "+report.Errors[quadlet])+ }+ return report, common.Classify(common.ErrConflict, fmt.Errorf("remove quadlet %s: %s", name, strings.Join(failures, "; ")))+ }+ return report, nil+}++func (s *Service) Lifecycle(ctx context.Context, name string, action func(podman.Systemd, context.Context, string) error) (podmantypes.UnitStatus, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.UnitStatus{}, err+ }++ entry, err := find(ctx, rt.Client, name)+ if err != nil {+ return podmantypes.UnitStatus{}, err+ }++ detail := describe(entry)+ if detail.Template {+ return podmantypes.UnitStatus{}, common.Classify(common.ErrConflict, fmt.Errorf("quadlet %s is a template and has no lifecycle actions", name))+ }+ if actionErr := action(rt.Systemd, ctx, detail.UnitName); actionErr != nil {+ return podmantypes.UnitStatus{}, actionErr+ }+ return rt.Systemd.UnitStatus(ctx, detail.UnitName)+}++func find(ctx context.Context, client *podman.Client, name string) (podmantypes.Quadlet, error) {+ entries, err := client.QuadletList(ctx, map[string][]string{"name": {name}})+ if err != nil {+ return podmantypes.Quadlet{}, err+ }++ index := slices.IndexFunc(entries, func(entry podmantypes.Quadlet) bool {+ return entry.Name == name+ })+ if index < 0 {+ return podmantypes.Quadlet{}, common.Classify(common.ErrNotFound, fmt.Errorf("quadlet %s not found", name))+ }+ return entries[index], nil+}++func describe(entry podmantypes.Quadlet) podmantypes.QuadletDetail {+ ext := path.Ext(entry.Name)+ stem := strings.TrimSuffix(entry.Name, ext)+ quadletType := podmantypes.QuadletType(strings.TrimPrefix(ext, "."))++ return podmantypes.QuadletDetail{+ Name: entry.Name,+ UnitName: cmp.Or(entry.UnitName, func() string {+ switch quadletType {+ case podmantypes.QuadletTypeContainer, podmantypes.QuadletTypeKube:+ return stem + ".service"+ case podmantypes.QuadletTypePod:+ return stem + "-pod.service"+ default:+ return stem + "-" + string(quadletType) + ".service"+ }+ }()),+ Path: entry.Path,+ Status: entry.Status,+ App: entry.App,+ Type: quadletType,+ Template: strings.HasSuffix(stem, "@") || strings.EqualFold(strings.TrimSpace(entry.Status), "loaded template"),+ }+}diff --git a/backend/internal/podman/children/quadlets/service_test.go b/backend/internal/podman/children/quadlets/service_test.gonew file mode 100644index 000000000..5998809fc--- /dev/null+++ b/backend/internal/podman/children/quadlets/service_test.go@@ -0,0 +1,262 @@+package quadlets++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+)++type fakeSystemd struct {+ calls []string+}++func (f *fakeSystemd) Availability(context.Context) podmantypes.SystemdAvailability {+ return podmantypes.SystemdAvailability{Available: true}+}++func (f *fakeSystemd) Start(_ context.Context, unit string) error {+ f.calls = append(f.calls, "start "+unit)+ return nil+}++func (f *fakeSystemd) Stop(_ context.Context, unit string) error {+ f.calls = append(f.calls, "stop "+unit)+ return nil+}++func (f *fakeSystemd) Restart(_ context.Context, unit string) error {+ f.calls = append(f.calls, "restart "+unit)+ return nil+}++func (f *fakeSystemd) UnitStatus(_ context.Context, unit string) (podmantypes.UnitStatus, error) {+ return podmantypes.UnitStatus{+ Name: unit,+ LoadState: "loaded",+ ActiveState: "active",+ SubState: "running",+ }, nil+}++func newTestService(t *testing.T, appsSupported bool, handler http.HandlerFunc) (*Service, *fakeSystemd) {+ t.Helper()+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)++ client, err := podman.NewClient(server.URL)+ require.NoError(t, err)+ systemd := &fakeSystemd{}+ return NewService(func(context.Context) (Runtime, error) {+ return Runtime{+ Client: client,+ Systemd: systemd,+ AppsSupported: appsSupported,+ }, nil+ }), systemd+}++func listHandler(body string, next http.HandlerFunc) http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.Method == http.MethodGet && r.URL.Path == "/v4.0.0/libpod/quadlets/json" {+ _, _ = w.Write([]byte(body))+ return+ }+ if next == nil {+ http.NotFound(w, r)+ return+ }+ next(w, r)+ }+}++func TestDescribeDerivesUnitsAndTemplates(t *testing.T) {+ tests := []struct {+ name string+ entry podmantypes.Quadlet+ want podmantypes.QuadletDetail+ }{+ {+ name: "container",+ entry: podmantypes.Quadlet{Name: "web.container", Status: "active"},+ want: podmantypes.QuadletDetail{+ Name: "web.container",+ UnitName: "web.service",+ Status: "active",+ Type: podmantypes.QuadletTypeContainer,+ },+ },+ {+ name: "kube",+ entry: podmantypes.Quadlet{Name: "shop.kube", Status: "inactive"},+ want: podmantypes.QuadletDetail{+ Name: "shop.kube",+ UnitName: "shop.service",+ Status: "inactive",+ Type: podmantypes.QuadletTypeKube,+ },+ },+ {+ name: "pod",+ entry: podmantypes.Quadlet{Name: "stack.pod", Status: "active"},+ want: podmantypes.QuadletDetail{+ Name: "stack.pod",+ UnitName: "stack-pod.service",+ Status: "active",+ Type: podmantypes.QuadletTypePod,+ },+ },+ {+ name: "network",+ entry: podmantypes.Quadlet{Name: "backend.network", Status: "Not loaded"},+ want: podmantypes.QuadletDetail{+ Name: "backend.network",+ UnitName: "backend-network.service",+ Status: "Not loaded",+ Type: podmantypes.QuadletTypeNetwork,+ },+ },+ {+ name: "reported unit wins",+ entry: podmantypes.Quadlet{+ Name: "data.volume",+ UnitName: "custom.service",+ Status: "active",+ },+ want: podmantypes.QuadletDetail{+ Name: "data.volume",+ UnitName: "custom.service",+ Status: "active",+ Type: podmantypes.QuadletTypeVolume,+ },+ },+ {+ name: "template file name",+ entry: podmantypes.Quadlet{Name: "[email protected]", Status: "inactive"},+ want: podmantypes.QuadletDetail{+ Name: "[email protected]",+ UnitName: "[email protected]",+ Status: "inactive",+ Type: podmantypes.QuadletTypeContainer,+ Template: true,+ },+ },+ {+ name: "template status",+ entry: podmantypes.Quadlet{Name: "job.container", Status: "loaded template"},+ want: podmantypes.QuadletDetail{+ Name: "job.container",+ UnitName: "job.service",+ Status: "loaded template",+ Type: podmantypes.QuadletTypeContainer,+ Template: true,+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ assert.Equal(t, tt.want, describe(tt.entry))+ })+ }+}++func TestLifecycleRunsDerivedUnitAndReadsStatus(t *testing.T) {+ svc, systemd := newTestService(t, true, listHandler(`[{"Name":"web.container","Status":"Not loaded"}]`, nil))++ status, err := svc.Lifecycle(t.Context(), "web.container", podman.Systemd.Start)+ require.NoError(t, err)+ assert.Equal(t, []string{"start web.service"}, systemd.calls)+ assert.Equal(t, "web.service", status.Name)+ assert.Equal(t, "active", status.ActiveState)+}++func TestLifecycleRejectsTemplates(t *testing.T) {+ svc, systemd := newTestService(t, true, listHandler(`[{"Name":"[email protected]","Status":"loaded template"}]`, nil))++ _, err := svc.Lifecycle(t.Context(), "[email protected]", podman.Systemd.Restart)+ require.ErrorIs(t, err, common.ErrConflict)+ assert.Empty(t, systemd.calls)+}++func TestLifecycleUnknownQuadlet(t *testing.T) {+ svc, _ := newTestService(t, true, listHandler(`[{"Name":"web.container.bak"}]`, nil))++ _, err := svc.Lifecycle(t.Context(), "web.container", podman.Systemd.Stop)+ require.ErrorIs(t, err, common.ErrNotFound)+}++func TestUpdateReplacesAndKeepsApplication(t *testing.T) {+ tests := []struct {+ name string+ listBody string+ appsSupported bool+ wantQuery string+ }{+ {+ name: "app member keeps its application",+ listBody: `[{"Name":"web.container","App":"shop"}]`,+ appsSupported: true,+ wantQuery: "application=shop&replace=true",+ },+ {+ name: "standalone quadlet",+ listBody: `[{"Name":"web.container"}]`,+ appsSupported: true,+ wantQuery: "replace=true",+ },+ {+ name: "apps unsupported",+ listBody: `[{"Name":"web.container","App":"shop"}]`,+ wantQuery: "replace=true",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ var gotQuery string+ svc, _ := newTestService(t, tt.appsSupported, listHandler(tt.listBody, func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, http.MethodPost, r.Method)+ assert.Equal(t, "/v4.0.0/libpod/quadlets", r.URL.Path)+ gotQuery = r.URL.RawQuery+ _, _ = w.Write([]byte(`{"InstalledQuadlets":{"web.container":"/etc/containers/systemd/web.container"},"QuadletErrors":{}}`))+ }))++ report, err := svc.Update(t.Context(), "web.container", podmantypes.QuadletUpdateRequest{Content: "[Container]\nImage=nginx\n"})+ require.NoError(t, err)+ assert.Equal(t, tt.wantQuery, gotQuery)+ assert.Contains(t, report.InstalledQuadlets, "web.container")+ })+ }+}++func TestInstallValidatesTypeAndApplication(t *testing.T) {+ tests := []struct {+ name string+ req podmantypes.QuadletInstallRequest+ appsSupported bool+ }{+ {name: "unsupported extension", req: podmantypes.QuadletInstallRequest{Name: "web.service", Content: "[Unit]\n"}, appsSupported: true},+ {name: "missing stem", req: podmantypes.QuadletInstallRequest{Name: ".container", Content: "[Container]\n"}, appsSupported: true},+ {name: "application without support", req: podmantypes.QuadletInstallRequest{Name: "web.container", Content: "[Container]\n", App: "shop"}},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ svc, _ := newTestService(t, tt.appsSupported, func(w http.ResponseWriter, r *http.Request) {+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)+ })++ _, err := svc.Install(t.Context(), tt.req)+ require.ErrorIs(t, err, common.ErrBadRequest)+ })+ }+}diff --git a/backend/internal/podman/children/secrets/handler.go b/backend/internal/podman/children/secrets/handler.gonew file mode 100644index 000000000..50a8e8fc9--- /dev/null+++ b/backend/internal/podman/children/secrets/handler.go@@ -0,0 +1,115 @@+package secrets++import (+ "context"++ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+)++type Handler struct {+ service *Service+ audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)+}++func NewHandler(service *Service, audit func(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any)) *Handler {+ return &Handler{service: service, audit: audit}+}++type ListSecretsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type GetSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ SecretID string `path:"secretId" doc:"Secret name or ID"`+}++type CreateSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body podmantypes.SecretCreateRequest+}++type UpdateSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ SecretID string `path:"secretId" doc:"Secret name"`+ Body podmantypes.SecretUpdateRequest+}++type DeleteSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ SecretID string `path:"secretId" doc:"Secret name or ID"`+}++func (h *Handler) List(ctx context.Context, input *ListSecretsInput) (*handlerutil.Page[podmantypes.Secret], error) {+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)+ if _, ok := httpx.EnvironmentScopeFromContext(ctx); ok {+ body, err := h.service.Aggregate(ctx, params)+ if err != nil {+ return nil, huma.Error500InternalServerError("Failed to list Podman secrets: " + err.Error())+ }+ return &handlerutil.Page[podmantypes.Secret]{Body: body}, nil+ }++ items, page, err := h.service.ListPaginated(ctx, params)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to list Podman secrets: "+apiErr.Message)+ }+ return &handlerutil.Page[podmantypes.Secret]{+ Body: base.Paginated[podmantypes.Secret]{+ Success: true,+ Data: kit.Ternary(items != nil, items, []podmantypes.Secret{}),+ Pagination: handlerutil.PaginationResponse(page),+ },+ }, nil+}++func (h *Handler) Get(ctx context.Context, input *GetSecretInput) (*handlerutil.Out[podmantypes.Secret], error) {+ secret, err := h.service.Inspect(ctx, input.SecretID)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to inspect Podman secret: "+apiErr.Message)+ }+ return &handlerutil.Out[podmantypes.Secret]{Body: base.ApiResponse[podmantypes.Secret]{Success: true, Data: secret}}, nil+}++func (h *Handler) Create(ctx context.Context, input *CreateSecretInput) (*handlerutil.Out[podmantypes.SecretCreateResponse], error) {+ id, err := h.service.Create(ctx, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to create Podman secret: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "secret.create", "secret", input.Body.Name, map[string]any{"secretId": id})+ return &handlerutil.Out[podmantypes.SecretCreateResponse]{Body: base.ApiResponse[podmantypes.SecretCreateResponse]{Success: true, Data: podmantypes.SecretCreateResponse{ID: id}}}, nil+}++func (h *Handler) Update(ctx context.Context, input *UpdateSecretInput) (*handlerutil.Out[podmantypes.Secret], error) {+ secret, err := h.service.Update(ctx, input.SecretID, input.Body)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to update Podman secret: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "secret.update", "secret", input.SecretID, map[string]any{"secretId": secret.ID})+ return &handlerutil.Out[podmantypes.Secret]{Body: base.ApiResponse[podmantypes.Secret]{Success: true, Data: secret}}, nil+}++func (h *Handler) Delete(ctx context.Context, input *DeleteSecretInput) (*handlerutil.Out[base.MessageResponse], error) {+ if err := h.service.Delete(ctx, input.SecretID); err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to remove Podman secret: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "secret.delete", "secret", input.SecretID, nil)+ return handlerutil.MessageOutput("Podman secret removed", ""), nil+}diff --git a/backend/internal/podman/children/secrets/module.go b/backend/internal/podman/children/secrets/module.gonew file mode 100644index 000000000..a462f85fb--- /dev/null+++ b/backend/internal/podman/children/secrets/module.go@@ -0,0 +1,38 @@+package secrets++import (+ "net/http"++ "github.com/danielgtaylor/huma/v2"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++const (+ secretsPath = "/environments/{id}/podman/secrets"+ secretsTag = "Podman"+)++func RegisterRoutes(api huma.API, h *Handler) {+ handlerutil.RegisterSecured(api, huma.Operation{+ OperationID: "list-podman-secrets",+ Method: http.MethodGet,+ Path: secretsPath,+ Summary: "List Podman secrets",+ Tags: []string{secretsTag},+ Metadata: map[string]any{authz.MetaEnvironmentAggregate: true},+ }, authz.PermPodmanRead, h.List)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("create-podman-secret", http.MethodPost, secretsPath, "Create Podman secret", "", secretsTag),+ authz.PermPodmanSecrets, h.Create)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-secret", http.MethodGet, secretsPath+"/{secretId}", "Inspect Podman secret", "Returns secret metadata; the value is never included", secretsTag),+ authz.PermPodmanRead, h.Get)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("update-podman-secret", http.MethodPut, secretsPath+"/{secretId}", "Replace Podman secret", "Replace the value, driver, and labels of an existing secret", secretsTag),+ authz.PermPodmanSecrets, h.Update)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("delete-podman-secret", http.MethodDelete, secretsPath+"/{secretId}", "Remove Podman secret", "", secretsTag),+ authz.PermPodmanSecrets, h.Delete)+}diff --git a/backend/internal/podman/children/secrets/service.go b/backend/internal/podman/children/secrets/service.gonew file mode 100644index 000000000..f3bc4dcef--- /dev/null+++ b/backend/internal/podman/children/secrets/service.go@@ -0,0 +1,134 @@+package secrets++import (+ "cmp"+ "context"+ "net/url"+ "strings"++ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+)++type Service struct {+ runtime func(context.Context) (podman.Runtime, error)+}++func NewService(runtime func(context.Context) (podman.Runtime, error)) *Service {+ return &Service{runtime: runtime}+}++var secretPagination = pagination.Config[podmantypes.Secret]{+ SearchAccessors: []pagination.SearchAccessor[podmantypes.Secret]{+ func(secret podmantypes.Secret) (string, error) {+ return secret.Spec.Name, nil+ },+ func(secret podmantypes.Secret) (string, error) {+ return secret.ID, nil+ },+ func(secret podmantypes.Secret) (string, error) {+ return secret.Spec.Driver.Name, nil+ },+ },+ SortBindings: []pagination.SortBinding[podmantypes.Secret]{+ {Key: "name", Fn: func(a, b podmantypes.Secret) int {+ return strings.Compare(a.Spec.Name, b.Spec.Name)+ }},+ {Key: "driver", Fn: func(a, b podmantypes.Secret) int {+ return strings.Compare(a.Spec.Driver.Name, b.Spec.Driver.Name)+ }},+ {Key: "createdAt", Fn: func(a, b podmantypes.Secret) int {+ return a.CreatedAt.Compare(b.CreatedAt)+ }},+ {Key: "updatedAt", Fn: func(a, b podmantypes.Secret) int {+ return a.UpdatedAt.Compare(b.UpdatedAt)+ }},+ },+}++func (s *Service) List(ctx context.Context) ([]podmantypes.Secret, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return nil, err+ }+ return rt.Client.SecretList(ctx, nil)+}++func (s *Service) ListPaginated(ctx context.Context, params pagination.QueryParams) ([]podmantypes.Secret, pagination.Response, error) {+ items, err := s.List(ctx)+ if err != nil {+ return nil, pagination.Response{}, err+ }+ result := secretPagination.SearchOrderAndPaginate(items, params)+ return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params), nil+}++func (s *Service) Aggregate(ctx context.Context, params pagination.QueryParams) (base.Paginated[podmantypes.Secret], error) {+ collection, err := httpx.CollectEnvironments[base.Paginated[podmantypes.Secret]](ctx, url.Values{"start": {"0"}, "limit": {"-1"}})+ if err != nil {+ return base.Paginated[podmantypes.Secret]{}, err+ }++ pages := make([]pagination.EnvironmentPage[podmantypes.Secret], 0, len(collection.Results))+ for _, result := range collection.Results {+ pages = append(pages, pagination.EnvironmentPage[podmantypes.Secret]{+ Environment: result.Environment,+ Items: result.Value.Data,+ TotalAvailable: cmp.Or(result.Value.Pagination.GrandTotalItems, result.Value.Pagination.TotalItems),+ })+ }+ data, resp := pagination.MergeEnvironmentPages(secretPagination, pages, params)++ return base.Paginated[podmantypes.Secret]{+ Success: true,+ Data: data,+ Pagination: handlerutil.PaginationResponse(resp),+ FailedEnvironments: collection.Failures,+ }, nil+}++func (s *Service) Inspect(ctx context.Context, nameOrID string) (podmantypes.Secret, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.Secret{}, err+ }+ return rt.Client.SecretInspect(ctx, nameOrID)+}++func (s *Service) Create(ctx context.Context, req podmantypes.SecretCreateRequest) (string, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return "", err+ }+ return rt.Client.SecretCreate(ctx, req, false)+}++func (s *Service) Update(ctx context.Context, name string, req podmantypes.SecretUpdateRequest) (podmantypes.Secret, error) {+ rt, err := s.runtime(ctx)+ if err != nil {+ return podmantypes.Secret{}, err+ }+ if _, replaceErr := rt.Client.SecretCreate(ctx, podmantypes.SecretCreateRequest{+ Name: name,+ Data: req.Data,+ Driver: req.Driver,+ DriverOptions: req.DriverOptions,+ Labels: req.Labels,+ }, true); replaceErr != nil {+ return podmantypes.Secret{}, replaceErr+ }+ return rt.Client.SecretInspect(ctx, name)+}++func (s *Service) Delete(ctx context.Context, nameOrID string) error {+ rt, err := s.runtime(ctx)+ if err != nil {+ return err+ }+ return rt.Client.SecretRemove(ctx, nameOrID)+}diff --git a/backend/internal/podman/children/secrets/service_test.go b/backend/internal/podman/children/secrets/service_test.gonew file mode 100644index 000000000..f91f56bac--- /dev/null+++ b/backend/internal/podman/children/secrets/service_test.go@@ -0,0 +1,78 @@+package secrets++import (+ "context"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++func newTestService(t *testing.T, handler http.HandlerFunc) *Service {+ t.Helper()+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)+ client, err := podman.NewClient(server.URL)+ require.NoError(t, err)+ return NewService(func(context.Context) (podman.Runtime, error) {+ return podman.Runtime{Client: client}, nil+ })+}++func TestUpdateReplacesSecretAndReturnsInspect(t *testing.T) {+ replaced := false+ svc := newTestService(t, func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/v4.0.0/libpod/secrets/create":+ query := r.URL.Query()+ assert.Equal(t, "db-pass", query.Get("name"))+ assert.Equal(t, "true", query.Get("replace"))+ assert.Equal(t, "file", query.Get("driver"))+ assert.JSONEq(t, `{"tier":"db"}`, query.Get("labels"))+ data, err := io.ReadAll(r.Body)+ assert.NoError(t, err)+ assert.Equal(t, "rotated", string(data))+ replaced = true+ _, _ = w.Write([]byte(`{"ID":"sec2"}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v4.0.0/libpod/secrets/db-pass/json":+ assert.Empty(t, r.URL.Query().Get("showsecret"))+ _, _ = w.Write([]byte(`{"ID":"sec2","Spec":{"Name":"db-pass","Driver":{"Name":"file"},"Labels":{"tier":"db"}}}`))+ default:+ http.NotFound(w, r)+ }+ })++ secret, err := svc.Update(t.Context(), "db-pass", podmantypes.SecretUpdateRequest{+ Data: "rotated",+ Driver: "file",+ Labels: map[string]string{"tier": "db"},+ })+ require.NoError(t, err)+ assert.True(t, replaced)+ assert.Equal(t, "sec2", secret.ID)+ assert.Equal(t, map[string]string{"tier": "db"}, secret.Spec.Labels)+}++func TestListPaginatedSearchesAndSortsSecrets(t *testing.T) {+ svc := newTestService(t, func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(`[+ {"ID":"a","Spec":{"Name":"zeta-token","Driver":{"Name":"file"}}},+ {"ID":"b","Spec":{"Name":"alpha-token","Driver":{"Name":"pass"}}},+ {"ID":"c","Spec":{"Name":"db-pass","Driver":{"Name":"file"}}}+ ]`))+ })++ items, page, err := svc.ListPaginated(t.Context(), handlerutil.PaginationParams(0, 20, "name", "asc", "token"))+ require.NoError(t, err)+ require.Len(t, items, 2)+ assert.Equal(t, "alpha-token", items[0].Spec.Name)+ assert.Equal(t, "zeta-token", items[1].Spec.Name)+ assert.Equal(t, int64(2), page.TotalItems)+}diff --git a/backend/internal/podman/handler.go b/backend/internal/podman/handler.gonew file mode 100644index 000000000..61a06ba18--- /dev/null+++ b/backend/internal/podman/handler.go@@ -0,0 +1,87 @@+package podman++import (+ "cmp"+ "context"+ "log/slog"+ "maps"++ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/types/v2/base"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++type Handler struct {+ service *Service+ eventService *event.EventService+}++type GetPodmanStatusInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type GetPodmanInfoInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type RunPodmanAutoUpdateInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body *podmantypes.AutoUpdateOptions+}++func (h *Handler) GetStatus(ctx context.Context, _ *GetPodmanStatusInput) (*handlerutil.Out[podmantypes.Status], error) {+ return &handlerutil.Out[podmantypes.Status]{Body: base.ApiResponse[podmantypes.Status]{Success: true, Data: h.service.Status(ctx)}}, nil+}++func (h *Handler) GetInfo(ctx context.Context, _ *GetPodmanInfoInput) (*handlerutil.Out[podmantypes.Info], error) {+ info, err := h.service.Info(ctx)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to get Podman info: "+apiErr.Message)+ }+ return &handlerutil.Out[podmantypes.Info]{Body: base.ApiResponse[podmantypes.Info]{Success: true, Data: info}}, nil+}++func (h *Handler) RunAutoUpdate(ctx context.Context, input *RunPodmanAutoUpdateInput) (*handlerutil.Out[podmantypes.AutoUpdateResult], error) {+ opts := kit.FromPtr(input.Body)+ result, err := h.service.AutoUpdate(ctx, opts)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to run Podman auto-update: "+apiErr.Message)+ }+ h.audit(ctx, input.EnvironmentID, "autoupdate", "autoupdate", "", map[string]any{+ "mode": result.Mode,+ "dryRun": opts.DryRun,+ "reports": len(result.Reports),+ })+ return &handlerutil.Out[podmantypes.AutoUpdateResult]{Body: base.ApiResponse[podmantypes.AutoUpdateResult]{Success: true, Data: result}}, nil+}++func (h *Handler) audit(ctx context.Context, environmentID, action, resourceType, resourceName string, metadata map[string]any) {+ actor := handlerutil.CurrentActor(ctx)+ meta := database.JSON{"action": action}+ maps.Copy(meta, metadata)++ if _, err := h.eventService.CreateEvent(ctx, event.CreateEventRequest{+ Type: event.EventType("podman." + action),+ Severity: event.EventSeverityInfo,+ Title: "Podman operation: " + action,+ Description: "Podman operation '" + action + "' completed",+ ResourceType: new("podman." + resourceType),+ ResourceID: mo.EmptyableToOption(resourceName).ToPointer(),+ ResourceName: mo.EmptyableToOption(resourceName).ToPointer(),+ UserID: mo.EmptyableToOption(actor.ID).ToPointer(),+ Username: mo.EmptyableToOption(actor.Username).ToPointer(),+ EnvironmentID: new(cmp.Or(environmentID, "0")),+ Metadata: meta,+ }); err != nil {+ slog.WarnContext(ctx, "Failed to audit Podman mutation", "action", action, "error", err)+ }+}diff --git a/backend/internal/podman/module.go b/backend/internal/podman/module.gonew file mode 100644index 000000000..b98480d57--- /dev/null+++ b/backend/internal/podman/module.go@@ -0,0 +1,51 @@+package podman++import (+ "net/http"++ "github.com/danielgtaylor/huma/v2"++ "github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/kube"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/pods"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/quadlets"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/secrets"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+)++const (+ podmanPath = "/environments/{id}/podman"+ podmanTag = "Podman"+)++type Module struct {+ service *Service+ event *event.EventService+}++func New(service *Service, eventService *event.EventService) *Module {+ return &Module{service: service, event: eventService}+}++func (m *Module) RegisterRoutes(api huma.API) {+ if m == nil {+ m = &Module{service: &Service{}}+ }++ h := &Handler{service: m.service, eventService: m.event}+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-status", http.MethodGet, podmanPath+"/status", "Get Podman status", "Report whether the environment runs Podman and which Podman features it supports", podmanTag),+ authz.PermPodmanRead, h.GetStatus)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("get-podman-info", http.MethodGet, podmanPath+"/info", "Get Podman info", "", podmanTag),+ authz.PermPodmanRead, h.GetInfo)+ handlerutil.RegisterSecured(api,+ handlerutil.Operation("run-podman-autoupdate", http.MethodPost, podmanPath+"/autoupdate", "Run Podman auto-update", "Run podman auto-update through the REST API or its systemd unit", podmanTag),+ authz.PermPodmanAutoUpdate, h.RunAutoUpdate)++ pods.RegisterRoutes(api, pods.NewHandler(m.service.pods, h.audit))+ quadlets.RegisterRoutes(api, quadlets.NewHandler(m.service.quadlets, h.audit))+ kube.RegisterRoutes(api, kube.NewHandler(m.service.kube, h.audit))+ secrets.RegisterRoutes(api, secrets.NewHandler(m.service.secrets, h.audit))+}diff --git a/backend/internal/podman/service.go b/backend/internal/podman/service.gonew file mode 100644index 000000000..cddf8be7e--- /dev/null+++ b/backend/internal/podman/service.go@@ -0,0 +1,307 @@+package podman++import (+ "cmp"+ "context"+ "errors"+ "fmt"+ "log/slog"+ "slices"+ "strings"+ "sync"+ "time"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/samber/mo"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/kube"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/pods"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/quadlets"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman/children/secrets"+ libpodman "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"+)++const (+ detectionTTL = 30 * time.Second+ autoUpdateUnit = "podman-auto-update.service"+ autoUpdatePollInterval = time.Second+)++type Config struct {+ Engine func(context.Context) (compat.EngineCompatibilityInfo, error)+ Host string+ NewSystemd func(rootless bool) libpodman.Systemd+ NotifyUpdates func(context.Context, []notifications.ContainerUpdateBatchEntry) error+}++type Service struct {+ *detector++ pods *pods.Service+ quadlets *quadlets.Service+ kube *kube.Service+ secrets *secrets.Service+}++type detector struct {+ config Config+ client *libpodman.Client+ clientErr error++ mu sync.Mutex+ cached libpodman.Runtime+ cachedAt time.Time+}++func NewService(cfg Config) *Service {+ client, clientErr := libpodman.NewClient(cfg.Host)+ d := &detector{+ config: cfg,+ client: client,+ clientErr: clientErr,+ }+ return &Service{+ detector: d,+ pods: pods.NewService(d.detect),+ quadlets: quadlets.NewService(d.quadletRuntime),+ kube: kube.NewService(d.detect),+ secrets: secrets.NewService(d.detect),+ }+}++func (s *Service) Status(ctx context.Context) podmantypes.Status {+ rt, err := s.detect(ctx)+ if err != nil {+ if !errors.Is(err, common.ErrPodmanNotDetected) {+ slog.DebugContext(ctx, "Podman detection failed", "error", err)+ }+ return podmantypes.Status{AutoUpdateMode: podmantypes.AutoUpdateModeUnavailable}+ }++ availability := rt.Systemd.Availability(ctx)+ features := libpodman.DetectFeatures(rt.Version.Version, availability.Available)+ return podmantypes.Status{+ Detected: true,+ Version: rt.Version.Version,+ APIVersion: rt.Version.APIVersion,+ Rootless: rt.Rootless,+ QuadletsSupported: features.QuadletsSupported,+ QuadletAppsSupported: features.QuadletAppsSupported,+ AutoUpdateMode: features.AutoUpdateMode,+ SystemdAvailable: availability.Available,+ SystemdScope: availability.Scope,+ SystemdReason: availability.Reason,+ }+}++func (s *Service) Info(ctx context.Context) (podmantypes.Info, error) {+ rt, err := s.detect(ctx)+ if err != nil {+ return podmantypes.Info{}, err+ }+ return rt.Client.Info(ctx)+}++func (s *Service) PodCount(ctx context.Context) mo.Option[int] {+ items, err := s.pods.List(ctx)+ if err != nil {+ if !errors.Is(err, common.ErrPodmanNotDetected) {+ slog.DebugContext(ctx, "Skipping Podman pod count", "error", err)+ }+ return mo.None[int]()+ }+ return mo.Some(len(items))+}++func (s *Service) ContainerUnitAction(ctx context.Context, containerRef string, action func(libpodman.Systemd, context.Context, string) error) (bool, error) {+ rt, err := s.detect(ctx)+ if err != nil || containerRef == "" {+ return false, nil+ }+ if !libpodman.DetectFeatures(rt.Version.Version, false).QuadletsSupported || !rt.Systemd.Availability(ctx).Available {+ return false, nil+ }++ containers, err := rt.Client.ContainerList(ctx, []string{podmantypes.SystemdUnitLabel}, nil)+ if err != nil {+ slog.WarnContext(ctx, "Could not list quadlet-managed containers", "container", containerRef, "error", err)+ return false, nil+ }++ index := slices.IndexFunc(containers, func(c podmantypes.Container) bool {+ return strings.HasPrefix(c.ID, containerRef) || slices.Contains(c.Names, strings.TrimPrefix(containerRef, "/"))+ })+ if index < 0 {+ return false, nil+ }++ unit := containers[index].Labels[podmantypes.SystemdUnitLabel]+ managed, err := s.quadletManaged(ctx, rt, unit)+ if err != nil {+ return true, fmt.Errorf("verify quadlet unit %s for container %s: %w", unit, containerRef, err)+ }+ if !managed {+ return false, nil+ }+ return true, action(rt.Systemd, ctx, unit)+}++func (s *Service) GuardQuadletManaged(ctx context.Context, labels map[string]string) error {+ unit := labels[podmantypes.SystemdUnitLabel]+ if unit == "" {+ return nil+ }++ rt, err := s.detect(ctx)+ if errors.Is(err, common.ErrPodmanNotDetected) {+ return nil+ }+ if err != nil {+ return fmt.Errorf("verify quadlet unit %s: %w", unit, err)+ }++ managed, err := s.quadletManaged(ctx, rt, unit)+ if err != nil {+ return fmt.Errorf("verify quadlet unit %s: %w", unit, err)+ }+ if managed {+ return fmt.Errorf("systemd unit %s: %w", unit, common.ErrContainerQuadletManaged)+ }+ return nil+}++func (s *Service) quadletManaged(ctx context.Context, rt libpodman.Runtime, unit string) (bool, error) {+ if !libpodman.DetectFeatures(rt.Version.Version, false).QuadletsSupported {+ return true, nil+ }++ installed, err := s.quadlets.List(ctx, nil)+ if err != nil {+ return false, err+ }+ return slices.ContainsFunc(installed, func(quadlet podmantypes.QuadletDetail) bool {+ return quadlet.UnitName == unit+ }), nil+}++func (s *Service) AutoUpdate(ctx context.Context, opts podmantypes.AutoUpdateOptions) (podmantypes.AutoUpdateResult, error) {+ rt, err := s.detect(ctx)+ if err != nil {+ return podmantypes.AutoUpdateResult{}, err+ }++ availability := rt.Systemd.Availability(ctx)+ switch libpodman.DetectFeatures(rt.Version.Version, availability.Available).AutoUpdateMode {+ case podmantypes.AutoUpdateModeREST:+ result, updateErr := rt.Client.AutoUpdate(ctx, opts)+ if updateErr != nil {+ return podmantypes.AutoUpdateResult{}, updateErr+ }+ if !opts.DryRun {+ entries := make([]notifications.ContainerUpdateBatchEntry, 0, len(result.Reports))+ for _, report := range result.Reports {+ if report.Updated == "true" {+ entries = append(entries, notifications.ContainerUpdateBatchEntry{+ ContainerName: report.ContainerName,+ ImageRef: report.ImageName,+ })+ }+ }+ if notifyErr := s.config.NotifyUpdates(ctx, entries); notifyErr != nil {+ slog.WarnContext(ctx, "Could not send Podman auto-update notification", "error", notifyErr)+ }+ }+ return result, nil+ case podmantypes.AutoUpdateModeSystemd:+ if opts.DryRun {+ return podmantypes.AutoUpdateResult{}, common.Classify(common.ErrBadRequest, errors.New("auto-update dry run requires Podman 6.2 or later"))+ }+ if len(opts.Filters) > 0 || opts.Rollback != nil || opts.TLSVerify != nil || opts.Authfile != "" {+ return podmantypes.AutoUpdateResult{}, common.Classify(common.ErrBadRequest, errors.New("auto-update filters, rollback, TLS verification and authfile options require Podman 6.2 or later"))+ }+ if startErr := rt.Systemd.Start(ctx, autoUpdateUnit); startErr != nil {+ return podmantypes.AutoUpdateResult{}, startErr+ }+ unit, statusErr := rt.Systemd.UnitStatus(ctx, autoUpdateUnit)+ for statusErr == nil && unit.ActiveState == "activating" {+ select {+ case <-ctx.Done():+ return podmantypes.AutoUpdateResult{}, ctx.Err()+ case <-time.After(autoUpdatePollInterval):+ }+ unit, statusErr = rt.Systemd.UnitStatus(ctx, autoUpdateUnit)+ }+ if statusErr != nil {+ return podmantypes.AutoUpdateResult{}, statusErr+ }+ return podmantypes.AutoUpdateResult{+ Mode: podmantypes.AutoUpdateModeSystemd,+ Reports: []podmantypes.AutoUpdateReport{},+ Errors: kit.Ternary(unit.ActiveState == "failed", []string{autoUpdateUnit + " failed: " + unit.SubState}, []string{}),+ Unit: &unit,+ }, nil+ default:+ return podmantypes.AutoUpdateResult{}, common.Classify(common.ErrConflict, fmt.Errorf("podman auto-update is unavailable: %s", cmp.Or(availability.Reason, "systemd is not reachable")))+ }+}++func (s *detector) detect(ctx context.Context) (libpodman.Runtime, error) {+ s.mu.Lock()+ cached, fresh := s.cached, time.Since(s.cachedAt) < detectionTTL+ s.mu.Unlock()+ if fresh {+ return cached, nil+ }++ engine, err := s.config.Engine(ctx)+ if err != nil {+ return libpodman.Runtime{}, err+ }+ if engine.Name != "podman" {+ return libpodman.Runtime{}, common.ErrPodmanNotDetected+ }+ if s.clientErr != nil {+ return libpodman.Runtime{}, s.clientErr+ }++ version, err := s.client.Version(ctx)+ if err != nil {+ return libpodman.Runtime{}, err+ }+ info, err := s.client.Info(ctx)+ if err != nil {+ return libpodman.Runtime{}, err+ }++ rt := libpodman.Runtime{+ Client: s.client,+ Version: version,+ Rootless: info.Host.Security.Rootless,+ Systemd: s.config.NewSystemd(info.Host.Security.Rootless),+ }+ s.mu.Lock()+ s.cached, s.cachedAt = rt, time.Now()+ s.mu.Unlock()+ return rt, nil+}++func (s *detector) quadletRuntime(ctx context.Context) (quadlets.Runtime, error) {+ rt, err := s.detect(ctx)+ if err != nil {+ return quadlets.Runtime{}, err+ }++ features := libpodman.DetectFeatures(rt.Version.Version, false)+ if !features.QuadletsSupported {+ return quadlets.Runtime{}, common.Classify(common.ErrBadRequest, fmt.Errorf("quadlet management requires Podman 5.8 or later; this host runs %s", rt.Version.Version))+ }+ return quadlets.Runtime{+ Client: rt.Client,+ Systemd: rt.Systemd,+ AppsSupported: features.QuadletAppsSupported,+ }, nil+}diff --git a/backend/internal/podman/service_test.go b/backend/internal/podman/service_test.gonew file mode 100644index 000000000..f69f970e8--- /dev/null+++ b/backend/internal/podman/service_test.go@@ -0,0 +1,406 @@+package podman++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "strconv"+ "strings"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.getarcane.app/docker/compat"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ libpodman "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/podman"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"+)++type fakeSystemd struct {+ availability podmantypes.SystemdAvailability+ statuses []podmantypes.UnitStatus+ calls []string+}++func (f *fakeSystemd) Availability(context.Context) podmantypes.SystemdAvailability {+ return f.availability+}++func (f *fakeSystemd) Start(_ context.Context, unit string) error {+ f.calls = append(f.calls, "start "+unit)+ return nil+}++func (f *fakeSystemd) Stop(_ context.Context, unit string) error {+ f.calls = append(f.calls, "stop "+unit)+ return nil+}++func (f *fakeSystemd) Restart(_ context.Context, unit string) error {+ f.calls = append(f.calls, "restart "+unit)+ return nil+}++func (f *fakeSystemd) UnitStatus(_ context.Context, unit string) (podmantypes.UnitStatus, error) {+ status := f.statuses[0]+ if len(f.statuses) > 1 {+ f.statuses = f.statuses[1:]+ }+ return podmantypes.UnitStatus{+ Name: unit,+ LoadState: status.LoadState,+ ActiveState: status.ActiveState,+ SubState: status.SubState,+ }, nil+}++type testHost struct {+ engine string+ version string+ rootless bool+ systemd *fakeSystemd+ routes map[string]http.HandlerFunc+ notified [][]notifications.ContainerUpdateBatchEntry+}++func newTestService(t *testing.T, host *testHost) *Service {+ t.Helper()++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch path := strings.TrimPrefix(r.URL.Path, "/v4.0.0/libpod"); path {+ case "/version":+ _, _ = w.Write([]byte(`{"Version":"` + host.version + `","ApiVersion":"` + host.version + `"}`))+ case "/info":+ _, _ = w.Write([]byte(`{"host":{"security":{"rootless":` + strconv.FormatBool(host.rootless) + `}}}`))+ default:+ route, ok := host.routes[path]+ if !ok {+ http.NotFound(w, r)+ return+ }+ route(w, r)+ }+ }))+ t.Cleanup(server.Close)++ return NewService(Config{+ Engine: func(context.Context) (compat.EngineCompatibilityInfo, error) {+ return compat.EngineCompatibilityInfo{Name: host.engine}, nil+ },+ Host: server.URL,+ NewSystemd: func(rootless bool) libpodman.Systemd {+ assert.Equal(t, host.rootless, rootless)+ return host.systemd+ },+ NotifyUpdates: func(_ context.Context, entries []notifications.ContainerUpdateBatchEntry) error {+ host.notified = append(host.notified, entries)+ return nil+ },+ })+}++func TestServiceStatusOnDocker(t *testing.T) {+ svc := newTestService(t, &testHost{engine: "docker"})++ assert.Equal(t, podmantypes.Status{AutoUpdateMode: podmantypes.AutoUpdateModeUnavailable}, svc.Status(t.Context()))++ _, err := svc.Info(t.Context())+ require.ErrorIs(t, err, common.ErrPodmanNotDetected)+ _, err = svc.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{})+ require.ErrorIs(t, err, common.ErrPodmanNotDetected)+ _, err = svc.pods.List(t.Context())+ require.ErrorIs(t, err, common.ErrPodmanNotDetected)+ assert.True(t, svc.PodCount(t.Context()).IsAbsent())+}++func TestServiceStatusEngineErrorReportsNotDetected(t *testing.T) {+ svc := NewService(Config{+ Engine: func(context.Context) (compat.EngineCompatibilityInfo, error) {+ return compat.EngineCompatibilityInfo{}, errors.New("daemon unreachable")+ },+ })++ assert.False(t, svc.Status(t.Context()).Detected)+ _, err := svc.Info(t.Context())+ require.ErrorContains(t, err, "daemon unreachable")+}++func TestServiceStatusOnPodman(t *testing.T) {+ tests := []struct {+ name string+ version string+ systemd podmantypes.SystemdAvailability+ want podmantypes.Status+ }{+ {+ name: "podman 6.1 with user bus",+ version: "6.1.0",+ systemd: podmantypes.SystemdAvailability{Available: true, Scope: podmantypes.SystemdScopeUser},+ want: podmantypes.Status{+ Detected: true,+ Version: "6.1.0",+ APIVersion: "6.1.0",+ Rootless: true,+ QuadletsSupported: true,+ QuadletAppsSupported: true,+ AutoUpdateMode: podmantypes.AutoUpdateModeSystemd,+ SystemdAvailable: true,+ SystemdScope: podmantypes.SystemdScopeUser,+ },+ },+ {+ name: "podman 5.4 without bus",+ version: "5.4.2",+ systemd: podmantypes.SystemdAvailability{Scope: podmantypes.SystemdScopeUser, Reason: "DBUS_SESSION_BUS_ADDRESS is not set"},+ want: podmantypes.Status{+ Detected: true,+ Version: "5.4.2",+ APIVersion: "5.4.2",+ Rootless: true,+ AutoUpdateMode: podmantypes.AutoUpdateModeUnavailable,+ SystemdScope: podmantypes.SystemdScopeUser,+ SystemdReason: "DBUS_SESSION_BUS_ADDRESS is not set",+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ svc := newTestService(t, &testHost{+ engine: "podman",+ version: tt.version,+ rootless: true,+ systemd: &fakeSystemd{availability: tt.systemd},+ })+ assert.Equal(t, tt.want, svc.Status(t.Context()))+ })+ }+}++func TestServiceQuadletsRequirePodman58(t *testing.T) {+ svc := newTestService(t, &testHost{+ engine: "podman",+ version: "5.7.1",+ systemd: &fakeSystemd{},+ })++ _, err := svc.quadlets.List(t.Context(), nil)+ require.ErrorIs(t, err, common.ErrBadRequest)+ require.ErrorContains(t, err, "5.8")+}++func TestServiceAutoUpdateSystemdMode(t *testing.T) {+ systemd := &fakeSystemd{+ availability: podmantypes.SystemdAvailability{Available: true, Scope: podmantypes.SystemdScopeSystem},+ statuses: []podmantypes.UnitStatus{+ {+ LoadState: "loaded",+ ActiveState: "inactive",+ SubState: "dead",+ },+ },+ }+ host := &testHost{+ engine: "podman",+ version: "6.1.0",+ systemd: systemd,+ }+ svc := newTestService(t, host)++ _, err := svc.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{DryRun: true})+ require.ErrorIs(t, err, common.ErrBadRequest)+ assert.Empty(t, systemd.calls)++ result, err := svc.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{})+ require.NoError(t, err)+ assert.Equal(t, []string{"start podman-auto-update.service"}, systemd.calls)+ assert.Equal(t, podmantypes.AutoUpdateModeSystemd, result.Mode)+ assert.Empty(t, result.Errors)+ require.NotNil(t, result.Unit)+ assert.Equal(t, "inactive", result.Unit.ActiveState)+ assert.Empty(t, host.notified)+}++func TestServiceAutoUpdateSystemdFailureReported(t *testing.T) {+ systemd := &fakeSystemd{+ availability: podmantypes.SystemdAvailability{Available: true},+ statuses: []podmantypes.UnitStatus{+ {ActiveState: "failed", SubState: "failed"},+ },+ }+ svc := newTestService(t, &testHost{+ engine: "podman",+ version: "5.8.0",+ systemd: systemd,+ })++ result, err := svc.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{})+ require.NoError(t, err)+ assert.Equal(t, []string{"podman-auto-update.service failed: failed"}, result.Errors)+}++func TestServiceAutoUpdateRESTModeNotifiesUpdatedContainers(t *testing.T) {+ var gotQuery string+ host := &testHost{+ engine: "podman",+ version: "6.2.0",+ systemd: &fakeSystemd{},+ routes: map[string]http.HandlerFunc{+ "/autoupdate": func(w http.ResponseWriter, r *http.Request) {+ gotQuery = r.URL.RawQuery+ _, _ = w.Write([]byte(`{"Reports":[` ++ `{"ContainerName":"web","ImageName":"docker.io/library/nginx:latest","Updated":"true"},` ++ `{"ContainerName":"db","ImageName":"docker.io/library/postgres:16","Updated":"false"}` ++ `],"Errors":[]}`))+ },+ },+ }+ svc := newTestService(t, host)++ result, err := svc.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{})+ require.NoError(t, err)+ assert.Equal(t, "dryRun=false", gotQuery)+ assert.Equal(t, podmantypes.AutoUpdateModeREST, result.Mode)+ require.Len(t, result.Reports, 2)+ assert.Equal(t, [][]notifications.ContainerUpdateBatchEntry{{+ {ContainerName: "web", ImageRef: "docker.io/library/nginx:latest"},+ }}, host.notified)++ _, err = svc.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{DryRun: true})+ require.NoError(t, err)+ assert.Equal(t, "dryRun=true", gotQuery)+ assert.Len(t, host.notified, 1)+}++func TestServiceAutoUpdateUnavailable(t *testing.T) {+ svc := newTestService(t, &testHost{+ engine: "podman",+ version: "5.8.0",+ systemd: &fakeSystemd{availability: podmantypes.SystemdAvailability{Reason: "bus not mounted"}},+ })++ _, err := svc.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{})+ require.ErrorIs(t, err, common.ErrConflict)+ require.ErrorContains(t, err, "bus not mounted")+}++func TestServiceContainerUnitAction(t *testing.T) {+ systemd := &fakeSystemd{availability: podmantypes.SystemdAvailability{Available: true}}+ svc := newTestService(t, &testHost{+ engine: "podman",+ version: "6.1.0",+ systemd: systemd,+ routes: map[string]http.HandlerFunc{+ "/containers/json": func(w http.ResponseWriter, r *http.Request) {+ assert.JSONEq(t, `{"label":["PODMAN_SYSTEMD_UNIT"]}`, r.URL.Query().Get("filters"))+ _, _ = w.Write([]byte(`[+ {"Id":"abc123def456","Names":["web"],"Labels":{"PODMAN_SYSTEMD_UNIT":"web.service"}},+ {"Id":"fed654cba321","Names":["spoof"],"Labels":{"PODMAN_SYSTEMD_UNIT":"nginx.service"}}+ ]`))+ },+ "/quadlets/json": func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`[{"Name":"web.container","UnitName":"web.service"}]`))+ },+ },+ })++ handled, err := svc.ContainerUnitAction(t.Context(), "abc123", libpodman.Systemd.Restart)+ require.NoError(t, err)+ assert.True(t, handled)++ handled, err = svc.ContainerUnitAction(t.Context(), "/web", libpodman.Systemd.Stop)+ require.NoError(t, err)+ assert.True(t, handled)++ handled, err = svc.ContainerUnitAction(t.Context(), "other", libpodman.Systemd.Start)+ require.NoError(t, err)+ assert.False(t, handled)++ handled, err = svc.ContainerUnitAction(t.Context(), "spoof", libpodman.Systemd.Stop)+ require.NoError(t, err)+ assert.False(t, handled)++ assert.Equal(t, []string{"restart web.service", "stop web.service"}, systemd.calls)+}++func TestServiceContainerUnitActionFallsBackWithoutQuadletSupport(t *testing.T) {+ tests := []struct {+ name string+ version string+ available bool+ }{+ {name: "podman before 5.8", version: "5.4.0", available: true},+ {name: "systemd unreachable", version: "6.1.0"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ systemd := &fakeSystemd{availability: podmantypes.SystemdAvailability{Available: tt.available}}+ svc := newTestService(t, &testHost{+ engine: "podman",+ version: tt.version,+ systemd: systemd,+ routes: map[string]http.HandlerFunc{+ "/containers/json": func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`[{"Id":"abc123def456","Names":["web"],"Labels":{"PODMAN_SYSTEMD_UNIT":"web.service"}}]`))+ },+ },+ })++ handled, err := svc.ContainerUnitAction(t.Context(), "web", libpodman.Systemd.Stop)+ require.NoError(t, err)+ assert.False(t, handled)+ assert.Empty(t, systemd.calls)+ })+ }+}++func TestServiceGuardQuadletManaged(t *testing.T) {+ tests := []struct {+ name string+ engine string+ version string+ unit string+ wantErr bool+ }{+ {name: "unlabelled", engine: "podman", version: "6.1.0"},+ {name: "installed quadlet", engine: "podman", version: "6.1.0", unit: "web.service", wantErr: true},+ {name: "stale label", engine: "podman", version: "6.1.0", unit: "gone.service"},+ {name: "unverifiable before 5.8", engine: "podman", version: "5.4.0", unit: "gone.service", wantErr: true},+ {name: "docker host", engine: "docker", unit: "web.service"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ svc := newTestService(t, &testHost{+ engine: tt.engine,+ version: tt.version,+ systemd: &fakeSystemd{},+ routes: map[string]http.HandlerFunc{+ "/quadlets/json": func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`[{"Name":"web.container","UnitName":"web.service"}]`))+ },+ },+ })++ err := svc.GuardQuadletManaged(t.Context(), map[string]string{podmantypes.SystemdUnitLabel: tt.unit})+ if tt.wantErr {+ require.ErrorIs(t, err, common.ErrContainerQuadletManaged)+ return+ }+ require.NoError(t, err)+ })+ }+}++func TestServiceContainerUnitActionOnDocker(t *testing.T) {+ svc := newTestService(t, &testHost{engine: "docker"})++ handled, err := svc.ContainerUnitAction(t.Context(), "abc123", libpodman.Systemd.Start)+ require.NoError(t, err)+ assert.False(t, handled)+}diff --git a/backend/internal/swarm/children/configs/handler.go b/backend/internal/swarm/children/configs/handler.goindex 40866a4e7..3c72d6973 100644--- a/backend/internal/swarm/children/configs/handler.go+++ b/backend/internal/swarm/children/configs/handler.go@@ -7,6 +7,7 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/swarm"+ kit "go.getarcane.app/kit/pkg""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil")@@ -28,6 +29,11 @@ func NewHandler(type ListSwarmConfigsInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`}type GetSwarmConfigInput struct {@@ -40,6 +46,12 @@ type CreateSwarmConfigInput struct {Body swarm.ConfigCreateRequest}+type UpdateSwarmConfigInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ConfigID string `path:"configId" doc:"Config ID"`+ Body swarm.ConfigUpdateRequest+}+type DeleteSwarmConfigInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`ConfigID string `path:"configId" doc:"Config ID"`@@ -55,16 +67,20 @@ type DeleteSwarmConfigInput struct {//// Returns the current swarm configs.// Returns a mapped HTTP error when config enumeration fails.-func (h *Handler) ListConfigs(ctx context.Context, input *ListSwarmConfigsInput) (*handlerutil.Out[[]swarm.ConfigSummary], error) {- items, err := h.service.ListConfigs(ctx)+func (h *Handler) ListConfigs(ctx context.Context, input *ListSwarmConfigsInput) (*handlerutil.Page[swarm.ConfigSummary], error) {+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)+ items, page, err := h.service.ListConfigs(ctx, params)if err != nil {return nil, h.mapError(err, "Failed to list swarm configs")}- if items == nil {- items = []swarm.ConfigSummary{}- }- return &handlerutil.Out[[]swarm.ConfigSummary]{Body: base.ApiResponse[[]swarm.ConfigSummary]{Success: true, Data: items}}, nil+ return &handlerutil.Page[swarm.ConfigSummary]{+ Body: base.Paginated[swarm.ConfigSummary]{+ Success: true,+ Data: kit.Ternary(items != nil, items, []swarm.ConfigSummary{}),+ Pagination: handlerutil.PaginationResponse(page),+ },+ }, nil}// GetConfig returns details for a single swarm config.@@ -112,6 +128,20 @@ func (h *Handler) CreateConfig(ctx context.Context, input *CreateSwarmConfigInpureturn &handlerutil.Out[swarm.ConfigSummary]{Body: base.ApiResponse[swarm.ConfigSummary]{Success: true, Data: *cfg}}, nil}+func (h *Handler) UpdateConfig(ctx context.Context, input *UpdateSwarmConfigInput) (*handlerutil.Out[swarm.ConfigSummary], error) {+ updated, err := h.service.UpdateConfig(ctx, input.ConfigID, input.Body)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm config not found")+ }+ return nil, h.mapError(err, "Failed to update swarm config")+ }++ h.audit(ctx, input.EnvironmentID, "config.update", "swarm_config", updated.ID, updated.Spec.Name, map[string]any{"configId": updated.ID, "name": updated.Spec.Name})++ return &handlerutil.Out[swarm.ConfigSummary]{Body: base.ApiResponse[swarm.ConfigSummary]{Success: true, Data: *updated}}, nil+}+// DeleteConfig removes a swarm config.//// It requires admin privileges, delegates removal to the swarm service, mapsdiff --git a/backend/internal/swarm/children/configs/module.go b/backend/internal/swarm/children/configs/module.goindex f406ecbe7..c1f3fd98c 100644--- a/backend/internal/swarm/children/configs/module.go+++ b/backend/internal/swarm/children/configs/module.go@@ -57,6 +57,21 @@ func RegisterRoutes(api huma.API, h *Handler) {authz.PermSwarmConfigs,h.CreateConfig,)+ middleware.RegisterWithPermission(+ api,+ huma.Operation{+ OperationID: "update-swarm-config",+ Method: http.MethodPut,+ Path: "/environments/{id}/swarm/configs/{configId}",+ Summary: "Update swarm config labels",+ Tags: []string{+ "Swarm",+ },+ Security: handlerutil.DefaultOperationSecurity(),+ },+ authz.PermSwarmConfigs,+ h.UpdateConfig,+ )middleware.RegisterWithPermission(api,huma.Operation{diff --git a/backend/internal/swarm/children/configs/service.go b/backend/internal/swarm/children/configs/service.goindex af7dcdae8..fa445ca5d 100644--- a/backend/internal/swarm/children/configs/service.go+++ b/backend/internal/swarm/children/configs/service.go@@ -1,6 +1,7 @@package configsimport (+ "cmp""context""encoding/json/v2""errors"@@ -12,6 +13,7 @@ import ("github.com/moby/moby/client""github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination")// Service manages swarm configs.@@ -24,23 +26,46 @@ func NewService(dockerService *docker.DockerClientService, ensureManager func(ctreturn &Service{docker: dockerService, ensureManager: ensureManager}}-func (s *Service) ListConfigs(ctx context.Context) ([]swarmtypes.ConfigSummary, error) {+var configPagination = pagination.Config[swarmtypes.ConfigSummary]{+ SearchAccessors: []pagination.SearchAccessor[swarmtypes.ConfigSummary]{+ func(item swarmtypes.ConfigSummary) (string, error) {+ return item.Spec.Name, nil+ },+ func(item swarmtypes.ConfigSummary) (string, error) {+ return item.ID, nil+ },+ },+ SortBindings: []pagination.SortBinding[swarmtypes.ConfigSummary]{+ {Key: "name", Fn: func(a, b swarmtypes.ConfigSummary) int {+ return strings.Compare(a.Spec.Name, b.Spec.Name)+ }},+ {Key: "createdAt", Fn: func(a, b swarmtypes.ConfigSummary) int {+ return a.CreatedAt.Compare(b.CreatedAt)+ }},+ {Key: "updatedAt", Fn: func(a, b swarmtypes.ConfigSummary) int {+ return a.UpdatedAt.Compare(b.UpdatedAt)+ }},+ },+}++func (s *Service) ListConfigs(ctx context.Context, params pagination.QueryParams) ([]swarmtypes.ConfigSummary, pagination.Response, error) {if err := s.ensureManager(ctx); err != nil {- return nil, err+ return nil, pagination.Response{}, err}- configsResult, err := s.docker.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.ConfigListResult, error) {+ listResult, err := s.docker.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.ConfigListResult, error) {return dockerClient.ConfigList(ctx, client.ConfigListOptions{})})if err != nil {- return nil, fmt.Errorf("failed to list swarm configs: %w", err)+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm configs: %w", err)}- items := make([]swarmtypes.ConfigSummary, 0, len(configsResult.Items))- for _, cfg := range configsResult.Items {- items = append(items, swarmtypes.NewConfigSummary(cfg))+ items := make([]swarmtypes.ConfigSummary, 0, len(listResult.Items))+ for _, item := range listResult.Items {+ items = append(items, swarmtypes.NewConfigSummary(item))}- return items, nil+ result := configPagination.SearchOrderAndPaginate(items, params)+ return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params), nil}func (s *Service) GetConfig(ctx context.Context, configID string) (*swarmtypes.ConfigSummary, error) {@@ -84,6 +109,31 @@ func (s *Service) CreateConfig(ctx context.Context, req swarmtypes.ConfigCreateRreturn s.GetConfig(ctx, createResult.ID)}+func (s *Service) UpdateConfig(ctx context.Context, configID string, req swarmtypes.ConfigUpdateRequest) (*swarmtypes.ConfigSummary, error) {+ current, err := s.GetConfig(ctx, configID)+ if err != nil {+ return nil, err+ }++ if _, updateErr := s.docker.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.ConfigUpdateResult, error) {+ return dockerClient.ConfigUpdate(ctx, current.ID, client.ConfigUpdateOptions{+ Version: swarm.Version{Index: cmp.Or(req.Version, current.Version.Index)},+ Spec: swarm.ConfigSpec{+ Annotations: swarm.Annotations{+ Name: current.Spec.Name,+ Labels: req.Labels,+ },+ Data: current.Spec.Data,+ Templating: current.Spec.Templating,+ },+ })+ }); updateErr != nil {+ return nil, fmt.Errorf("failed to update swarm config: %w", updateErr)+ }++ return s.GetConfig(ctx, current.ID)+}+func (s *Service) RemoveConfig(ctx context.Context, configID string) error {if err := s.ensureManager(ctx); err != nil {return errdiff --git a/backend/internal/swarm/children/configs/service_test.go b/backend/internal/swarm/children/configs/service_test.gonew file mode 100644index 000000000..7f4ea47fd--- /dev/null+++ b/backend/internal/swarm/children/configs/service_test.go@@ -0,0 +1,71 @@+package configs++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"+ "github.com/moby/moby/api/types/swarm"+ "github.com/moby/moby/client"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/internal/docker"+)++func TestService_UpdateConfig_KeepsDataAndReplacesLabels(t *testing.T) {+ current := swarm.Config{+ ID: "config-1",+ Version: swarm.Version{Index: 4},+ Spec: swarm.ConfigSpec{+ Annotations: swarm.Annotations{+ Name: "nginx-conf",+ Labels: map[string]string{"old": "label"},+ },+ Data: []byte("listen 80;"),+ },+ }+ var updatedSpec map[string]any++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v1.41/configs/config-1":+ assert.NoError(t, json.NewEncoder(w).Encode(current))+ case r.Method == http.MethodPost && r.URL.Path == "/v1.41/configs/config-1/update":+ assert.Equal(t, "4", r.URL.Query().Get("version"))+ assert.NoError(t, json.NewDecoder(r.Body).Decode(&updatedSpec))+ current.Version.Index = 5+ current.Spec.Labels = map[string]string{"tier": "db"}+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ cli, err := client.New(+ client.WithHost(server.URL),+ client.WithAPIVersion("1.41"),+ client.WithHTTPClient(server.Client()),+ )+ require.NoError(t, err)+ t.Cleanup(func() { _ = cli.Close() })++ svc := NewService(&docker.DockerClientService{Client: cli}, func(context.Context) error {+ return nil+ })+ updated, err := svc.UpdateConfig(t.Context(), "config-1", swarmtypes.ConfigUpdateRequest{+ Version: 4,+ Labels: map[string]string{"tier": "db"},+ })+ require.NoError(t, err)++ assert.Equal(t, "nginx-conf", updatedSpec["Name"])+ assert.Equal(t, map[string]any{"tier": "db"}, updatedSpec["Labels"])+ assert.Equal(t, "bGlzdGVuIDgwOw==", updatedSpec["Data"])+ assert.Equal(t, uint64(5), updated.Version.Index)+ assert.Equal(t, map[string]string{"tier": "db"}, updated.Spec.Labels)+}diff --git a/backend/internal/swarm/children/secrets/handler.go b/backend/internal/swarm/children/secrets/handler.goindex 3d0c4fdad..6eaafd903 100644--- a/backend/internal/swarm/children/secrets/handler.go+++ b/backend/internal/swarm/children/secrets/handler.go@@ -7,6 +7,7 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/swarm"+ kit "go.getarcane.app/kit/pkg""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil")@@ -28,6 +29,11 @@ func NewHandler(type ListSwarmSecretsInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`}type GetSwarmSecretInput struct {@@ -40,6 +46,12 @@ type CreateSwarmSecretInput struct {Body swarm.SecretCreateRequest}+type UpdateSwarmSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ SecretID string `path:"secretId" doc:"Secret ID"`+ Body swarm.SecretUpdateRequest+}+type DeleteSwarmSecretInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`SecretID string `path:"secretId" doc:"Secret ID"`@@ -55,16 +67,20 @@ type DeleteSwarmSecretInput struct {//// Returns the current swarm secrets.// Returns a mapped HTTP error when secret enumeration fails.-func (h *Handler) ListSecrets(ctx context.Context, input *ListSwarmSecretsInput) (*handlerutil.Out[[]swarm.SecretSummary], error) {- items, err := h.service.ListSecrets(ctx)+func (h *Handler) ListSecrets(ctx context.Context, input *ListSwarmSecretsInput) (*handlerutil.Page[swarm.SecretSummary], error) {+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)+ items, page, err := h.service.ListSecrets(ctx, params)if err != nil {return nil, h.mapError(err, "Failed to list swarm secrets")}- if items == nil {- items = []swarm.SecretSummary{}- }- return &handlerutil.Out[[]swarm.SecretSummary]{Body: base.ApiResponse[[]swarm.SecretSummary]{Success: true, Data: items}}, nil+ return &handlerutil.Page[swarm.SecretSummary]{+ Body: base.Paginated[swarm.SecretSummary]{+ Success: true,+ Data: kit.Ternary(items != nil, items, []swarm.SecretSummary{}),+ Pagination: handlerutil.PaginationResponse(page),+ },+ }, nil}// GetSecret returns details for a single swarm secret.@@ -112,6 +128,20 @@ func (h *Handler) CreateSecret(ctx context.Context, input *CreateSwarmSecretInpureturn &handlerutil.Out[swarm.SecretSummary]{Body: base.ApiResponse[swarm.SecretSummary]{Success: true, Data: *secret}}, nil}+func (h *Handler) UpdateSecret(ctx context.Context, input *UpdateSwarmSecretInput) (*handlerutil.Out[swarm.SecretSummary], error) {+ updated, err := h.service.UpdateSecret(ctx, input.SecretID, input.Body)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm secret not found")+ }+ return nil, h.mapError(err, "Failed to update swarm secret")+ }++ h.audit(ctx, input.EnvironmentID, "secret.update", "swarm_secret", updated.ID, updated.Spec.Name, map[string]any{"secretId": updated.ID, "name": updated.Spec.Name})++ return &handlerutil.Out[swarm.SecretSummary]{Body: base.ApiResponse[swarm.SecretSummary]{Success: true, Data: *updated}}, nil+}+// DeleteSecret removes a swarm secret.//// It requires admin privileges, delegates removal to the swarm service, mapsdiff --git a/backend/internal/swarm/children/secrets/module.go b/backend/internal/swarm/children/secrets/module.goindex 28391f80e..593ac61f3 100644--- a/backend/internal/swarm/children/secrets/module.go+++ b/backend/internal/swarm/children/secrets/module.go@@ -57,6 +57,21 @@ func RegisterRoutes(api huma.API, h *Handler) {authz.PermSwarmSecrets,h.CreateSecret,)+ middleware.RegisterWithPermission(+ api,+ huma.Operation{+ OperationID: "update-swarm-secret",+ Method: http.MethodPut,+ Path: "/environments/{id}/swarm/secrets/{secretId}",+ Summary: "Update swarm secret labels",+ Tags: []string{+ "Swarm",+ },+ Security: handlerutil.DefaultOperationSecurity(),+ },+ authz.PermSwarmSecrets,+ h.UpdateSecret,+ )middleware.RegisterWithPermission(api,huma.Operation{diff --git a/backend/internal/swarm/children/secrets/service.go b/backend/internal/swarm/children/secrets/service.goindex ce8df0eeb..98f430817 100644--- a/backend/internal/swarm/children/secrets/service.go+++ b/backend/internal/swarm/children/secrets/service.go@@ -1,6 +1,7 @@package secretsimport (+ "cmp""context""encoding/json/v2""errors"@@ -12,6 +13,7 @@ import ("github.com/moby/moby/client""github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination")// Service manages swarm secrets.@@ -24,23 +26,46 @@ func NewService(dockerService *docker.DockerClientService, ensureManager func(ctreturn &Service{docker: dockerService, ensureManager: ensureManager}}-func (s *Service) ListSecrets(ctx context.Context) ([]swarmtypes.SecretSummary, error) {+var secretPagination = pagination.Config[swarmtypes.SecretSummary]{+ SearchAccessors: []pagination.SearchAccessor[swarmtypes.SecretSummary]{+ func(item swarmtypes.SecretSummary) (string, error) {+ return item.Spec.Name, nil+ },+ func(item swarmtypes.SecretSummary) (string, error) {+ return item.ID, nil+ },+ },+ SortBindings: []pagination.SortBinding[swarmtypes.SecretSummary]{+ {Key: "name", Fn: func(a, b swarmtypes.SecretSummary) int {+ return strings.Compare(a.Spec.Name, b.Spec.Name)+ }},+ {Key: "createdAt", Fn: func(a, b swarmtypes.SecretSummary) int {+ return a.CreatedAt.Compare(b.CreatedAt)+ }},+ {Key: "updatedAt", Fn: func(a, b swarmtypes.SecretSummary) int {+ return a.UpdatedAt.Compare(b.UpdatedAt)+ }},+ },+}++func (s *Service) ListSecrets(ctx context.Context, params pagination.QueryParams) ([]swarmtypes.SecretSummary, pagination.Response, error) {if err := s.ensureManager(ctx); err != nil {- return nil, err+ return nil, pagination.Response{}, err}- secretsResult, err := s.docker.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.SecretListResult, error) {+ listResult, err := s.docker.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.SecretListResult, error) {return dockerClient.SecretList(ctx, client.SecretListOptions{})})if err != nil {- return nil, fmt.Errorf("failed to list swarm secrets: %w", err)+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm secrets: %w", err)}- items := make([]swarmtypes.SecretSummary, 0, len(secretsResult.Items))- for _, secret := range secretsResult.Items {- items = append(items, swarmtypes.NewSecretSummary(secret))+ items := make([]swarmtypes.SecretSummary, 0, len(listResult.Items))+ for _, item := range listResult.Items {+ items = append(items, swarmtypes.NewSecretSummary(item))}- return items, nil+ result := secretPagination.SearchOrderAndPaginate(items, params)+ return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params), nil}func (s *Service) GetSecret(ctx context.Context, secretID string) (*swarmtypes.SecretSummary, error) {@@ -84,6 +109,31 @@ func (s *Service) CreateSecret(ctx context.Context, req swarmtypes.SecretCreateRreturn s.GetSecret(ctx, createResult.ID)}+func (s *Service) UpdateSecret(ctx context.Context, secretID string, req swarmtypes.SecretUpdateRequest) (*swarmtypes.SecretSummary, error) {+ current, err := s.GetSecret(ctx, secretID)+ if err != nil {+ return nil, err+ }++ if _, updateErr := s.docker.Call(ctx, func(ctx context.Context, dockerClient *client.Client) (client.SecretUpdateResult, error) {+ return dockerClient.SecretUpdate(ctx, current.ID, client.SecretUpdateOptions{+ Version: swarm.Version{Index: cmp.Or(req.Version, current.Version.Index)},+ Spec: swarm.SecretSpec{+ Annotations: swarm.Annotations{+ Name: current.Spec.Name,+ Labels: req.Labels,+ },+ Driver: current.Spec.Driver,+ Templating: current.Spec.Templating,+ },+ })+ }); updateErr != nil {+ return nil, fmt.Errorf("failed to update swarm secret: %w", updateErr)+ }++ return s.GetSecret(ctx, current.ID)+}+func (s *Service) RemoveSecret(ctx context.Context, secretID string) error {if err := s.ensureManager(ctx); err != nil {return errdiff --git a/backend/internal/swarm/children/secrets/service_test.go b/backend/internal/swarm/children/secrets/service_test.gonew file mode 100644index 000000000..09b317eb6--- /dev/null+++ b/backend/internal/swarm/children/secrets/service_test.go@@ -0,0 +1,72 @@+package secrets++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"+ "github.com/moby/moby/api/types/swarm"+ "github.com/moby/moby/client"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/internal/docker"+)++func TestService_UpdateSecret_ReplacesLabelsOnly(t *testing.T) {+ current := swarm.Secret{+ ID: "secret-1",+ Version: swarm.Version{Index: 4},+ Spec: swarm.SecretSpec{+ Annotations: swarm.Annotations{+ Name: "db-pass",+ Labels: map[string]string{"old": "label"},+ },+ Driver: &swarm.Driver{Name: "vault"},+ },+ }+ var updatedSpec map[string]any++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v1.41/secrets/secret-1":+ assert.NoError(t, json.NewEncoder(w).Encode(current))+ case r.Method == http.MethodPost && r.URL.Path == "/v1.41/secrets/secret-1/update":+ assert.Equal(t, "4", r.URL.Query().Get("version"))+ assert.NoError(t, json.NewDecoder(r.Body).Decode(&updatedSpec))+ current.Version.Index = 5+ current.Spec.Labels = map[string]string{"tier": "db"}+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ cli, err := client.New(+ client.WithHost(server.URL),+ client.WithAPIVersion("1.41"),+ client.WithHTTPClient(server.Client()),+ )+ require.NoError(t, err)+ t.Cleanup(func() { _ = cli.Close() })++ svc := NewService(&docker.DockerClientService{Client: cli}, func(context.Context) error {+ return nil+ })+ updated, err := svc.UpdateSecret(t.Context(), "secret-1", swarmtypes.SecretUpdateRequest{+ Version: 4,+ Labels: map[string]string{"tier": "db"},+ })+ require.NoError(t, err)++ assert.Equal(t, "db-pass", updatedSpec["Name"])+ assert.Equal(t, map[string]any{"tier": "db"}, updatedSpec["Labels"])+ assert.Equal(t, map[string]any{"Name": "vault"}, updatedSpec["Driver"])+ assert.NotContains(t, updatedSpec, "Data")+ assert.Equal(t, uint64(5), updated.Version.Index)+ assert.Equal(t, map[string]string{"tier": "db"}, updated.Spec.Labels)+}diff --git a/backend/internal/system/children/upgrade/service.go b/backend/internal/system/children/upgrade/service.goindex 305f50ecb..160b0e978 100644--- a/backend/internal/system/children/upgrade/service.go+++ b/backend/internal/system/children/upgrade/service.go@@ -19,6 +19,7 @@ import ("github.com/containerd/errdefs""github.com/distribution/reference"+ "github.com/getarcaneapp/arcane/types/v2/podman""github.com/getarcaneapp/arcane/types/v2/scheduler"usertypes "github.com/getarcaneapp/arcane/types/v2/user"versiontypes "github.com/getarcaneapp/arcane/types/v2/version"@@ -201,9 +202,13 @@ func (s *Service) CanUpgrade(ctx context.Context) (bool, error) {if err != nil {return false, errors.New("docker socket is not accessible")}- if _, inspectErr := libarcane.InspectCurrentArcaneContainer(ctx, dockerClient); inspectErr != nil {+ self, inspectErr := libarcane.InspectCurrentArcaneContainer(ctx, dockerClient)+ if inspectErr != nil {return false, errors.New("arcane is not running in a Docker container")}+ if unit := kit.FromPtr(self.Config).Labels[podman.SystemdUnitLabel]; unit != "" {+ return false, fmt.Errorf("arcane runs from the Quadlet unit %s; update it with podman auto-update instead", unit)+ }return true, nil}@@ -324,6 +329,9 @@ func (s *Service) prepareUpgrade(ctx context.Context, user usertypes.Actor, targif err != nil {return nil, err}+ if unit := kit.FromPtr(current.Config).Labels[podman.SystemdUnitLabel]; unit != "" {+ return nil, fmt.Errorf("systemd unit %s: %w", unit, common.ErrContainerQuadletManaged)+ }containerName := strings.TrimPrefix(current.Name, "/")config := kit.FromPtr(current.Config)diff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.goindex 576222430..12d298f3b 100644--- a/backend/internal/updater/service.go+++ b/backend/internal/updater/service.go@@ -17,6 +17,7 @@ import ("github.com/containerd/errdefs"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"imageupdatetypes "github.com/getarcaneapp/arcane/types/v2/imageupdate"+ "github.com/getarcaneapp/arcane/types/v2/podman"projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/getarcaneapp/arcane/types/v2/scheduler"arcaneupdater "github.com/getarcaneapp/arcane/types/v2/updater"@@ -73,6 +74,12 @@ var ("container_start": event.EventTypeContainerStart,"container_update": event.EventTypeContainerUpdate,}++ updateLabelPolicy = updater.LabelPolicy{+ IsUpdateDisabledFunc: func(l map[string]string) bool {+ return labels.IsUpdateDisabled(l) || l[podman.SystemdUnitLabel] != ""+ },+ })// UpdaterService is Arcane's handler-facing service for the standalone updater engine.@@ -218,7 +225,7 @@ func NewUpdaterService(Notifier: service,EventRecorder: service,UsedImageCollector: updater.UsedImageCollectorFunc(service.CollectUsedImages),- LabelPolicy: updater.DefaultLabelPolicy(),+ LabelPolicy: updateLabelPolicy,SelfContainerID: kit.Ternary(selfErr != nil, "", selfContainerID),OperationTimeout: timeouts.DefaultAutoUpdateOperation,Logger: slog.Default(),diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.goindex 047586465..2aa675d0f 100644--- a/backend/internal/updater/service_test.go+++ b/backend/internal/updater/service_test.go@@ -20,6 +20,7 @@ import ("github.com/compose-spec/compose-go/v2/types"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+ "github.com/getarcaneapp/arcane/types/v2/podman"projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/getarcaneapp/arcane/types/v2/scheduler"arcaneupdater "github.com/getarcaneapp/arcane/types/v2/updater"@@ -1352,6 +1353,25 @@ func TestUpdaterService_ApplyPending_RoutesLegacyArcaneServerThroughSelfUpgrade(assert.Empty(t, projectUpdater.calls, "legacy Arcane server should not be updated through project services")}+func TestUpdateLabelPolicyDisablesQuadletContainers(t *testing.T) {+ tests := []struct {+ name string+ labels map[string]string+ want bool+ }{+ {name: "unlabelled", labels: map[string]string{}},+ {name: "quadlet unit", labels: map[string]string{podman.SystemdUnitLabel: "web.service"}, want: true},+ {name: "empty quadlet unit", labels: map[string]string{podman.SystemdUnitLabel: ""}},+ {name: "updater opt out", labels: map[string]string{labels.LabelUpdater: "false"}, want: true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ assert.Equal(t, tt.want, updateLabelPolicy.IsUpdateDisabled(tt.labels))+ })+ }+}+// The engine picks the reference Arcane's updates are applied to, so its choice// is worth pinning here as well as in the library.func TestPullableImageRef(t *testing.T) {diff --git a/backend/internal/volume/children/backup/helpers_test.go b/backend/internal/volume/children/backup/helpers_test.goindex 10777c43e..eec6004e7 100644--- a/backend/internal/volume/children/backup/helpers_test.go+++ b/backend/internal/volume/children/backup/helpers_test.go@@ -22,6 +22,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/podman")func TestResolveBackupStorageMountFromMounts(t *testing.T) {@@ -180,7 +181,7 @@ func setupVolumeBackupLifecycleTest(t *testing.T, handler http.Handler) *Servicedb := &database.DB{DB: gormDB}dockerService := docker.NewDockerClientService(t.Context(), db, &config.Config{}, nil).WithClient(dockerClient)eventService := event.NewEventService(db, &config.Config{}, nil)- containerService := containerdomain.NewContainerService(eventService, dockerService, nil, nil, nil, nil)+ containerService := containerdomain.NewContainerService(eventService, dockerService, nil, nil, nil, nil, podman.NewService(podman.Config{Engine: dockerService.Engine}))return NewService(Dependencies{Docker: dockerService,StopContainer: containerService.StopContainer,diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.goindex cd50e0a1c..6e0afa9b5 100644--- a/backend/pkg/authz/access_policy.go+++ b/backend/pkg/authz/access_policy.go@@ -89,9 +89,15 @@ var accessSurfacesInternal = []AccessSurface{routeSurfaceInternal("route.swarm.cluster", "/swarm/cluster", "Cluster", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmRead}, 100),routeSurfaceInternal("route.swarm.configs", "/swarm/configs", "Configs", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmRead}, 0),routeSurfaceInternal("route.swarm.secrets", "/swarm/secrets", "Secrets", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmRead}, 0),+ routeSurfaceInternal("route.podman", "/podman/pods", "Podman", AccessScopeModeSelectedEnvPlusGlobal, []string{PermPodmanRead}, 0),+ routeSurfaceInternal("route.podman.quadlets", "/podman/quadlets", "Quadlets", AccessScopeModeSelectedEnvPlusGlobal, []string{PermPodmanRead}, 0),+ allOfRouteSurfaceInternal("route.podman.quadlets.new", "/podman/quadlets/new", "Install quadlet", AccessScopeModeSelectedEnvPlusGlobal, []string{PermPodmanRead, PermPodmanQuadlets}),+ allOfRouteSurfaceInternal("route.podman.kube", "/podman/kube", "Kube", AccessScopeModeSelectedEnvPlusGlobal, []string{PermPodmanRead, PermPodmanKube}),+ routeSurfaceInternal("route.podman.secrets", "/podman/secrets", "Podman secrets", AccessScopeModeSelectedEnvPlusGlobal, []string{PermPodmanRead}, 0),+ allOfRouteSurfaceInternal("route.podman.autoupdate", "/podman/autoupdate", "Podman auto-update", AccessScopeModeSelectedEnvPlusGlobal, []string{PermPodmanRead, PermPodmanAutoUpdate}),routeSurfaceInternal("route.events", "/events", "Events", AccessScopeModeGlobalOnly, []string{PermEventsRead}, 110),routeSurfaceInternal("route.activities", "", "Activities", AccessScopeModeAnyEffectiveScope, []string{PermActivitiesRead}, 0),- allOfRouteSurfaceInternal("route.oidc-role-mappings", "", "OIDC Role Mappings", AllPermissions()),+ allOfRouteSurfaceInternal("route.oidc-role-mappings", "", "OIDC Role Mappings", AccessScopeModeGlobalOnly, AllPermissions()),routeSurfaceInternal("route.customize.templates.create","/customize/templates/create","Create template",@@ -115,7 +121,7 @@ var accessSurfacesInternal = []AccessSurface{0),routeSurfaceInternal("route.customize.templates.detail", "/customize/templates/{id}", "Template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),- allOfRouteSurfaceInternal("route.customize.registries.browse", "/customize/registries/{id}", "Registry browser", []string{PermRegistriesRead, PermRegistriesBrowse}),+ allOfRouteSurfaceInternal("route.customize.registries.browse", "/customize/registries/{id}", "Registry browser", AccessScopeModeGlobalOnly, []string{PermRegistriesRead, PermRegistriesBrowse}),settingsCategorySurfaceInternal("activity", "/settings/activity", "Activity", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),settingsCategorySurfaceInternal("apikeys", "/settings/api-keys", "API Keys", AccessScopeModeGlobalOnly, []string{PermApiKeysList, PermApiKeysRead}),@@ -264,8 +270,8 @@ func routeSurfaceInternal(id, url, label, scopeMode string, permissions []string}}-func allOfRouteSurfaceInternal(id, url, label string, permissions []string) AccessSurface {- surface := routeSurfaceInternal(id, url, label, AccessScopeModeGlobalOnly, permissions, 0)+func allOfRouteSurfaceInternal(id, url, label, scopeMode string, permissions []string) AccessSurface {+ surface := routeSurfaceInternal(id, url, label, scopeMode, permissions, 0)surface.MatchMode = AccessMatchModeAllOfreturn surface}diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.goindex 4a20e711f..e29f484a3 100644--- a/backend/pkg/authz/catalog.go+++ b/backend/pkg/authz/catalog.go@@ -194,6 +194,15 @@ var permissionCatalog = []PermissionCatalogResource{{"secrets", PermSwarmSecrets, "Manage secrets", ""},{"unlock", PermSwarmUnlock, "Unlock / join tokens", ""},}},+ {"podman", "Podman", PermissionScopeEnv, []PermissionCatalogAction{+ {"read", PermPodmanRead, "Read", ""},+ {"pods", PermPodmanPods, "Manage pods", ""},+ {"quadlets", PermPodmanQuadlets, "Manage quadlets", ""},+ {"quadlets:lifecycle", PermPodmanQuadletsLifecycle, "Start / stop quadlets", ""},+ {"kube", PermPodmanKube, "Play / generate kube", ""},+ {"secrets", PermPodmanSecrets, "Manage secrets", ""},+ {"autoupdate", PermPodmanAutoUpdate, "Run auto-update", ""},+ }},{"gitops", "GitOps Syncs", PermissionScopeEnv, []PermissionCatalogAction{{"list", PermGitOpsList, "List", ""},{"read", PermGitOpsRead, "Read", ""},diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.goindex 8bf880a4f..618d17e08 100644--- a/backend/pkg/authz/permissions.go+++ b/backend/pkg/authz/permissions.go@@ -188,6 +188,14 @@ const (PermSwarmSecrets = "swarm:secrets"PermSwarmUnlock = "swarm:unlock"+ PermPodmanRead = "podman:read"+ PermPodmanPods = "podman:pods"+ PermPodmanQuadlets = "podman:quadlets"+ PermPodmanQuadletsLifecycle = "podman:quadlets:lifecycle"+ PermPodmanKube = "podman:kube"+ PermPodmanSecrets = "podman:secrets"+ PermPodmanAutoUpdate = "podman:autoupdate"+PermGitOpsList = "gitops:list"PermGitOpsRead = "gitops:read"PermGitOpsCreate = "gitops:create"@@ -352,6 +360,7 @@ func BuiltInEditorPermissions() []string {PermVolumesList, PermVolumesRead, PermVolumesCreate, PermVolumesRename, PermVolumesDelete, PermVolumesPrune, PermVolumesUpload, PermVolumesBackup,PermNetworksList, PermNetworksRead, PermNetworksCreate, PermNetworksDelete, PermNetworksPrune, PermNetworksConnect, PermNetworksDisconnect,PermSwarmRead, PermSwarmSpec, PermSwarmNodes, PermSwarmServices, PermSwarmServicesLogs, PermSwarmStacks, PermSwarmConfigs, PermSwarmSecrets,+ PermPodmanRead, PermPodmanPods, PermPodmanQuadlets, PermPodmanQuadletsLifecycle, PermPodmanKube, PermPodmanSecrets, PermPodmanAutoUpdate,PermGitOpsList, PermGitOpsRead, PermGitOpsCreate, PermGitOpsUpdate, PermGitOpsDelete, PermGitOpsSync, PermGitOpsBackup,PermWebhooksList, PermWebhooksCreate, PermWebhooksUpdate, PermWebhooksDelete,PermJobsManage, PermNotificationsManage, PermDashboardRead,@@ -389,6 +398,7 @@ func BuiltInDeployerPermissions() []string {PermVolumesList, PermVolumesRead,PermNetworksList, PermNetworksRead,PermSwarmRead, PermSwarmServicesLogs,+ PermPodmanRead, PermPodmanQuadletsLifecycle, PermPodmanAutoUpdate,PermGitOpsList, PermGitOpsRead, PermGitOpsSync,PermDashboardRead,PermSystemRead,@@ -420,6 +430,7 @@ func BuiltInViewerPermissions() []string {PermVolumesList, PermVolumesRead,PermNetworksList, PermNetworksRead,PermSwarmRead, PermSwarmServicesLogs,+ PermPodmanRead,PermGitOpsList, PermGitOpsRead,PermWebhooksList,PermDashboardRead,@@ -443,6 +454,7 @@ func BuiltInMonitorPermissions() []string {PermVolumesList, PermVolumesRead,PermNetworksList, PermNetworksRead,PermSwarmRead, PermSwarmServicesLogs,+ PermPodmanRead,PermDashboardRead,PermSystemRead,PermImageUpdatesRead,diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.goindex 55fcfe575..5049e4fdf 100644--- a/backend/pkg/libarcane/edge/commands.go+++ b/backend/pkg/libarcane/edge/commands.go@@ -270,6 +270,33 @@ var commandRoutes = []commandRoute{{Method: http.MethodPut, PathPattern: "/api/environments/{id}/swarm/secrets/{secretId}", CommandName: "swarm.secret.update"},{Method: http.MethodDelete, PathPattern: "/api/environments/{id}/swarm/secrets/{secretId}", CommandName: "swarm.secret.delete"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/status", CommandName: "podman.status"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/info", CommandName: "podman.info"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/autoupdate", CommandName: "podman.autoupdate"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/pods", CommandName: "podman.pod.list"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/pods", CommandName: "podman.pod.create"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/pods/prune", CommandName: "podman.pod.prune"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/pods/stats", CommandName: "podman.pod.stats"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/pods/{podId}", CommandName: "podman.pod.inspect"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/pods/{podId}/top", CommandName: "podman.pod.top"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/pods/{podId}/{action}", CommandName: "podman.pod.action"},+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/podman/pods/{podId}", CommandName: "podman.pod.delete"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/quadlets", CommandName: "podman.quadlet.list"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/quadlets", CommandName: "podman.quadlet.install"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/quadlets/{name}", CommandName: "podman.quadlet.inspect"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/quadlets/{name}/file", CommandName: "podman.quadlet.file"},+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/podman/quadlets/{name}", CommandName: "podman.quadlet.update"},+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/podman/quadlets/{name}", CommandName: "podman.quadlet.delete"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/quadlets/{name}/{action}", CommandName: "podman.quadlet.action"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/kube/play", CommandName: "podman.kube.play"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/kube/down", CommandName: "podman.kube.down"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/kube/generate", CommandName: "podman.kube.generate"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/secrets", CommandName: "podman.secret.list"},+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/podman/secrets", CommandName: "podman.secret.create"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/podman/secrets/{secretId}", CommandName: "podman.secret.inspect"},+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/podman/secrets/{secretId}", CommandName: "podman.secret.update"},+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/podman/secrets/{secretId}", CommandName: "podman.secret.delete"},+{PathPattern: "/api/environments/{id}/ws/projects/{projectId}/logs", CommandName: "project.logs.stream", Stream: true},{PathPattern: "/api/environments/{id}/ws/containers/stats", CommandName: "container.stats.batch.stream", Stream: true},{PathPattern: "/api/environments/{id}/ws/containers/{containerId}/logs", CommandName: "container.logs.stream", Stream: true},diff --git a/backend/pkg/libarcane/podman/autoupdate.go b/backend/pkg/libarcane/podman/autoupdate.gonew file mode 100644index 000000000..e867a88f9--- /dev/null+++ b/backend/pkg/libarcane/podman/autoupdate.go@@ -0,0 +1,37 @@+package podman++import (+ "context"+ "net/http"+ "net/url"+ "strconv"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+)++func (c *Client) AutoUpdate(ctx context.Context, opts podmantypes.AutoUpdateOptions) (podmantypes.AutoUpdateResult, error) {+ query, err := filtersQuery(url.Values{"dryRun": {strconv.FormatBool(opts.DryRun)}}, opts.Filters)+ if err != nil {+ return podmantypes.AutoUpdateResult{}, err+ }+ if opts.Rollback != nil {+ query.Set("rollback", strconv.FormatBool(*opts.Rollback))+ }+ if opts.TLSVerify != nil {+ query.Set("tlsVerify", strconv.FormatBool(*opts.TLSVerify))+ }+ if opts.Authfile != "" {+ query.Set("authfile", opts.Authfile)+ }++ out, err := c.doJSON[podmantypes.AutoUpdateResult](ctx, request{+ method: http.MethodPost,+ path: "/autoupdate",+ query: query,+ })+ return podmantypes.AutoUpdateResult{+ Mode: podmantypes.AutoUpdateModeREST,+ Reports: out.Reports,+ Errors: out.Errors,+ }, err+}diff --git a/backend/pkg/libarcane/podman/autoupdate_test.go b/backend/pkg/libarcane/podman/autoupdate_test.gonew file mode 100644index 000000000..92c67a0b4--- /dev/null+++ b/backend/pkg/libarcane/podman/autoupdate_test.go@@ -0,0 +1,49 @@+package podman++import (+ "net/http"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestClientAutoUpdate(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, http.MethodPost, r.Method)+ assert.Equal(t, "/v4.0.0/libpod/autoupdate", r.URL.Path)+ query := r.URL.Query()+ assert.Equal(t, "true", query.Get("dryRun"))+ assert.Equal(t, "false", query.Get("rollback"))+ assert.Empty(t, query.Get("tlsVerify"))+ assert.Equal(t, "/run/auth.json", query.Get("authfile"))+ assert.JSONEq(t, `{"label":["app=web"]}`, query.Get("filters"))+ _, _ = w.Write([]byte(`{+ "Reports":[{"ContainerID":"abc","ContainerName":"web","ImageName":"nginx:latest","Policy":"registry","SystemdUnit":"web.service","Updated":"pending"}],+ "Errors":["db: image not found"]+ }`))+ })++ result, err := client.AutoUpdate(t.Context(), podmantypes.AutoUpdateOptions{+ DryRun: true,+ Rollback: new(false),+ Authfile: "/run/auth.json",+ Filters: map[string][]string{"label": {"app=web"}},+ })+ require.NoError(t, err)+ assert.Equal(t, podmantypes.AutoUpdateResult{+ Mode: podmantypes.AutoUpdateModeREST,+ Reports: []podmantypes.AutoUpdateReport{+ {+ ContainerID: "abc",+ ContainerName: "web",+ ImageName: "nginx:latest",+ Policy: "registry",+ SystemdUnit: "web.service",+ Updated: "pending",+ },+ },+ Errors: []string{"db: image not found"},+ }, result)+}diff --git a/backend/pkg/libarcane/podman/client.go b/backend/pkg/libarcane/podman/client.gonew file mode 100644index 000000000..ba9755782--- /dev/null+++ b/backend/pkg/libarcane/podman/client.go@@ -0,0 +1,221 @@+package podman++import (+ "cmp"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/url"+ "strings"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ kit "go.getarcane.app/kit/pkg"+ "golang.org/x/mod/semver"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+)++const apiPrefix = "/v4.0.0/libpod"++type Client struct {+ baseURL string+ httpClient *http.Client+}++type Runtime struct {+ Client *Client+ Version podmantypes.Version+ Rootless bool+ Systemd Systemd+}++type Features struct {+ QuadletsSupported bool+ QuadletAppsSupported bool+ AutoUpdateMode podmantypes.AutoUpdateMode+}++type request struct {+ method string+ path string+ query url.Values+ body io.Reader+ contentType string+}++type apiError struct {+ Cause string `json:"cause"`+ Message string `json:"message"`+ Response int `json:"response"`+}++func NewClient(host string) (*Client, error) {+ parsed, err := url.Parse(host)+ if err != nil {+ return nil, fmt.Errorf("parse podman host %q: %w", host, err)+ }++ switch parsed.Scheme {+ case "unix":+ return &Client{+ baseURL: "http://podman",+ httpClient: &http.Client{+ Transport: &http.Transport{+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {+ return (&net.Dialer{}).DialContext(ctx, "unix", parsed.Path)+ },+ },+ },+ }, nil+ case "tcp", "http":+ return &Client{+ baseURL: "http://" + parsed.Host,+ httpClient: &http.Client{},+ }, nil+ case "https":+ return &Client{+ baseURL: "https://" + parsed.Host,+ httpClient: &http.Client{},+ }, nil+ default:+ return nil, common.Classify(common.ErrBadRequest, fmt.Errorf("unsupported podman host scheme %q", parsed.Scheme))+ }+}++func DetectFeatures(version string, systemdAvailable bool) Features {+ v := kit.EnsurePrefix(strings.TrimSpace(version), "v")+ return Features{+ QuadletsSupported: semver.Compare(v, "v5.8.0") >= 0,+ QuadletAppsSupported: semver.Compare(v, "v6.1.0") >= 0,+ AutoUpdateMode: func() podmantypes.AutoUpdateMode {+ switch {+ case semver.Compare(v, "v6.2.0") >= 0:+ return podmantypes.AutoUpdateModeREST+ case systemdAvailable:+ return podmantypes.AutoUpdateModeSystemd+ default:+ return podmantypes.AutoUpdateModeUnavailable+ }+ }(),+ }+}++func (c *Client) Version(ctx context.Context) (podmantypes.Version, error) {+ return c.doJSON[podmantypes.Version](ctx, request{method: http.MethodGet, path: "/version"})+}++func (c *Client) Info(ctx context.Context) (podmantypes.Info, error) {+ return c.doJSON[podmantypes.Info](ctx, request{method: http.MethodGet, path: "/info"})+}++func (c *Client) ContainerList(ctx context.Context, labels, pods []string) ([]podmantypes.Container, error) {+ query, err := filtersQuery(url.Values{"all": {"true"}}, map[string][]string{+ "label": labels,+ "pod": pods,+ })+ if err != nil {+ return nil, err+ }++ return c.doJSON[[]podmantypes.Container](ctx, request{+ method: http.MethodGet,+ path: "/containers/json",+ query: query,+ })+}++func (c *Client) doJSON[T any](ctx context.Context, req request) (T, error) {+ var out T+ body, err := c.do(ctx, req)+ if err != nil {+ return out, err+ }+ defer func() { _ = body.Close() }()++ if decodeErr := json.NewDecoder(body).Decode(&out); decodeErr != nil && !errors.Is(decodeErr, io.EOF) {+ return out, fmt.Errorf("decode podman %s %s: %w", req.method, req.path, decodeErr)+ }+ return out, nil+}++func (c *Client) doText(ctx context.Context, req request) (string, error) {+ body, err := c.do(ctx, req)+ if err != nil {+ return "", err+ }+ defer func() { _ = body.Close() }()++ data, err := io.ReadAll(body)+ if err != nil {+ return "", fmt.Errorf("read podman %s %s: %w", req.method, req.path, err)+ }+ return string(data), nil+}++func (c *Client) do(ctx context.Context, req request) (io.ReadCloser, error) {+ target := c.baseURL + apiPrefix + req.path+ if len(req.query) > 0 {+ target += "?" + req.query.Encode()+ }++ httpReq, err := http.NewRequestWithContext(ctx, req.method, target, req.body)+ if err != nil {+ return nil, fmt.Errorf("build podman request: %w", err)+ }+ if req.contentType != "" {+ httpReq.Header.Set("Content-Type", req.contentType)+ }++ resp, err := c.httpClient.Do(httpReq)+ if err != nil {+ return nil, common.Classify(common.ErrUnavailable, fmt.Errorf("podman %s %s: %w", req.method, req.path, err))+ }+ if resp.StatusCode < http.StatusBadRequest {+ return resp.Body, nil+ }+ defer func() { _ = resp.Body.Close() }()++ data, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))+ var apiErr apiError+ message := strings.TrimSpace(string(data))+ if json.Unmarshal(data, &apiErr) == nil {+ message = cmp.Or(apiErr.Message, apiErr.Cause, message)+ }+ err = fmt.Errorf("podman %s %s: %s", req.method, req.path, cmp.Or(message, resp.Status))++ switch resp.StatusCode {+ case http.StatusBadRequest:+ return nil, common.Classify(common.ErrBadRequest, err)+ case http.StatusNotFound:+ return nil, common.Classify(common.ErrNotFound, err)+ case http.StatusConflict:+ return nil, common.Classify(common.ErrConflict, err)+ case http.StatusServiceUnavailable:+ return nil, common.Classify(common.ErrUnavailable, err)+ default:+ return nil, err+ }+}++func filtersQuery(query url.Values, filters map[string][]string) (url.Values, error) {+ set := make(map[string][]string, len(filters))+ for key, values := range filters {+ if len(values) > 0 {+ set[key] = values+ }+ }+ if len(set) == 0 {+ return query, nil+ }++ encoded, err := json.Marshal(set)+ if err != nil {+ return nil, fmt.Errorf("encode podman filters: %w", err)+ }+ query.Set("filters", string(encoded))+ return query, nil+}diff --git a/backend/pkg/libarcane/podman/client_test.go b/backend/pkg/libarcane/podman/client_test.gonew file mode 100644index 000000000..7a289e3eb--- /dev/null+++ b/backend/pkg/libarcane/podman/client_test.go@@ -0,0 +1,176 @@+package podman++import (+ "net/http"+ "net/http/httptest"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+)++func newTestClient(t *testing.T, handler http.HandlerFunc) *Client {+ t.Helper()+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)++ client, err := NewClient(server.URL)+ require.NoError(t, err)+ return client+}++func TestNewClient(t *testing.T) {+ tests := []struct {+ name string+ host string+ baseURL string+ wantErr bool+ }{+ {name: "unix", host: "unix:///run/podman/podman.sock", baseURL: "http://podman"},+ {name: "tcp", host: "tcp://10.0.0.5:8888", baseURL: "http://10.0.0.5:8888"},+ {name: "https", host: "https://podman.example:8443", baseURL: "https://podman.example:8443"},+ {name: "unsupported", host: "ssh://user@host", wantErr: true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ client, err := NewClient(tt.host)+ if tt.wantErr {+ require.ErrorIs(t, err, common.ErrBadRequest)+ return+ }+ require.NoError(t, err)+ assert.Equal(t, tt.baseURL, client.baseURL)+ })+ }+}++func TestDetectFeatures(t *testing.T) {+ tests := []struct {+ name string+ version string+ systemdAvailable bool+ want Features+ }{+ {+ name: "podman 4 with systemd",+ version: "4.9.4",+ systemdAvailable: true,+ want: Features{AutoUpdateMode: podmantypes.AutoUpdateModeSystemd},+ },+ {+ name: "podman 5.7 without systemd",+ version: "5.7.1",+ want: Features{AutoUpdateMode: podmantypes.AutoUpdateModeUnavailable},+ },+ {+ name: "podman 5.8",+ version: "5.8.0",+ systemdAvailable: true,+ want: Features{+ QuadletsSupported: true,+ AutoUpdateMode: podmantypes.AutoUpdateModeSystemd,+ },+ },+ {+ name: "podman 6.1 with v prefix",+ version: "v6.1.2",+ want: Features{+ QuadletsSupported: true,+ QuadletAppsSupported: true,+ AutoUpdateMode: podmantypes.AutoUpdateModeUnavailable,+ },+ },+ {+ name: "podman 6.2 uses rest",+ version: "6.2.0",+ want: Features{+ QuadletsSupported: true,+ QuadletAppsSupported: true,+ AutoUpdateMode: podmantypes.AutoUpdateModeREST,+ },+ },+ {+ name: "invalid version",+ version: "unknown",+ systemdAvailable: true,+ want: Features{AutoUpdateMode: podmantypes.AutoUpdateModeSystemd},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ assert.Equal(t, tt.want, DetectFeatures(tt.version, tt.systemdAvailable))+ })+ }+}++func TestClientVersionAndInfo(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/v4.0.0/libpod/version":+ _, _ = w.Write([]byte(`{"Version":"5.8.1","ApiVersion":"1.41","Components":[{"Name":"Podman Engine","Version":"5.8.1"}]}`))+ case "/v4.0.0/libpod/info":+ _, _ = w.Write([]byte(`{"host":{"hostname":"box","security":{"rootless":true}},"store":{"containerStore":{"number":3}},"version":{"APIVersion":"5.8.1","Version":"5.8.1"}}`))+ default:+ http.NotFound(w, r)+ }+ })++ version, err := client.Version(t.Context())+ require.NoError(t, err)+ assert.Equal(t, "5.8.1", version.Version)+ assert.Equal(t, "1.41", version.APIVersion)+ require.Len(t, version.Components, 1)+ assert.Equal(t, "Podman Engine", version.Components[0].Name)++ info, err := client.Info(t.Context())+ require.NoError(t, err)+ assert.True(t, info.Host.Security.Rootless)+ assert.Equal(t, "box", info.Host.Hostname)+ assert.Equal(t, 3, info.Store.ContainerStore.Number)+ assert.Equal(t, "5.8.1", info.Version.APIVersion)+}++func TestClientContainerList(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, "/v4.0.0/libpod/containers/json", r.URL.Path)+ assert.Equal(t, "true", r.URL.Query().Get("all"))+ assert.JSONEq(t, `{"label":["PODMAN_SYSTEMD_UNIT=web.service"]}`, r.URL.Query().Get("filters"))+ _, _ = w.Write([]byte(`[{"Id":"abc","Names":["web"],"Labels":{"PODMAN_SYSTEMD_UNIT":"web.service"},"PodName":"","IsInfra":false}]`))+ })++ containers, err := client.ContainerList(t.Context(), []string{podmantypes.SystemdUnitLabel + "=web.service"}, nil)+ require.NoError(t, err)+ require.Len(t, containers, 1)+ assert.Equal(t, "abc", containers[0].ID)+ assert.Equal(t, "web.service", containers[0].Labels[podmantypes.SystemdUnitLabel])+}++func TestClientErrorClassification(t *testing.T) {+ tests := []struct {+ name string+ status int+ kind error+ }{+ {name: "not found", status: http.StatusNotFound, kind: common.ErrNotFound},+ {name: "conflict", status: http.StatusConflict, kind: common.ErrConflict},+ {name: "bad request", status: http.StatusBadRequest, kind: common.ErrBadRequest},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(tt.status)+ _, _ = w.Write([]byte(`{"cause":"no such pod","message":"pod web: no such pod","response":0}`))+ })++ _, err := client.PodInspect(t.Context(), "web")+ require.ErrorIs(t, err, tt.kind)+ assert.Contains(t, err.Error(), "pod web: no such pod")+ })+ }+}diff --git a/backend/pkg/libarcane/podman/kube.go b/backend/pkg/libarcane/podman/kube.gonew file mode 100644index 000000000..a64857ea9--- /dev/null+++ b/backend/pkg/libarcane/podman/kube.go@@ -0,0 +1,55 @@+package podman++import (+ "context"+ "net/http"+ "net/url"+ "strconv"+ "strings"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+)++func (c *Client) KubePlay(ctx context.Context, req podmantypes.KubePlayRequest) (podmantypes.KubePlayReport, error) {+ query := url.Values{+ "replace": {strconv.FormatBool(req.Replace)},+ "network": req.Networks,+ }+ if req.Start != nil {+ query.Set("start", strconv.FormatBool(*req.Start))+ }++ return c.doJSON[podmantypes.KubePlayReport](ctx, request{+ method: http.MethodPost,+ path: "/play/kube",+ query: query,+ body: strings.NewReader(req.YAML),+ contentType: "application/yaml",+ })+}++func (c *Client) KubeDown(ctx context.Context, req podmantypes.KubeDownRequest) (podmantypes.KubeDownReport, error) {+ return c.doJSON[podmantypes.KubeDownReport](ctx, request{+ method: http.MethodDelete,+ path: "/play/kube",+ query: url.Values{"force": {strconv.FormatBool(req.Force)}},+ body: strings.NewReader(req.YAML),+ contentType: "application/yaml",+ })+}++func (c *Client) KubeGenerate(ctx context.Context, req podmantypes.KubeGenerateRequest) (string, error) {+ query := url.Values{+ "names": req.Names,+ "service": {strconv.FormatBool(req.Service)},+ }+ if req.Type != "" {+ query.Set("type", string(req.Type))+ }++ return c.doText(ctx, request{+ method: http.MethodGet,+ path: "/generate/kube",+ query: query,+ })+}diff --git a/backend/pkg/libarcane/podman/kube_test.go b/backend/pkg/libarcane/podman/kube_test.gonew file mode 100644index 000000000..be81ef9b4--- /dev/null+++ b/backend/pkg/libarcane/podman/kube_test.go@@ -0,0 +1,56 @@+package podman++import (+ "io"+ "net/http"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestClientKubePlayDownGenerate(t *testing.T) {+ const manifest = "apiVersion: v1\nkind: Pod\n"+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/v4.0.0/libpod/play/kube":+ assert.Equal(t, "network=frontend&replace=true&start=false", r.URL.RawQuery)+ data, err := io.ReadAll(r.Body)+ assert.NoError(t, err)+ assert.Equal(t, manifest, string(data))+ _, _ = w.Write([]byte(`{"Pods":[{"ID":"pod123","Containers":["abc"]}],"Volumes":[{"Name":"data"}]}`))+ case r.Method == http.MethodDelete && r.URL.Path == "/v4.0.0/libpod/play/kube":+ assert.Equal(t, "force=true", r.URL.RawQuery)+ _, _ = w.Write([]byte(`{"StopReport":[{"Id":"pod123","Errs":[]}],"RmReport":[{"Id":"pod123","RemovedCtrs":{}}]}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v4.0.0/libpod/generate/kube":+ assert.Equal(t, "names=web&names=db&service=true&type=deployment", r.URL.RawQuery)+ _, _ = w.Write([]byte(manifest))+ default:+ http.NotFound(w, r)+ }+ })++ played, err := client.KubePlay(t.Context(), podmantypes.KubePlayRequest{+ YAML: manifest,+ Start: new(false),+ Replace: true,+ Networks: []string{"frontend"},+ })+ require.NoError(t, err)+ require.Len(t, played.Pods, 1)+ assert.Equal(t, "pod123", played.Pods[0].ID)+ assert.Equal(t, "data", played.Volumes[0].Name)++ down, err := client.KubeDown(t.Context(), podmantypes.KubeDownRequest{YAML: manifest, Force: true})+ require.NoError(t, err)+ assert.Equal(t, "pod123", down.RmReport[0].ID)++ generated, err := client.KubeGenerate(t.Context(), podmantypes.KubeGenerateRequest{+ Names: []string{"web", "db"},+ Type: podmantypes.KubeGenerateTypeDeployment,+ Service: true,+ })+ require.NoError(t, err)+ assert.Equal(t, manifest, generated)+}diff --git a/backend/pkg/libarcane/podman/pods.go b/backend/pkg/libarcane/podman/pods.gonew file mode 100644index 000000000..d6601faba--- /dev/null+++ b/backend/pkg/libarcane/podman/pods.go@@ -0,0 +1,247 @@+package podman++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "strconv"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+)++type PodAction string++const (+ PodActionStart PodAction = "start"+ PodActionStop PodAction = "stop"+ PodActionRestart PodAction = "restart"+ PodActionPause PodAction = "pause"+ PodActionUnpause PodAction = "unpause"+ PodActionKill PodAction = "kill"+)++type PodActionOptions struct {+ Timeout *int+ Signal string+}++type PodPortMapping struct {+ ContainerPort uint16 `json:"container_port"`+ HostPort uint16 `json:"host_port,omitempty"`+ HostIP string `json:"host_ip,omitempty"`+ Protocol string `json:"protocol,omitempty"`+ Range uint16 `json:"range,omitempty"`+}++type PodNamespace struct {+ NSMode string `json:"nsmode,omitempty"`+ Value string `json:"value,omitempty"`+}++type PodNetworkOptions struct {+ StaticIPs []string `json:"static_ips,omitempty"`+ Aliases []string `json:"aliases,omitempty"`+ StaticMAC string `json:"static_mac,omitempty"`+ InterfaceName string `json:"interface_name,omitempty"`+}++type PodMount struct {+ Destination string `json:"destination"`+ Type string `json:"type"`+ Source string `json:"source"`+ Options []string `json:"options,omitempty"`+}++type PodNamedVolume struct {+ Name string `json:"Name"`+ Dest string `json:"Dest"`+ Options []string `json:"Options,omitempty"`+}++type PodIDMap struct {+ ContainerID int `json:"container_id"`+ HostID int `json:"host_id"`+ Size int `json:"size"`+}++type PodIDMappings struct {+ HostUIDMapping bool `json:"HostUIDMapping"`+ HostGIDMapping bool `json:"HostGIDMapping"`+ UIDMap []PodIDMap `json:"UIDMap,omitempty"`+ GIDMap []PodIDMap `json:"GIDMap,omitempty"`+}++type PodMemoryLimits struct {+ Limit *int64 `json:"limit,omitempty"`+ Swap *int64 `json:"swap,omitempty"`+}++type PodCPULimits struct {+ Shares *uint64 `json:"shares,omitempty"`+ Quota *int64 `json:"quota,omitempty"`+ Period *uint64 `json:"period,omitempty"`+ Cpus string `json:"cpus,omitempty"`+ Mems string `json:"mems,omitempty"`+}++type PodWeightDevice struct {+ Major int64 `json:"major"`+ Minor int64 `json:"minor"`+ Weight *uint16 `json:"weight,omitempty"`+}++type PodThrottleDevice struct {+ Major int64 `json:"major"`+ Minor int64 `json:"minor"`+ Rate uint64 `json:"rate"`+}++type PodBlockIO struct {+ Weight *uint16 `json:"weight,omitempty"`+ WeightDevice []PodWeightDevice `json:"weightDevice,omitempty"`+ ThrottleReadBpsDevice []PodThrottleDevice `json:"throttleReadBpsDevice,omitempty"`+ ThrottleWriteBpsDevice []PodThrottleDevice `json:"throttleWriteBpsDevice,omitempty"`+}++type PodResources struct {+ Memory *PodMemoryLimits `json:"memory,omitempty"`+ CPU *PodCPULimits `json:"cpu,omitempty"`+ BlockIO *PodBlockIO `json:"blockIO,omitempty"`+}++type PodSpec struct {+ Name string `json:"name"`+ Hostname string `json:"hostname,omitempty"`+ ExitPolicy string `json:"exit_policy,omitempty"`+ Labels map[string]string `json:"labels,omitempty"`+ NoInfra bool `json:"no_infra,omitempty"`+ InfraConmonPidFile string `json:"infra_conmon_pid_file,omitempty"`+ InfraCommand []string `json:"infra_command,omitempty"`+ InfraImage string `json:"infra_image,omitempty"`+ InfraName string `json:"infra_name,omitempty"`+ Ipc *PodNamespace `json:"ipcns,omitempty"`+ SharedNamespaces []string `json:"shared_namespaces,omitempty"`+ RestartPolicy string `json:"restart_policy,omitempty"`+ RestartRetries *uint `json:"restart_tries,omitempty"`+ ShareParent *bool `json:"share_parent,omitempty"`+ Pid *PodNamespace `json:"pidns,omitempty"`+ Userns *PodNamespace `json:"userns,omitempty"`+ Uts *PodNamespace `json:"utsns,omitempty"`+ Devices []string `json:"pod_devices,omitempty"`+ Sysctl map[string]string `json:"sysctl,omitempty"`+ NetNS *PodNamespace `json:"netns,omitempty"`+ PortMappings []PodPortMapping `json:"portmappings,omitempty"`+ Networks map[string]PodNetworkOptions `json:"Networks,omitempty"`+ NoManageResolvConf bool `json:"no_manage_resolv_conf,omitempty"`+ DNSServer []string `json:"dns_server,omitempty"`+ DNSSearch []string `json:"dns_search,omitempty"`+ DNSOption []string `json:"dns_option,omitempty"`+ NoManageHostname bool `json:"no_manage_hostname,omitempty"`+ NoManageHosts bool `json:"no_manage_hosts,omitempty"`+ HostAdd []string `json:"hostadd,omitempty"`+ HostsFile string `json:"hostsFile,omitempty"`+ NetworkOptions map[string][]string `json:"network_options,omitempty"`+ CgroupParent string `json:"cgroup_parent,omitempty"`+ ResourceLimits *PodResources `json:"resource_limits,omitempty"`+ Mounts []PodMount `json:"mounts,omitempty"`+ Volumes []PodNamedVolume `json:"volumes,omitempty"`+ VolumesFrom []string `json:"volumes_from,omitempty"`+ ShmSize *int64 `json:"shm_size,omitempty"`+ ShmSizeSystemd *int64 `json:"shm_size_systemd,omitempty"`+ SecurityOpt []string `json:"security_opt,omitempty"`+ IDMappings *PodIDMappings `json:"idmappings,omitempty"`+}++func (c *Client) PodList(ctx context.Context, filters map[string][]string) ([]podmantypes.Pod, error) {+ query, err := filtersQuery(url.Values{}, filters)+ if err != nil {+ return nil, err+ }++ return c.doJSON[[]podmantypes.Pod](ctx, request{+ method: http.MethodGet,+ path: "/pods/json",+ query: query,+ })+}++func (c *Client) PodInspect(ctx context.Context, nameOrID string) (podmantypes.PodInspect, error) {+ return c.doJSON[podmantypes.PodInspect](ctx, request{method: http.MethodGet, path: "/pods/" + url.PathEscape(nameOrID) + "/json"})+}++func (c *Client) PodCreate(ctx context.Context, spec PodSpec) (string, error) {+ encoded, err := json.Marshal(spec)+ if err != nil {+ return "", fmt.Errorf("encode pod spec: %w", err)+ }++ out, err := c.doJSON[podmantypes.PodCreateResponse](ctx, request{+ method: http.MethodPost,+ path: "/pods/create",+ body: bytes.NewReader(encoded),+ contentType: "application/json",+ })+ return out.ID, err+}++func (c *Client) PodAction(ctx context.Context, nameOrID string, action PodAction, opts PodActionOptions) error {+ query := url.Values{}+ if opts.Timeout != nil && action == PodActionStop {+ query.Set("t", strconv.Itoa(*opts.Timeout))+ }+ if opts.Signal != "" && action == PodActionKill {+ query.Set("signal", opts.Signal)+ }++ _, err := c.doText(ctx, request{+ method: http.MethodPost,+ path: "/pods/" + url.PathEscape(nameOrID) + "/" + string(action),+ query: query,+ })+ return err+}++func (c *Client) PodRemove(ctx context.Context, nameOrID string, force bool) error {+ _, err := c.doText(ctx, request{+ method: http.MethodDelete,+ path: "/pods/" + url.PathEscape(nameOrID),+ query: url.Values{"force": {strconv.FormatBool(force)}},+ })+ return err+}++func (c *Client) PodPrune(ctx context.Context) ([]podmantypes.PodPruneReport, error) {+ return c.doJSON[[]podmantypes.PodPruneReport](ctx, request{method: http.MethodPost, path: "/pods/prune"})+}++func (c *Client) PodTop(ctx context.Context, nameOrID, psArgs string) (podmantypes.PodTop, error) {+ query := url.Values{"stream": {"false"}}+ if psArgs != "" {+ query.Set("ps_args", psArgs)+ }++ return c.doJSON[podmantypes.PodTop](ctx, request{+ method: http.MethodGet,+ path: "/pods/" + url.PathEscape(nameOrID) + "/top",+ query: query,+ })+}++func (c *Client) PodStats(ctx context.Context, namesOrIDs []string) ([]podmantypes.PodStats, error) {+ query := url.Values{+ "stream": {"false"},+ "namesOrIDs": namesOrIDs,+ }+ if len(namesOrIDs) == 0 {+ query.Set("all", "true")+ }++ return c.doJSON[[]podmantypes.PodStats](ctx, request{+ method: http.MethodGet,+ path: "/pods/stats",+ query: query,+ })+}diff --git a/backend/pkg/libarcane/podman/pods_test.go b/backend/pkg/libarcane/podman/pods_test.gonew file mode 100644index 000000000..7f1b0ad4a--- /dev/null+++ b/backend/pkg/libarcane/podman/pods_test.go@@ -0,0 +1,125 @@+package podman++import (+ "encoding/json"+ "io"+ "net/http"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestClientPodCreate(t *testing.T) {+ var body map[string]any+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, http.MethodPost, r.Method)+ assert.Equal(t, "/v4.0.0/libpod/pods/create", r.URL.Path)+ data, err := io.ReadAll(r.Body)+ assert.NoError(t, err)+ assert.NoError(t, json.Unmarshal(data, &body))+ w.WriteHeader(http.StatusCreated)+ _, _ = w.Write([]byte(`{"Id":"pod123"}`))+ })++ id, err := client.PodCreate(t.Context(), PodSpec{+ Name: "web",+ Hostname: "web-host",+ PortMappings: []PodPortMapping{+ {ContainerPort: 80, HostPort: 8080},+ },+ Networks: map[string]PodNetworkOptions{"frontend": {}},+ InfraName: "web-infra",+ })+ require.NoError(t, err)+ assert.Equal(t, "pod123", id)+ assert.Equal(t, "web", body["name"])+ assert.Equal(t, "web-host", body["hostname"])+ assert.Equal(t, "web-infra", body["infra_name"])+ assert.Contains(t, body, "Networks")+ assert.Equal(t, []any{map[string]any{"container_port": float64(80), "host_port": float64(8080)}}, body["portmappings"])+}++func TestClientPodAction(t *testing.T) {+ tests := []struct {+ name string+ action PodAction+ opts PodActionOptions+ query string+ }{+ {name: "start", action: PodActionStart},+ {name: "stop with timeout", action: PodActionStop, opts: PodActionOptions{Timeout: new(5)}, query: "t=5"},+ {name: "kill with signal", action: PodActionKill, opts: PodActionOptions{Signal: "SIGTERM"}, query: "signal=SIGTERM"},+ {name: "restart ignores signal", action: PodActionRestart, opts: PodActionOptions{Signal: "SIGTERM"}},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, http.MethodPost, r.Method)+ assert.Equal(t, "/v4.0.0/libpod/pods/web/"+string(tt.action), r.URL.Path)+ assert.Equal(t, tt.query, r.URL.RawQuery)+ _, _ = w.Write([]byte(`{"Id":"pod123","Errs":[]}`))+ })++ require.NoError(t, client.PodAction(t.Context(), "web", tt.action, tt.opts))+ })+ }+}++func TestClientPodStats(t *testing.T) {+ tests := []struct {+ name string+ names []string+ query string+ }{+ {name: "all pods", query: "all=true&stream=false"},+ {name: "named pods", names: []string{"web", "db"}, query: "namesOrIDs=web&namesOrIDs=db&stream=false"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, "/v4.0.0/libpod/pods/stats", r.URL.Path)+ assert.Equal(t, tt.query, r.URL.RawQuery)+ _, _ = w.Write([]byte(`[{"Pod":"pod123","CID":"abc","Name":"web-infra","CPU":"0.10%","MemUsage":"1MB / 2GB","NetIO":"1kB / 2kB","PIDS":"1"}]`))+ })++ stats, err := client.PodStats(t.Context(), tt.names)+ require.NoError(t, err)+ require.Len(t, stats, 1)+ assert.Equal(t, "pod123", stats[0].Pod)+ assert.Equal(t, "1kB / 2kB", stats[0].NetIO)+ })+ }+}++func TestClientPodListAndInspect(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/v4.0.0/libpod/pods/json":+ assert.JSONEq(t, `{"label":["app=web"]}`, r.URL.Query().Get("filters"))+ _, _ = w.Write([]byte(`[{"Id":"pod123","Name":"web","Status":"Running","InfraId":"infra1","Containers":[{"Id":"abc","Names":"web-app","Status":"running"}]}]`))+ case "/v4.0.0/libpod/pods/web/json":+ _, _ = w.Write([]byte(`{+ "Id":"pod123","Name":"web","State":"Running","InfraContainerID":"infra1","NumContainers":2,+ "SharedNamespaces":["net","ipc"],"Containers":[{"Id":"abc","Name":"web-app","State":"running"}]+ }`))+ default:+ http.NotFound(w, r)+ }+ })++ pods, err := client.PodList(t.Context(), map[string][]string{"label": {"app=web"}})+ require.NoError(t, err)+ require.Len(t, pods, 1)+ assert.Equal(t, "infra1", pods[0].InfraID)+ require.Len(t, pods[0].Containers, 1)+ assert.Equal(t, "web-app", pods[0].Containers[0].Names)++ pod, err := client.PodInspect(t.Context(), "web")+ require.NoError(t, err)+ assert.Equal(t, "infra1", pod.InfraContainerID)+ assert.Equal(t, uint(2), pod.NumContainers)+ assert.Equal(t, []string{"net", "ipc"}, pod.SharedNamespaces)+}diff --git a/backend/pkg/libarcane/podman/quadlets.go b/backend/pkg/libarcane/podman/quadlets.gonew file mode 100644index 000000000..f7c4efe84--- /dev/null+++ b/backend/pkg/libarcane/podman/quadlets.go@@ -0,0 +1,71 @@+package podman++import (+ "context"+ "net/http"+ "net/url"+ "strconv"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+)++type QuadletInstallOptions struct {+ File podmantypes.QuadletFile+ ExtraFiles []podmantypes.QuadletFile+ Replace bool+ Application string+ AppsSupported bool+}++type QuadletRemoveOptions struct {+ Force bool+ Ignore bool+}++func (c *Client) QuadletList(ctx context.Context, filters map[string][]string) ([]podmantypes.Quadlet, error) {+ query, err := filtersQuery(url.Values{}, filters)+ if err != nil {+ return nil, err+ }++ return c.doJSON[[]podmantypes.Quadlet](ctx, request{+ method: http.MethodGet,+ path: "/quadlets/json",+ query: query,+ })+}++func (c *Client) QuadletFile(ctx context.Context, name string) (string, error) {+ return c.doText(ctx, request{method: http.MethodGet, path: "/quadlets/" + url.PathEscape(name) + "/file"})+}++func (c *Client) QuadletInstall(ctx context.Context, opts QuadletInstallOptions) (podmantypes.QuadletInstallReport, error) {+ archive, err := buildTar(append([]podmantypes.QuadletFile{opts.File}, opts.ExtraFiles...))+ if err != nil {+ return podmantypes.QuadletInstallReport{}, err+ }++ query := url.Values{"replace": {strconv.FormatBool(opts.Replace)}}+ if opts.AppsSupported && opts.Application != "" {+ query.Set("application", opts.Application)+ }++ return c.doJSON[podmantypes.QuadletInstallReport](ctx, request{+ method: http.MethodPost,+ path: "/quadlets",+ query: query,+ body: archive,+ contentType: "application/x-tar",+ })+}++func (c *Client) QuadletRemove(ctx context.Context, name string, opts QuadletRemoveOptions) (podmantypes.QuadletRemoveReport, error) {+ return c.doJSON[podmantypes.QuadletRemoveReport](ctx, request{+ method: http.MethodDelete,+ path: "/quadlets/" + url.PathEscape(name),+ query: url.Values{+ "force": {strconv.FormatBool(opts.Force)},+ "ignore": {strconv.FormatBool(opts.Ignore)},+ },+ })+}diff --git a/backend/pkg/libarcane/podman/quadlets_test.go b/backend/pkg/libarcane/podman/quadlets_test.gonew file mode 100644index 000000000..d3b1f5bcc--- /dev/null+++ b/backend/pkg/libarcane/podman/quadlets_test.go@@ -0,0 +1,93 @@+package podman++import (+ "bytes"+ "io"+ "net/http"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestClientQuadletInstall(t *testing.T) {+ tests := []struct {+ name string+ appsSupported bool+ query string+ }{+ {name: "apps supported", appsSupported: true, query: "application=shop&replace=true"},+ {name: "apps unsupported", query: "replace=true"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ var archive []byte+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, http.MethodPost, r.Method)+ assert.Equal(t, "/v4.0.0/libpod/quadlets", r.URL.Path)+ assert.Equal(t, tt.query, r.URL.RawQuery)+ assert.Equal(t, "application/x-tar", r.Header.Get("Content-Type"))+ data, err := io.ReadAll(r.Body)+ assert.NoError(t, err)+ archive = data+ _, _ = w.Write([]byte(`{"InstalledQuadlets":{"web.kube":"/etc/containers/systemd/web.kube"},"QuadletErrors":{}}`))+ })++ report, err := client.QuadletInstall(t.Context(), QuadletInstallOptions{+ File: podmantypes.QuadletFile{Name: "web.kube", Content: "[Kube]\nYaml=web.yaml\n"},+ ExtraFiles: []podmantypes.QuadletFile{{Name: "web.yaml", Content: "kind: Pod\n"}},+ Replace: true,+ Application: "shop",+ AppsSupported: tt.appsSupported,+ })+ require.NoError(t, err)+ assert.Equal(t, "/etc/containers/systemd/web.kube", report.InstalledQuadlets["web.kube"])+ assert.Equal(t, map[string]string{+ "web.kube": "[Kube]\nYaml=web.yaml\n",+ "web.yaml": "kind: Pod\n",+ }, readTar(t, bytes.NewReader(archive)))+ })+ }+}++func TestClientQuadletListFileRemove(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v4.0.0/libpod/quadlets/json":+ assert.JSONEq(t, `{"name":["web*"],"status":["active"]}`, r.URL.Query().Get("filters"))+ _, _ = w.Write([]byte(`[{"Name":"web.container","UnitName":"web.service","Path":"/etc/containers/systemd/web.container","Status":"active","App":"shop"}]`))+ case r.Method == http.MethodGet && r.URL.Path == "/v4.0.0/libpod/quadlets/web.container/file":+ _, _ = w.Write([]byte("[Container]\nImage=nginx\n"))+ case r.Method == http.MethodDelete && r.URL.Path == "/v4.0.0/libpod/quadlets/web.container":+ assert.Equal(t, "force=true&ignore=false", r.URL.RawQuery)+ _, _ = w.Write([]byte(`{"Removed":["web.container"],"Errors":{}}`))+ default:+ http.NotFound(w, r)+ }+ })++ quadlets, err := client.QuadletList(t.Context(), map[string][]string{+ "name": {"web*"},+ "pod": nil,+ "status": {"active"},+ })+ require.NoError(t, err)+ require.Len(t, quadlets, 1)+ assert.Equal(t, podmantypes.Quadlet{+ Name: "web.container",+ UnitName: "web.service",+ Path: "/etc/containers/systemd/web.container",+ Status: "active",+ App: "shop",+ }, quadlets[0])++ content, err := client.QuadletFile(t.Context(), "web.container")+ require.NoError(t, err)+ assert.Equal(t, "[Container]\nImage=nginx\n", content)++ report, err := client.QuadletRemove(t.Context(), "web.container", QuadletRemoveOptions{Force: true})+ require.NoError(t, err)+ assert.Equal(t, []string{"web.container"}, report.Removed)+}diff --git a/backend/pkg/libarcane/podman/secrets.go b/backend/pkg/libarcane/podman/secrets.gonew file mode 100644index 000000000..5f1fd5b62--- /dev/null+++ b/backend/pkg/libarcane/podman/secrets.go@@ -0,0 +1,69 @@+package podman++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "strings"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+)++func (c *Client) SecretList(ctx context.Context, filters map[string][]string) ([]podmantypes.Secret, error) {+ query, err := filtersQuery(url.Values{}, filters)+ if err != nil {+ return nil, err+ }++ return c.doJSON[[]podmantypes.Secret](ctx, request{+ method: http.MethodGet,+ path: "/secrets/json",+ query: query,+ })+}++func (c *Client) SecretInspect(ctx context.Context, nameOrID string) (podmantypes.Secret, error) {+ return c.doJSON[podmantypes.Secret](ctx, request{+ method: http.MethodGet,+ path: "/secrets/" + url.PathEscape(nameOrID) + "/json",+ })+}++func (c *Client) SecretCreate(ctx context.Context, req podmantypes.SecretCreateRequest, replace bool) (string, error) {+ query := url.Values{"name": {req.Name}}+ if replace {+ query.Set("replace", "true")+ }+ if req.Driver != "" {+ query.Set("driver", req.Driver)+ }+ for key, values := range map[string]map[string]string{+ "driveropts": req.DriverOptions,+ "labels": req.Labels,+ } {+ if len(values) == 0 {+ continue+ }+ encoded, err := json.Marshal(values)+ if err != nil {+ return "", fmt.Errorf("encode secret %s: %w", key, err)+ }+ query.Set(key, string(encoded))+ }++ out, err := c.doJSON[podmantypes.SecretCreateResponse](ctx, request{+ method: http.MethodPost,+ path: "/secrets/create",+ query: query,+ body: strings.NewReader(req.Data),+ contentType: "application/octet-stream",+ })+ return out.ID, err+}++func (c *Client) SecretRemove(ctx context.Context, nameOrID string) error {+ _, err := c.doText(ctx, request{method: http.MethodDelete, path: "/secrets/" + url.PathEscape(nameOrID)})+ return err+}diff --git a/backend/pkg/libarcane/podman/secrets_test.go b/backend/pkg/libarcane/podman/secrets_test.gonew file mode 100644index 000000000..d6c61c5f0--- /dev/null+++ b/backend/pkg/libarcane/podman/secrets_test.go@@ -0,0 +1,73 @@+package podman++import (+ "io"+ "net/http"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestClientSecrets(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v4.0.0/libpod/secrets/json":+ _, _ = w.Write([]byte(`[{"ID":"sec1","CreatedAt":"2026-01-02T03:04:05Z","Spec":{"Name":"db-pass","Driver":{"Name":"file"},"Labels":{"app":"db"}}}]`))+ case r.Method == http.MethodGet && r.URL.Path == "/v4.0.0/libpod/secrets/db-pass/json":+ assert.Empty(t, r.URL.Query().Get("showsecret"))+ _, _ = w.Write([]byte(`{"ID":"sec1","CreatedAt":"2026-01-02T03:04:05Z","Spec":{"Name":"db-pass","Driver":{"Name":"file","Options":{"path":"/s"}},"Labels":{"app":"db"}}}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v4.0.0/libpod/secrets/create" && r.URL.Query().Get("replace") == "true":+ assert.Equal(t, "db-pass", r.URL.Query().Get("name"))+ data, err := io.ReadAll(r.Body)+ assert.NoError(t, err)+ assert.Equal(t, "rotated", string(data))+ _, _ = w.Write([]byte(`{"ID":"sec2"}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v4.0.0/libpod/secrets/create":+ query := r.URL.Query()+ assert.Equal(t, "db-pass", query.Get("name"))+ assert.Equal(t, "file", query.Get("driver"))+ assert.JSONEq(t, `{"app":"db"}`, query.Get("labels"))+ assert.Empty(t, query.Get("driveropts"))+ data, err := io.ReadAll(r.Body)+ assert.NoError(t, err)+ assert.Equal(t, "hunter2", string(data))+ _, _ = w.Write([]byte(`{"ID":"sec1"}`))+ case r.Method == http.MethodDelete && r.URL.Path == "/v4.0.0/libpod/secrets/db-pass":+ w.WriteHeader(http.StatusNoContent)+ default:+ http.NotFound(w, r)+ }+ })++ secrets, err := client.SecretList(t.Context(), nil)+ require.NoError(t, err)+ require.Len(t, secrets, 1)+ assert.Equal(t, "db-pass", secrets[0].Spec.Name)+ assert.Equal(t, "file", secrets[0].Spec.Driver.Name)++ id, err := client.SecretCreate(t.Context(), podmantypes.SecretCreateRequest{+ Name: "db-pass",+ Data: "hunter2",+ Driver: "file",+ Labels: map[string]string{"app": "db"},+ }, false)+ require.NoError(t, err)+ assert.Equal(t, "sec1", id)++ secret, err := client.SecretInspect(t.Context(), "db-pass")+ require.NoError(t, err)+ assert.Equal(t, "sec1", secret.ID)+ assert.Equal(t, map[string]string{"path": "/s"}, secret.Spec.Driver.Options)+ assert.Equal(t, map[string]string{"app": "db"}, secret.Spec.Labels)++ replacedID, err := client.SecretCreate(t.Context(), podmantypes.SecretCreateRequest{+ Name: "db-pass",+ Data: "rotated",+ }, true)+ require.NoError(t, err)+ assert.Equal(t, "sec2", replacedID)++ require.NoError(t, client.SecretRemove(t.Context(), "db-pass"))+}diff --git a/backend/pkg/libarcane/podman/systemd.go b/backend/pkg/libarcane/podman/systemd.gonew file mode 100644index 000000000..ca6157115--- /dev/null+++ b/backend/pkg/libarcane/podman/systemd.go@@ -0,0 +1,166 @@+package podman++import (+ "cmp"+ "context"+ "errors"+ "fmt"+ "os"+ "strconv"+ "strings"++ "github.com/coreos/go-systemd/v22/dbus"+ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ godbus "github.com/godbus/dbus/v5"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+)++const defaultSystemBusAddress = "unix:path=/run/dbus/system_bus_socket"++type Systemd interface {+ Availability(ctx context.Context) podmantypes.SystemdAvailability+ Start(ctx context.Context, unit string) error+ Stop(ctx context.Context, unit string) error+ Restart(ctx context.Context, unit string) error+ UnitStatus(ctx context.Context, unit string) (podmantypes.UnitStatus, error)+}++type dbusSystemd struct {+ address string+ scope podmantypes.SystemdScope+ reason string+}++func NewSystemd(host string, rootless bool, getenv func(string) string) Systemd {+ scope := kit.Ternary(rootless, podmantypes.SystemdScopeUser, podmantypes.SystemdScopeSystem)+ busVariable := kit.Ternary(rootless, "DBUS_SESSION_BUS_ADDRESS", "DBUS_SYSTEM_BUS_ADDRESS")+ address := getenv(busVariable)+ scheme, _, _ := strings.Cut(host, "://")++ switch {+ case address == "" && host != "" && scheme != "unix" && scheme != "npipe":+ return &dbusSystemd{+ scope: scope,+ reason: fmt.Sprintf("the Podman engine at %s is remote; set %s to that host's bus to manage its systemd units", host, busVariable),+ }+ case address == "" && rootless:+ return &dbusSystemd{+ scope: scope,+ reason: "DBUS_SESSION_BUS_ADDRESS is not set; rootless Podman needs the user's session bus mounted and the variable set",+ }+ default:+ return &dbusSystemd{+ address: cmp.Or(address, defaultSystemBusAddress),+ scope: scope,+ }+ }+}++func (s *dbusSystemd) Availability(ctx context.Context) podmantypes.SystemdAvailability {+ conn, err := s.connect(ctx)+ if err != nil {+ return podmantypes.SystemdAvailability{+ Scope: s.scope,+ Reason: err.Error(),+ }+ }+ conn.Close()++ return podmantypes.SystemdAvailability{+ Available: true,+ Scope: s.scope,+ }+}++func (s *dbusSystemd) Start(ctx context.Context, unit string) error {+ return s.runJob(ctx, unit, "start", func(conn *dbus.Conn, ch chan<- string) (int, error) {+ return conn.StartUnitContext(ctx, unit, "replace", ch)+ })+}++func (s *dbusSystemd) Stop(ctx context.Context, unit string) error {+ return s.runJob(ctx, unit, "stop", func(conn *dbus.Conn, ch chan<- string) (int, error) {+ return conn.StopUnitContext(ctx, unit, "replace", ch)+ })+}++func (s *dbusSystemd) Restart(ctx context.Context, unit string) error {+ return s.runJob(ctx, unit, "restart", func(conn *dbus.Conn, ch chan<- string) (int, error) {+ return conn.RestartUnitContext(ctx, unit, "replace", ch)+ })+}++func (s *dbusSystemd) UnitStatus(ctx context.Context, unit string) (podmantypes.UnitStatus, error) {+ conn, err := s.connect(ctx)+ if err != nil {+ return podmantypes.UnitStatus{}, err+ }+ defer conn.Close()++ units, err := conn.ListUnitsByNamesContext(ctx, []string{unit})+ if err != nil {+ return podmantypes.UnitStatus{}, fmt.Errorf("read systemd unit %s: %w", unit, err)+ }+ if len(units) == 0 {+ return podmantypes.UnitStatus{}, common.Classify(common.ErrNotFound, fmt.Errorf("systemd unit %s not found", unit))+ }++ return podmantypes.UnitStatus{+ Name: units[0].Name,+ Description: units[0].Description,+ LoadState: units[0].LoadState,+ ActiveState: units[0].ActiveState,+ SubState: units[0].SubState,+ }, nil+}++func (s *dbusSystemd) connect(ctx context.Context) (*dbus.Conn, error) {+ if s.address == "" {+ return nil, common.Classify(common.ErrUnavailable, errors.New(s.reason))+ }++ conn, err := dbus.NewConnection(func() (*godbus.Conn, error) {+ busConn, dialErr := godbus.Dial(s.address, godbus.WithContext(ctx))+ if dialErr != nil {+ return nil, dialErr+ }+ if authErr := busConn.Auth([]godbus.Auth{godbus.AuthExternal(strconv.Itoa(os.Getuid()))}); authErr != nil {+ _ = busConn.Close()+ return nil, authErr+ }+ if helloErr := busConn.Hello(); helloErr != nil {+ _ = busConn.Close()+ return nil, helloErr+ }+ return busConn, nil+ })+ if err != nil {+ return nil, common.Classify(common.ErrUnavailable, fmt.Errorf("connect to systemd %s bus at %s: %w", s.scope, s.address, err))+ }+ return conn, nil+}++func (s *dbusSystemd) runJob(ctx context.Context, unit, action string, start func(*dbus.Conn, chan<- string) (int, error)) error {+ conn, err := s.connect(ctx)+ if err != nil {+ return err+ }+ defer conn.Close()++ done := make(chan string, 1)+ if _, startErr := start(conn, done); startErr != nil {+ return fmt.Errorf("%s systemd unit %s: %w", action, unit, startErr)+ }++ select {+ case <-ctx.Done():+ return fmt.Errorf("%s systemd unit %s: %w", action, unit, ctx.Err())+ case result := <-done:+ if result != "done" {+ return common.Classify(common.ErrConflict, fmt.Errorf("%s systemd unit %s: job %s", action, unit, result))+ }+ return nil+ }+}diff --git a/backend/pkg/libarcane/podman/systemd_test.go b/backend/pkg/libarcane/podman/systemd_test.gonew file mode 100644index 000000000..3a0575677--- /dev/null+++ b/backend/pkg/libarcane/podman/systemd_test.go@@ -0,0 +1,98 @@+package podman++import (+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+)++func TestNewSystemd(t *testing.T) {+ tests := []struct {+ name string+ host string+ rootless bool+ env map[string]string+ want *dbusSystemd+ }{+ {+ name: "rootful default system bus",+ want: &dbusSystemd{+ address: defaultSystemBusAddress,+ scope: podmantypes.SystemdScopeSystem,+ },+ },+ {+ name: "rootful custom system bus",+ env: map[string]string{"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/host/bus"},+ want: &dbusSystemd{+ address: "unix:path=/host/bus",+ scope: podmantypes.SystemdScopeSystem,+ },+ },+ {+ name: "rootless session bus",+ rootless: true,+ env: map[string]string{+ "DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus",+ "DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/host/bus",+ },+ want: &dbusSystemd{+ address: "unix:path=/run/user/1000/bus",+ scope: podmantypes.SystemdScopeUser,+ },+ },+ {+ name: "local unix socket",+ host: "unix:///run/podman/podman.sock",+ want: &dbusSystemd{+ address: defaultSystemBusAddress,+ scope: podmantypes.SystemdScopeSystem,+ },+ },+ {+ name: "remote engine without bus",+ host: "tcp://podman.example:2375",+ want: &dbusSystemd{+ scope: podmantypes.SystemdScopeSystem,+ reason: "the Podman engine at tcp://podman.example:2375 is remote; set DBUS_SYSTEM_BUS_ADDRESS to that host's bus to manage its systemd units",+ },+ },+ {+ name: "remote engine with explicit bus",+ host: "ssh://[email protected]",+ rootless: true,+ env: map[string]string{"DBUS_SESSION_BUS_ADDRESS": "tcp:host=podman.example,port=55556"},+ want: &dbusSystemd{+ address: "tcp:host=podman.example,port=55556",+ scope: podmantypes.SystemdScopeUser,+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ assert.Equal(t, tt.want, NewSystemd(tt.host, tt.rootless, func(key string) string {+ return tt.env[key]+ }))+ })+ }+}++func TestSystemdRootlessWithoutSessionBus(t *testing.T) {+ systemd := NewSystemd("", true, func(string) string {+ return ""+ })++ availability := systemd.Availability(t.Context())+ assert.False(t, availability.Available)+ assert.Equal(t, podmantypes.SystemdScopeUser, availability.Scope)+ assert.Contains(t, availability.Reason, "DBUS_SESSION_BUS_ADDRESS")++ require.ErrorIs(t, systemd.Start(t.Context(), "web.service"), common.ErrUnavailable)+ _, err := systemd.UnitStatus(t.Context(), "web.service")+ require.ErrorIs(t, err, common.ErrUnavailable)+}diff --git a/backend/pkg/libarcane/podman/tar.go b/backend/pkg/libarcane/podman/tar.gonew file mode 100644index 000000000..15dd1216a--- /dev/null+++ b/backend/pkg/libarcane/podman/tar.go@@ -0,0 +1,46 @@+package podman++import (+ "archive/tar"+ "bytes"+ "fmt"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ kit "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+)++func buildTar(files []podmantypes.QuadletFile) (*bytes.Buffer, error) {+ buf := &bytes.Buffer{}+ writer := tar.NewWriter(buf)+ seen := make(map[string]struct{}, len(files))++ for _, file := range files {+ name, err := kit.ValidateFileName(file.Name)+ if err != nil {+ return nil, common.Classify(common.ErrBadRequest, fmt.Errorf("invalid file name %q: %w", file.Name, err))+ }+ if _, ok := seen[name]; ok {+ return nil, common.Classify(common.ErrBadRequest, fmt.Errorf("duplicate file name %q", name))+ }+ seen[name] = struct{}{}++ if headerErr := writer.WriteHeader(&tar.Header{+ Name: name,+ Mode: 0o644,+ Size: int64(len(file.Content)),+ Typeflag: tar.TypeReg,+ }); headerErr != nil {+ return nil, fmt.Errorf("write tar header for %s: %w", name, headerErr)+ }+ if _, writeErr := writer.Write([]byte(file.Content)); writeErr != nil {+ return nil, fmt.Errorf("write tar entry for %s: %w", name, writeErr)+ }+ }++ if err := writer.Close(); err != nil {+ return nil, fmt.Errorf("close tar: %w", err)+ }+ return buf, nil+}diff --git a/backend/pkg/libarcane/podman/tar_test.go b/backend/pkg/libarcane/podman/tar_test.gonew file mode 100644index 000000000..3f1de78fb--- /dev/null+++ b/backend/pkg/libarcane/podman/tar_test.go@@ -0,0 +1,64 @@+package podman++import (+ "archive/tar"+ "errors"+ "io"+ "testing"++ podmantypes "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+)++func readTar(t *testing.T, r io.Reader) map[string]string {+ t.Helper()+ files := map[string]string{}+ reader := tar.NewReader(r)+ for {+ header, err := reader.Next()+ if errors.Is(err, io.EOF) {+ return files+ }+ require.NoError(t, err)+ assert.Equal(t, int64(0o644), header.Mode)+ data, err := io.ReadAll(reader)+ require.NoError(t, err)+ files[header.Name] = string(data)+ }+}++func TestBuildTar(t *testing.T) {+ archive, err := buildTar([]podmantypes.QuadletFile{+ {Name: "web.kube", Content: "[Kube]\nYaml=web.yaml\n"},+ {Name: "web.yaml", Content: "apiVersion: v1\nkind: Pod\n"},+ })+ require.NoError(t, err)++ assert.Equal(t, map[string]string{+ "web.kube": "[Kube]\nYaml=web.yaml\n",+ "web.yaml": "apiVersion: v1\nkind: Pod\n",+ }, readTar(t, archive))+}++func TestBuildTarRejectsInvalidNames(t *testing.T) {+ tests := []struct {+ name string+ files []podmantypes.QuadletFile+ }{+ {name: "empty", files: []podmantypes.QuadletFile{{Name: ""}}},+ {name: "parent", files: []podmantypes.QuadletFile{{Name: ".."}}},+ {name: "nested path", files: []podmantypes.QuadletFile{{Name: "../web.container"}}},+ {name: "absolute path", files: []podmantypes.QuadletFile{{Name: "/etc/web.container"}}},+ {name: "duplicate", files: []podmantypes.QuadletFile{{Name: "web.container"}, {Name: "web.container"}}},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ _, err := buildTar(tt.files)+ require.ErrorIs(t, err, common.ErrBadRequest)+ })+ }+}diff --git a/backend/pkg/libarcane/startup/dockerhost.go b/backend/pkg/libarcane/startup/dockerhost.gonew file mode 100644index 000000000..aca6856e9--- /dev/null+++ b/backend/pkg/libarcane/startup/dockerhost.go@@ -0,0 +1,36 @@+package startup++import (+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "strings"++ kit "go.getarcane.app/kit/pkg"+)++func ResolveDockerHost(host string, stat func(string) (fs.FileInfo, error)) string {+ if host != "unix://"+defaultDockerSocketPath {+ return host+ }+ if _, err := stat(defaultDockerSocketPath); err == nil {+ return host+ }++ xdgRuntimeDir := strings.TrimSpace(os.Getenv("XDG_RUNTIME_DIR"))+ for _, candidate := range []string{+ "/run/podman/podman.sock",+ kit.Ternary(xdgRuntimeDir == "", "", filepath.Join(xdgRuntimeDir, "podman", "podman.sock")),+ fmt.Sprintf("/run/user/%d/podman/podman.sock", os.Getuid()),+ } {+ if candidate == "" {+ continue+ }+ if _, err := stat(candidate); err == nil {+ return "unix://" + candidate+ }+ }++ return host+}diff --git a/backend/pkg/libarcane/startup/dockerhost_test.go b/backend/pkg/libarcane/startup/dockerhost_test.gonew file mode 100644index 000000000..5f8163bff--- /dev/null+++ b/backend/pkg/libarcane/startup/dockerhost_test.go@@ -0,0 +1,77 @@+package startup++import (+ "fmt"+ "io/fs"+ "os"+ "slices"+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestResolveDockerHost(t *testing.T) {+ const defaultHost = "unix:///var/run/docker.sock"+ userSocket := fmt.Sprintf("/run/user/%d/podman/podman.sock", os.Getuid())++ tests := []struct {+ name string+ host string+ xdg string+ existing []string+ want string+ }{+ {+ name: "custom host is kept",+ host: "tcp://docker:2375",+ existing: []string{"/run/podman/podman.sock"},+ want: "tcp://docker:2375",+ },+ {+ name: "docker socket present keeps default",+ host: defaultHost,+ existing: []string{"/var/run/docker.sock", "/run/podman/podman.sock"},+ want: defaultHost,+ },+ {+ name: "rootful podman socket wins",+ host: defaultHost,+ xdg: "/run/user/1000",+ existing: []string{"/run/podman/podman.sock", "/run/user/1000/podman/podman.sock"},+ want: "unix:///run/podman/podman.sock",+ },+ {+ name: "xdg runtime dir socket",+ host: defaultHost,+ xdg: "/run/user/1000",+ existing: []string{"/run/user/1000/podman/podman.sock", userSocket},+ want: "unix:///run/user/1000/podman/podman.sock",+ },+ {+ name: "uid runtime dir socket without xdg",+ host: defaultHost,+ existing: []string{userSocket},+ want: "unix://" + userSocket,+ },+ {+ name: "no sockets keeps default",+ host: defaultHost,+ xdg: "/run/user/1000",+ want: defaultHost,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Setenv("XDG_RUNTIME_DIR", tt.xdg)+ stat := func(path string) (fs.FileInfo, error) {+ if slices.Contains(tt.existing, path) {+ return nil, nil+ }+ return nil, fs.ErrNotExist+ }++ assert.Equal(t, tt.want, ResolveDockerHost(tt.host, stat))+ })+ }+}diff --git a/backend/pkg/libarcane/startup/runtime_identity_linux.go b/backend/pkg/libarcane/startup/runtime_identity_linux.goindex 47c05648b..d12faa514 100644--- a/backend/pkg/libarcane/startup/runtime_identity_linux.go+++ b/backend/pkg/libarcane/startup/runtime_identity_linux.go@@ -24,7 +24,7 @@ func reexecWithRuntimeIdentity(ctx context.Context, req runtimeIdentityRequest)cmd := exec.CommandContext(ctx, executable, os.Args[1:]...) //nolint:gosec // re-executing our own binary with the same args under a different UID/GID// Forward shutdown instead of the default SIGKILL so the child can unregister its actor host.cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }- cmd.Env = os.Environ()+ cmd.Env = append(os.Environ(), "DOCKER_HOST="+req.DockerHost)cmd.Stdin = os.Stdincmd.Stdout = os.Stdoutcmd.Stderr = os.Stderrdiff --git a/backend/pkg/scheduler/auto_heal_job.go b/backend/pkg/scheduler/auto_heal_job.goindex 8af0ac596..615b729c8 100644--- a/backend/pkg/scheduler/auto_heal_job.go+++ b/backend/pkg/scheduler/auto_heal_job.go@@ -10,6 +10,7 @@ import ("sync""time"+ "github.com/getarcaneapp/arcane/types/v2/podman"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/moby/moby/api/types/container""github.com/moby/moby/client"@@ -243,6 +244,15 @@ func (j *AutoHealJob) processCandidateInternal(}}containerName := docker.ContainerNameFromNames(candidate.Names)+ if unit := candidate.Labels[podman.SystemdUnitLabel]; unit != "" {+ slog.DebugContext(ctx, "auto-heal skipping quadlet-managed container", "container", containerName, "unit", unit)+ return schedulertypes.TargetOutcome{+ ResourceType: "container",+ ID: containerID,+ Status: schedulertypes.Skipped,+ Message: "managed by systemd unit " + unit + "; its Restart= policy owns recovery",+ }, nil+ }// The daemon-side health filter already selected unhealthy containers; the// inspect re-confirms right before restarting so a container that recovereddiff --git a/backend/pkg/scheduler/auto_heal_job_test.go b/backend/pkg/scheduler/auto_heal_job_test.goindex e7396c580..08cbbe224 100644--- a/backend/pkg/scheduler/auto_heal_job_test.go+++ b/backend/pkg/scheduler/auto_heal_job_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/getarcaneapp/arcane/types/v2/podman"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/libtnb/sqlite""github.com/moby/moby/api/types/container""github.com/moby/moby/client"@@ -52,6 +54,33 @@ func TestAutoHeal_FilterCandidates_SkipsSelfContainer(t *testing.T) {require.Len(t, candidates, 2)}+func TestAutoHeal_ProcessCandidate_SkipsQuadletContainers(t *testing.T) {+ job := &AutoHealJob{+ restarts: make(map[string]*restartRecord),+ inspectContainer: func(context.Context, *client.Client, string) (container.InspectResponse, error) {+ t.Fatal("quadlet-managed containers must not be inspected")+ return container.InspectResponse{}, nil+ },+ restartContainer: func(context.Context, *client.Client, string) error {+ t.Fatal("quadlet-managed containers must not be restarted")+ return nil+ },+ }++ target, err := job.processCandidateInternal(t.Context(), nil, container.Summary{+ ID: "quadlet-id",+ Names: []string{"/web"},+ Labels: map[string]string{podman.SystemdUnitLabel: "web.service"},+ }, 5, 30*time.Minute, 30)+ require.NoError(t, err)+ require.Equal(t, schedulertypes.TargetOutcome{+ ResourceType: "container",+ ID: "quadlet-id",+ Status: schedulertypes.Skipped,+ Message: "managed by systemd unit web.service; its Restart= policy owns recovery",+ }, target)+}+func TestAutoHeal_CanRestart_UnderLimit(t *testing.T) {job := newTestAutoHealJob()diff --git a/cli/go.mod b/cli/go.modindex 2ffa49735..d069ae38d 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -14,6 +14,7 @@ require (github.com/charmbracelet/x/ansi v0.11.9github.com/charmbracelet/x/term v0.2.2github.com/creack/pty v1.1.24+ github.com/docker/go-connections v0.8.2github.com/docker/go-units v0.5.0github.com/getarcaneapp/arcane/types/v2 v2.14.0github.com/gofrs/flock v0.13.1@@ -66,7 +67,6 @@ require (github.com/digitorus/pkcs7 v0.0.0-20230818184609-3a137a874352 // indirectgithub.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7 // indirectgithub.com/distribution/reference v0.6.0 // indirect- github.com/docker/go-connections v0.8.2 // indirectgithub.com/felixge/httpsnoop v1.1.0 // indirectgithub.com/go-chi/chi/v5 v5.3.1 // indirectgithub.com/go-logfmt/logfmt v0.6.1 // indirectdiff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.goindex fb9f8ead0..6ce6470f2 100644--- a/cli/internal/types/endpoints.go+++ b/cli/internal/types/endpoints.go@@ -595,6 +595,41 @@ func Webhook(envID, webhookID string) string {}func WebhookTrigger(token string) string { return pathf("/api/webhooks/trigger/%s", token) }+func PodmanStatus(envID string) string { return pathf("/api/environments/%s/podman/status", envID) }+func PodmanAutoUpdate(envID string) string {+ return pathf("/api/environments/%s/podman/autoupdate", envID)+}+func PodmanPods(envID string) string { return pathf("/api/environments/%s/podman/pods", envID) }+func PodmanPod(envID, podID string) string {+ return pathf("/api/environments/%s/podman/pods/%s", envID, podID)+}++func PodmanPodAction(envID, podID, action string) string {+ return pathf("/api/environments/%s/podman/pods/%s/%s", envID, podID, action)+}++func PodmanQuadlets(envID string) string {+ return pathf("/api/environments/%s/podman/quadlets", envID)+}++func PodmanQuadlet(envID, name string) string {+ return pathf("/api/environments/%s/podman/quadlets/%s", envID, name)+}++func PodmanQuadletAction(envID, name, action string) string {+ return pathf("/api/environments/%s/podman/quadlets/%s/%s", envID, name, action)+}++func PodmanKube(envID, action string) string {+ return pathf("/api/environments/%s/podman/kube/%s", envID, action)+}++func PodmanSecrets(envID string) string { return pathf("/api/environments/%s/podman/secrets", envID) }++func PodmanSecret(envID, secretID string) string {+ return pathf("/api/environments/%s/podman/secrets/%s", envID, secretID)+}+// GitOps sync endpointsfunc GitOpsSyncs(envID string) string { return pathf("/api/environments/%s/gitops-syncs", envID) }diff --git a/cli/pkg/podman/cmd.go b/cli/pkg/podman/cmd.gonew file mode 100644index 000000000..8b5ca6658--- /dev/null+++ b/cli/pkg/podman/cmd.go@@ -0,0 +1,139 @@+package podman++import (+ "fmt"+ "net/http"++ "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/spf13/cobra"+ "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"+)++func Command() *cobra.Command {+ cmd := &cobra.Command{+ Use: "podman",+ Aliases: []string{"pm"},+ Short: "Manage Podman pods, quadlets, kube YAML, and secrets",+ }+ cmd.AddCommand(+ newStatusCmd(),+ newAutoUpdateCmd(),+ newPodsCmd(),+ newQuadletsCmd(),+ newKubeCmd(),+ newSecretsCmd(),+ )+ cmdutil.SetScope(cmdutil.ScopeResource, cmd)+ return cmd+}++func newStatusCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "status",+ Short: "Show Podman detection and capabilities",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.Status]{+ Method: http.MethodGet,+ Path: types.PodmanStatus(c.EnvID()),+ FailureMessage: "failed to get Podman status",+ Render: func(data podman.Status) error {+ if !data.Detected {+ output.Info("Podman was not detected on this environment")+ return nil+ }+ output.Header("Podman Status")+ output.KeyValue("Version", data.Version)+ output.KeyValue("API version", data.APIVersion)+ output.KeyValue("Rootless", kit.Ternary(data.Rootless, "Yes", "No"))+ output.KeyValue("Quadlets", kit.Ternary(data.QuadletsSupported, "Supported", "Unsupported"))+ output.KeyValue("Quadlet apps", kit.Ternary(data.QuadletAppsSupported, "Supported", "Unsupported"))+ output.KeyValue("Auto-update mode", data.AutoUpdateMode)+ output.KeyValue("systemd", kit.Ternary(data.SystemdAvailable, string(data.SystemdScope), "Unavailable"))+ if data.SystemdReason != "" {+ output.KeyValue("systemd reason", data.SystemdReason)+ }+ return nil+ },+ })+ },+ }+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)+ return cmd+}++func newAutoUpdateCmd() *cobra.Command {+ var opts struct {+ dryRun bool+ force bool+ }+ cmd := &cobra.Command{+ Use: "autoupdate",+ Aliases: []string{"auto-update"},+ Short: "Run podman auto-update",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, args []string) error {+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.force || opts.dryRun, "Are you sure you want to auto-update Podman containers?")+ if confirmationErr != nil || !confirmed {+ return confirmationErr+ }++ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.AutoUpdateResult]{+ Method: http.MethodPost,+ Path: types.PodmanAutoUpdate(c.EnvID()),+ Body: podman.AutoUpdateOptions{DryRun: opts.dryRun},+ FailureMessage: "failed to run Podman auto-update",+ Render: func(data podman.AutoUpdateResult) error {+ output.Header("Podman Auto-Update")+ output.KeyValue("Mode", data.Mode)+ if data.Unit != nil {+ output.KeyValue("Unit", data.Unit.Name)+ output.KeyValue("State", data.Unit.ActiveState+"/"+data.Unit.SubState)+ }+ for _, message := range data.Errors {+ output.Warning("%s", message)+ }+ if len(data.Reports) > 0 {+ rows := make([][]string, len(data.Reports))+ for i, report := range data.Reports {+ rows[i] = []string{+ report.ContainerName,+ report.ImageName,+ report.Policy,+ report.SystemdUnit,+ report.Updated,+ }+ }+ if printErr := cmdutil.PrintTable(cmd, []string{"CONTAINER", "IMAGE", "POLICY", "UNIT", "UPDATED"}, rows); printErr != nil {+ return printErr+ }+ }+ if len(data.Errors) > 0 {+ return fmt.Errorf("auto-update reported %d error(s)", len(data.Errors))+ }+ return nil+ },+ })+ },+ }+ cmd.Flags().BoolVar(&opts.dryRun, "dry-run", false, "Report pending updates without applying them")+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Skip the confirmation prompt")+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)+ return cmd+}diff --git a/cli/pkg/podman/kube.go b/cli/pkg/podman/kube.gonew file mode 100644index 000000000..18096c37a--- /dev/null+++ b/cli/pkg/podman/kube.go@@ -0,0 +1,193 @@+package podman++import (+ "errors"+ "fmt"+ "net/http"+ "os"+ "slices"+ "strconv"+ "strings"++ "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/spf13/cobra"+ "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"+)++func newKubeCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "kube",+ Short: "Play, tear down, and generate Kubernetes YAML",+ }+ cmd.AddCommand(+ newKubePlayCmd(),+ newKubeDownCmd(),+ newKubeGenerateCmd(),+ )+ return cmd+}++func newKubePlayCmd() *cobra.Command {+ var opts struct {+ replace bool+ noStart bool+ networks []string+ }+ cmd := &cobra.Command{+ Use: "play <file>",+ Short: "Create pods from Kubernetes YAML",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ content, err := os.ReadFile(args[0])+ if err != nil {+ return fmt.Errorf("failed to read kube YAML: %w", err)+ }++ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.KubePlayReport]{+ Method: http.MethodPost,+ Path: types.PodmanKube(c.EnvID(), "play"),+ Body: podman.KubePlayRequest{+ YAML: string(content),+ Start: kit.Ternary(opts.noStart, new(false), nil),+ Replace: opts.replace,+ Networks: opts.networks,+ },+ FailureMessage: "failed to play kube YAML",+ Render: func(data podman.KubePlayReport) error {+ failed := slices.ContainsFunc(data.Pods, func(pod podman.KubePlayPod) bool {+ return len(pod.ContainerErrors) > 0+ })+ if !failed {+ output.Success("Kube YAML played successfully")+ }+ for _, volume := range data.Volumes {+ output.KeyValue("Volume", volume.Name)+ }+ if len(data.Pods) == 0 {+ return nil+ }+ rows := make([][]string, len(data.Pods))+ for i, pod := range data.Pods {+ rows[i] = []string{+ pod.ID[:min(len(pod.ID), 12)],+ strconv.Itoa(len(pod.Containers)),+ strings.Join(pod.ContainerErrors, "; "),+ }+ }+ if printErr := cmdutil.PrintTable(cmd, []string{"POD", "CONTAINERS", "ERRORS"}, rows); printErr != nil {+ return printErr+ }+ if failed {+ return errors.New("some containers failed to start")+ }+ return nil+ },+ })+ },+ }+ cmd.Flags().BoolVar(&opts.replace, "replace", false, "Replace existing pods and containers")+ cmd.Flags().BoolVar(&opts.noStart, "no-start", false, "Create the pods without starting them")+ cmd.Flags().StringArrayVar(&opts.networks, "network", nil, "Network to attach the pods to (repeatable)")+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)+ return cmd+}++func newKubeDownCmd() *cobra.Command {+ var opts struct {+ force bool+ }+ cmd := &cobra.Command{+ Use: "down <file>",+ Short: "Remove pods created from Kubernetes YAML",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ content, err := os.ReadFile(args[0])+ if err != nil {+ return fmt.Errorf("failed to read kube YAML: %w", err)+ }++ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.force, fmt.Sprintf("Are you sure you want to tear down the pods in %s?", args[0]))+ if confirmationErr != nil || !confirmed {+ return confirmationErr+ }++ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.KubeDownReport]{+ Method: http.MethodPost,+ Path: types.PodmanKube(c.EnvID(), "down"),+ Body: podman.KubeDownRequest{+ YAML: string(content),+ Force: opts.force,+ },+ FailureMessage: "failed to tear down kube YAML",+ Render: func(data podman.KubeDownReport) error {+ output.Success("Kube YAML torn down successfully")+ output.KeyValue("Stopped pods", len(data.StopReport))+ output.KeyValue("Removed pods", len(data.RmReport))+ return nil+ },+ })+ },+ }+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Also remove volumes created by the YAML and skip the confirmation prompt")+ return cmd+}++func newKubeGenerateCmd() *cobra.Command {+ var opts struct {+ kind podman.KubeGenerateType+ service bool+ }+ cmd := &cobra.Command{+ Use: "generate <name>...",+ Short: "Generate Kubernetes YAML from pods, containers, or volumes",+ Args: cobra.MinimumNArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.KubeGenerateResponse]{+ Method: http.MethodPost,+ Path: types.PodmanKube(c.EnvID(), "generate"),+ Body: podman.KubeGenerateRequest{+ Names: args,+ Type: opts.kind,+ Service: opts.service,+ },+ FailureMessage: "failed to generate kube YAML",+ Render: func(data podman.KubeGenerateResponse) error {+ _, writeErr := fmt.Fprint(output.Stdout(), data.YAML)+ return writeErr+ },+ })+ },+ }+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.kind, "type", "", podman.KubeGenerateTypePod, "Kubernetes kind to generate",+ podman.KubeGenerateTypePod,+ podman.KubeGenerateTypeService,+ podman.KubeGenerateTypeDeployment,+ podman.KubeGenerateTypeDaemonSet,+ podman.KubeGenerateTypeJob,+ )+ cmd.Flags().BoolVar(&opts.service, "service", false, "Also generate a Kubernetes service")+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)+ return cmd+}diff --git a/cli/pkg/podman/podcreate.go b/cli/pkg/podman/podcreate.gonew file mode 100644index 000000000..0b881d8b9--- /dev/null+++ b/cli/pkg/podman/podcreate.go@@ -0,0 +1,379 @@+package podman++import (+ "bufio"+ "cmp"+ "errors"+ "fmt"+ "maps"+ "net/http"+ "os"+ "slices"+ "strconv"+ "strings"++ "github.com/docker/go-connections/nat"+ "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/spf13/cobra"+ "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"+)++var podNetworkModes = []string{"bridge", "host", "none", "private", "slirp4netns", "pasta", "ns"}++type podCreateOptions struct {+ name string+ hostname string+ labels map[string]string+ labelFiles []string+ exitPolicy string+ restart string+ infra bool+ infraImage string+ infraCommand string+ infraName string+ infraConmonPidFile string+ share string+ shareParent bool+ pid string+ ipc string+ uts string+ userns string+ uidMap []string+ gidMap []string+ networks []string+ networkAliases []string+ ip string+ ip6 string+ macAddress string+ publish []string+ dns []string+ dnsSearch []string+ dnsOptions []string+ addHosts []string+ noHosts bool+ noHostname bool+ hostsFile string+ cgroupParent string+ cpus float64+ cpuShares uint64+ cpusetCPUs string+ cpusetMems string+ memory string+ memorySwap string+ blkioWeight uint16+ blkioWeightDevices []string+ deviceReadBps []string+ deviceWriteBps []string+ devices []string+ gpus []string+ volumes []string+ volumesFrom []string+ shmSize string+ shmSizeSystemd string+ securityOpt []string+ sysctl map[string]string+}++func newPodCreateCmd() *cobra.Command {+ var opts podCreateOptions+ cmd := &cobra.Command{+ Use: "create",+ Short: "Create a pod",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ req, err := opts.request(cmd)+ if err != nil {+ return err+ }++ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.PodCreateResponse]{+ Method: http.MethodPost,+ Path: types.PodmanPods(c.EnvID()),+ Body: req,+ FailureMessage: "failed to create pod",+ Render: func(data podman.PodCreateResponse) error {+ output.Success("Pod %s created successfully", opts.name)+ output.KeyValue("ID", data.ID)+ return nil+ },+ })+ },+ }+ flags := cmd.Flags()+ flags.StringVarP(&opts.name, "name", "n", "", "Pod name (required)")+ flags.StringVar(&opts.hostname, "hostname", "", "Pod hostname")+ flags.StringToStringVarP(&opts.labels, "label", "l", nil, "Label (KEY=VALUE)")+ flags.StringArrayVar(&opts.labelFiles, "label-file", nil, "Read labels from a local file of KEY=VALUE lines")+ flags.StringVar(&opts.exitPolicy, "exit-policy", "", "Behaviour when the last container exits (continue or stop)")+ flags.StringVar(&opts.restart, "restart", "", "Restart policy for containers (no, always, on-failure[:N], unless-stopped)")+ flags.BoolVar(&opts.infra, "infra", true, "Create an infra container to share namespaces with")+ flags.StringVar(&opts.infraImage, "infra-image", "", "Image for the infra container")+ flags.StringVar(&opts.infraCommand, "infra-command", "", "Entrypoint of the infra container")+ flags.StringVar(&opts.infraName, "infra-name", "", "Name of the infra container")+ flags.StringVar(&opts.infraConmonPidFile, "infra-conmon-pidfile", "", "Path that receives the infra container's conmon PID")+ flags.StringVar(&opts.share, "share", "", "Comma-separated namespaces to share (default ipc,net,uts; prefix + to add to the default)")+ flags.BoolVar(&opts.shareParent, "share-parent", true, "Use the pod's cgroup as the cgroup parent of its containers")+ flags.StringVar(&opts.pid, "pid", "", "PID namespace (host, private, ns:PATH, container:ID)")+ flags.StringVar(&opts.ipc, "ipc", "", "IPC namespace (host, private, shareable, none, ns:PATH, container:ID)")+ flags.StringVar(&opts.uts, "uts", "", "UTS namespace (host, private, ns:PATH, container:ID)")+ flags.StringVar(&opts.userns, "userns", "", "User namespace (auto, keep-id[:OPTS], host, nomap, ns:PATH)")+ flags.StringSliceVar(&opts.uidMap, "uidmap", nil, "UID mapping CONTAINER:HOST:SIZE")+ flags.StringSliceVar(&opts.gidMap, "gidmap", nil, "GID mapping CONTAINER:HOST:SIZE")+ flags.StringArrayVar(&opts.networks, "network", nil, "Network mode (bridge, host, none, private, slirp4netns[:OPTS], pasta[:OPTS], ns:PATH) or network NAME[:alias=A,ip=IP,mac=MAC,interface_name=IF]")+ flags.StringSliceVar(&opts.networkAliases, "network-alias", nil, "Network-scoped alias on the --network")+ flags.StringVar(&opts.ip, "ip", "", "Static IPv4 address on the --network")+ flags.StringVar(&opts.ip6, "ip6", "", "Static IPv6 address on the --network")+ flags.StringVar(&opts.macAddress, "mac-address", "", "Static MAC address on the --network")+ flags.StringArrayVarP(&opts.publish, "publish", "p", nil, "Publish a port ([hostIp:][hostPort:]containerPort[/protocol])")+ flags.StringSliceVar(&opts.dns, "dns", nil, "DNS server, or none to keep the image's resolv.conf")+ flags.StringSliceVar(&opts.dnsSearch, "dns-search", nil, "DNS search domain")+ flags.StringSliceVar(&opts.dnsOptions, "dns-option", nil, "DNS resolver option")+ flags.StringSliceVar(&opts.addHosts, "add-host", nil, "Extra /etc/hosts entry (HOST:IP)")+ flags.BoolVar(&opts.noHosts, "no-hosts", false, "Use the image's /etc/hosts")+ flags.BoolVar(&opts.noHostname, "no-hostname", false, "Use the image's /etc/hostname")+ flags.StringVar(&opts.hostsFile, "hosts-file", "", "Base file for /etc/hosts, or image or none")+ flags.StringVar(&opts.cgroupParent, "cgroup-parent", "", "Parent cgroup of the pod")+ flags.Float64Var(&opts.cpus, "cpus", 0, "Number of CPUs")+ flags.Uint64VarP(&opts.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)")+ flags.StringVar(&opts.cpusetCPUs, "cpuset-cpus", "", "CPUs allowed to run the pod (0-3, 0,1)")+ flags.StringVar(&opts.cpusetMems, "cpuset-mems", "", "Memory nodes allowed to run the pod (0-3, 0,1)")+ flags.StringVarP(&opts.memory, "memory", "m", "", "Memory limit (512m, 2g)")+ flags.StringVar(&opts.memorySwap, "memory-swap", "", "Memory plus swap limit, or -1 for unlimited swap")+ flags.Uint16Var(&opts.blkioWeight, "blkio-weight", 0, "Block IO weight (10-1000)")+ flags.StringArrayVar(&opts.blkioWeightDevices, "blkio-weight-device", nil, "Per-device block IO weight (MAJOR:MINOR:WEIGHT)")+ flags.StringArrayVar(&opts.deviceReadBps, "device-read-bps", nil, "Per-device read rate limit (MAJOR:MINOR:RATE, e.g. 8:0:1mb)")+ flags.StringArrayVar(&opts.deviceWriteBps, "device-write-bps", nil, "Per-device write rate limit (MAJOR:MINOR:RATE, e.g. 8:0:1mb)")+ flags.StringArrayVar(&opts.devices, "device", nil, "Host device (HOST[:CONTAINER[:PERMISSIONS]])")+ flags.StringSliceVar(&opts.gpus, "gpus", nil, "NVIDIA GPUs to add through CDI, or all")+ flags.StringArrayVarP(&opts.volumes, "volume", "v", nil, "Bind mount or named volume (SOURCE:DESTINATION[:OPTIONS])")+ flags.StringArrayVar(&opts.volumesFrom, "volumes-from", nil, "Mount volumes from a container (CONTAINER[:OPTIONS])")+ flags.StringVar(&opts.shmSize, "shm-size", "", "Size of /dev/shm (64m)")+ flags.StringVar(&opts.shmSizeSystemd, "shm-size-systemd", "", "Size of systemd tmpfs mounts (64m)")+ flags.StringArrayVar(&opts.securityOpt, "security-opt", nil, "Security option (label=disable, seccomp=unconfined)")+ flags.StringToStringVar(&opts.sysctl, "sysctl", nil, "Namespaced kernel parameter (KEY=VALUE)")+ _ = cmd.MarkFlagRequired("name")+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)+ return cmd+}++func (o podCreateOptions) request(cmd *cobra.Command) (podman.PodCreateRequest, error) {+ labels, err := o.allLabels()+ if err != nil {+ return podman.PodCreateRequest{}, err+ }++ ports := make([]podman.PodPortMapping, 0, len(o.publish))+ for _, spec := range o.publish {+ mappings, parseErr := nat.ParsePortSpec(spec)+ if parseErr != nil {+ return podman.PodCreateRequest{}, fmt.Errorf("invalid --publish %q: %w", spec, parseErr)+ }+ for _, mapping := range mappings {+ hostPort, portErr := strconv.ParseUint(cmp.Or(mapping.Binding.HostPort, "0"), 10, 16)+ if portErr != nil {+ return podman.PodCreateRequest{}, fmt.Errorf("invalid --publish %q: %w", spec, portErr)+ }+ ports = append(ports, podman.PodPortMapping{+ ContainerPort: uint16(mapping.Port.Int()),+ HostPort: uint16(hostPort),+ HostIP: mapping.Binding.HostIP,+ Protocol: mapping.Port.Proto(),+ })+ }+ }++ networkMode, networkOptions, networks, err := o.networkSettings()+ if err != nil {+ return podman.PodCreateRequest{}, err+ }++ deviceLimits := func(flag string, values []string) ([]podman.PodDeviceLimit, error) {+ out := make([]podman.PodDeviceLimit, 0, len(values))+ for _, value := range values {+ index := strings.LastIndex(value, ":")+ if index <= 0 {+ return nil, fmt.Errorf("invalid --%s %q: use MAJOR:MINOR:VALUE", flag, value)+ }+ out = append(out, podman.PodDeviceLimit{Device: value[:index], Value: value[index+1:]})+ }+ return out, nil+ }+ weightDevices, err := deviceLimits("blkio-weight-device", o.blkioWeightDevices)+ if err != nil {+ return podman.PodCreateRequest{}, err+ }+ readBps, err := deviceLimits("device-read-bps", o.deviceReadBps)+ if err != nil {+ return podman.PodCreateRequest{}, err+ }+ writeBps, err := deviceLimits("device-write-bps", o.deviceWriteBps)+ if err != nil {+ return podman.PodCreateRequest{}, err+ }++ volumes := make([]podman.PodVolume, 0, len(o.volumes))+ for _, value := range o.volumes {+ parts := strings.SplitN(value, ":", 3)+ if len(parts) < 2 {+ return podman.PodCreateRequest{}, fmt.Errorf("invalid --volume %q: use SOURCE:DESTINATION[:OPTIONS]", value)+ }+ volumes = append(volumes, podman.PodVolume{+ Source: parts[0],+ Destination: parts[1],+ Options: kit.Ternary(len(parts) == 3, strings.Split(parts[len(parts)-1], ","), nil),+ })+ }++ policy, retries, hasRetries := strings.Cut(o.restart, ":")+ restartRetries, err := strconv.ParseUint(cmp.Or(retries, "0"), 10, 32)+ if err != nil {+ return podman.PodCreateRequest{}, fmt.Errorf("invalid --restart %q: %w", o.restart, err)+ }++ share := strings.TrimSpace(o.share)+ noShare := cmd.Flags().Changed("share") && (share == "" || share == "none")+ return podman.PodCreateRequest{+ Name: o.name,+ Hostname: o.hostname,+ Labels: kit.Ternary(len(labels) > 0, labels, nil),+ ExitPolicy: o.exitPolicy,+ RestartPolicy: kit.Ternary(policy == "never", "no", policy),+ RestartRetries: kit.Ternary(hasRetries, new(uint(restartRetries)), nil),+ NoInfra: !o.infra || (noShare && !cmd.Flags().Changed("infra")),+ InfraImage: o.infraImage,+ InfraCommand: strings.Fields(o.infraCommand),+ InfraName: o.infraName,+ InfraConmonPidFile: o.infraConmonPidFile,+ SharedNamespaces: func() []string {+ if share == "" || noShare {+ return nil+ }+ if added, ok := strings.CutPrefix(share, "+"); ok {+ return append([]string{"ipc", "net", "uts"}, strings.Split(added, ",")...)+ }+ return strings.Split(share, ",")+ }(),+ ShareParent: kit.Ternary(cmd.Flags().Changed("share-parent"), new(o.shareParent), nil),+ Pid: o.pid,+ Ipc: o.ipc,+ Uts: o.uts,+ Userns: o.userns,+ UIDMap: o.uidMap,+ GIDMap: o.gidMap,+ NetworkMode: networkMode,+ NetworkOptions: networkOptions,+ Networks: networks,+ PortMappings: ports,+ DNSServers: slices.DeleteFunc(slices.Clone(o.dns), func(server string) bool {+ return server == "none"+ }),+ DNSSearch: o.dnsSearch,+ DNSOptions: o.dnsOptions,+ NoManageResolvConf: slices.Contains(o.dns, "none"),+ AddHosts: o.addHosts,+ NoHosts: o.noHosts,+ NoHostname: o.noHostname,+ HostsFile: o.hostsFile,+ CgroupParent: o.cgroupParent,+ CPUs: o.cpus,+ CPUShares: o.cpuShares,+ CPUSetCPUs: o.cpusetCPUs,+ CPUSetMems: o.cpusetMems,+ Memory: o.memory,+ MemorySwap: o.memorySwap,+ BlkioWeight: o.blkioWeight,+ BlkioWeightDevices: weightDevices,+ DeviceReadBps: readBps,+ DeviceWriteBps: writeBps,+ Devices: o.devices,+ GPUs: o.gpus,+ Volumes: volumes,+ VolumesFrom: o.volumesFrom,+ ShmSize: o.shmSize,+ ShmSizeSystemd: o.shmSizeSystemd,+ SecurityOpt: o.securityOpt,+ Sysctl: o.sysctl,+ }, nil+}++func (o podCreateOptions) allLabels() (map[string]string, error) {+ labels := map[string]string{}+ for _, path := range o.labelFiles {+ file, err := os.Open(path)+ if err != nil {+ return nil, fmt.Errorf("read --label-file: %w", err)+ }+ scanner := bufio.NewScanner(file)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" || strings.HasPrefix(line, "#") {+ continue+ }+ key, value, _ := strings.Cut(line, "=")+ labels[key] = value+ }+ if readErr := cmp.Or(scanner.Err(), file.Close()); readErr != nil {+ return nil, fmt.Errorf("read --label-file %s: %w", path, readErr)+ }+ }+ maps.Copy(labels, o.labels)+ return labels, nil+}++func (o podCreateOptions) networkSettings() (string, []string, []podman.PodNetwork, error) {+ var mode string+ var options []string+ var networks []podman.PodNetwork+ for _, value := range o.networks {+ name, rest, _ := strings.Cut(value, ":")+ if slices.Contains(podNetworkModes, name) {+ mode = kit.Ternary(name == "ns", value, name)+ options = kit.Ternary(name == "ns" || rest == "", options, strings.Split(rest, ","))+ continue+ }+ network := podman.PodNetwork{Name: name}+ for option := range strings.SplitSeq(rest, ",") {+ key, optionValue, _ := strings.Cut(option, "=")+ switch key {+ case "":+ case "alias":+ network.Aliases = append(network.Aliases, optionValue)+ case "ip", "ip6":+ network.StaticIPs = append(network.StaticIPs, optionValue)+ case "mac":+ network.StaticMAC = optionValue+ case "interface_name":+ network.InterfaceName = optionValue+ default:+ return "", nil, nil, fmt.Errorf("invalid --network option %q", option)+ }+ }+ networks = append(networks, network)+ }+ if len(o.networkAliases) == 0 && o.ip == "" && o.ip6 == "" && o.macAddress == "" {+ return mode, options, networks, nil+ }+ if len(networks) != 1 {+ return "", nil, nil, errors.New("--ip, --ip6, --mac-address, and --network-alias need exactly one --network NAME")+ }+ networks[0] = podman.PodNetwork{+ Name: networks[0].Name,+ Aliases: append(networks[0].Aliases, o.networkAliases...),+ StaticIPs: slices.DeleteFunc(append(networks[0].StaticIPs, o.ip, o.ip6), func(ip string) bool {+ return ip == ""+ }),+ StaticMAC: cmp.Or(o.macAddress, networks[0].StaticMAC),+ InterfaceName: networks[0].InterfaceName,+ }+ return mode, options, networks, nil+}diff --git a/cli/pkg/podman/podcreate_test.go b/cli/pkg/podman/podcreate_test.gonew file mode 100644index 000000000..bdc5ccd60--- /dev/null+++ b/cli/pkg/podman/podcreate_test.go@@ -0,0 +1,117 @@+package podman++import (+ "testing"++ "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/spf13/cobra"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestPodCreateOptionsRequest(t *testing.T) {+ tests := []struct {+ name string+ opts podCreateOptions+ want podman.PodCreateRequest+ wantErr string+ }{+ {+ name: "network modes, named networks, and limits",+ opts: podCreateOptions{+ name: "web",+ infra: true,+ share: "+pid",+ restart: "on-failure:3",+ networks: []string{"pasta:--ipv4-only", "backend:alias=api,interface_name=eth1"},+ ip: "10.89.0.10",+ macAddress: "92:d0:c6:0a:29:33",+ publish: []string{"8080:80/tcp"},+ dns: []string{"none", "1.1.1.1"},+ deviceReadBps: []string{"8:0:1mb"},+ volumes: []string{"/srv/data:/data:ro,Z", "cache:/cache"},+ infraCommand: "/catatonit -P",+ labels: map[string]string{"tier": "front"},+ memory: "512m",+ securityOpt: []string{"label=disable"},+ volumesFrom: []string{"seed"},+ blkioWeight: 300,+ cpus: 1.5,+ hostsFile: "none",+ shmSizeSystemd: "32m",+ },+ want: podman.PodCreateRequest{+ Name: "web",+ Labels: map[string]string{"tier": "front"},+ RestartPolicy: "on-failure",+ RestartRetries: new(uint(3)),+ InfraCommand: []string{"/catatonit", "-P"},+ SharedNamespaces: []string{"ipc", "net", "uts", "pid"},+ NetworkMode: "pasta",+ NetworkOptions: []string{"--ipv4-only"},+ Networks: []podman.PodNetwork{{+ Name: "backend",+ Aliases: []string{"api"},+ StaticIPs: []string{"10.89.0.10"},+ StaticMAC: "92:d0:c6:0a:29:33",+ InterfaceName: "eth1",+ }},+ PortMappings: []podman.PodPortMapping{{+ ContainerPort: 80,+ HostPort: 8080,+ Protocol: "tcp",+ }},+ DNSServers: []string{"1.1.1.1"},+ NoManageResolvConf: true,+ HostsFile: "none",+ CPUs: 1.5,+ Memory: "512m",+ BlkioWeight: 300,+ BlkioWeightDevices: []podman.PodDeviceLimit{},+ DeviceReadBps: []podman.PodDeviceLimit{{Device: "8:0", Value: "1mb"}},+ DeviceWriteBps: []podman.PodDeviceLimit{},+ Volumes: []podman.PodVolume{+ {+ Source: "/srv/data",+ Destination: "/data",+ Options: []string{"ro", "Z"},+ },+ {Source: "cache", Destination: "/cache"},+ },+ VolumesFrom: []string{"seed"},+ ShmSizeSystemd: "32m",+ SecurityOpt: []string{"label=disable"},+ },+ },+ {+ name: "static IP without a named network",+ opts: podCreateOptions{+ name: "web",+ infra: true,+ ip: "10.0.0.2",+ },+ wantErr: "need exactly one --network NAME",+ },+ {+ name: "volume without destination",+ opts: podCreateOptions{+ name: "web",+ infra: true,+ volumes: []string{"data"},+ },+ wantErr: "invalid --volume",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := tt.opts.request(&cobra.Command{})+ if tt.wantErr != "" {+ require.ErrorContains(t, err, tt.wantErr)+ return+ }+ require.NoError(t, err)+ assert.Equal(t, tt.want, got)+ })+ }+}diff --git a/cli/pkg/podman/pods.go b/cli/pkg/podman/pods.gonew file mode 100644index 000000000..24f3aca28--- /dev/null+++ b/cli/pkg/podman/pods.go@@ -0,0 +1,186 @@+package podman++import (+ "cmp"+ "fmt"+ "net/http"+ "net/url"+ "strconv"+ "strings"++ "github.com/getarcaneapp/arcane/types/v2/base"+ "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/spf13/cobra"+ "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"+)++func newPodsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "pods",+ Aliases: []string{"pod"},+ Short: "Manage Podman pods",+ }+ cmd.AddCommand(+ newPodListCmd(),+ newPodInspectCmd(),+ newPodCreateCmd(),+ newPodDeleteCmd(),+ )+ for _, action := range []struct{ name, verb string }{+ {name: "start", verb: "Start"},+ {name: "stop", verb: "Stop"},+ {name: "restart", verb: "Restart"},+ } {+ var timeout int+ actionCmd := &cobra.Command{+ Use: action.name + " <pod>",+ Short: action.verb + " a pod",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{+ Method: http.MethodPost,+ Path: types.PodmanPodAction(c.EnvID(), args[0], action.name),+ Body: podman.PodActionRequest{Timeout: kit.Ternary(cmd.Flags().Changed("timeout"), new(timeout), nil)},+ FailureMessage: "failed to " + action.name + " pod",+ Render: func(base.MessageResponse) error {+ output.Success("Pod %s: %s completed", args[0], action.name)+ return nil+ },+ })+ },+ }+ if action.name == "stop" {+ actionCmd.Flags().IntVarP(&timeout, "timeout", "t", 10, "Seconds to wait before killing the pod")+ }+ cmd.AddCommand(actionCmd)+ }+ return cmd+}++func newPodListCmd() *cobra.Command {+ var opts struct {+ limit int+ start int+ all bool+ }+ cmd := &cobra.Command{+ Use: "list",+ Aliases: []string{"ls"},+ Short: "List pods",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[podman.Pod]{+ Resource: "pods",+ Endpoint: types.PodmanPods(c.EnvID()),+ Params: cmdutil.ListParams{+ Resource: "pods",+ Limit: opts.limit,+ FallbackDefault: 20,+ Start: opts.start,+ All: opts.all,+ },+ Headers: []string{"ID", "NAME", "STATUS", "CONTAINERS", "CREATED"},+ Row: func(pod podman.Pod) []string {+ return []string{+ pod.ID[:min(len(pod.ID), 12)],+ pod.Name,+ output.TintStatus(pod.Status),+ strconv.Itoa(len(pod.Containers)),+ pod.Created.Format("2006-01-02 15:04"),+ }+ },+ })+ },+ }+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of pods to show")+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)+ return cmd+}++func newPodInspectCmd() *cobra.Command {+ return &cobra.Command{+ Use: "inspect <pod>",+ Aliases: []string{"get"},+ Short: "Show pod details",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.PodInspect]{+ Method: http.MethodGet,+ Path: types.PodmanPod(c.EnvID(), args[0]),+ FailureMessage: "failed to inspect pod",+ Render: func(data podman.PodInspect) error {+ output.Header("Pod Details")+ output.KeyValue("ID", data.ID)+ output.KeyValue("Name", data.Name)+ output.KeyValue("State", output.TintStatus(data.State))+ output.KeyValue("Created", data.Created.Format("2006-01-02 15:04"))+ output.KeyValue("Hostname", cmp.Or(data.Hostname, "-"))+ output.KeyValue("Infra container", cmp.Or(data.InfraContainerID[:min(len(data.InfraContainerID), 12)], "-"))+ output.KeyValue("Shared namespaces", cmp.Or(strings.Join(data.SharedNamespaces, ", "), "-"))+ output.KeyValue("Containers", data.NumContainers)+ if len(data.Containers) == 0 {+ return nil+ }+ rows := make([][]string, len(data.Containers))+ for i, container := range data.Containers {+ rows[i] = []string{container.ID[:min(len(container.ID), 12)], container.Name, output.TintStatus(container.State)}+ }+ return cmdutil.PrintTable(cmd, []string{"ID", "NAME", "STATE"}, rows)+ },+ })+ },+ }+}++func newPodDeleteCmd() *cobra.Command {+ var opts struct {+ force bool+ }+ cmd := &cobra.Command{+ Use: "delete <pod>",+ Aliases: []string{"rm", "remove"},+ Short: "Delete a pod",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{+ Force: opts.force,+ Prompt: fmt.Sprintf("Are you sure you want to delete pod %s?", args[0]),+ Path: cmdutil.AppendQuery(types.PodmanPod(c.EnvID(), args[0]), url.Values{"force": []string{strconv.FormatBool(opts.force)}}),+ FailureMessage: "failed to delete pod",+ SuccessMessage: fmt.Sprintf("Pod %s deleted successfully", args[0]),+ })+ },+ }+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Stop and remove running containers and skip the confirmation prompt")+ return cmd+}diff --git a/cli/pkg/podman/quadlets.go b/cli/pkg/podman/quadlets.gonew file mode 100644index 000000000..84b813a36--- /dev/null+++ b/cli/pkg/podman/quadlets.go@@ -0,0 +1,267 @@+package podman++import (+ "cmp"+ "fmt"+ "maps"+ "net/http"+ "net/url"+ "os"+ "path/filepath"+ "slices"+ "strings"++ "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/spf13/cobra"+ "go.getarcane.app/kit/pkg"++ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"+)++func newQuadletsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "quadlets",+ Aliases: []string{"quadlet", "q"},+ Short: "Manage Podman quadlets",+ }+ cmd.AddCommand(+ newQuadletListCmd(),+ newQuadletGetCmd(),+ newQuadletInstallCmd(),+ newQuadletDeleteCmd(),+ )+ for _, action := range []struct{ name, verb string }{+ {name: "start", verb: "Start"},+ {name: "stop", verb: "Stop"},+ {name: "restart", verb: "Restart"},+ } {+ cmd.AddCommand(&cobra.Command{+ Use: action.name + " <name>",+ Short: action.verb + " a quadlet's systemd unit",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.UnitStatus]{+ Method: http.MethodPost,+ Path: types.PodmanQuadletAction(c.EnvID(), args[0], action.name),+ FailureMessage: "failed to " + action.name + " quadlet",+ Render: func(data podman.UnitStatus) error {+ output.Success("Quadlet %s: %s completed", args[0], action.name)+ output.KeyValue("Unit", data.Name)+ output.KeyValue("State", output.TintStatus(data.ActiveState)+" ("+data.SubState+")")+ return nil+ },+ })+ },+ })+ }+ return cmd+}++func newQuadletListCmd() *cobra.Command {+ var opts struct {+ names []string+ pods []string+ statuses []string+ limit int+ start int+ all bool+ }+ cmd := &cobra.Command{+ Use: "list",+ Aliases: []string{"ls"},+ Short: "List quadlets",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ query := url.Values{+ "name": opts.names,+ "pod": opts.pods,+ "status": opts.statuses,+ }.Encode()+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[podman.QuadletDetail]{+ Resource: "quadlets",+ Endpoint: types.PodmanQuadlets(c.EnvID()) + kit.Ternary(query != "", "?"+query, ""),+ Params: cmdutil.ListParams{+ Resource: "quadlets",+ Limit: opts.limit,+ FallbackDefault: 20,+ Start: opts.start,+ All: opts.all,+ },+ Headers: []string{"NAME", "UNIT", "TYPE", "STATUS", "APP"},+ Row: func(quadlet podman.QuadletDetail) []string {+ return []string{+ quadlet.Name,+ quadlet.UnitName,+ string(quadlet.Type),+ output.TintStatus(quadlet.Status),+ cmp.Or(quadlet.App, "-"),+ }+ },+ })+ },+ }+ cmd.Flags().StringArrayVar(&opts.names, "name", nil, "Filter by quadlet name")+ cmd.Flags().StringArrayVar(&opts.pods, "pod", nil, "Filter by pod (Podman 6.0+)")+ cmd.Flags().StringArrayVar(&opts.statuses, "status", nil, "Filter by status (Podman 6.0+)")+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of quadlets to show")+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)+ return cmd+}++func newQuadletGetCmd() *cobra.Command {+ return &cobra.Command{+ Use: "get <name>",+ Aliases: []string{"inspect"},+ Short: "Show quadlet details",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.QuadletDetail]{+ Method: http.MethodGet,+ Path: types.PodmanQuadlet(c.EnvID(), args[0]),+ FailureMessage: "failed to get quadlet",+ Render: func(data podman.QuadletDetail) error {+ output.Header("Quadlet Details")+ output.KeyValue("Name", data.Name)+ output.KeyValue("Unit", data.UnitName)+ output.KeyValue("Type", data.Type)+ output.KeyValue("Path", data.Path)+ output.KeyValue("Status", output.TintStatus(data.Status))+ output.KeyValue("App", cmp.Or(data.App, "-"))+ output.KeyValue("Template", kit.Ternary(data.Template, "Yes", "No"))+ if data.UnitStatus != nil {+ output.KeyValue("Load state", data.UnitStatus.LoadState)+ output.KeyValue("Active state", output.TintStatus(data.UnitStatus.ActiveState)+" ("+data.UnitStatus.SubState+")")+ }+ if len(data.Containers) == 0 {+ return nil+ }+ rows := make([][]string, len(data.Containers))+ for i, container := range data.Containers {+ rows[i] = []string{+ container.ID[:min(len(container.ID), 12)],+ strings.Join(container.Names, ", "),+ container.Image,+ output.TintStatus(container.State),+ }+ }+ return cmdutil.PrintTable(cmd, []string{"ID", "NAME", "IMAGE", "STATE"}, rows)+ },+ })+ },+ }+}++func newQuadletInstallCmd() *cobra.Command {+ var opts struct {+ app string+ extraFiles []string+ }+ cmd := &cobra.Command{+ Use: "install <file>",+ Short: "Install a quadlet file",+ Long: "Install a quadlet file. The file name, including its extension (.container, .pod, .kube, .network, .volume, .image, .build), becomes the quadlet name.",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ content, err := os.ReadFile(args[0])+ if err != nil {+ return fmt.Errorf("failed to read quadlet file: %w", err)+ }+ extraFiles := make([]podman.QuadletFile, len(opts.extraFiles))+ for i, extraPath := range opts.extraFiles {+ extraContent, readErr := os.ReadFile(extraPath)+ if readErr != nil {+ return fmt.Errorf("failed to read extra file: %w", readErr)+ }+ extraFiles[i] = podman.QuadletFile{+ Name: filepath.Base(extraPath),+ Content: string(extraContent),+ }+ }++ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.QuadletInstallReport]{+ Method: http.MethodPost,+ Path: types.PodmanQuadlets(c.EnvID()),+ Body: podman.QuadletInstallRequest{+ Name: filepath.Base(args[0]),+ Content: string(content),+ ExtraFiles: extraFiles,+ App: opts.app,+ },+ FailureMessage: "failed to install quadlet",+ Render: func(data podman.QuadletInstallReport) error {+ for _, name := range slices.Sorted(maps.Keys(data.InstalledQuadlets)) {+ output.Success("Installed %s at %s", name, data.InstalledQuadlets[name])+ }+ for _, name := range slices.Sorted(maps.Keys(data.QuadletErrors)) {+ output.Warning("%s: %s", name, data.QuadletErrors[name])+ }+ if len(data.QuadletErrors) > 0 {+ return fmt.Errorf("%d quadlet file(s) failed to install", len(data.QuadletErrors))+ }+ return nil+ },+ })+ },+ }+ cmd.Flags().StringVar(&opts.app, "app", "", "Application the quadlet belongs to (Podman 6.1+)")+ cmd.Flags().StringArrayVar(&opts.extraFiles, "extra-file", nil, "Additional file installed beside the quadlet, such as kube YAML (repeatable)")+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)+ return cmd+}++func newQuadletDeleteCmd() *cobra.Command {+ var opts struct {+ force bool+ }+ cmd := &cobra.Command{+ Use: "delete <name>",+ Aliases: []string{"rm", "remove"},+ Short: "Delete a quadlet",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{+ Force: opts.force,+ Prompt: fmt.Sprintf("Are you sure you want to delete quadlet %s?", args[0]),+ Path: types.PodmanQuadlet(c.EnvID(), args[0]),+ FailureMessage: "failed to delete quadlet",+ SuccessMessage: fmt.Sprintf("Quadlet %s deleted successfully", args[0]),+ })+ },+ }+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")+ return cmd+}diff --git a/cli/pkg/podman/secrets.go b/cli/pkg/podman/secrets.gonew file mode 100644index 000000000..b0612cd90--- /dev/null+++ b/cli/pkg/podman/secrets.go@@ -0,0 +1,255 @@+package podman++import (+ "cmp"+ "fmt"+ "maps"+ "net/http"+ "os"+ "slices"++ "github.com/getarcaneapp/arcane/types/v2/podman"+ "github.com/spf13/cobra"++ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"+)++func newSecretsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "secrets",+ Aliases: []string{"secret"},+ Short: "Manage Podman secrets",+ }+ cmd.AddCommand(+ newSecretListCmd(),+ newSecretInspectCmd(),+ newSecretCreateCmd(),+ newSecretUpdateCmd(),+ newSecretDeleteCmd(),+ )+ return cmd+}++func newSecretListCmd() *cobra.Command {+ var opts struct {+ limit int+ start int+ all bool+ }+ cmd := &cobra.Command{+ Use: "list",+ Aliases: []string{"ls"},+ Short: "List Podman secrets",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[podman.Secret]{+ Resource: "secrets",+ Endpoint: types.PodmanSecrets(c.EnvID()),+ Params: cmdutil.ListParams{+ Resource: "secrets",+ Limit: opts.limit,+ FallbackDefault: 20,+ Start: opts.start,+ All: opts.all,+ },+ Headers: []string{"ID", "NAME", "DRIVER", "CREATED"},+ Row: func(secret podman.Secret) []string {+ return []string{+ secret.ID[:min(len(secret.ID), 12)],+ secret.Spec.Name,+ secret.Spec.Driver.Name,+ secret.CreatedAt.Format("2006-01-02 15:04"),+ }+ },+ })+ },+ }+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of secrets to show")+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)+ return cmd+}++func newSecretInspectCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "inspect <secret>",+ Aliases: []string{"get"},+ Short: "Show Podman secret metadata",+ Long: "Show a Podman secret's metadata. The secret value is never returned.",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.Secret]{+ Method: http.MethodGet,+ Path: types.PodmanSecret(c.EnvID(), args[0]),+ FailureMessage: "failed to inspect Podman secret",+ Render: func(data podman.Secret) error {+ output.Header("Secret Details")+ output.KeyValue("ID", data.ID)+ output.KeyValue("Name", data.Spec.Name)+ output.KeyValue("Driver", cmp.Or(data.Spec.Driver.Name, "-"))+ output.KeyValue("Created", data.CreatedAt.Format("2006-01-02 15:04"))+ output.KeyValue("Updated", data.UpdatedAt.Format("2006-01-02 15:04"))+ for _, key := range slices.Sorted(maps.Keys(data.Spec.Labels)) {+ output.KeyValue("Label "+key, data.Spec.Labels[key])+ }+ return nil+ },+ })+ },+ }+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)+ return cmd+}++func newSecretCreateCmd() *cobra.Command {+ var opts struct {+ file string+ driver string+ labels map[string]string+ }+ cmd := &cobra.Command{+ Use: "create <name>",+ Short: "Create a Podman secret",+ Long: "Create a Podman secret from --file, or from a hidden prompt (or one line of stdin) when --file is omitted.",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ data, err := func() (string, error) {+ if opts.file == "" {+ return output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Secret value", "file")+ }+ content, readErr := os.ReadFile(opts.file)+ return string(content), readErr+ }()+ if err != nil {+ return fmt.Errorf("failed to read secret value: %w", err)+ }++ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.SecretCreateResponse]{+ Method: http.MethodPost,+ Path: types.PodmanSecrets(c.EnvID()),+ Body: podman.SecretCreateRequest{+ Name: args[0],+ Data: data,+ Driver: opts.driver,+ Labels: opts.labels,+ },+ FailureMessage: "failed to create Podman secret",+ Render: func(created podman.SecretCreateResponse) error {+ output.Success("Secret %s created successfully", args[0])+ output.KeyValue("ID", cmp.Or(created.ID, "-"))+ return nil+ },+ })+ },+ }+ cmd.Flags().StringVar(&opts.file, "file", "", "Read the secret value from this file")+ cmd.Flags().StringVar(&opts.driver, "driver", "", "Secret driver (default file)")+ cmd.Flags().StringToStringVar(&opts.labels, "label", nil, "Label (KEY=VALUE)")+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)+ return cmd+}++func newSecretUpdateCmd() *cobra.Command {+ var opts struct {+ file string+ driver string+ labels map[string]string+ }+ cmd := &cobra.Command{+ Use: "update <name>",+ Aliases: []string{"replace"},+ Short: "Replace a Podman secret's value",+ Long: "Replace a Podman secret's value from --file, or from a hidden prompt (or one line of stdin) when --file is omitted. " ++ "Podman replaces the whole secret, so pass --driver and --label again to keep them.",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ data, err := func() (string, error) {+ if opts.file == "" {+ return output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "New secret value", "file")+ }+ content, readErr := os.ReadFile(opts.file)+ return string(content), readErr+ }()+ if err != nil {+ return fmt.Errorf("failed to read secret value: %w", err)+ }++ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.Run(cmd, c, cmdutil.Spec[podman.Secret]{+ Method: http.MethodPut,+ Path: types.PodmanSecret(c.EnvID(), args[0]),+ Body: podman.SecretUpdateRequest{+ Data: data,+ Driver: opts.driver,+ Labels: opts.labels,+ },+ FailureMessage: "failed to update Podman secret",+ Render: func(updated podman.Secret) error {+ output.Success("Secret %s updated successfully", args[0])+ output.KeyValue("ID", cmp.Or(updated.ID, "-"))+ return nil+ },+ })+ },+ }+ cmd.Flags().StringVar(&opts.file, "file", "", "Read the new secret value from this file")+ cmd.Flags().StringVar(&opts.driver, "driver", "", "Secret driver (default file)")+ cmd.Flags().StringToStringVar(&opts.labels, "label", nil, "Label (KEY=VALUE)")+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)+ return cmd+}++func newSecretDeleteCmd() *cobra.Command {+ var opts struct {+ force bool+ }+ cmd := &cobra.Command{+ Use: "delete <secret>",+ Aliases: []string{"rm", "remove"},+ Short: "Delete a Podman secret",+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := cmdutil.ClientFromCommand(cmd)+ if err != nil {+ return err+ }++ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{+ Force: opts.force,+ Prompt: fmt.Sprintf("Are you sure you want to delete secret %s?", args[0]),+ Path: types.PodmanSecret(c.EnvID(), args[0]),+ FailureMessage: "failed to delete Podman secret",+ SuccessMessage: fmt.Sprintf("Secret %s deleted successfully", args[0]),+ })+ },+ }+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")+ return cmd+}diff --git a/cli/pkg/root.go b/cli/pkg/root.goindex 62b3d788f..20000615e 100644--- a/cli/pkg/root.go+++ b/cli/pkg/root.go@@ -36,6 +36,7 @@ import ("github.com/getarcaneapp/arcane/cli/v2/pkg/images""github.com/getarcaneapp/arcane/cli/v2/pkg/jobs""github.com/getarcaneapp/arcane/cli/v2/pkg/networks"+ "github.com/getarcaneapp/arcane/cli/v2/pkg/podman""github.com/getarcaneapp/arcane/cli/v2/pkg/projects""github.com/getarcaneapp/arcane/cli/v2/pkg/registries""github.com/getarcaneapp/arcane/cli/v2/pkg/repos"@@ -130,7 +131,7 @@ func NewRootCommand() *cobra.Command {containers.Command(), imagesCmd, volumes.Command(), networks.Command(), projects.Command(), environments.Command(),registries.Command(), repos.Command(), templates.Command(), settings.Command(), jobs.Command(), system.Command(),updater.Command(), selfupdate.Command(), admin.Command(), gitops.Command(), variables.Command(), activities.Command(),- webhooks.Command(),+ webhooks.Command(), podman.Command(),)instrumentCommandTree(root)return rootdiff --git a/docker/examples/compose.podman-rootful.yaml b/docker/examples/compose.podman-rootful.yamlnew file mode 100644index 000000000..4a604c00b--- /dev/null+++ b/docker/examples/compose.podman-rootful.yaml@@ -0,0 +1,32 @@+# Arcane runs as root (PUID/PGID=0) so the host system bus lets it manage Quadlet units and podman-auto-update.+services:+ arcane:+ image: getarcaneapp/manager:latest+ container_name: arcane+ ports:+ - '3552:3552'+ volumes:+ - /run/podman/podman.sock:/var/run/docker.sock+ - /run/dbus/system_bus_socket:/run/dbus/system_bus_socket+ - arcane-data:/app/data+ environment:+ - ENCRYPTION_KEY=replace_me_with_a_random_32_char_value+ - PUID=0+ - PGID=0+ - TZ=UTC+ security_opt:+ - label=disable+ # Use host cgroup namespace for better container self-detection+ # This allows Arcane to detect its own container ID more reliably+ cgroup: host+ healthcheck:+ test: ['CMD', './arcane', 'health', '--timeout', '2s']+ interval: 10s+ timeout: 3s+ retries: 5+ start_period: 15s+ restart: unless-stopped+ stop_grace_period: 15s++volumes:+ arcane-data:diff --git a/docker/examples/compose.podman-rootless.yaml b/docker/examples/compose.podman-rootless.yamlnew file mode 100644index 000000000..48910dc28--- /dev/null+++ b/docker/examples/compose.podman-rootless.yaml@@ -0,0 +1,38 @@+# Replace 1000 with the uid and gid of the user running rootless Podman.+# Run `loginctl enable-linger <user>` so the user's Podman socket and session bus survive logout.+# keep-id maps that uid into the container unchanged. Arcane starts as root, then switches to PUID/PGID,+# so it reaches the Podman socket and the session bus as their owner.+services:+ arcane:+ image: getarcaneapp/manager:latest+ container_name: arcane+ user: '0:0'+ userns_mode: keep-id+ ports:+ - '3552:3552'+ volumes:+ - /run/user/1000/podman/podman.sock:/var/run/docker.sock+ - /run/user/1000/bus:/run/user/1000/bus+ - arcane-data:/app/data+ environment:+ - ENCRYPTION_KEY=replace_me_with_a_random_32_char_value+ - DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus+ - PUID=1000+ - PGID=1000+ - TZ=UTC+ security_opt:+ - label=disable+ # Use host cgroup namespace for better container self-detection+ # This allows Arcane to detect its own container ID more reliably+ cgroup: host+ healthcheck:+ test: ['CMD', './arcane', 'health', '--timeout', '2s']+ interval: 10s+ timeout: 3s+ retries: 5+ start_period: 15s+ restart: unless-stopped+ stop_grace_period: 15s++volumes:+ arcane-data:diff --git a/docker/examples/quadlet/arcane.container b/docker/examples/quadlet/arcane.containernew file mode 100644index 000000000..65cedbfbc--- /dev/null+++ b/docker/examples/quadlet/arcane.container@@ -0,0 +1,31 @@+# Arcane runs as root (PUID/PGID=0) so the host system bus lets it manage Quadlet units and podman-auto-update.+[Unit]+Description=Arcane+Wants=network-online.target+After=network-online.target++[Container]+Image=docker.io/getarcaneapp/manager:latest+ContainerName=arcane+AutoUpdate=registry+PublishPort=3552:3552+Volume=/run/podman/podman.sock:/var/run/docker.sock+Volume=/run/dbus/system_bus_socket:/run/dbus/system_bus_socket+Volume=arcane-data:/app/data+Environment=ENCRYPTION_KEY=replace_me_with_a_random_32_char_value+Environment=PUID=0+Environment=PGID=0+Environment=TZ=UTC+SecurityLabelDisable=true+HealthCmd=./arcane health --timeout 2s+HealthInterval=10s+HealthTimeout=3s+HealthRetries=5+HealthStartPeriod=15s+StopTimeout=15++[Service]+Restart=always++[Install]+WantedBy=multi-user.target default.targetdiff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 5c54d1c8f..c79f67827 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -580,6 +580,7 @@"dashboard_all_container_summary": "{running} Running · {stopped} Stopped","dashboard_all_no_images": "No images tracked","dashboard_all_image_summary": "{inUse} In Use · {unused} Unused",+ "dashboard_all_podman_environments": "{count} Podman environments","dashboard_all_no_volumes": "No volumes found","dashboard_all_volume_summary": "{inUse} In Use · {unused} Unused","dashboard_updates_up_to_date": "You're up to date",@@ -1309,14 +1310,12 @@"swarm_configs_title": "Configs","swarm_configs_subtitle": "Manage cluster config objects","create_config": "Create Config",- "swarm_configs_create_subtitle": "Create a swarm config with name and data",- "swarm_configs_list_title": "Existing Configs",- "select_one_to_edit_or_remove": "Select one to edit or remove",- "swarm_configs_name_placeholder": "Config name",- "swarm_configs_data_placeholder": "Config data",- "swarm_configs_delete_button": "Delete Config",- "swarm_configs_empty": "No configs found.",- "swarm_configs_immutable_notice": "Swarm configs are immutable. Create a new config and update services to use it instead.",+ "swarm_configs_edit_title": "Edit config",+ "swarm_configs_name_placeholder": "nginx-conf",+ "swarm_configs_name_locked": "Name cannot be changed. Create a new config to use a different name.",+ "swarm_configs_content_label": "Content",+ "swarm_configs_data_placeholder": "Paste the config file contents…",+ "swarm_configs_immutable_notice": "Config content can't be changed. Create a new config to change it, then update services to use it.","swarm_configs_name_required": "Config name is required","swarm_configs_delete_confirm": "Delete config \"{name}\"?","swarm_configs_create_failed": "Failed to create config",@@ -1326,13 +1325,14 @@"swarm_secrets_title": "Secrets","swarm_secrets_subtitle": "Manage cluster secret objects","create_secret": "Create Secret",- "swarm_secrets_create_subtitle": "Create a swarm secret with name and data",- "swarm_secrets_list_title": "Existing Secrets",- "swarm_secrets_name_placeholder": "Secret name",- "swarm_secrets_data_placeholder": "Secret data",- "swarm_secrets_delete_button": "Delete Secret",- "swarm_secrets_empty": "No secrets found.",- "swarm_secrets_immutable_notice": "Swarm secrets are immutable. Create a new secret and update services to use it instead.",+ "swarm_secrets_edit_title": "Edit secret",+ "swarm_secrets_name_placeholder": "db-password",+ "swarm_secrets_name_locked": "Name cannot be changed. Create a new secret to use a different name.",+ "swarm_secrets_data_placeholder": "Enter secret value…",+ "swarm_secrets_value_help": "Secret values cannot be viewed after creation.",+ "swarm_secrets_immutable_notice": "Swarm secret values can't be changed. Create a new secret to rotate it, then update services to use it.",+ "swarm_secrets_label_key_placeholder": "com.example.team",+ "swarm_secrets_label_value_placeholder": "platform","swarm_secrets_name_required": "Secret name is required","swarm_secrets_delete_confirm": "Delete secret \"{name}\"?","swarm_secrets_create_failed": "Failed to create secret",@@ -3642,8 +3642,8 @@"system_backups_recovery_key_save_failed": "Failed to configure the recovery key.","system_backups_enabled_description": "Run an encrypted Arcane recovery backup on the configured cron schedule.","backups_started": "Backup started",- "backups_running": "Backup in progress",- "system_backups_created": "Arcane system backup created successfully.",+ "backups_running": "Backup in progress",+ "system_backups_created": "Arcane system backup created successfully.","system_backups_create_failed": "Failed to create Arcane system backup.","system_backups_policy_saved": "System backup schedule saved.","system_backups_policy_failed": "Failed to save the system backup schedule.",@@ -3671,7 +3671,6 @@"system_backups_discover_description": "Open an Arcane system-recovery repository with its separate recovery key and add its snapshots to this table.","system_backups_discovered": "Found {count} new system backup(s).","system_backups_discover_failed": "Failed to discover system backups. Check the destination and recovery key.",- "containers_status_dead": "Dead","common_add": "Add","common_custom": "Custom","common_mode": "Mode",@@ -3738,87 +3737,87 @@"system_volume_backups_no_matching_volumes": "No matching volumes.","system_volume_backups_ignore_anonymous": "Ignore anonymous volumes","system_volume_backups_ignore_anonymous_description": "Anonymous Docker volumes remain visible above but are skipped during backup runs.",- "jobs_run_queued": "Run queued",- "jobs_submitting": "Queuing…",- "jobs_run_history": "Run history",- "jobs_run_attempts": "Attempts",- "jobs_last_success": "Last success",- "jobs_last_error": "Last error",- "jobs_next_retry": "Next retry",- "jobs_restart_worker": "Restart worker",- "jobs_retry_run": "Retry run",- "jobs_cancel_run": "Cancel pending run",- "jobs_last_confirmed": "Last confirmed",- "jobs_run_empty": "No runs recorded yet.",- "jobs_upgrade_required": "Upgrade this agent to use durable jobs.",- "jobs_offline_status": "This environment is offline. Showing its last confirmed job status.",- "jobs_run_targets": "Target outcomes",- "jobs_run_steps": "Steps",- "jobs_step_progress": "{completed}/{total}",- "jobs_step_failed": "{count} failed",- "jobs_step_prepare": "Prepare check",- "jobs_step_discover": "Discover images",- "jobs_step_check": "Check images",- "jobs_step_scan": "Scan images",- "jobs_step_patch": "Patch images",- "jobs_step_sync": "Sync from Git",- "jobs_step_backup": "Back up",- "jobs_step_tags": "Check tag policies",- "jobs_step_finalize": "Finalize",- "jobs_step_resume": "Check for saved plan",- "jobs_step_candidates": "Select candidates",- "jobs_step_plan": "Plan updates",- "jobs_step_apply": "Apply updates",- "jobs_worker_health": "Worker health",- "jobs_run_previous": "Previous page",- "jobs_run_next": "Next page",- "jobs_run_error": "Unable to load job runs.",- "jobs_worker_restarted": "Worker restart requested",- "jobs_status_unknown": "Unknown",- "jobs_status_healthy": "Healthy",- "jobs_status_degraded": "Degraded",- "jobs_status_stopped": "Stopped",- "jobs_status_starting": "Starting",- "jobs_status_queued": "Queued",- "jobs_status_waiting": "Waiting for environment",- "jobs_status_running": "Running",- "jobs_status_retrying": "Retrying",- "jobs_status_succeeded": "Succeeded",- "jobs_status_partial": "Partial",- "jobs_status_skipped": "Skipped",- "jobs_status_failed": "Failed",- "jobs_status_needs_attention": "Needs attention",- "jobs_status_canceled": "Canceled",- "jobs_containers_load_error": "Failed to load containers",- "jobs_container_label_excluded": "Excluded by label",- "jobs_volume_backup_group": "Volume backups",- "jobs_system_backup_group": "System backups",- "jobs_dynamic_job_name": "{name} · {target}",- "jobs_capability_unknown": "This agent has not been reached yet. Job capabilities will be checked when it reconnects.",- "jobs_remote_status": "Agent status",+ "jobs_run_queued": "Run queued",+ "jobs_submitting": "Queuing…",+ "jobs_run_history": "Run history",+ "jobs_run_attempts": "Attempts",+ "jobs_last_success": "Last success",+ "jobs_last_error": "Last error",+ "jobs_next_retry": "Next retry",+ "jobs_restart_worker": "Restart worker",+ "jobs_retry_run": "Retry run",+ "jobs_cancel_run": "Cancel pending run",+ "jobs_last_confirmed": "Last confirmed",+ "jobs_run_empty": "No runs recorded yet.",+ "jobs_upgrade_required": "Upgrade this agent to use durable jobs.",+ "jobs_offline_status": "This environment is offline. Showing its last confirmed job status.",+ "jobs_run_targets": "Target outcomes",+ "jobs_run_steps": "Steps",+ "jobs_step_progress": "{completed}/{total}",+ "jobs_step_failed": "{count} failed",+ "jobs_step_prepare": "Prepare check",+ "jobs_step_discover": "Discover images",+ "jobs_step_check": "Check images",+ "jobs_step_scan": "Scan images",+ "jobs_step_patch": "Patch images",+ "jobs_step_sync": "Sync from Git",+ "jobs_step_backup": "Back up",+ "jobs_step_tags": "Check tag policies",+ "jobs_step_finalize": "Finalize",+ "jobs_step_resume": "Check for saved plan",+ "jobs_step_candidates": "Select candidates",+ "jobs_step_plan": "Plan updates",+ "jobs_step_apply": "Apply updates",+ "jobs_worker_health": "Worker health",+ "jobs_run_previous": "Previous page",+ "jobs_run_next": "Next page",+ "jobs_run_error": "Unable to load job runs.",+ "jobs_worker_restarted": "Worker restart requested",+ "jobs_status_unknown": "Unknown",+ "jobs_status_healthy": "Healthy",+ "jobs_status_degraded": "Degraded",+ "jobs_status_stopped": "Stopped",+ "jobs_status_starting": "Starting",+ "jobs_status_queued": "Queued",+ "jobs_status_waiting": "Waiting for environment",+ "jobs_status_running": "Running",+ "jobs_status_retrying": "Retrying",+ "jobs_status_succeeded": "Succeeded",+ "jobs_status_partial": "Partial",+ "jobs_status_skipped": "Skipped",+ "jobs_status_failed": "Failed",+ "jobs_status_needs_attention": "Needs attention",+ "jobs_status_canceled": "Canceled",+ "jobs_containers_load_error": "Failed to load containers",+ "jobs_container_label_excluded": "Excluded by label",+ "jobs_volume_backup_group": "Volume backups",+ "jobs_system_backup_group": "System backups",+ "jobs_dynamic_job_name": "{name} · {target}",+ "jobs_capability_unknown": "This agent has not been reached yet. Job capabilities will be checked when it reconnects.",+ "jobs_remote_status": "Agent status","jobs_target_runs": "Targets ({count})","jobs_run_all": "Run all","jobs_local_health_check": "Local environment health","jobs_health_check": "Environment health",- "jobs_health_scope_description": "Checks the health and connectivity of this environment.",- "editor_compose_updater_detail": "Image update policy",- "editor_compose_updater_info": "Project defaults apply to all services. Service updater fields override project defaults. Explicit updater labels take precedence for each field.",- "editor_compose_updater_enabled_detail": "Enable image updates",- "editor_compose_updater_enabled_info": "Boolean. Set to false to disable automatic update installation for the affected services. This does not stop update checks; use update-check: false for that.",- "editor_compose_updater_strategy_detail": "Update strategy",- "editor_compose_updater_strategy_info": "Defaults to digest: the configured tag is kept and only its image digest is followed. Set auto to let complete stable semantic version tags follow newer eligible tags, or tag to require version-based selection. A constraint or tag-pattern without a strategy also enables version-based selection.",- "editor_compose_updater_constraint_detail": "Version constraint",- "editor_compose_updater_constraint_info": "Semantic version constraint for tag updates, such as 3.x or >=3.1.0 <4.0.0. Without a constraint, updates stay within the current major, or the current minor for 0.x.",- "editor_compose_updater_tag_pattern_detail": "Tag pattern",- "editor_compose_updater_tag_pattern_info": "Regular expression matched against the whole tag. Use a named version capture to select a variant, such as (?P<version>\\d+\\.\\d+\\.\\d+)-alpine.",- "activity_type_job_run": "Automation run",- "jobs_resolve_run": "Resolve after review",- "jobs_resolve_description": "Confirm you have reviewed this interrupted run and checked its results. Resolving it preserves its history and allows later scheduled work to proceed. It does not run updates or mark this run successful.",- "jobs_resolution_details": "Resolved by {user} on {date}",- "jobs_activity_summary": "Run activity",- "jobs_activity_output": "Operation output",- "jobs_attention_schedule_blocked": "This run needs review and blocks later runs of this job.",- "jobs_resolution_reason": "Resolution reason",+ "jobs_health_scope_description": "Checks the health and connectivity of this environment.",+ "editor_compose_updater_detail": "Image update policy",+ "editor_compose_updater_info": "Project defaults apply to all services. Service updater fields override project defaults. Explicit updater labels take precedence for each field.",+ "editor_compose_updater_enabled_detail": "Enable image updates",+ "editor_compose_updater_enabled_info": "Boolean. Set to false to disable automatic update installation for the affected services. This does not stop update checks; use update-check: false for that.",+ "editor_compose_updater_strategy_detail": "Update strategy",+ "editor_compose_updater_strategy_info": "Defaults to digest: the configured tag is kept and only its image digest is followed. Set auto to let complete stable semantic version tags follow newer eligible tags, or tag to require version-based selection. A constraint or tag-pattern without a strategy also enables version-based selection.",+ "editor_compose_updater_constraint_detail": "Version constraint",+ "editor_compose_updater_constraint_info": "Semantic version constraint for tag updates, such as 3.x or >=3.1.0 <4.0.0. Without a constraint, updates stay within the current major, or the current minor for 0.x.",+ "editor_compose_updater_tag_pattern_detail": "Tag pattern",+ "editor_compose_updater_tag_pattern_info": "Regular expression matched against the whole tag. Use a named version capture to select a variant, such as (?P<version>\\d+\\.\\d+\\.\\d+)-alpine.",+ "activity_type_job_run": "Automation run",+ "jobs_resolve_run": "Resolve after review",+ "jobs_resolve_description": "Confirm you have reviewed this interrupted run and checked its results. Resolving it preserves its history and allows later scheduled work to proceed. It does not run updates or mark this run successful.",+ "jobs_resolution_details": "Resolved by {user} on {date}",+ "jobs_activity_summary": "Run activity",+ "jobs_activity_output": "Operation output",+ "jobs_attention_schedule_blocked": "This run needs review and blocks later runs of this job.",+ "jobs_resolution_reason": "Resolution reason","git_repository_url_placeholder": "https://github.com/user/repo.git","git_repository_token_url_change": "The repository URL has changed. Re-enter the stored token or select Clear stored token before saving.","git_repository_ssh_key_url_change": "The repository URL has changed. Re-enter the stored SSH key or select Clear stored SSH key before saving.",@@ -3836,159 +3835,422 @@"container_port_placeholder": "80","protocol_tcp": "TCP","protocol_udp": "UDP",- "features_title": "Features",- "features_vulnerability_management": "Vulnerability management",- "features_vulnerability_description": "Enable vulnerability scanning, reports, and scan-based image patching. Turning this off retains saved reports and settings and lets active work finish. Standalone image patching remains available. Turning it back on restores your saved schedules.",- "features_vulnerability_disabled": "Vulnerability management is disabled for this environment. Saved reports and settings are retained.",- "features_unsupported": "Upgrade this environment’s Arcane agent to manage feature availability. Its existing behavior is unchanged.",- "features_unavailable": "Feature settings are unavailable. Check the environment connection and try again.",- "features_environment_override": "This feature setting is managed by an environment variable. Change FEATURE_VULNERABILITY_MANAGEMENT_ENABLED on this environment to update it.",- "features_swarm_description": "Show Swarm services, stacks, nodes, and cluster management for this environment. Turning this off hides Swarm from navigation.",- "features_swarm_locked": "This environment is part of an active swarm cluster, so Swarm stays enabled. Leave the swarm to turn it off.",- "features_swarm_environment_override": "This feature setting is managed by an environment variable. Change FEATURE_SWARM_ENABLED on this environment to update it.",- "history": "History",- "destination": "Destination",- "changes": "Changes",- "conflicts": "Conflicts",- "added": "Added",- "modified": "Modified",- "removed": "Removed",- "resolve": "Resolve",- "git_backup": "Git Backup",- "back_up_now": "Back up now",- "back_up_to_git": "Back up to Git",- "not_backed_up_to_git": "This project is not backed up to Git",- "not_backed_up_yet": "Not backed up yet",- "pending_changes": "Pending changes",- "backing_up": "Backing up",- "backed_up": "Backed up",- "needs_attention": "Needs attention",- "last_backup": "Last backup",- "last_check": "Last check",- "backup_started": "Backup started",- "backup_failed": "Backup failed",- "backup_history": "Backup History",- "backup_history_empty": "No backups have been pushed to this repository yet",- "backup_history_load_failed": "Failed to load the backup history",- "backup_revision_load_failed": "Failed to load this revision",- "changed_files_count": "{count} files",- "no_file_changes": "No file changes in this revision",- "resolve_backup": "Resolve Backup",- "backup_preview_load_failed": "Failed to load the backup preview",- "backup_files_changed_in_repository": "Backup files changed in the repository",- "backup_folder_occupied": "The backup folder already contains other files",- "backup_up_to_date": "The repository is up to date",- "no_pending_changes": "No pending changes",- "use_arcane_files": "Use Arcane files",- "use_arcane_files_description": "Arcane's current files replace the backup files in the repository in a new commit. Existing history is kept.",- "backup_resolved": "Backup resolved",- "backup_resolve_failed": "Failed to resolve the backup",- "disconnect_backup_title": "Stop backing up \"{name}\" to Git?",- "disconnect_backup_message": "Arcane stops backing this project up to Git. Local files and the repository history are kept.",- "disconnect_backup_success": "Git backup disconnected",- "disconnect_backup_failed": "Failed to disconnect the Git backup",- "direction": "Direction",- "deploy_from_git": "Deploy from Git",- "deploy_from_git_description": "Configuration lives in the repository; Arcane pulls it in",- "back_up_to_git_description": "Configuration lives in Arcane; saved changes are committed to the repository",- "deployments": "Deployments",- "backups": "Backups",- "recent_backups": "Recent backups",- "files_in_last_backup": "Files in last backup",- "file_limit": "{limit} limit",- "on_save": "On save",- "pull_from_git": "Pull from Git",- "backup_state": "Backup state",- "backup_completed": "Backup completed",- "destination_folder": "Destination folder",- "destination_folder_description": "Folder in the repository that receives this project's files.",- "destination_folder_locked": "To move the backup somewhere else, disconnect it and connect it again.",- "destination_folder_required": "Destination folder is required",- "destination_folder_invalid": "Enter a folder inside the repository, without a leading slash",- "included_files": "Included files",- "included_files_description": "The compose file is always included.",- "environment_file": "Environment file",- "environment_file_warning": "Environment files often contain secrets. Their contents will be stored in the repository history. This is usually not recommended.",- "include_environment_file": "Include environment file",- "include_environment_file_description": "Commit the project's .env file with the backup.",- "automatic_backup": "Automatic backup",- "automatic_backup_description": "Check for changes on a schedule.",- "back_up_on_save": "Back up on save",- "back_up_on_save_description": "Commit right after changes are saved in Arcane.",- "check_interval": "Check interval",- "save_and_back_up": "Save and back up",- "project_backup_name": "{name} backup",- "project_required": "Select a project",- "no_project_files": "No files found for this project",- "repository_path": "Repository Path",- "every": "every",- "minutes": "minutes",- "commits_files_to": "Commits {count} file(s) to",- "create_new_project": "Create a new project",- "link_existing_project_description": "Link an existing project instead of creating one. Its files are replaced from the repository; local .env values are kept.",- "containers_processes_title": "Processes",- "containers_processes_description": "Processes running inside the container, as reported by Docker. Refreshes every few seconds.",- "containers_processes_unavailable": "Container is not running. Processes unavailable.",- "containers_processes_empty": "No processes reported",- "projects_empty_title": "No projects yet",- "projects_empty_description": "A project deploys a Compose file and its environment together. Create one to get started.",- "registries_empty_title": "No container registries",- "registries_empty_description": "Add a registry to pull private images with stored credentials.",- "s3_destinations_empty_title": "No S3 destinations",- "s3_destinations_empty_description": "Add an S3-compatible destination to store backups away from this server.",- "image_build_history_empty_title": "No builds yet",- "image_build_history_empty_description": "Builds you start from the Build Workspace tab will appear here.",- "system_backups_empty_title": "No backups yet",- "system_backups_empty_description": "Create a backup or set up a schedule to protect Arcane's data.",- "security_no_images_description": "Pull or build an image first, then scan it for vulnerabilities.",- "security_not_scanned_title": "No images scanned yet",- "security_not_scanned_description": "Vulnerability results appear after an image is scanned. No results here does not mean no vulnerabilities.",- "security_no_findings_description": "Scanned images have no recorded vulnerabilities.",- "git_sync_add_description": "Connect a Git repository path to this environment and keep the project in sync with it.",- "environments_settings_offline_title": "Environment offline",- "environments_settings_offline_description": "These settings load from the environment and are unavailable until it reconnects. Your place on this tab is kept.",- "build_workspace_unavailable_title": "Build workspace unavailable",- "build_workspace_unavailable_description": "Arcane could not use the configured Builds Directory. Check that the path exists and is writable by Arcane, or change it in build settings.",- "build_workspace_open_settings": "Open build settings",- "build_workspace_ask_admin": "Ask an administrator to check the Builds Directory setting.",- "port_link_base_server_url_hint": "Opens {url}, built from this environment's Base Server URL.",- "volumes_size_calculation_failed": "Couldn't calculate volume sizes: {error}",- "volumes_size_not_reported": "Size not reported by this volume's driver",- "jobs_summary_failing": "Failing",- "jobs_last_run": "Last run",- "jobs_never_run": "Never run",- "jobs_prerequisites": "Prerequisites",- "jobs_prerequisite_met": "Met",- "jobs_prerequisite_unmet": "Not met",- "jobs_empty_title": "No automations for this environment",- "jobs_system_description": "Built-in jobs that always run. Schedules can still be adjusted.",- "environments_agent_mtls_downloads_label": "Certificate files",- "environments_agent_mtls_downloads_description": "Download the full bundle, or the certificate and key separately.",- "timeouts_seconds_help": "Timeout in seconds ({range})",- "settings_section_avatars": "Avatars",- "settings_section_avatars_description": "How user avatars are sourced and uploaded.",- "roles_details_section": "Role details",- "security_trivy_server_section": "Remote server",- "security_trivy_resource_section": "Resource limits",- "all_environments_preview": "All environments (preview)",- "all_environments_preview_description": "Resource lists show and act on every enabled environment, with an Environment column.",- "all_environments_preview_turn_off": "Turn off preview",- "all_environments_request_failed": "Request to {environment} failed",- "all_environments_confirm_note": "This runs on all {count} environments.",- "all_environments_count": "{count} environments",- "all_environments_unavailable": "Not shown, these environments could not be loaded: {environments}",- "all_environments_not_included": "not included: more than {limit} environments are shown at once",- "all_environments_limit": "Environment limit",- "all_environments_limit_description": "Maximum environments a list includes, for every user. Environments beyond the limit are reported as not included.",- "all_environments_limit_help": "Enter a whole number from 2 to 256.",- "environment_colors": "Environment colors",- "environment_colors_description": "Colors for environment names in resource lists while the all environments preview is on.",- "environment_color_in_use": "That color is already used by another environment",- "environment_label_style": "Environment labels",- "environment_label_style_description": "Show the environment name in resource lists, or just its color dot with the name on hover.",- "environment_label_style_name": "Name",- "environment_label_style_dot": "Color dot",- "environment_column_short": "Env",- "previews": "Previews",- "previews_description": "Preview features are still in development. They may not work as expected and are subject to change or removal."+ "features_title": "Features",+ "features_vulnerability_management": "Vulnerability management",+ "features_vulnerability_description": "Enable vulnerability scanning, reports, and scan-based image patching. Turning this off retains saved reports and settings and lets active work finish. Standalone image patching remains available. Turning it back on restores your saved schedules.",+ "features_vulnerability_disabled": "Vulnerability management is disabled for this environment. Saved reports and settings are retained.",+ "features_unsupported": "Upgrade this environment’s Arcane agent to manage feature availability. Its existing behavior is unchanged.",+ "features_unavailable": "Feature settings are unavailable. Check the environment connection and try again.",+ "features_environment_override": "This feature setting is managed by an environment variable. Change FEATURE_VULNERABILITY_MANAGEMENT_ENABLED on this environment to update it.",+ "features_swarm_description": "Show Swarm services, stacks, nodes, and cluster management for this environment. Turning this off hides Swarm from navigation.",+ "features_swarm_locked": "This environment is part of an active swarm cluster, so Swarm stays enabled. Leave the swarm to turn it off.",+ "features_swarm_environment_override": "This feature setting is managed by an environment variable. Change FEATURE_SWARM_ENABLED on this environment to update it.",+ "history": "History",+ "destination": "Destination",+ "changes": "Changes",+ "conflicts": "Conflicts",+ "added": "Added",+ "modified": "Modified",+ "removed": "Removed",+ "resolve": "Resolve",+ "git_backup": "Git Backup",+ "back_up_now": "Back up now",+ "back_up_to_git": "Back up to Git",+ "not_backed_up_to_git": "This project is not backed up to Git",+ "not_backed_up_yet": "Not backed up yet",+ "pending_changes": "Pending changes",+ "backing_up": "Backing up",+ "backed_up": "Backed up",+ "needs_attention": "Needs attention",+ "last_backup": "Last backup",+ "last_check": "Last check",+ "backup_started": "Backup started",+ "backup_failed": "Backup failed",+ "backup_history": "Backup History",+ "backup_history_empty": "No backups have been pushed to this repository yet",+ "backup_history_load_failed": "Failed to load the backup history",+ "backup_revision_load_failed": "Failed to load this revision",+ "changed_files_count": "{count} files",+ "no_file_changes": "No file changes in this revision",+ "resolve_backup": "Resolve Backup",+ "backup_preview_load_failed": "Failed to load the backup preview",+ "backup_files_changed_in_repository": "Backup files changed in the repository",+ "backup_folder_occupied": "The backup folder already contains other files",+ "backup_up_to_date": "The repository is up to date",+ "no_pending_changes": "No pending changes",+ "use_arcane_files": "Use Arcane files",+ "use_arcane_files_description": "Arcane's current files replace the backup files in the repository in a new commit. Existing history is kept.",+ "backup_resolved": "Backup resolved",+ "backup_resolve_failed": "Failed to resolve the backup",+ "disconnect_backup_title": "Stop backing up \"{name}\" to Git?",+ "disconnect_backup_message": "Arcane stops backing this project up to Git. Local files and the repository history are kept.",+ "disconnect_backup_success": "Git backup disconnected",+ "disconnect_backup_failed": "Failed to disconnect the Git backup",+ "direction": "Direction",+ "deploy_from_git": "Deploy from Git",+ "deploy_from_git_description": "Configuration lives in the repository; Arcane pulls it in",+ "back_up_to_git_description": "Configuration lives in Arcane; saved changes are committed to the repository",+ "deployments": "Deployments",+ "backups": "Backups",+ "recent_backups": "Recent backups",+ "files_in_last_backup": "Files in last backup",+ "file_limit": "{limit} limit",+ "on_save": "On save",+ "pull_from_git": "Pull from Git",+ "backup_state": "Backup state",+ "backup_completed": "Backup completed",+ "destination_folder": "Destination folder",+ "destination_folder_description": "Folder in the repository that receives this project's files.",+ "destination_folder_locked": "To move the backup somewhere else, disconnect it and connect it again.",+ "destination_folder_required": "Destination folder is required",+ "destination_folder_invalid": "Enter a folder inside the repository, without a leading slash",+ "included_files": "Included files",+ "included_files_description": "The compose file is always included.",+ "environment_file": "Environment file",+ "environment_file_warning": "Environment files often contain secrets. Their contents will be stored in the repository history. This is usually not recommended.",+ "include_environment_file": "Include environment file",+ "include_environment_file_description": "Commit the project's .env file with the backup.",+ "automatic_backup": "Automatic backup",+ "automatic_backup_description": "Check for changes on a schedule.",+ "back_up_on_save": "Back up on save",+ "back_up_on_save_description": "Commit right after changes are saved in Arcane.",+ "check_interval": "Check interval",+ "save_and_back_up": "Save and back up",+ "project_backup_name": "{name} backup",+ "project_required": "Select a project",+ "no_project_files": "No files found for this project",+ "repository_path": "Repository Path",+ "every": "every",+ "minutes": "minutes",+ "commits_files_to": "Commits {count} file(s) to",+ "create_new_project": "Create a new project",+ "link_existing_project_description": "Link an existing project instead of creating one. Its files are replaced from the repository; local .env values are kept.",+ "containers_processes_title": "Processes",+ "containers_processes_description": "Processes running inside the container, as reported by Docker. Refreshes every few seconds.",+ "containers_processes_unavailable": "Container is not running. Processes unavailable.",+ "containers_processes_empty": "No processes reported",+ "projects_empty_title": "No projects yet",+ "projects_empty_description": "A project deploys a Compose file and its environment together. Create one to get started.",+ "registries_empty_title": "No container registries",+ "registries_empty_description": "Add a registry to pull private images with stored credentials.",+ "s3_destinations_empty_title": "No S3 destinations",+ "s3_destinations_empty_description": "Add an S3-compatible destination to store backups away from this server.",+ "image_build_history_empty_title": "No builds yet",+ "image_build_history_empty_description": "Builds you start from the Build Workspace tab will appear here.",+ "system_backups_empty_title": "No backups yet",+ "system_backups_empty_description": "Create a backup or set up a schedule to protect Arcane's data.",+ "security_no_images_description": "Pull or build an image first, then scan it for vulnerabilities.",+ "security_not_scanned_title": "No images scanned yet",+ "security_not_scanned_description": "Vulnerability results appear after an image is scanned. No results here does not mean no vulnerabilities.",+ "security_no_findings_description": "Scanned images have no recorded vulnerabilities.",+ "git_sync_add_description": "Connect a Git repository path to this environment and keep the project in sync with it.",+ "environments_settings_offline_title": "Environment offline",+ "environments_settings_offline_description": "These settings load from the environment and are unavailable until it reconnects. Your place on this tab is kept.",+ "build_workspace_unavailable_title": "Build workspace unavailable",+ "build_workspace_unavailable_description": "Arcane could not use the configured Builds Directory. Check that the path exists and is writable by Arcane, or change it in build settings.",+ "build_workspace_open_settings": "Open build settings",+ "build_workspace_ask_admin": "Ask an administrator to check the Builds Directory setting.",+ "port_link_base_server_url_hint": "Opens {url}, built from this environment's Base Server URL.",+ "volumes_size_calculation_failed": "Couldn't calculate volume sizes: {error}",+ "volumes_size_not_reported": "Size not reported by this volume's driver",+ "jobs_summary_failing": "Failing",+ "jobs_last_run": "Last run",+ "jobs_never_run": "Never run",+ "jobs_prerequisites": "Prerequisites",+ "jobs_prerequisite_met": "Met",+ "jobs_prerequisite_unmet": "Not met",+ "jobs_empty_title": "No automations for this environment",+ "jobs_system_description": "Built-in jobs that always run. Schedules can still be adjusted.",+ "environments_agent_mtls_downloads_label": "Certificate files",+ "environments_agent_mtls_downloads_description": "Download the full bundle, or the certificate and key separately.",+ "timeouts_seconds_help": "Timeout in seconds ({range})",+ "settings_section_avatars": "Avatars",+ "settings_section_avatars_description": "How user avatars are sourced and uploaded.",+ "roles_details_section": "Role details",+ "security_trivy_server_section": "Remote server",+ "security_trivy_resource_section": "Resource limits",+ "all_environments_preview": "All environments (preview)",+ "all_environments_preview_description": "Resource lists show and act on every enabled environment, with an Environment column.",+ "all_environments_preview_turn_off": "Turn off preview",+ "all_environments_request_failed": "Request to {environment} failed",+ "all_environments_confirm_note": "This runs on all {count} environments.",+ "all_environments_count": "{count} environments",+ "all_environments_unavailable": "Not shown, these environments could not be loaded: {environments}",+ "all_environments_not_included": "not included: more than {limit} environments are shown at once",+ "all_environments_limit": "Environment limit",+ "all_environments_limit_description": "Maximum environments a list includes, for every user. Environments beyond the limit are reported as not included.",+ "all_environments_limit_help": "Enter a whole number from 2 to 256.",+ "environment_colors": "Environment colors",+ "environment_colors_description": "Colors for environment names in resource lists while the all environments preview is on.",+ "environment_color_in_use": "That color is already used by another environment",+ "environment_label_style": "Environment labels",+ "environment_label_style_description": "Show the environment name in resource lists, or just its color dot with the name on hover.",+ "environment_label_style_name": "Name",+ "environment_label_style_dot": "Color dot",+ "environment_column_short": "Env",+ "previews": "Previews",+ "previews_description": "Preview features are still in development. They may not work as expected and are subject to change or removal.",+ "podman": "Podman",+ "podman_action_success": "{action} completed for {name}",+ "podman_comma_separated": "Separate multiple values with commas.",+ "podman_force_remove": "Stop and remove running containers",+ "podman_managed_by_quadlet": "Managed by quadlet",+ "podman_quadlet_update_disabled": "This container is managed by a quadlet and systemd. Arcane does not edit, redeploy, or auto-update it; updates run through Podman auto-update.",+ "podman_pids": "PIDs",+ "podman_unit": "Systemd unit",+ "podman_unit_load_state": "Load state",+ "podman_unit_active_state": "Active state",+ "podman_pod": "pod",+ "podman_pods_title": "Pods",+ "podman_pods_subtitle": "Groups of containers that share namespaces on this Podman host",+ "podman_pods_total": "Total pods",+ "podman_pods_prune": "Prune pods",+ "podman_pods_prune_confirm": "Remove all stopped pods? This action cannot be undone.",+ "podman_pods_prune_failed": "Failed to prune pods",+ "podman_pods_prune_success": "Removed {count} pod(s)",+ "podman_pod_create_description": "Create a pod that containers can join.",+ "podman_updates_paused": "Live updates stopped. Showing the last loaded state.",+ "podman_pod_device_limit_device_placeholder": "8:0",+ "podman_pod_name_placeholder": "web-pod",+ "podman_pod_hostname_placeholder": "web",+ "podman_pod_network_namespace_path_placeholder": "/run/netns/web",+ "podman_pod_network_name_placeholder": "podman",+ "podman_pod_network_aliases_placeholder": "api, web",+ "podman_pod_network_ip_placeholder": "10.89.0.10",+ "podman_pod_network_mac_placeholder": "92:d0:c6:0a:29:33",+ "podman_pod_network_interface_placeholder": "eth1",+ "podman_pod_dns_servers_placeholder": "1.1.1.1, 9.9.9.9",+ "podman_pod_dns_search_placeholder": "example.com",+ "podman_pod_dns_options_placeholder": "ndots:2, timeout:3",+ "podman_pod_host_name_placeholder": "db.internal",+ "podman_pod_host_ip_placeholder": "10.0.0.5",+ "podman_pod_hosts_file_placeholder": "/etc/hosts",+ "podman_pod_cpus_placeholder": "1.5",+ "podman_pod_cpu_shares_placeholder": "1024",+ "podman_pod_cpuset_cpus_placeholder": "0-3",+ "podman_pod_cpuset_mems_placeholder": "0-1",+ "podman_pod_memory_placeholder": "512m",+ "podman_pod_memory_swap_placeholder": "1g",+ "podman_pod_blkio_weight_placeholder": "500",+ "podman_pod_cgroup_parent_placeholder": "machine.slice",+ "podman_pod_volume_source_placeholder": "/srv/web",+ "podman_pod_volume_target_placeholder": "/data",+ "podman_pod_volume_options_placeholder": "ro, Z",+ "podman_pod_volumes_from_placeholder": "data-seed:ro",+ "podman_pod_shm_size_placeholder": "64m",+ "podman_pod_shm_size_systemd_placeholder": "64m",+ "podman_pod_device_placeholder": "/dev/fuse",+ "podman_pod_gpus_placeholder": "all",+ "podman_pod_shared_namespaces_placeholder": "ipc, net, uts",+ "podman_pod_pid_namespace_placeholder": "private",+ "podman_pod_ipc_namespace_placeholder": "shareable",+ "podman_pod_uts_namespace_placeholder": "private",+ "podman_pod_user_namespace_placeholder": "keep-id",+ "podman_pod_uid_map_placeholder": "0:100000:65536",+ "podman_pod_gid_map_placeholder": "0:100000:65536",+ "podman_pod_security_opt_placeholder": "label=disable",+ "podman_pod_infra_image_placeholder": "registry.k8s.io/pause:3.9",+ "podman_pod_infra_command_placeholder": "/catatonit -P",+ "podman_pod_infra_name_placeholder": "web-pod-infra",+ "podman_pod_infra_conmon_pidfile_placeholder": "/run/user/1000/web-pod-infra.pid",+ "podman_pod_network_options_pasta_placeholder": "--ipv4-only, -T 8080",+ "podman_pod_network_options_slirp_placeholder": "port_handler=slirp4netns, mtu=1500",+ "podman_pod_sysctl_key_placeholder": "net.ipv4.ip_unprivileged_port_start",+ "podman_pod_sysctl_value_placeholder": "80",+ "podman_pod_label_key_placeholder": "app",+ "podman_pod_label_value_placeholder": "web",+ "podman_pod_blkio_weight_device_placeholder": "200",+ "podman_pod_device_read_bps_placeholder": "10mb",+ "podman_pod_device_write_bps_placeholder": "5mb",+ "podman_pod_shared_namespaces": "Shared namespaces",+ "podman_pod_shared_namespaces_description": "Namespaces shared between pod members, for example ipc, net, uts.",+ "podman_pod_no_infra": "Without infra container",+ "podman_pod_no_infra_description": "Create the pod without an infra container. Shared namespaces and published ports need one.",+ "podman_pod_infra": "Infra container",+ "podman_pod_name_invalid": "Start with a letter or digit, then use letters, digits, underscores, dots, or dashes.",+ "podman_pod_section_networking": "Networking",+ "podman_pod_section_dns_hosts": "DNS & hosts",+ "podman_pod_section_namespaces": "Namespaces & security",+ "podman_pod_section_storage": "Storage & devices",+ "podman_pod_section_lifecycle": "Lifecycle",+ "podman_pod_exit_policy": "Exit policy",+ "podman_pod_exit_policy_description": "What the pod does when its last container exits.",+ "podman_pod_exit_policy_continue": "Keep running",+ "podman_pod_exit_policy_stop": "Stop the pod",+ "podman_pod_restart_policy_description": "Restart policy applied to every container in the pod.",+ "podman_pod_restart_policy_default": "Container default",+ "podman_pod_restart_retries_description": "Restart attempts before giving up. Only used with the on-failure policy.",+ "podman_pod_infra_image": "Infra image",+ "podman_pod_infra_image_description": "Image for the infra container. Leave empty for Podman's built-in pause image.",+ "podman_pod_infra_command": "Infra command",+ "podman_pod_infra_command_description": "Overrides the infra image's entrypoint. Separate arguments with spaces.",+ "podman_pod_infra_name": "Infra container name",+ "podman_pod_infra_conmon_pidfile": "Conmon PID file",+ "podman_pod_infra_conmon_pidfile_description": "Path on the host that receives the infra container's conmon PID.",+ "podman_pod_share_parent": "Use the pod cgroup as parent",+ "podman_pod_share_parent_description": "Containers that join the pod use its cgroup as their cgroup parent.",+ "podman_pod_pid_namespace": "PID namespace",+ "podman_pod_ipc_namespace": "IPC namespace",+ "podman_pod_uts_namespace": "UTS namespace",+ "podman_pod_namespace_description": "host, private, ns:<path>, or container:<id>. Leave empty for the default.",+ "podman_pod_user_namespace": "User namespace",+ "podman_pod_user_namespace_description": "auto, keep-id, keep-id:uid=1000, nomap, host, or ns:<path>. Leave empty for the default.",+ "podman_pod_uid_map": "UID mappings",+ "podman_pod_gid_map": "GID mappings",+ "podman_pod_id_map_description": "CONTAINER:HOST:SIZE entries, separated by commas. When only one is set, it is used for both.",+ "podman_pod_security_opt": "Security options",+ "podman_pod_security_opt_description": "For example label=disable or seccomp=unconfined. Separate options with commas.",+ "podman_pod_sysctl": "Kernel parameters",+ "podman_pod_sysctl_description": "Namespaced sysctl values applied to the pod.",+ "podman_pod_network_mode": "Network mode",+ "podman_pod_network_mode_description": "Default uses the bridge network, or the named networks below.",+ "podman_pod_network_mode_default": "Default",+ "podman_pod_network_mode_private": "Private",+ "podman_pod_network_mode_path": "Namespace path",+ "podman_pod_network_namespace_path": "Network namespace path",+ "podman_pod_network_options": "Network mode options",+ "podman_pod_network_options_description": "Options for pasta or slirp4netns. Separate options with commas.",+ "podman_pod_networks": "Networks",+ "podman_pod_networks_description": "Named networks to join, with optional aliases, static IPs, MAC address, and interface name.",+ "podman_pod_add_network": "Add network",+ "podman_pod_interface_name": "Interface",+ "podman_pod_dns_servers": "DNS servers",+ "podman_pod_dns_search": "DNS search domains",+ "podman_pod_dns_options": "DNS options",+ "podman_pod_no_resolv_conf": "Keep the image's resolv.conf",+ "podman_pod_no_resolv_conf_description": "Podman does not write /etc/resolv.conf; DNS settings above are ignored.",+ "podman_pod_add_hosts": "Extra hosts",+ "podman_pod_add_hosts_description": "Hostname and IP pairs added to /etc/hosts.",+ "podman_pod_add_host": "Add host",+ "podman_pod_no_hosts": "Keep the image's /etc/hosts",+ "podman_pod_no_hostname": "Keep the image's /etc/hostname",+ "podman_pod_hosts_file": "Base hosts file",+ "podman_pod_hosts_file_description": "Host file that /etc/hosts starts from, or image or none.",+ "podman_pod_cpus_description": "Number of CPUs the pod may use, for example 1.5.",+ "podman_pod_cpu_shares_description": "Relative CPU weight against other workloads. The default is 1024.",+ "podman_pod_cpuset_cpus": "CPU set",+ "podman_pod_cpuset_cpus_description": "CPUs allowed to run the pod, for example 0-3 or 0,1.",+ "podman_pod_cpuset_mems": "Memory nodes",+ "podman_pod_cpuset_mems_description": "NUMA memory nodes allowed, for example 0-1. Only effective on NUMA systems.",+ "podman_pod_memory": "Memory limit",+ "podman_pod_size_description": "A number with an optional unit: b, k, m, or g.",+ "podman_pod_memory_swap": "Memory + swap limit",+ "podman_pod_memory_swap_description": "Total of memory and swap, or -1 for unlimited swap.",+ "podman_pod_blkio_weight": "Block IO weight",+ "podman_pod_blkio_weight_description": "Relative weight between 10 and 1000.",+ "podman_pod_blkio_weight_devices": "Per-device IO weights",+ "podman_pod_device_read_bps": "Device read limits",+ "podman_pod_device_write_bps": "Device write limits",+ "podman_pod_device_limit_description": "Devices are MAJOR:MINOR numbers, for example 8:0 (see lsblk). Rates use b, k, m, or g.",+ "podman_pod_add_device": "Add device",+ "podman_pod_cgroup_parent": "Cgroup parent",+ "podman_pod_cgroup_parent_description": "Parent cgroup the pod is created under.",+ "podman_pod_devices": "Devices",+ "podman_pod_devices_description": "Host devices as HOST[:CONTAINER[:PERMISSIONS]].",+ "podman_pod_gpus": "GPUs",+ "podman_pod_gpus_description": "NVIDIA GPU indexes or all, added through CDI. Separate values with commas.",+ "podman_pod_volumes_description": "Absolute host paths are bind mounts; other sources are named volumes. Options such as ro, z, or U are comma-separated.",+ "podman_pod_volume_options": "Options",+ "podman_pod_volumes_from": "Volumes from",+ "podman_pod_volumes_from_description": "Containers whose volumes are mounted, as CONTAINER[:OPTIONS]. Separate entries with commas.",+ "podman_pod_shm_size": "/dev/shm size",+ "podman_pod_shm_size_systemd": "systemd tmpfs size",+ "podman_pod_shm_size_systemd_description": "Size of /run and /run/lock in systemd containers.",+ "podman_pod_invalid_size": "Enter a size such as 512m or 2g.",+ "podman_pod_invalid_number": "Enter a number.",+ "podman_pod_invalid_cpuset": "Use numbers and ranges, for example 0-3,6.",+ "podman_pod_invalid_blkio_weight": "Enter a weight between 10 and 1000.",+ "podman_pod_invalid_device_limit": "Use MAJOR:MINOR devices and a value on every row.",+ "podman_pod_invalid_id_map": "Use CONTAINER:HOST:SIZE entries.",+ "podman_pod_invalid_rows": "Complete or remove the highlighted rows.",+ "podman_pod_no_containers": "This pod has no containers",+ "podman_pod_not_running": "The pod is not running.",+ "podman_quadlet": "quadlet",+ "podman_quadlets_title": "Quadlets",+ "podman_quadlets_subtitle": "Systemd units that run Podman containers, pods, and kube workloads",+ "podman_quadlets_total": "Total quadlets",+ "podman_quadlets_unsupported": "Quadlet management requires Podman 5.8 or later.",+ "podman_quadlet_install": "Install quadlet",+ "podman_quadlet_install_description": "Install a quadlet file. Podman reloads systemd so the unit becomes available.",+ "podman_quadlet_install_failed": "Failed to install {name}",+ "podman_quadlet_install_success": "{name} installed",+ "podman_quadlet_template": "Template",+ "podman_quadlet_app": "Application",+ "podman_quadlet_app_description": "Group this quadlet with related files under one application.",+ "podman_quadlet_extra_file": "Additional file",+ "podman_quadlet_extra_files": "Additional files",+ "podman_quadlet_extra_files_description": "Files installed beside the quadlet, such as env files or a Containerfile.",+ "podman_quadlet_update_files_description": "Files to install or replace beside the quadlet when you save, such as its kube YAML.",+ "podman_quadlet_add_file": "Add file",+ "podman_quadlet_file_name_placeholder": "File name, for example app.env",+ "podman_quadlet_no_containers": "No containers are running for this quadlet",+ "podman_kube_title": "Kube",+ "podman_kube_subtitle": "Play, tear down, and generate Kubernetes YAML with Podman",+ "podman_kube_yaml": "Kubernetes YAML",+ "podman_kube_play": "Play",+ "podman_kube_play_description": "Create pods, containers, and volumes from the YAML, or tear them down.",+ "podman_kube_play_failed": "Failed to play Kubernetes YAML",+ "podman_kube_play_success": "Created {count} pod(s)",+ "podman_kube_down_failed": "Failed to tear down Kubernetes YAML",+ "podman_kube_down_success": "Removed {count} pod(s)",+ "podman_kube_down_confirm": "Tear down every pod and container defined in this YAML?",+ "podman_kube_play_partial": "Created {count} pod(s), but some containers failed",+ "podman_kube_start": "Start pods after creating them",+ "podman_kube_replace": "Replace existing pods and containers",+ "podman_kube_force_description": "Also remove volumes created by the YAML when tearing it down.",+ "podman_kube_pod_created": "Pod {id}: {count} container(s)",+ "podman_kube_pod_removed": "Pod {id} removed",+ "podman_kube_generate": "Generate",+ "podman_kube_generate_description": "Generate Kubernetes YAML from existing pods, containers, or volumes.",+ "podman_kube_generate_names": "Pods, containers, or volumes",+ "podman_kube_generate_service": "Also generate a service",+ "podman_kube_generate_failed": "Failed to generate Kubernetes YAML",+ "podman_kube_generated": "Generated YAML",+ "podman_kube_use_generated": "Use in editor",+ "podman_secrets_title": "Secrets",+ "podman_secrets_subtitle": "Podman secrets available to containers on this host",+ "podman_secrets_driver_placeholder": "file",+ "podman_secrets_driver_option_key_placeholder": "path",+ "podman_secrets_driver_option_value_placeholder": "/run/secrets/store",+ "podman_secrets_new_value_label": "New value",+ "podman_secrets_new_value_placeholder": "Enter new secret value…",+ "podman_secrets_new_value_help": "Secret values cannot be viewed after creation. Podman replaces the whole secret, so enter a new value to save any change.",+ "podman_autoupdate_subtitle": "Update containers that opt in with the io.containers.autoupdate label",+ "podman_autoupdate_run": "Run auto-update",+ "podman_autoupdate_rest_description": "Podman pulls newer images and restarts the systemd units of updated containers. Each container is reported.",+ "podman_autoupdate_systemd_description": "Starts podman-auto-update.service through systemd. This Podman version reports no per-container results and has no dry run.",+ "podman_autoupdate_dry_run": "Dry run",+ "podman_autoupdate_dry_run_description": "Report available updates without applying them.",+ "podman_autoupdate_rollback": "Roll back failed updates",+ "podman_autoupdate_failed": "Podman auto-update failed",+ "podman_autoupdate_success": "Podman auto-update finished",+ "podman_autoupdate_partial": "Podman auto-update finished with errors",+ "podman_autoupdate_no_reports": "No containers use auto-update",+ "podman_autoupdate_policy": "Policy",+ "podman_autoupdate_unavailable": "Podman auto-update needs a reachable systemd or Podman 6.2 or later.",+ "podman_info_swap": "Swap",+ "podman_info_rootless": "Rootless",+ "podman_info_rootful": "Rootful",+ "podman_info_database_backend": "Database Backend",+ "podman_info_event_logger": "Event Logger",+ "podman_info_remote_service": "Remote Service",+ "podman_info_oci_runtime": "OCI Runtime",+ "podman_info_conmon": "Conmon",+ "podman_info_cgroup_controllers": "Cgroup Controllers",+ "podman_info_network_backend": "Network Backend",+ "podman_info_dns": "DNS",+ "podman_info_default_network": "Default Network",+ "podman_info_rootless_network": "Rootless Network",+ "podman_info_search_registries": "Search Registries",+ "podman_info_selinux": "SELinux",+ "podman_info_apparmor": "AppArmor",+ "podman_info_seccomp": "Seccomp",+ "podman_info_seccomp_profile": "Seccomp Profile",+ "podman_info_uid_map": "UID Map",+ "podman_info_gid_map": "GID Map",+ "podman_info_capabilities": "Capabilities",+ "podman_info_run_root": "Run Root",+ "podman_info_volume_path": "Volume Path",+ "podman_info_quadlet_apps": "Quadlet Apps",+ "podman_info_systemd": "Systemd"}diff --git a/frontend/src/lib/components/badges/index.ts b/frontend/src/lib/components/badges/index.tsindex 6b8b15a3b..35ab1e3fc 100644--- a/frontend/src/lib/components/badges/index.ts+++ b/frontend/src/lib/components/badges/index.ts@@ -1,2 +1,3 @@export { default as PortBadge } from './port-badge.svelte';export { default as UiConfigDisabledTag } from './ui-config-disabled-tag.svelte';+export { default as LabelBadges } from './label-badges.svelte';diff --git a/frontend/src/lib/components/badges/label-badges.svelte b/frontend/src/lib/components/badges/label-badges.sveltenew file mode 100644index 000000000..7d8f69a1c--- /dev/null+++ b/frontend/src/lib/components/badges/label-badges.svelte@@ -0,0 +1,22 @@+<script lang="ts">+ import { Badge } from '#lib/components/ui/badge/index.js';++ let { labels, limit = 2 }: { labels: Record<string, string> | null | undefined; limit?: number } = $props();++ const entries = $derived(Object.entries(labels ?? {}));+</script>++{#if entries.length === 0}+ <span class="text-sm text-muted-foreground">-</span>+{:else}+ <div class="flex flex-wrap items-center gap-1.5">+ {#each entries.slice(0, limit) as [key, value] (key)}+ <Badge variant="gray" mono class="max-w-50" title={`${key}=${value}`}>+ <span class="block min-w-0 truncate">{value ? `${key}=${value}` : key}</span>+ </Badge>+ {/each}+ {#if entries.length > limit}+ <Badge variant="outline">{`+${entries.length - limit}`}</Badge>+ {/if}+ </div>+{/if}diff --git a/frontend/src/lib/components/code-editor/analysis/types.ts b/frontend/src/lib/components/code-editor/analysis/types.tsindex 5b6cb35ff..17b184d86 100644--- a/frontend/src/lib/components/code-editor/analysis/types.ts+++ b/frontend/src/lib/components/code-editor/analysis/types.ts@@ -10,6 +10,7 @@ export type CodeLanguage =| 'javascript'| 'typescript'| 'markdown'+ | 'systemd'| 'plaintext';export type CodeValidationMode = 'compose' | 'env' | 'none';diff --git a/frontend/src/lib/components/code-editor/editor.svelte b/frontend/src/lib/components/code-editor/editor.svelteindex 79fcc764d..9f50038e5 100644--- a/frontend/src/lib/components/code-editor/editor.svelte+++ b/frontend/src/lib/components/code-editor/editor.svelte@@ -48,6 +48,7 @@javascript: { validation: 'none', extensions: () => [javascript({ jsx: true })] },typescript: { validation: 'none', extensions: () => [javascript({ typescript: true, jsx: true })] },markdown: { validation: 'none', extensions: () => [markdown()] },+ systemd: { validation: 'none', extensions: () => [StreamLanguage.define(properties)] },plaintext: { validation: 'none', extensions: () => [] }} satisfies Record<CodeLanguage, { validation: CodeValidationMode; extensions: () => Extension[] }>));@@ -668,6 +669,7 @@javascript: createEnterIndentKeymap('javascript'),typescript: createEnterIndentKeymap('typescript'),markdown: createEnterIndentKeymap('markdown'),+ systemd: createEnterIndentKeymap('systemd'),plaintext: createEnterIndentKeymap('plaintext')};diff --git a/frontend/src/lib/components/dialogs/docker-info-body.svelte b/frontend/src/lib/components/dialogs/docker-info-body.sveltenew file mode 100644index 000000000..1d227798a--- /dev/null+++ b/frontend/src/lib/components/dialogs/docker-info-body.svelte@@ -0,0 +1,197 @@+<script lang="ts">+ import { Badge } from '#lib/components/ui/badge/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import type { DockerInfo } from '#lib/types/docker.js';+ import { bytes, withOccurrenceKeys } from '#lib/utils/formatting.js';++ import {+ blockRow,+ capRow,+ commitRow,+ formatTime,+ infoRow,+ sectionHeading,+ stat,+ storageDetailsSection,+ tagGroup+ } from './engine-info-parts.svelte';++ let { info }: { info: DockerInfo } = $props();++ function shortCommit(commit: { ID?: string } | undefined | null): string {+ const id = commit?.ID;+ if (!id) return '-';+ return id.length > 12 ? id.slice(0, 12) : id;+ }++ const swarm = $derived(+ info.Swarm as {+ LocalNodeState?: string;+ ControlAvailable?: boolean;+ NodeID?: string;+ Managers?: number;+ Nodes?: number;+ }+ );+ const swarmActive = $derived(!!swarm?.LocalNodeState && swarm.LocalNodeState !== 'inactive');+</script>++<div class="space-y-3 pt-2">+ {#if info.Warnings && info.Warnings.length > 0}+ <div class="space-y-0.5 border-l-2 border-warning/50 pl-2.5">+ <h3 class="text-3xs font-semibold tracking-wider text-warning uppercase">+ {m.docker_info_warnings_section()}+ </h3>+ <ul class="space-y-0.5">+ {#each withOccurrenceKeys(info.Warnings) as { value: warning, key } (key)}+ <li class="text-xs wrap-anywhere text-warning">{warning}</li>+ {/each}+ </ul>+ </div>+ {/if}++ <div class="flex flex-wrap items-center gap-x-5 gap-y-1.5 border-b border-border/50 pb-2.5">+ {@render stat(m.common_running(), info.ContainersRunning ?? 0, 'bg-success')}+ {@render stat(m.paused(), info.ContainersPaused ?? 0, 'bg-warning')}+ {@render stat(m.common_stopped(), info.ContainersStopped ?? 0, 'bg-destructive')}+ {@render stat(m.images(), info.Images ?? 0, 'bg-info')}+ <div class="hidden h-3 w-px bg-border/50 sm:block"></div>+ {@render stat(m.common_cpus(), info.NCPU ?? 0)}+ {@render stat(m.docker_info_memory_label(), (info.MemTotal ? bytes.format(info.MemTotal) : null) ?? '-')}+ {@render stat(m.goroutines(), info.NGoroutines ?? 0)}+ {@render stat(m.docker_info_file_descriptors(), info.NFd ?? 0)}+ </div>++ <div class="columns-1 gap-6 sm:columns-2 lg:columns-3 [&>*]:mb-4 [&>*]:break-inside-avoid">+ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_system_section())}+ <div class="space-y-0.5">+ {@render infoRow(m.common_name(), info.Name)}+ {@render infoRow(m.common_id(), info.ID, true)}+ {@render infoRow(m.docker_info_os_label(), info.OperatingSystem)}+ {@render infoRow(m.docker_info_os_version_label(), info.OSVersion)}+ {@render infoRow(m.docker_info_os_type_label(), info.OSType)}+ {@render infoRow(m.common_architecture(), info.Architecture)}+ {@render infoRow(m.docker_info_kernel_version_label(), info.KernelVersion)}+ {@render infoRow(m.docker_info_system_time(), formatTime(info.SystemTime), false)}+ {@render infoRow(m.docker_info_root_dir(), info.DockerRootDir, true)}+ {@render infoRow(m.docker_info_index_server_label(), info.IndexServerAddress, true)}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_version_section())}+ <div class="space-y-0.5">+ {@render infoRow(m.docker_info_server_version_label(), info.ServerVersion)}+ {@render infoRow(m.docker_info_api_version_label(), info.apiVersion)}+ {@render infoRow(m.go_version(), info.goVersion)}+ {@render commitRow(info.gitCommit)}+ {@render infoRow(m.build_time(), formatTime(info.buildTime), false)}+ {@render infoRow(m.docker_info_experimental(), info.ExperimentalBuild ? m.common_yes() : m.common_no(), false)}+ {@render infoRow(m.docker_info_containerd_commit_label(), shortCommit(info.ContainerdCommit), true)}+ {@render infoRow(m.docker_info_runc_commit_label(), shortCommit(info.RuncCommit), true)}+ {@render infoRow(m.docker_info_init_commit_label(), shortCommit(info.InitCommit), true)}+ {#if info.ProductLicense}+ {@render infoRow(m.docker_info_product_license_label(), info.ProductLicense, false)}+ {/if}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.common_configuration())}+ <div class="space-y-0.5">+ {@render infoRow(m.docker_info_storage_driver_label(), info.Driver)}+ {@render infoRow(m.docker_info_logging_driver_label(), info.LoggingDriver)}+ {@render infoRow(m.docker_info_cgroup_driver_label(), info.CgroupDriver)}+ {@render infoRow(m.docker_info_cgroup_version_label(), info.CgroupVersion)}+ {@render infoRow(m.isolation(), info.Isolation)}+ {@render infoRow(m.docker_info_init_binary(), info.InitBinary)}+ {@render infoRow(m.docker_info_default_runtime(), info.DefaultRuntime)}+ {@render infoRow(m.docker_info_debug_label(), info.Debug ? m.common_yes() : m.common_no(), false)}+ {@render infoRow(m.docker_info_live_restore_label(), info.LiveRestoreEnabled ? m.common_yes() : m.common_no(), false)}+ {@render infoRow(m.docker_info_event_listeners_label(), info.NEventsListener ?? 0, false)}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(`${m.resource_networks_cap()} & ${m.docker_info_proxy_label()}`)}+ <div class="space-y-0.5">+ {@render infoRow(m.docker_info_ipv4_forwarding(), info.IPv4Forwarding ? m.common_enabled() : m.common_disabled(), false)}+ {@render infoRow(m.docker_info_http_proxy(), info.HttpProxy)}+ {@render infoRow(m.docker_info_https_proxy(), info.HttpsProxy)}+ {#if info.NoProxy}+ {@render blockRow(m.docker_info_no_proxy(), info.NoProxy)}+ {:else}+ {@render infoRow(m.docker_info_no_proxy(), info.NoProxy)}+ {/if}+ {#if info.DefaultAddressPools && info.DefaultAddressPools.length > 0}+ {@render blockRow(+ m.docker_info_address_pools_label(),+ info.DefaultAddressPools.map((pool) => `${pool.Base}/${pool.Size}`).join(' ')+ )}+ {/if}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_plugins_section())}+ <div class="space-y-1">+ {@render tagGroup(m.resource_volumes_cap(), info.Plugins?.Volume)}+ {@render tagGroup(m.resource_networks_cap(), info.Plugins?.Network)}+ {@render tagGroup(m.common_logs(), info.Plugins?.Log)}+ {@render tagGroup(m.docker_info_authorization_plugin(), info.Plugins?.Authorization)}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_capabilities_section())}+ <div class="grid grid-cols-2 gap-x-4 gap-y-0.5">+ {@render capRow(m.docker_info_memory_limit_label(), info.MemoryLimit)}+ {@render capRow(m.docker_info_swap_limit_label(), info.SwapLimit)}+ {@render capRow(m.docker_info_kernel_memory_tcp_label(), info.KernelMemoryTCP)}+ {@render capRow(m.docker_info_cpu_cfs_period_label(), info.CpuCfsPeriod)}+ {@render capRow(m.docker_info_cpu_cfs_quota_label(), info.CpuCfsQuota)}+ {@render capRow(m.docker_info_cpu_shares_label(), info.CPUShares)}+ {@render capRow(m.docker_info_cpu_set_label(), info.CPUSet)}+ {@render capRow(m.docker_info_pids_limit_label(), info.PidsLimit)}+ {@render capRow(m.docker_info_oom_kill_disable_label(), info.OomKillDisable)}+ </div>+ </section>++ {#if swarmActive}+ <section class="space-y-1.5">+ {@render sectionHeading(m.swarm())}+ <div class="space-y-0.5">+ {@render infoRow(m.docker_info_swarm_state_label(), swarm.LocalNodeState, false)}+ {@render infoRow(m.docker_info_swarm_manager_label(), swarm.ControlAvailable ? m.common_yes() : m.common_no(), false)}+ {@render infoRow(m.docker_info_swarm_node_id_label(), swarm.NodeID, true)}+ {@render infoRow(m.docker_info_swarm_managers_label(), swarm.Managers ?? 0, false)}+ {@render infoRow(m.nodes(), swarm.Nodes ?? 0, false)}+ </div>+ </section>+ {/if}++ <section class="space-y-1.5">+ {@render sectionHeading(`${m.security()} & ${m.docker_info_runtimes()}`)}+ <div class="space-y-1">+ {@render tagGroup(m.docker_info_security_options(), info.SecurityOptions)}+ {@render tagGroup(m.docker_info_runtimes(), Object.keys(info.Runtimes ?? {}))}+ </div>+ </section>++ {#if info.DriverStatus && info.DriverStatus.length > 0}+ {@render storageDetailsSection(info.DriverStatus)}+ {/if}++ {#if info.Labels && info.Labels.length > 0}+ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_labels_section())}+ <div class="flex flex-wrap gap-1">+ {#each withOccurrenceKeys(info.Labels) as { value: label, key } (key)}+ <Badge variant="outline" size="sm" mono>{label}</Badge>+ {/each}+ </div>+ </section>+ {/if}+ </div>+</div>diff --git a/frontend/src/lib/components/dialogs/docker-info-dialog.svelte b/frontend/src/lib/components/dialogs/docker-info-dialog.svelteindex 34d099ba0..012442351 100644--- a/frontend/src/lib/components/dialogs/docker-info-dialog.svelte+++ b/frontend/src/lib/components/dialogs/docker-info-dialog.svelte@@ -1,58 +1,51 @@+<script module lang="ts">+ import type { DockerInfo } from '#lib/types/docker.js';+ import type { PodmanInfo, PodmanStatus } from '#lib/types/podman.js';++ export type EngineInfo =+ | { engine: 'docker'; docker: DockerInfo }+ | { engine: 'podman'; podman: PodmanInfo; status: PodmanStatus; podCount: number };+</script>+<script lang="ts">import { ArcaneButton } from '#lib/components/arcane-button/index.js';- import { Badge } from '#lib/components/ui/badge/index.js';- import { CopyButton } from '#lib/components/ui/copy-button/index.js';import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';import { Spinner } from '#lib/components/ui/spinner/index.js';- import { CheckIcon, CloseIcon } from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';- import type { DockerInfo } from '#lib/types/docker.js';- import { bytes, formatDateTimeShort, withOccurrenceKeys } from '#lib/utils/formatting.js';++ import DockerInfoBody from './docker-info-body.svelte';+ import PodmanInfoBody from './podman-info-body.svelte';interface Props {open: boolean;- dockerInfo: DockerInfo | null;- dockerInfoPromise?: Promise<DockerInfo> | null;+ engine: EngineInfo['engine'];+ info: EngineInfo | null;+ infoPromise?: Promise<EngineInfo> | null;errorMessage?: string | null;}- let { open = $bindable(), dockerInfo, dockerInfoPromise = null, errorMessage = null }: Props = $props();-- function handleClose() {- open = false;- }-- function formatTime(timeStr: string | undefined) {- if (!timeStr) return '-';- return formatDateTimeShort(timeStr) || timeStr;- }+ let { open = $bindable(), engine, info, infoPromise = null, errorMessage = null }: Props = $props();- function shortCommit(commit: { ID?: string } | undefined | null): string {- const id = commit?.ID;- if (!id) return '-';- return id.length > 12 ? id.slice(0, 12) : id;- }-- function swarmActive(info: DockerInfo): boolean {- const state = (info.Swarm as { LocalNodeState?: string } | undefined)?.LocalNodeState;- return !!state && state !== 'inactive';- }+ const title = $derived.by(() => {+ if (engine === 'podman') return m.podman();+ return info?.engine === 'docker' && info.docker.Name ? info.docker.Name : 'Docker Engine';+ });</script><ResponsiveDialog{open}onOpenChange={(nextOpen) => (open = nextOpen)}- title={m.docker_engine_title({ engine: dockerInfo?.Name ?? 'Docker Engine' })}+ title={m.docker_engine_title({ engine: title })}description={m.docker_info_dialog_description()}contentClass="sm:max-w-275"showCloseButton={false}>{#snippet children()}- {#if dockerInfo}- {@render dialogBody(dockerInfo)}- {:else if dockerInfoPromise}- {#await dockerInfoPromise then resolvedDockerInfo}- {@render dialogBody(resolvedDockerInfo)}+ {#if info}+ {@render dialogBody(info)}+ {:else if infoPromise}+ {#await infoPromise then resolvedInfo}+ {@render dialogBody(resolvedInfo)}{:catch}<div class="flex min-h-56 flex-col items-center justify-center gap-3 pt-4"><p class="text-sm font-medium">{errorMessage ?? m.common_failed()}</p>@@ -71,305 +64,14 @@{/snippet}{#snippet footer()}- <ArcaneButton action="base" tone="outline" onclick={handleClose} customLabel={m.common_close()} />+ <ArcaneButton action="base" tone="outline" onclick={() => (open = false)} customLabel={m.common_close()} />{/snippet}</ResponsiveDialog>-{#snippet dialogBody(info: DockerInfo)}- <div class="space-y-3 pt-2">- {#if info.Warnings && info.Warnings.length > 0}- {@render warningsCard(info.Warnings)}- {/if}-- {@render statStrip(info)}-- <div class="columns-1 gap-6 sm:columns-2 lg:columns-3 [&>*]:mb-4 [&>*]:break-inside-avoid">- {@render systemSection(info)}- {@render versionSection(info)}- {@render configurationSection(info)}- {@render networkSection(info)}- {@render pluginsSection(info)}- {@render capabilitiesSection(info)}- {#if swarmActive(info)}- {@render swarmSection(info)}- {/if}- {@render securitySection(info)}- {#if info.DriverStatus && info.DriverStatus.length > 0}- {@render storageDetailsSection(info)}- {/if}- {#if info.Labels && info.Labels.length > 0}- {@render labelsSection(info)}- {/if}- </div>- </div>-{/snippet}--{#snippet warningsCard(warnings: string[])}- <div class="space-y-0.5 border-l-2 border-warning/50 pl-2.5">- <h3 class="text-3xs font-semibold tracking-wider text-warning uppercase">- {m.docker_info_warnings_section()}- </h3>- <ul class="space-y-0.5">- {#each withOccurrenceKeys(warnings) as { value: warning, key } (key)}- <li class="text-xs wrap-anywhere text-warning">{warning}</li>- {/each}- </ul>- </div>-{/snippet}--{#snippet statStrip(info: DockerInfo)}- <div class="flex flex-wrap items-center gap-x-5 gap-y-1.5 border-b border-border/50 pb-2.5">- {@render stat(m.common_running(), info.ContainersRunning ?? 0, 'bg-success')}- {@render stat(m.paused(), info.ContainersPaused ?? 0, 'bg-warning')}- {@render stat(m.common_stopped(), info.ContainersStopped ?? 0, 'bg-destructive')}- {@render stat(m.images(), info.Images ?? 0, 'bg-info')}- <div class="hidden h-3 w-px bg-border/50 sm:block"></div>- {@render stat(m.common_cpus(), info.NCPU ?? 0)}- {@render stat(m.docker_info_memory_label(), (info.MemTotal ? bytes.format(info.MemTotal) : null) ?? '-')}- {@render stat(m.goroutines(), info.NGoroutines ?? 0)}- {@render stat(m.docker_info_file_descriptors(), info.NFd ?? 0)}- </div>-{/snippet}--{#snippet stat(label: string, value: string | number, dot?: string)}- <div class="flex items-baseline gap-1.5">- {#if dot}- <span class="size-1.5 shrink-0 self-center rounded-full {dot}"></span>- {/if}- <span class="text-sm font-semibold tabular-nums">{value}</span>- <span class="text-3xs tracking-tight whitespace-nowrap text-muted-foreground uppercase">{label}</span>- </div>-{/snippet}--{#snippet systemSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.docker_info_system_section()}- </h3>- <div class="space-y-0.5">- {@render infoRow(m.common_name(), info.Name)}- {@render infoRow(m.common_id(), info.ID, true)}- {@render infoRow(m.docker_info_os_label(), info.OperatingSystem)}- {@render infoRow(m.docker_info_os_version_label(), info.OSVersion)}- {@render infoRow(m.docker_info_os_type_label(), info.OSType)}- {@render infoRow(m.common_architecture(), info.Architecture)}- {@render infoRow(m.docker_info_kernel_version_label(), info.KernelVersion)}- {@render infoRow(m.docker_info_system_time(), formatTime(info.SystemTime), false)}- {@render infoRow(m.docker_info_root_dir(), info.DockerRootDir, true)}- {@render infoRow(m.docker_info_index_server_label(), info.IndexServerAddress, true)}- </div>- </section>-{/snippet}--{#snippet versionSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.docker_info_version_section()}- </h3>- <div class="space-y-0.5">- {@render infoRow(m.docker_info_server_version_label(), info.ServerVersion)}- {@render infoRow(m.docker_info_api_version_label(), info.apiVersion)}- {@render infoRow(m.go_version(), info.goVersion)}- <div class="grid grid-cols-label-value items-baseline gap-x-3">- <span class="text-3xs leading-4 tracking-tight text-muted-foreground uppercase">{m.docker_info_git_commit_label()}</span>- <div class="flex items-center justify-end gap-1.5">- <code class="rounded bg-muted px-1.5 py-0.5 text-xs">{info.gitCommit?.slice(0, 8) ?? '-'}</code>- {#if info.gitCommit}- <CopyButton text={info.gitCommit} size="icon" class="size-5" title={m.docker_copy_commit_hash()} />- {/if}- </div>- </div>- {@render infoRow(m.build_time(), formatTime(info.buildTime), false)}- {@render infoRow(m.docker_info_experimental(), info.ExperimentalBuild ? m.common_yes() : m.common_no(), false)}- {@render infoRow(m.docker_info_containerd_commit_label(), shortCommit(info.ContainerdCommit), true)}- {@render infoRow(m.docker_info_runc_commit_label(), shortCommit(info.RuncCommit), true)}- {@render infoRow(m.docker_info_init_commit_label(), shortCommit(info.InitCommit), true)}- {#if info.ProductLicense}- {@render infoRow(m.docker_info_product_license_label(), info.ProductLicense, false)}- {/if}- </div>- </section>-{/snippet}--{#snippet configurationSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.common_configuration()}- </h3>- <div class="space-y-0.5">- {@render infoRow(m.docker_info_storage_driver_label(), info.Driver)}- {@render infoRow(m.docker_info_logging_driver_label(), info.LoggingDriver)}- {@render infoRow(m.docker_info_cgroup_driver_label(), info.CgroupDriver)}- {@render infoRow(m.docker_info_cgroup_version_label(), info.CgroupVersion)}- {@render infoRow(m.isolation(), info.Isolation)}- {@render infoRow(m.docker_info_init_binary(), info.InitBinary)}- {@render infoRow(m.docker_info_default_runtime(), info.DefaultRuntime)}- {@render infoRow(m.docker_info_debug_label(), info.Debug ? m.common_yes() : m.common_no(), false)}- {@render infoRow(m.docker_info_live_restore_label(), info.LiveRestoreEnabled ? m.common_yes() : m.common_no(), false)}- {@render infoRow(m.docker_info_event_listeners_label(), info.NEventsListener ?? 0, false)}- </div>- </section>-{/snippet}--{#snippet capabilitiesSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.docker_info_capabilities_section()}- </h3>- <div class="grid grid-cols-2 gap-x-4 gap-y-0.5">- {@render capRow(m.docker_info_memory_limit_label(), info.MemoryLimit)}- {@render capRow(m.docker_info_swap_limit_label(), info.SwapLimit)}- {@render capRow(m.docker_info_kernel_memory_tcp_label(), info.KernelMemoryTCP)}- {@render capRow(m.docker_info_cpu_cfs_period_label(), info.CpuCfsPeriod)}- {@render capRow(m.docker_info_cpu_cfs_quota_label(), info.CpuCfsQuota)}- {@render capRow(m.docker_info_cpu_shares_label(), info.CPUShares)}- {@render capRow(m.docker_info_cpu_set_label(), info.CPUSet)}- {@render capRow(m.docker_info_pids_limit_label(), info.PidsLimit)}- {@render capRow(m.docker_info_oom_kill_disable_label(), info.OomKillDisable)}- </div>- </section>-{/snippet}--{#snippet storageDetailsSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.docker_info_storage_details_section()}- </h3>- <div class="space-y-0.5">- {#each info.DriverStatus ?? [] as entry (entry)}- {@render infoRow(entry[0] ?? '', entry[1], false)}- {/each}- </div>- </section>-{/snippet}--{#snippet networkSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.resource_networks_cap()} & {m.docker_info_proxy_label()}- </h3>- <div class="space-y-0.5">- {@render infoRow(m.docker_info_ipv4_forwarding(), info.IPv4Forwarding ? m.common_enabled() : m.common_disabled(), false)}- {@render infoRow(m.docker_info_http_proxy(), info.HttpProxy)}- {@render infoRow(m.docker_info_https_proxy(), info.HttpsProxy)}- {#if info.NoProxy}- {@render blockRow(m.docker_info_no_proxy(), info.NoProxy)}- {:else}- {@render infoRow(m.docker_info_no_proxy(), info.NoProxy)}- {/if}- {#if info.DefaultAddressPools && info.DefaultAddressPools.length > 0}- {@render blockRow(- m.docker_info_address_pools_label(),- info.DefaultAddressPools.map((pool) => `${pool.Base}/${pool.Size}`).join(' ')- )}- {/if}- </div>- </section>-{/snippet}--{#snippet securitySection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.security()} & {m.docker_info_runtimes()}- </h3>- <div class="space-y-1">- {@render tagGroup(m.docker_info_security_options(), info.SecurityOptions)}- {@render tagGroup(m.docker_info_runtimes(), Object.keys(info.Runtimes ?? {}))}- </div>- </section>-{/snippet}--{#snippet pluginsSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.docker_info_plugins_section()}- </h3>- <div class="space-y-1">- {@render tagGroup(m.resource_volumes_cap(), info.Plugins?.Volume)}- {@render tagGroup(m.resource_networks_cap(), info.Plugins?.Network)}- {@render tagGroup(m.common_logs(), info.Plugins?.Log)}- {@render tagGroup(m.docker_info_authorization_plugin(), info.Plugins?.Authorization)}- </div>- </section>-{/snippet}--{#snippet swarmSection(info: DockerInfo)}- {@const swarm = info.Swarm as {- LocalNodeState?: string;- ControlAvailable?: boolean;- NodeID?: string;- Managers?: number;- Nodes?: number;- }}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.swarm()}- </h3>- <div class="space-y-0.5">- {@render infoRow(m.docker_info_swarm_state_label(), swarm.LocalNodeState, false)}- {@render infoRow(m.docker_info_swarm_manager_label(), swarm.ControlAvailable ? m.common_yes() : m.common_no(), false)}- {@render infoRow(m.docker_info_swarm_node_id_label(), swarm.NodeID, true)}- {@render infoRow(m.docker_info_swarm_managers_label(), swarm.Managers ?? 0, false)}- {@render infoRow(m.nodes(), swarm.Nodes ?? 0, false)}- </div>- </section>-{/snippet}--{#snippet labelsSection(info: DockerInfo)}- <section class="space-y-1.5">- <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">- {m.docker_info_labels_section()}- </h3>- <div class="flex flex-wrap gap-1">- {#each withOccurrenceKeys(info.Labels) as { value: label, key } (key)}- <Badge variant="outline" size="sm" mono>{label}</Badge>- {/each}- </div>- </section>-{/snippet}--{#snippet tagGroup(label: string, items: string[] | undefined)}- <div class="grid grid-cols-label-value items-baseline gap-x-3">- <span class="text-3xs leading-4 tracking-tight text-muted-foreground uppercase">{label}</span>- <div class="flex flex-wrap justify-end gap-1">- {#each withOccurrenceKeys(items) as { value: item, key } (key)}- <Badge variant="outline" size="sm">{item}</Badge>- {:else}- <span class="text-xs text-muted-foreground">-</span>- {/each}- </div>- </div>-{/snippet}--{#snippet capRow(label: string, value: boolean | undefined)}- <div class="flex items-center justify-between gap-2">- <span class="text-3xs tracking-tight wrap-anywhere text-muted-foreground uppercase">{label}</span>- {#if value}- <CheckIcon class="size-3 shrink-0 text-success" />- <span class="sr-only">{m.common_yes()}</span>- {:else}- <CloseIcon class="size-3 shrink-0 text-muted-foreground/50" />- <span class="sr-only">{m.common_no()}</span>- {/if}- </div>-{/snippet}--{#snippet blockRow(label: string, value: string)}- <div class="space-y-0.5 pt-0.5">- <div class="text-3xs tracking-tight text-muted-foreground uppercase">{label}</div>- <div- class="max-h-48 overflow-y-auto rounded-md bg-muted/30 px-2 py-1 font-mono text-2xs leading-relaxed break-all text-foreground/80"- >- {value}- </div>- </div>-{/snippet}--{#snippet infoRow(label: string, value: string | number | undefined | null, mono: boolean = true)}- <div class="grid grid-cols-label-value items-baseline gap-x-3">- <span class="text-3xs leading-4 tracking-tight text-muted-foreground uppercase">{label}</span>- <span class="text-right text-xs leading-4 wrap-anywhere {mono ? 'font-mono' : ''}">- {value === undefined || value === null || value === '' ? '-' : value}- </span>- </div>+{#snippet dialogBody(resolved: EngineInfo)}+ {#if resolved.engine === 'podman'}+ <PodmanInfoBody info={resolved.podman} status={resolved.status} podCount={resolved.podCount} />+ {:else}+ <DockerInfoBody info={resolved.docker} />+ {/if}{/snippet}diff --git a/frontend/src/lib/components/dialogs/engine-info-parts.svelte b/frontend/src/lib/components/dialogs/engine-info-parts.sveltenew file mode 100644index 000000000..2e99a51c0--- /dev/null+++ b/frontend/src/lib/components/dialogs/engine-info-parts.svelte@@ -0,0 +1,105 @@+<script module lang="ts">+ import { Badge } from '#lib/components/ui/badge/index.js';+ import { CopyButton } from '#lib/components/ui/copy-button/index.js';+ import { CheckIcon, CloseIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { formatDateTimeShort, withOccurrenceKeys } from '#lib/utils/formatting.js';++ export function formatTime(timeStr: string | undefined) {+ if (!timeStr) return '-';+ return formatDateTimeShort(timeStr) || timeStr;+ }++ export { sectionHeading, stat, tagGroup, capRow, commitRow, blockRow, infoRow, presentRow, storageDetailsSection };+</script>++{#snippet sectionHeading(title: string)}+ <h3 class="border-b border-border/50 pb-1 text-3xs font-semibold tracking-wider text-muted-foreground uppercase">+ {title}+ </h3>+{/snippet}++{#snippet stat(label: string, value: string | number, dot?: string)}+ <div class="flex items-baseline gap-1.5">+ {#if dot}+ <span class="size-1.5 shrink-0 self-center rounded-full {dot}"></span>+ {/if}+ <span class="text-sm font-semibold tabular-nums">{value}</span>+ <span class="text-3xs tracking-tight whitespace-nowrap text-muted-foreground uppercase">{label}</span>+ </div>+{/snippet}++{#snippet tagGroup(label: string, items: string[] | undefined)}+ <div class="grid grid-cols-label-value items-baseline gap-x-3">+ <span class="text-3xs leading-4 tracking-tight text-muted-foreground uppercase">{label}</span>+ <div class="flex flex-wrap justify-end gap-1">+ {#each withOccurrenceKeys(items) as { value: item, key } (key)}+ <Badge variant="outline" size="sm">{item}</Badge>+ {:else}+ <span class="text-xs text-muted-foreground">-</span>+ {/each}+ </div>+ </div>+{/snippet}++{#snippet capRow(label: string, value: boolean | undefined)}+ <div class="flex items-center justify-between gap-2">+ <span class="text-3xs tracking-tight wrap-anywhere text-muted-foreground uppercase">{label}</span>+ {#if value}+ <CheckIcon class="size-3 shrink-0 text-success" />+ <span class="sr-only">{m.common_yes()}</span>+ {:else}+ <CloseIcon class="size-3 shrink-0 text-muted-foreground/50" />+ <span class="sr-only">{m.common_no()}</span>+ {/if}+ </div>+{/snippet}++{#snippet commitRow(commit: string | undefined)}+ <div class="grid grid-cols-label-value items-baseline gap-x-3">+ <span class="text-3xs leading-4 tracking-tight text-muted-foreground uppercase">{m.docker_info_git_commit_label()}</span>+ <div class="flex items-center justify-end gap-1.5">+ <code class="rounded bg-muted px-1.5 py-0.5 text-xs">{commit?.slice(0, 8) ?? '-'}</code>+ {#if commit}+ <CopyButton text={commit} size="icon" class="size-5" title={m.docker_copy_commit_hash()} />+ {/if}+ </div>+ </div>+{/snippet}++{#snippet blockRow(label: string, value: string)}+ <div class="space-y-0.5 pt-0.5">+ <div class="text-3xs tracking-tight text-muted-foreground uppercase">{label}</div>+ <div+ class="max-h-48 overflow-y-auto rounded-md bg-muted/30 px-2 py-1 font-mono text-2xs leading-relaxed break-all text-foreground/80"+ >+ {value}+ </div>+ </div>+{/snippet}++{#snippet infoRow(label: string, value: string | number | undefined | null, mono: boolean = true)}+ <div class="grid grid-cols-label-value items-baseline gap-x-3">+ <span class="text-3xs leading-4 tracking-tight text-muted-foreground uppercase">{label}</span>+ <span class="text-right text-xs leading-4 wrap-anywhere {mono ? 'font-mono' : ''}">+ {value === undefined || value === null || value === '' ? '-' : value}+ </span>+ </div>+{/snippet}++{#snippet presentRow(label: string, value: string | number | undefined | null, mono: boolean = true)}+ {#if value !== undefined && value !== null && value !== ''}+ {@render infoRow(label, value, mono)}+ {/if}+{/snippet}++{#snippet storageDetailsSection(entries: string[][])}+ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_storage_details_section())}+ <div class="space-y-0.5">+ {#each entries as entry (entry)}+ {@render infoRow(entry[0] ?? '', entry[1], false)}+ {/each}+ </div>+ </section>+{/snippet}diff --git a/frontend/src/lib/components/dialogs/podman-info-body.svelte b/frontend/src/lib/components/dialogs/podman-info-body.sveltenew file mode 100644index 000000000..6f1a54cc7--- /dev/null+++ b/frontend/src/lib/components/dialogs/podman-info-body.svelte@@ -0,0 +1,182 @@+<script lang="ts">+ import { m } from '#lib/paraglide/messages.js';+ import type { PodmanInfo, PodmanInfoIdMap, PodmanStatus } from '#lib/types/podman.js';+ import { bytes } from '#lib/utils/formatting.js';++ import {+ capRow,+ commitRow,+ formatTime,+ presentRow,+ sectionHeading,+ stat,+ storageDetailsSection,+ tagGroup+ } from './engine-info-parts.svelte';++ let { info, status, podCount }: { info: PodmanInfo; status: PodmanStatus; podCount: number } = $props();++ function firstLine(value: string | undefined): string {+ return value?.split('\n')[0]?.trim() ?? '';+ }++ function formatIdMap(entries: PodmanInfoIdMap[] | undefined): string {+ return (entries ?? []).map((entry) => `${entry.container_id}:${entry.host_id}:${entry.size}`).join(', ');+ }++ const host = $derived(info.host);+ const store = $derived(info.store);+ const distribution = $derived.by(() => {+ const { distribution: name, variant, version, codename } = host.distribution;+ const label = [name, variant, version === 'unknown' ? '' : version].filter(Boolean).join(' ');+ return codename ? `${label} (${codename})` : label;+ });+ const rootlessNetworkHelper = $derived(host.rootlessNetworkCmd === 'slirp4netns' ? host.slirp4netns : host.pasta);+ const capabilities = $derived(+ (host.security.capabilities ?? '')+ .split(',')+ .map((capability) => capability.trim())+ .filter(Boolean)+ );+ const storageDetails = $derived(Object.entries(store.graphStatus ?? {}));+</script>++<div class="space-y-3 pt-2">+ <div class="flex flex-wrap items-center gap-x-5 gap-y-1.5 border-b border-border/50 pb-2.5">+ {@render stat(m.common_running(), store.containerStore.running, 'bg-success')}+ {@render stat(m.paused(), store.containerStore.paused, 'bg-warning')}+ {@render stat(m.common_stopped(), store.containerStore.stopped, 'bg-destructive')}+ {@render stat(m.podman_pods_title(), podCount, 'bg-primary')}+ {@render stat(m.images(), store.imageStore.number, 'bg-info')}+ <div class="hidden h-3 w-px bg-border/50 sm:block"></div>+ {@render stat(m.common_cpus(), host.cpus)}+ {@render stat(m.docker_info_memory_label(), (host.memTotal ? bytes.format(host.memTotal) : null) ?? '-')}+ </div>++ <div class="columns-1 gap-6 sm:columns-2 lg:columns-3 [&>*]:mb-4 [&>*]:break-inside-avoid">+ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_system_section())}+ <div class="space-y-0.5">+ {@render presentRow(m.hostname(), host.hostname)}+ {@render presentRow(m.docker_info_os_label(), distribution, false)}+ {@render presentRow(m.docker_info_kernel_version_label(), host.kernel)}+ {@render presentRow(m.common_architecture(), host.arch)}+ {@render presentRow(m.podman_info_swap(), host.swapTotal ? bytes.format(host.swapTotal) : null, false)}+ {@render presentRow(m.common_uptime(), host.uptime, false)}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.podman())}+ <div class="space-y-0.5">+ {@render presentRow(m.common_version(), info.version.version)}+ {@render presentRow(m.docker_info_api_version_label(), info.version.apiVersion)}+ {@render presentRow(m.go_version(), info.version.goVersion)}+ {@render presentRow(m.build_time(), info.version.builtTime ? formatTime(info.version.builtTime) : '', false)}+ {#if info.version.gitCommit}+ {@render commitRow(info.version.gitCommit)}+ {/if}+ {@render presentRow(m.common_mode(), host.security.rootless ? m.podman_info_rootless() : m.podman_info_rootful(), false)}+ {@render presentRow(m.podman_info_database_backend(), host.databaseBackend)}+ {@render presentRow(m.podman_info_event_logger(), host.eventLogger)}+ {@render presentRow(m.docker_info_logging_driver_label(), host.logDriver)}+ {@render presentRow(m.podman_info_remote_service(), host.serviceIsRemote ? m.common_yes() : m.common_no(), false)}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.runtime())}+ <div class="space-y-1">+ {@render presentRow(m.podman_info_oci_runtime(), firstLine(host.ociRuntime.version) || host.ociRuntime.name)}+ {@render presentRow(m.podman_info_conmon(), firstLine(host.conmon.version))}+ {@render presentRow(m.docker_info_cgroup_driver_label(), host.cgroupManager)}+ {@render presentRow(m.docker_info_cgroup_version_label(), host.cgroupVersion)}+ {#if host.cgroupControllers && host.cgroupControllers.length > 0}+ {@render tagGroup(m.podman_info_cgroup_controllers(), host.cgroupControllers)}+ {/if}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.podman_pod_section_networking())}+ <div class="space-y-1">+ {@render presentRow(m.podman_info_network_backend(), host.networkBackendInfo.version || host.networkBackend)}+ {@render presentRow(m.podman_info_dns(), host.networkBackendInfo.dns.version)}+ {@render presentRow(m.podman_info_default_network(), host.networkBackendInfo.defaultNetwork)}+ {#if host.security.rootless}+ {@render presentRow(+ m.podman_info_rootless_network(),+ firstLine(rootlessNetworkHelper.version) || host.rootlessNetworkCmd+ )}+ {/if}+ {#if info.registries.search && info.registries.search.length > 0}+ {@render tagGroup(m.podman_info_search_registries(), info.registries.search)}+ {/if}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.security())}+ <div class="grid grid-cols-2 gap-x-4 gap-y-0.5">+ {@render capRow(m.podman_info_rootless(), host.security.rootless)}+ {@render capRow(m.podman_info_selinux(), host.security.selinuxEnabled)}+ {@render capRow(m.podman_info_apparmor(), host.security.apparmorEnabled)}+ {@render capRow(m.podman_info_seccomp(), host.security.seccompEnabled)}+ </div>+ <div class="space-y-1">+ {@render presentRow(m.podman_info_seccomp_profile(), host.security.seccompProfilePath)}+ {@render presentRow(m.podman_info_uid_map(), formatIdMap(host.idMappings.uidmap))}+ {@render presentRow(m.podman_info_gid_map(), formatIdMap(host.idMappings.gidmap))}+ {#if capabilities.length > 0}+ {@render tagGroup(m.podman_info_capabilities(), capabilities)}+ {/if}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.storage())}+ <div class="space-y-0.5">+ {@render presentRow(m.docker_info_storage_driver_label(), store.graphDriverName)}+ {@render presentRow(m.docker_info_root_dir(), store.graphRoot)}+ {@render presentRow(m.podman_info_run_root(), store.runRoot)}+ {@render presentRow(m.podman_info_volume_path(), store.volumePath)}+ </div>+ </section>++ {#if storageDetails.length > 0}+ {@render storageDetailsSection(storageDetails)}+ {/if}++ <section class="space-y-1.5">+ {@render sectionHeading(m.features_title())}+ <div class="grid grid-cols-2 gap-x-4 gap-y-0.5">+ {@render capRow(m.podman_quadlets_title(), status.quadletsSupported)}+ {@render capRow(m.podman_info_quadlet_apps(), status.quadletAppsSupported)}+ {@render capRow(m.podman_info_systemd(), status.systemdAvailable)}+ </div>+ <div class="space-y-0.5">+ {@render presentRow(m.common_scope(), status.systemdScope, false)}+ {@render presentRow(+ m.auto_update_title(),+ status.autoUpdateMode === 'unavailable' ? m.common_unavailable() : status.autoUpdateMode,+ false+ )}+ </div>+ </section>++ <section class="space-y-1.5">+ {@render sectionHeading(m.docker_info_plugins_section())}+ <div class="space-y-1">+ {#if info.plugins.volume && info.plugins.volume.length > 0}+ {@render tagGroup(m.resource_volumes_cap(), info.plugins.volume)}+ {/if}+ {#if info.plugins.network && info.plugins.network.length > 0}+ {@render tagGroup(m.resource_networks_cap(), info.plugins.network)}+ {/if}+ {#if info.plugins.log && info.plugins.log.length > 0}+ {@render tagGroup(m.common_logs(), info.plugins.log)}+ {/if}+ </div>+ </section>+ </div>+</div>diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelteindex 4478af4bb..d5f515e61 100644--- a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte+++ b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte@@ -22,6 +22,7 @@user = null,versionInformation,swarmItems = [],+ podmanItems = [],permissionsManifest = null,debug = false}: {@@ -29,6 +30,7 @@user?: User | null;versionInformation?: AppVersionInformation;swarmItems?: NavigationItem[];+ podmanItems?: NavigationItem[];permissionsManifest?: PermissionsManifest | null;debug?: boolean;} = $props();@@ -43,6 +45,9 @@const resourceItems = $derived(filterByPermissions(navigationItems.resourceItems, memoizedUser ?? null, currentEnvId, permissionsManifest));+ const permittedPodmanItems = $derived(+ filterByPermissions(podmanItems, memoizedUser ?? null, currentEnvId, permissionsManifest)+ );const settingsItems = $derived(filterByPermissions(navigationItems.settingsItems, memoizedUser ?? null, currentEnvId, permissionsManifest));@@ -157,6 +162,19 @@</section>{/if}+ {#if permittedPodmanItems.length > 0}+ <section>+ <h4 class="mb-4 px-3 text-2xs font-semibold tracking-widest text-muted-foreground/70 uppercase">+ {m.podman()}+ </h4>+ <div class="space-y-2">+ {#each permittedPodmanItems as item (item.url)}+ {@render navLink(item, true)}+ {/each}+ </div>+ </section>+ {/if}+{#if settingsItems.length > 0}<section><h4 class="mb-4 px-3 text-2xs font-semibold tracking-widest text-muted-foreground/70 uppercase">diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav.svelteindex 9fdef9dab..d65ed818a 100644--- a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte+++ b/frontend/src/lib/components/mobile-nav/mobile-nav.svelte@@ -2,10 +2,15 @@import { page } from '$app/state';import { onDestroy } from 'svelte';- import { getAvailableMobileNavItems, getSwarmNavigationItems } from '#lib/config/navigation-config.js';+ import {+ getAvailableMobileNavItems,+ getPodmanNavigationItems,+ getSwarmNavigationItems+ } from '#lib/config/navigation-config.js';import { m } from '#lib/paraglide/messages.js';import { environmentStore } from '#lib/stores/environment.store.svelte.js';import type { PermissionsManifest, User } from '#lib/types/auth.js';+ import type { PodmanStatus } from '#lib/types/podman.js';import type { AppVersionInformation } from '#lib/types/settings.js';import { cn } from '#lib/utils.js';import { getMobileNavigation } from '#lib/utils/navigation.js';@@ -19,12 +24,14 @@user = null,versionInformation,swarmEnabled,+ podmanStatuses = {},permissionsManifest = null,class: className = ''}: {user?: User | null;versionInformation?: AppVersionInformation;swarmEnabled?: boolean;+ podmanStatuses?: Record<string, PodmanStatus>;permissionsManifest?: PermissionsManifest | null;class?: string;} = $props();@@ -33,10 +40,17 @@const navigationSettings = $derived(navigation.settings);const currentEnvId = $derived(environmentStore.selected?.id || '0');const swarmItems = $derived(getSwarmNavigationItems(swarmEnabled, currentEnvId));+ const podmanItems = $derived(getPodmanNavigationItems(podmanStatuses, currentEnvId));const pinnedItems = $derived.by(() => {if (!navigationSettings?.pinnedItems) return [];- const availableItems = getAvailableMobileNavItems({ swarmEnabled, user, currentEnvId, accessManifest: permissionsManifest });+ const availableItems = getAvailableMobileNavItems({+ swarmEnabled,+ podmanStatuses,+ user,+ currentEnvId,+ accessManifest: permissionsManifest+ });return navigationSettings.pinnedItems.map((url) => availableItems.find((item) => item.url === url)).filter((item) => item !== undefined);@@ -181,4 +195,11 @@{/if}</nav>-<MobileNavSheet bind:open={() => menuOpen, setMenuOpen} {user} {versionInformation} {swarmItems} {permissionsManifest} />+<MobileNavSheet+ bind:open={() => menuOpen, setMenuOpen}+ {user}+ {versionInformation}+ {swarmItems}+ {podmanItems}+ {permissionsManifest}+/>diff --git a/frontend/src/lib/components/sheets/create-pod-sheet.svelte b/frontend/src/lib/components/sheets/create-pod-sheet.sveltenew file mode 100644index 000000000..47faeb826--- /dev/null+++ b/frontend/src/lib/components/sheets/create-pod-sheet.svelte@@ -0,0 +1,935 @@+<script lang="ts">+ import { z } from 'zod/v4';++ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';+ import FormInput from '#lib/components/form/form-input.svelte';+ import KeyValueEditor, { type KeyValueRow } from '#lib/components/form/key-value-editor.svelte';+ import PortMappingEditor, { type PortMappingRow } from '#lib/components/form/port-mapping-editor.svelte';+ import RowListEditor from '#lib/components/form/row-list-editor.svelte';+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';+ import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';+ import * as Accordion from '#lib/components/ui/accordion/index.js';+ import { Input } from '#lib/components/ui/input/index.js';+ import { Label } from '#lib/components/ui/label/index.js';+ import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import type { EnvironmentRef } from '#lib/stores/environment.store.svelte.js';+ import type {+ PodmanPodCreateRequest,+ PodmanPodDeviceLimit,+ PodmanPodExitPolicy,+ PodmanPodRestartPolicy+ } from '#lib/types/podman.js';+ import { destinationEnvironmentId } from '#lib/utils/environments.js';+ import { parseList } from '#lib/utils/form-parsers.js';+ import { createForm, preventDefault } from '#lib/utils/settings.svelte.js';++ type CreatePodFormProps = {+ open: boolean;+ environments: EnvironmentRef[];+ onSubmit: (request: PodmanPodCreateRequest, environmentId: string) => void;+ isLoading: boolean;+ };++ type NetworkRow = { name: string; aliases: string; staticIps: string; staticMac: string; interfaceName: string };+ type HostRow = { host: string; ip: string };+ type DeviceRow = { device: string };+ type VolumeRow = { source: string; destination: string; options: string };+ type DeviceLimitRow = { device: string; value: string };++ let { open = $bindable(false), environments, onSubmit, isLoading }: CreatePodFormProps = $props();++ let pickedEnvironmentId = $state('');+ const environmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'podman:pods', environments));++ const sizePattern = /^\d+(\.\d+)?\s*[bkmg]?b?$/i;+ const cpusetPattern = /^\d+(-\d+)?(,\d+(-\d+)?)*$/;+ const idMapPattern = /^\d+:\d+:\d+$/;+ const devicePattern = /^\d+:\d+$/;++ const optionalSize = z.string().refine((value) => value === '' || sizePattern.test(value), m.podman_pod_invalid_size());+ const optionalNumber = z.string().refine((value) => value === '' || Number(value) >= 0, m.podman_pod_invalid_number());+ const optionalCpuset = z.string().refine((value) => value === '' || cpusetPattern.test(value), m.podman_pod_invalid_cpuset());+ const optionalIdMap = z+ .string()+ .refine((value) => parseList(value).every((entry) => idMapPattern.test(entry)), m.podman_pod_invalid_id_map());++ const formSchema = z.object({+ podName: z+ .string()+ .min(1, m.common_field_required({ field: m.common_name() }))+ .regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/, m.podman_pod_name_invalid()),+ hostname: z.string(),+ exitPolicy: z.string(),+ restartPolicy: z.string(),+ restartRetries: z.string().refine((value) => value === '' || Number.isInteger(Number(value)), m.podman_pod_invalid_number()),+ noInfra: z.boolean(),+ infraImage: z.string(),+ infraCommand: z.string(),+ infraName: z.string(),+ infraConmonPidFile: z.string(),+ sharedNamespaces: z.string(),+ shareParent: z.boolean(),+ pid: z.string(),+ ipc: z.string(),+ uts: z.string(),+ userns: z.string(),+ uidMap: optionalIdMap,+ gidMap: optionalIdMap,+ securityOpt: z.string(),+ networkMode: z.string(),+ networkPath: z.string(),+ networkOptions: z.string(),+ dnsServers: z.string(),+ dnsSearch: z.string(),+ dnsOptions: z.string(),+ noResolvConf: z.boolean(),+ noHosts: z.boolean(),+ noHostname: z.boolean(),+ hostsFile: z.string(),+ cgroupParent: z.string(),+ cpus: optionalNumber,+ cpuShares: z.string().refine((value) => value === '' || Number.isInteger(Number(value)), m.podman_pod_invalid_number()),+ cpusetCpus: optionalCpuset,+ cpusetMems: optionalCpuset,+ memory: optionalSize,+ memorySwap: z+ .string()+ .refine((value) => value === '' || value === '-1' || sizePattern.test(value), m.podman_pod_invalid_size()),+ blkioWeight: z+ .string()+ .refine(+ (value) => value === '' || (Number.isInteger(Number(value)) && Number(value) >= 10 && Number(value) <= 1000),+ m.podman_pod_invalid_blkio_weight()+ ),+ gpus: z.string(),+ volumesFrom: z.string(),+ shmSize: optionalSize,+ shmSizeSystemd: optionalSize+ });++ const defaults: z.infer<typeof formSchema> = {+ podName: '',+ hostname: '',+ exitPolicy: 'default',+ restartPolicy: 'default',+ restartRetries: '',+ noInfra: false,+ infraImage: '',+ infraCommand: '',+ infraName: '',+ infraConmonPidFile: '',+ sharedNamespaces: '',+ shareParent: true,+ pid: '',+ ipc: '',+ uts: '',+ userns: '',+ uidMap: '',+ gidMap: '',+ securityOpt: '',+ networkMode: 'default',+ networkPath: '',+ networkOptions: '',+ dnsServers: '',+ dnsSearch: '',+ dnsOptions: '',+ noResolvConf: false,+ noHosts: false,+ noHostname: false,+ hostsFile: '',+ cgroupParent: '',+ cpus: '',+ cpuShares: '',+ cpusetCpus: '',+ cpusetMems: '',+ memory: '',+ memorySwap: '',+ blkioWeight: '',+ gpus: '',+ volumesFrom: '',+ shmSize: '',+ shmSizeSystemd: ''+ };++ function emptyRows() {+ return {+ labels: [] as KeyValueRow[],+ sysctls: [] as KeyValueRow[],+ ports: [] as PortMappingRow[],+ networks: [] as NetworkRow[],+ hosts: [] as HostRow[],+ devices: [] as DeviceRow[],+ volumes: [] as VolumeRow[],+ weightDevices: [] as DeviceLimitRow[],+ readBps: [] as DeviceLimitRow[],+ writeBps: [] as DeviceLimitRow[]+ };+ }++ let resetToken = $state(0);+ let submitted = $state(false);+ let rows = $state(emptyRows());+ let form = $derived.by(() => {+ resetToken;+ return createForm<typeof formSchema>(formSchema, { ...defaults });+ });+ let inputs = $derived(form.inputs);++ const exitPolicies = [+ { value: 'default', label: m.podman_pod_restart_policy_default() },+ { value: 'continue', label: m.podman_pod_exit_policy_continue() },+ { value: 'stop', label: m.podman_pod_exit_policy_stop() }+ ];+ const restartPolicies = [+ { value: 'default', label: m.podman_pod_restart_policy_default() },+ { value: 'no', label: m.common_no() },+ { value: 'always', label: m.common_always() },+ { value: 'on-failure', label: m.restart_policy_on_failure() },+ { value: 'unless-stopped', label: m.restart_policy_unless_stopped() }+ ];+ const networkModes = [+ { value: 'default', label: m.podman_pod_network_mode_default() },+ { value: 'bridge', label: m.bridge() },+ { value: 'host', label: m.host() },+ { value: 'none', label: m.none() },+ { value: 'private', label: m.podman_pod_network_mode_private() },+ { value: 'slirp4netns', label: 'slirp4netns' },+ { value: 'pasta', label: 'pasta' },+ { value: 'path', label: m.podman_pod_network_mode_path() }+ ];++ const filled = (...values: string[]) => values.some((value) => value.trim() !== '');+ const deviceLimitInvalid = (limits: DeviceLimitRow[]) =>+ limits.some((row) => filled(row.device, row.value) && (!devicePattern.test(row.device.trim()) || !row.value.trim()));+ const portsInvalid = $derived(+ rows.ports.some((row) => filled(row.hostPort, row.containerPort, row.hostIp) && !(Number(row.containerPort) > 0))+ );+ const networksInvalid = $derived(+ rows.networks.some((row) => filled(row.aliases, row.staticIps, row.staticMac, row.interfaceName) && !row.name.trim())+ );+ const hostsInvalid = $derived(rows.hosts.some((row) => filled(row.host, row.ip) && !(row.host.trim() && row.ip.trim())));+ const volumesInvalid = $derived(+ rows.volumes.some((row) => filled(row.source, row.destination, row.options) && !(row.source.trim() && row.destination.trim()))+ );+ const limitsInvalid = $derived(+ deviceLimitInvalid(rows.weightDevices) || deviceLimitInvalid(rows.readBps) || deviceLimitInvalid(rows.writeBps)+ );++ function nonEmpty<T>(items: T[]): T[] | undefined {+ return items.length > 0 ? items : undefined;+ }++ function keyValues(entries: KeyValueRow[]): Record<string, string> | undefined {+ const pairs = entries.filter((row) => row.key.trim()).map((row) => [row.key.trim(), row.value.trim()] as const);+ return pairs.length > 0 ? Object.fromEntries(pairs) : undefined;+ }++ function deviceLimits(limits: DeviceLimitRow[]): PodmanPodDeviceLimit[] | undefined {+ return nonEmpty(+ limits.filter((row) => filled(row.device, row.value)).map((row) => ({ device: row.device.trim(), value: row.value.trim() }))+ );+ }++ function handleSubmit() {+ submitted = true;+ const data = form.validate();+ if (!data || portsInvalid || networksInvalid || hostsInvalid || volumesInvalid || limitsInvalid) return;++ const networkMode = data.networkMode === 'path' ? `ns:${data.networkPath}` : data.networkMode;+ onSubmit(+ {+ name: data.podName,+ hostname: data.hostname || undefined,+ labels: keyValues(rows.labels),+ exitPolicy: data.exitPolicy === 'default' ? undefined : (data.exitPolicy as PodmanPodExitPolicy),+ restartPolicy: data.restartPolicy === 'default' ? undefined : (data.restartPolicy as PodmanPodRestartPolicy),+ restartRetries: data.restartPolicy === 'on-failure' && data.restartRetries ? Number(data.restartRetries) : undefined,+ noInfra: data.noInfra || undefined,+ infraImage: data.noInfra ? undefined : data.infraImage || undefined,+ infraCommand: data.noInfra ? undefined : nonEmpty(data.infraCommand.split(/\s+/).filter(Boolean)),+ infraName: data.noInfra ? undefined : data.infraName || undefined,+ infraConmonPidFile: data.noInfra ? undefined : data.infraConmonPidFile || undefined,+ sharedNamespaces: nonEmpty(parseList(data.sharedNamespaces)),+ shareParent: data.shareParent ? undefined : false,+ pid: data.pid || undefined,+ ipc: data.ipc || undefined,+ uts: data.uts || undefined,+ userns: data.userns || undefined,+ uidMap: nonEmpty(parseList(data.uidMap)),+ gidMap: nonEmpty(parseList(data.gidMap)),+ securityOpt: nonEmpty(parseList(data.securityOpt)),+ sysctl: keyValues(rows.sysctls),+ networkMode: data.networkMode === 'default' ? undefined : networkMode,+ networkOptions: nonEmpty(parseList(data.networkOptions)),+ networks: nonEmpty(+ rows.networks+ .filter((row) => row.name.trim())+ .map((row) => ({+ name: row.name.trim(),+ aliases: nonEmpty(parseList(row.aliases)),+ staticIps: nonEmpty(parseList(row.staticIps)),+ staticMac: row.staticMac.trim() || undefined,+ interfaceName: row.interfaceName.trim() || undefined+ }))+ ),+ portMappings: nonEmpty(+ rows.ports+ .filter((row) => row.containerPort.trim())+ .map((row) => ({+ containerPort: Number(row.containerPort),+ hostPort: row.hostPort.trim() ? Number(row.hostPort) : undefined,+ hostIp: row.hostIp.trim() || undefined,+ protocol: row.protocol+ }))+ ),+ dnsServers: nonEmpty(parseList(data.dnsServers)),+ dnsSearch: nonEmpty(parseList(data.dnsSearch)),+ dnsOptions: nonEmpty(parseList(data.dnsOptions)),+ noManageResolvConf: data.noResolvConf || undefined,+ addHosts: nonEmpty(rows.hosts.filter((row) => row.host.trim()).map((row) => `${row.host.trim()}:${row.ip.trim()}`)),+ noHosts: data.noHosts || undefined,+ noHostname: data.noHostname || undefined,+ hostsFile: data.hostsFile || undefined,+ cgroupParent: data.cgroupParent || undefined,+ cpus: data.cpus ? Number(data.cpus) : undefined,+ cpuShares: data.cpuShares ? Number(data.cpuShares) : undefined,+ cpusetCpus: data.cpusetCpus || undefined,+ cpusetMems: data.cpusetMems || undefined,+ memory: data.memory || undefined,+ memorySwap: data.memorySwap || undefined,+ blkioWeight: data.blkioWeight ? Number(data.blkioWeight) : undefined,+ blkioWeightDevices: deviceLimits(rows.weightDevices),+ deviceReadBps: deviceLimits(rows.readBps),+ deviceWriteBps: deviceLimits(rows.writeBps),+ devices: nonEmpty(rows.devices.map((row) => row.device.trim()).filter(Boolean)),+ gpus: nonEmpty(parseList(data.gpus)),+ volumes: nonEmpty(+ rows.volumes+ .filter((row) => row.source.trim())+ .map((row) => ({+ source: row.source.trim(),+ destination: row.destination.trim(),+ options: nonEmpty(parseList(row.options))+ }))+ ),+ volumesFrom: nonEmpty(parseList(data.volumesFrom)),+ shmSize: data.shmSize || undefined,+ shmSizeSystemd: data.shmSizeSystemd || undefined+ },+ environmentId+ );+ }++ function handleOpenChange(newOpenState: boolean) {+ open = newOpenState;+ if (!newOpenState) {+ pickedEnvironmentId = '';+ submitted = false;+ rows = emptyRows();+ resetToken += 1;+ }+ }+</script>++{#snippet rowsError(invalid: boolean)}+ {#if submitted && invalid}+ <p class="text-xs font-medium text-destructive">{m.podman_pod_invalid_rows()}</p>+ {/if}+{/snippet}++{#snippet deviceLimitEditor(label: string, limits: DeviceLimitRow[], valuePlaceholder: string)}+ <div class="space-y-2">+ <Label>{label}</Label>+ <RowListEditor+ rows={limits}+ disabled={isLoading}+ createRow={() => ({ device: '', value: '' })}+ addLabel={m.podman_pod_add_device()}+ >+ {#snippet children(row)}+ <Input+ type="text"+ placeholder={m.podman_pod_device_limit_device_placeholder()}+ bind:value={row.device}+ disabled={isLoading}+ mono+ class="flex-1"+ />+ <Input type="text" placeholder={valuePlaceholder} bind:value={row.value} disabled={isLoading} mono class="flex-1" />+ {/snippet}+ </RowListEditor>+ {@render rowsError(deviceLimitInvalid(limits))}+ </div>+{/snippet}++<ResponsiveDialog.Root+ {open}+ onOpenChange={handleOpenChange}+ variant="sheet"+ title={m.common_create_button({ resource: m.podman_pod() })}+ description={m.podman_pod_create_description()}+ contentClass="sm:max-w-150"+>+ {#snippet children()}+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">+ <EnvironmentDestinationSelect+ bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}+ permission="podman:pods"+ {environments}+ variant="field"+ />+ <FormInput+ label={m.common_name()}+ placeholder={m.podman_pod_name_placeholder()}+ disabled={isLoading}+ bind:input={inputs.podName}+ />+ <FormInput+ label={m.hostname()}+ placeholder={m.podman_pod_hostname_placeholder()}+ disabled={isLoading}+ bind:input={inputs.hostname}+ />++ <Accordion.Root type="single" class="w-full">+ <Accordion.Item value="networking">+ <Accordion.Trigger>{m.podman_pod_section_networking()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="space-y-4 pt-4">+ <SelectWithLabel+ id="pod-network-mode"+ bind:value={inputs.networkMode.value}+ label={m.podman_pod_network_mode()}+ description={m.podman_pod_network_mode_description()}+ options={networkModes}+ disabled={isLoading}+ />+ {#if inputs.networkMode.value === 'path'}+ <FormInput+ label={m.podman_pod_network_namespace_path()}+ placeholder={m.podman_pod_network_namespace_path_placeholder()}+ disabled={isLoading}+ bind:input={inputs.networkPath}+ />+ {/if}+ {#if inputs.networkMode.value === 'pasta' || inputs.networkMode.value === 'slirp4netns'}+ <FormInput+ label={m.podman_pod_network_options()}+ description={m.podman_pod_network_options_description()}+ placeholder={inputs.networkMode.value === 'pasta'+ ? m.podman_pod_network_options_pasta_placeholder()+ : m.podman_pod_network_options_slirp_placeholder()}+ disabled={isLoading}+ bind:input={inputs.networkOptions}+ />+ {/if}+ <div class="space-y-2">+ <Label>{m.podman_pod_networks()}</Label>+ <p class="text-xs text-muted-foreground">{m.podman_pod_networks_description()}</p>+ <RowListEditor+ bind:rows={rows.networks}+ disabled={isLoading}+ createRow={() => ({ name: '', aliases: '', staticIps: '', staticMac: '', interfaceName: '' })}+ addLabel={m.podman_pod_add_network()}+ >+ {#snippet children(row)}+ <div class="grid flex-1 grid-cols-1 gap-2 sm:grid-cols-2">+ <Input+ type="text"+ placeholder={m.podman_pod_network_name_placeholder()}+ bind:value={row.name}+ disabled={isLoading}+ mono+ />+ <Input+ type="text"+ placeholder={m.podman_pod_network_aliases_placeholder()}+ title={m.containers_aliases()}+ bind:value={row.aliases}+ disabled={isLoading}+ mono+ />+ <Input+ type="text"+ placeholder={m.podman_pod_network_ip_placeholder()}+ title={m.static_ip()}+ bind:value={row.staticIps}+ disabled={isLoading}+ mono+ />+ <Input+ type="text"+ placeholder={m.podman_pod_network_mac_placeholder()}+ title={m.containers_mac_address()}+ bind:value={row.staticMac}+ disabled={isLoading}+ mono+ />+ <Input+ type="text"+ placeholder={m.podman_pod_network_interface_placeholder()}+ title={m.podman_pod_interface_name()}+ bind:value={row.interfaceName}+ disabled={isLoading}+ mono+ />+ </div>+ {/snippet}+ </RowListEditor>+ {@render rowsError(networksInvalid)}+ </div>+ <div class="space-y-2">+ <Label>{m.common_port_mappings()}</Label>+ <PortMappingEditor bind:rows={rows.ports} disabled={isLoading} />+ {@render rowsError(portsInvalid)}+ </div>+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="dns">+ <Accordion.Trigger>{m.podman_pod_section_dns_hosts()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="space-y-4 pt-4">+ <FormInput+ label={m.podman_pod_dns_servers()}+ description={m.podman_comma_separated()}+ placeholder={m.podman_pod_dns_servers_placeholder()}+ disabled={isLoading}+ bind:input={inputs.dnsServers}+ />+ <FormInput+ label={m.podman_pod_dns_search()}+ description={m.podman_comma_separated()}+ placeholder={m.podman_pod_dns_search_placeholder()}+ disabled={isLoading}+ bind:input={inputs.dnsSearch}+ />+ <FormInput+ label={m.podman_pod_dns_options()}+ description={m.podman_comma_separated()}+ placeholder={m.podman_pod_dns_options_placeholder()}+ disabled={isLoading}+ bind:input={inputs.dnsOptions}+ />+ <FormInput+ label={m.podman_pod_no_resolv_conf()}+ description={m.podman_pod_no_resolv_conf_description()}+ type="switch"+ disabled={isLoading}+ bind:input={inputs.noResolvConf}+ />+ <div class="space-y-2">+ <Label>{m.podman_pod_add_hosts()}</Label>+ <p class="text-xs text-muted-foreground">{m.podman_pod_add_hosts_description()}</p>+ <RowListEditor+ bind:rows={rows.hosts}+ disabled={isLoading}+ createRow={() => ({ host: '', ip: '' })}+ addLabel={m.podman_pod_add_host()}+ >+ {#snippet children(row)}+ <Input+ type="text"+ placeholder={m.podman_pod_host_name_placeholder()}+ bind:value={row.host}+ disabled={isLoading}+ mono+ class="flex-1"+ />+ <Input+ type="text"+ placeholder={m.podman_pod_host_ip_placeholder()}+ bind:value={row.ip}+ disabled={isLoading}+ mono+ class="flex-1"+ />+ {/snippet}+ </RowListEditor>+ {@render rowsError(hostsInvalid)}+ </div>+ <FormInput+ label={m.podman_pod_hosts_file()}+ description={m.podman_pod_hosts_file_description()}+ placeholder={m.podman_pod_hosts_file_placeholder()}+ disabled={isLoading || inputs.noHosts.value}+ bind:input={inputs.hostsFile}+ />+ <FormInput label={m.podman_pod_no_hosts()} type="switch" disabled={isLoading} bind:input={inputs.noHosts} />+ <FormInput label={m.podman_pod_no_hostname()} type="switch" disabled={isLoading} bind:input={inputs.noHostname} />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="resources">+ <Accordion.Trigger>{m.common_resources()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="space-y-4 pt-4">+ <div class="grid gap-4 sm:grid-cols-2">+ <FormInput+ label={m.common_cpus()}+ description={m.podman_pod_cpus_description()}+ placeholder={m.podman_pod_cpus_placeholder()}+ disabled={isLoading}+ bind:input={inputs.cpus}+ />+ <FormInput+ label={m.cpu_shares()}+ description={m.podman_pod_cpu_shares_description()}+ placeholder={m.podman_pod_cpu_shares_placeholder()}+ disabled={isLoading}+ bind:input={inputs.cpuShares}+ />+ <FormInput+ label={m.podman_pod_cpuset_cpus()}+ description={m.podman_pod_cpuset_cpus_description()}+ placeholder={m.podman_pod_cpuset_cpus_placeholder()}+ disabled={isLoading}+ bind:input={inputs.cpusetCpus}+ />+ <FormInput+ label={m.podman_pod_cpuset_mems()}+ description={m.podman_pod_cpuset_mems_description()}+ placeholder={m.podman_pod_cpuset_mems_placeholder()}+ disabled={isLoading}+ bind:input={inputs.cpusetMems}+ />+ <FormInput+ label={m.podman_pod_memory()}+ description={m.podman_pod_size_description()}+ placeholder={m.podman_pod_memory_placeholder()}+ disabled={isLoading}+ bind:input={inputs.memory}+ />+ <FormInput+ label={m.podman_pod_memory_swap()}+ description={m.podman_pod_memory_swap_description()}+ placeholder={m.podman_pod_memory_swap_placeholder()}+ disabled={isLoading}+ bind:input={inputs.memorySwap}+ />+ <FormInput+ label={m.podman_pod_blkio_weight()}+ description={m.podman_pod_blkio_weight_description()}+ placeholder={m.podman_pod_blkio_weight_placeholder()}+ disabled={isLoading}+ bind:input={inputs.blkioWeight}+ />+ <FormInput+ label={m.podman_pod_cgroup_parent()}+ description={m.podman_pod_cgroup_parent_description()}+ placeholder={m.podman_pod_cgroup_parent_placeholder()}+ disabled={isLoading}+ bind:input={inputs.cgroupParent}+ />+ </div>+ <p class="text-xs text-muted-foreground">{m.podman_pod_device_limit_description()}</p>+ {@render deviceLimitEditor(+ m.podman_pod_blkio_weight_devices(),+ rows.weightDevices,+ m.podman_pod_blkio_weight_device_placeholder()+ )}+ {@render deviceLimitEditor(+ m.podman_pod_device_read_bps(),+ rows.readBps,+ m.podman_pod_device_read_bps_placeholder()+ )}+ {@render deviceLimitEditor(+ m.podman_pod_device_write_bps(),+ rows.writeBps,+ m.podman_pod_device_write_bps_placeholder()+ )}+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="storage">+ <Accordion.Trigger>{m.podman_pod_section_storage()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="space-y-4 pt-4">+ <div class="space-y-2">+ <Label>{m.volume_mounts_title()}</Label>+ <p class="text-xs text-muted-foreground">{m.podman_pod_volumes_description()}</p>+ <RowListEditor+ bind:rows={rows.volumes}+ disabled={isLoading}+ createRow={() => ({ source: '', destination: '', options: '' })}+ addLabel={m.add_volume_mount_button()}+ >+ {#snippet children(row)}+ <Input+ type="text"+ placeholder={m.podman_pod_volume_source_placeholder()}+ title={m.container_source_path_or_volume()}+ bind:value={row.source}+ disabled={isLoading}+ mono+ class="flex-1"+ />+ <Input+ type="text"+ placeholder={m.podman_pod_volume_target_placeholder()}+ title={m.container_path()}+ bind:value={row.destination}+ disabled={isLoading}+ mono+ class="flex-1"+ />+ <Input+ type="text"+ placeholder={m.podman_pod_volume_options_placeholder()}+ title={m.podman_pod_volume_options()}+ bind:value={row.options}+ disabled={isLoading}+ mono+ class="flex-1"+ />+ {/snippet}+ </RowListEditor>+ {@render rowsError(volumesInvalid)}+ </div>+ <FormInput+ label={m.podman_pod_volumes_from()}+ description={m.podman_pod_volumes_from_description()}+ placeholder={m.podman_pod_volumes_from_placeholder()}+ disabled={isLoading}+ bind:input={inputs.volumesFrom}+ />+ <div class="grid gap-4 sm:grid-cols-2">+ <FormInput+ label={m.podman_pod_shm_size()}+ description={m.podman_pod_size_description()}+ placeholder={m.podman_pod_shm_size_placeholder()}+ disabled={isLoading}+ bind:input={inputs.shmSize}+ />+ <FormInput+ label={m.podman_pod_shm_size_systemd()}+ description={m.podman_pod_shm_size_systemd_description()}+ placeholder={m.podman_pod_shm_size_systemd_placeholder()}+ disabled={isLoading}+ bind:input={inputs.shmSizeSystemd}+ />+ </div>+ <div class="space-y-2">+ <Label>{m.podman_pod_devices()}</Label>+ <p class="text-xs text-muted-foreground">{m.podman_pod_devices_description()}</p>+ <RowListEditor+ bind:rows={rows.devices}+ disabled={isLoading}+ createRow={() => ({ device: '' })}+ addLabel={m.podman_pod_add_device()}+ >+ {#snippet children(row)}+ <Input+ type="text"+ placeholder={m.podman_pod_device_placeholder()}+ bind:value={row.device}+ disabled={isLoading}+ mono+ class="flex-1"+ />+ {/snippet}+ </RowListEditor>+ </div>+ <FormInput+ label={m.podman_pod_gpus()}+ description={m.podman_pod_gpus_description()}+ placeholder={m.podman_pod_gpus_placeholder()}+ disabled={isLoading}+ bind:input={inputs.gpus}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="namespaces">+ <Accordion.Trigger>{m.podman_pod_section_namespaces()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="space-y-4 pt-4">+ <FormInput+ label={m.podman_pod_shared_namespaces()}+ description={m.podman_pod_shared_namespaces_description()}+ placeholder={m.podman_pod_shared_namespaces_placeholder()}+ disabled={isLoading || inputs.noInfra.value}+ bind:input={inputs.sharedNamespaces}+ />+ <FormInput+ label={m.podman_pod_share_parent()}+ description={m.podman_pod_share_parent_description()}+ type="switch"+ disabled={isLoading}+ bind:input={inputs.shareParent}+ />+ <div class="grid gap-4 sm:grid-cols-2">+ <FormInput+ label={m.podman_pod_pid_namespace()}+ description={m.podman_pod_namespace_description()}+ placeholder={m.podman_pod_pid_namespace_placeholder()}+ disabled={isLoading}+ bind:input={inputs.pid}+ />+ <FormInput+ label={m.podman_pod_ipc_namespace()}+ description={m.podman_pod_namespace_description()}+ placeholder={m.podman_pod_ipc_namespace_placeholder()}+ disabled={isLoading}+ bind:input={inputs.ipc}+ />+ <FormInput+ label={m.podman_pod_uts_namespace()}+ description={m.podman_pod_namespace_description()}+ placeholder={m.podman_pod_uts_namespace_placeholder()}+ disabled={isLoading}+ bind:input={inputs.uts}+ />+ <FormInput+ label={m.podman_pod_user_namespace()}+ description={m.podman_pod_user_namespace_description()}+ placeholder={m.podman_pod_user_namespace_placeholder()}+ disabled={isLoading}+ bind:input={inputs.userns}+ />+ <FormInput+ label={m.podman_pod_uid_map()}+ description={m.podman_pod_id_map_description()}+ placeholder={m.podman_pod_uid_map_placeholder()}+ disabled={isLoading}+ bind:input={inputs.uidMap}+ />+ <FormInput+ label={m.podman_pod_gid_map()}+ description={m.podman_pod_id_map_description()}+ placeholder={m.podman_pod_gid_map_placeholder()}+ disabled={isLoading}+ bind:input={inputs.gidMap}+ />+ </div>+ <FormInput+ label={m.podman_pod_security_opt()}+ description={m.podman_pod_security_opt_description()}+ placeholder={m.podman_pod_security_opt_placeholder()}+ disabled={isLoading}+ bind:input={inputs.securityOpt}+ />+ <div class="space-y-2">+ <Label>{m.podman_pod_sysctl()}</Label>+ <p class="text-xs text-muted-foreground">{m.podman_pod_sysctl_description()}</p>+ <KeyValueEditor+ bind:rows={rows.sysctls}+ keyPlaceholder={m.podman_pod_sysctl_key_placeholder()}+ valuePlaceholder={m.podman_pod_sysctl_value_placeholder()}+ disabled={isLoading}+ />+ </div>+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="lifecycle">+ <Accordion.Trigger>{m.podman_pod_section_lifecycle()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="space-y-4 pt-4">+ <SelectWithLabel+ id="pod-exit-policy"+ bind:value={inputs.exitPolicy.value}+ label={m.podman_pod_exit_policy()}+ description={m.podman_pod_exit_policy_description()}+ options={exitPolicies}+ disabled={isLoading}+ />+ <SelectWithLabel+ id="pod-restart-policy"+ bind:value={inputs.restartPolicy.value}+ label={m.restart_policy_label()}+ description={m.podman_pod_restart_policy_description()}+ options={restartPolicies}+ disabled={isLoading}+ />+ {#if inputs.restartPolicy.value === 'on-failure'}+ <FormInput+ label={m.max_retry_label()}+ description={m.podman_pod_restart_retries_description()}+ placeholder={m.max_retry_placeholder()}+ disabled={isLoading}+ bind:input={inputs.restartRetries}+ />+ {/if}+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="infra">+ <Accordion.Trigger>{m.podman_pod_infra()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="space-y-4 pt-4">+ <FormInput+ label={m.podman_pod_no_infra()}+ description={m.podman_pod_no_infra_description()}+ type="switch"+ disabled={isLoading}+ bind:input={inputs.noInfra}+ />+ <FormInput+ label={m.podman_pod_infra_image()}+ description={m.podman_pod_infra_image_description()}+ placeholder={m.podman_pod_infra_image_placeholder()}+ disabled={isLoading || inputs.noInfra.value}+ bind:input={inputs.infraImage}+ />+ <FormInput+ label={m.podman_pod_infra_command()}+ description={m.podman_pod_infra_command_description()}+ placeholder={m.podman_pod_infra_command_placeholder()}+ disabled={isLoading || inputs.noInfra.value}+ bind:input={inputs.infraCommand}+ />+ <FormInput+ label={m.podman_pod_infra_name()}+ placeholder={m.podman_pod_infra_name_placeholder()}+ disabled={isLoading || inputs.noInfra.value}+ bind:input={inputs.infraName}+ />+ <FormInput+ label={m.podman_pod_infra_conmon_pidfile()}+ description={m.podman_pod_infra_conmon_pidfile_description()}+ placeholder={m.podman_pod_infra_conmon_pidfile_placeholder()}+ disabled={isLoading || inputs.noInfra.value}+ bind:input={inputs.infraConmonPidFile}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="labels">+ <Accordion.Trigger>{m.common_labels()}</Accordion.Trigger>+ <Accordion.Content>+ <div class="pt-4">+ <KeyValueEditor+ bind:rows={rows.labels}+ keyPlaceholder={m.podman_pod_label_key_placeholder()}+ valuePlaceholder={m.podman_pod_label_value_placeholder()}+ addLabel={m.add_label()}+ disabled={isLoading}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>+ </Accordion.Root>+ </form>+ {/snippet}++ {#snippet footer()}+ <SheetFooterActions+ bind:open+ onCancel={() => handleOpenChange(false)}+ cancelDisabled={isLoading}+ submitDisabled={isLoading}+ submitLoading={isLoading}+ onSubmit={handleSubmit}+ submitLabel={m.common_create_button({ resource: m.podman_pod() })}+ />+ {/snippet}+</ResponsiveDialog.Root>diff --git a/frontend/src/lib/components/sheets/podman-secret-form-sheet.svelte b/frontend/src/lib/components/sheets/podman-secret-form-sheet.sveltenew file mode 100644index 000000000..3a3042501--- /dev/null+++ b/frontend/src/lib/components/sheets/podman-secret-form-sheet.svelte@@ -0,0 +1,195 @@+<script lang="ts">+ import { untrack } from 'svelte';+ import { toast } from 'svelte-sonner';++ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';+ import KeyValueEditor from '#lib/components/form/key-value-editor.svelte';+ import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';+ import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';+ import { Label } from '#lib/components/ui/label/index.js';+ import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';+ import { Textarea } from '#lib/components/ui/textarea/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import type { EnvironmentRef } from '#lib/stores/environment.store.svelte.js';+ import type { PodmanSecret } from '#lib/types/podman.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { destinationEnvironmentId, type EnvironmentRow } from '#lib/utils/environments.js';+ import { keyValueRowsToRecord, recordToKeyValueRows } from '#lib/utils/form-parsers.js';+ import { formatRelativeTime } from '#lib/utils/formatting.js';+ import { preventDefault } from '#lib/utils/settings.svelte.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ let {+ open = $bindable(false),+ environments,+ existing,+ onSaved+ }: {+ open: boolean;+ environments: EnvironmentRef[];+ existing: EnvironmentRow<PodmanSecret> | null;+ onSaved: () => Promise<void>;+ } = $props();++ const initial = untrack(() => existing?.spec);+ let pickedEnvironmentId = $state('');+ let name = $state(initial?.name ?? '');+ let driver = $state(initial?.driver.name ?? '');+ let driverOptions = $state(recordToKeyValueRows(initial?.driver.options));+ let labels = $state(recordToKeyValueRows(initial?.labels));+ let value = $state('');+ let submitting = $state(false);++ const environmentId = $derived(+ existing?.environmentId ?? destinationEnvironmentId(pickedEnvironmentId, 'podman:secrets', environments)+ );+ const canManage = $derived(hasPermission('podman:secrets', environmentId));+ const valueLabel = $derived(existing ? m.podman_secrets_new_value_label() : m.value());++ const description = $derived(+ existing+ ? [+ existing.spec.name,+ existing.environmentName,+ existing.spec.driver.name,+ `${m.common_created()} ${formatRelativeTime(existing.createdAt) || m.common_unknown()}`,+ `${m.common_updated()} ${formatRelativeTime(existing.updatedAt) || m.common_unknown()}`+ ]+ .filter(Boolean)+ .join(' · ')+ : m.podman_secrets_subtitle()+ );++ async function handleSubmit() {+ const trimmedName = name.trim();+ if (!trimmedName) {+ toast.error(m.swarm_secrets_name_required());+ return;+ }+ if (!value) {+ toast.error(m.common_field_required({ field: valueLabel }));+ return;+ }+ const request = {+ data: value,+ driver: driver.trim() || undefined,+ driverOptions: keyValueRowsToRecord(driverOptions),+ labels: keyValueRowsToRecord(labels)+ };+ const resourceName = `${m.swarm_secret()} "${trimmedName}"`;+ submitting = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(+ existing+ ? podmanService.updateSecret(trimmedName, request, environmentId)+ : podmanService.createSecret({ ...request, name: trimmedName }, environmentId)+ ),+ message: existing ? m.common_update_failed({ resource: resourceName }) : m.swarm_secrets_create_failed(),+ setLoadingState: (loading) => (submitting = loading),+ onSuccess: async () => {+ toast.success(+ existing ? m.common_update_success({ resource: resourceName }) : m.swarm_secrets_create_success({ name: trimmedName })+ );+ await onSaved();+ }+ });+ }+</script>++<ResponsiveDialog.Root+ bind:open+ variant="sheet"+ title={existing ? m.swarm_secrets_edit_title() : m.create_secret()}+ {description}+ contentClass="sm:max-w-150"+>+ {#snippet children()}+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">+ {#if !existing}+ <EnvironmentDestinationSelect+ bind:value={() => environmentId, (next) => (pickedEnvironmentId = next)}+ permission="podman:secrets"+ {environments}+ variant="field"+ />+ {/if}++ <TextInputWithLabel+ id="podman-secret-name"+ label={m.common_name()}+ placeholder={m.swarm_secrets_name_placeholder()}+ bind:value={name}+ helpText={existing ? m.swarm_secrets_name_locked() : undefined}+ disabled={!!existing || submitting || !canManage}+ required={!existing}+ />++ <TextInputWithLabel+ id="podman-secret-driver"+ label={m.common_driver()}+ placeholder={m.podman_secrets_driver_placeholder()}+ bind:value={driver}+ disabled={submitting || !canManage}+ />++ <div class="space-y-2.5">+ <Label>{m.common_driver_options()}</Label>+ <KeyValueEditor+ bind:rows={driverOptions}+ keyPlaceholder={m.podman_secrets_driver_option_key_placeholder()}+ valuePlaceholder={m.podman_secrets_driver_option_value_placeholder()}+ disabled={submitting || !canManage}+ />+ </div>++ <div class="space-y-2.5">+ <div>+ <Label>{m.common_labels()}</Label>+ <p class="mt-0.5 text-xs text-muted-foreground">{m.common_labels_description({ resource: m.swarm_secret() })}</p>+ </div>+ <KeyValueEditor+ bind:rows={labels}+ keyPlaceholder={m.swarm_secrets_label_key_placeholder()}+ valuePlaceholder={m.swarm_secrets_label_value_placeholder()}+ addLabel={m.add_label()}+ disabled={submitting || !canManage}+ />+ </div>++ <div class="space-y-2.5">+ <Label for="podman-secret-value">+ {valueLabel}{#if !existing}<span class="ml-0.5 text-destructive">*</span>{/if}+ </Label>+ <Textarea+ id="podman-secret-value"+ rows={6}+ mono+ size="sm"+ autocomplete="off"+ spellcheck={false}+ bind:value+ placeholder={existing ? m.podman_secrets_new_value_placeholder() : m.swarm_secrets_data_placeholder()}+ disabled={submitting || !canManage}+ />+ <p class="text-xs text-muted-foreground">+ {existing ? m.podman_secrets_new_value_help() : m.swarm_secrets_value_help()}+ </p>+ </div>+ </form>+ {/snippet}++ {#snippet footer()}+ <SheetFooterActions+ bind:open+ cancelDisabled={submitting}+ showSubmit={canManage}+ submitAction={existing ? 'save' : 'create'}+ submitDisabled={submitting || !value}+ submitLoading={submitting}+ onSubmit={handleSubmit}+ submitLabel={existing ? m.common_save_changes() : m.create_secret()}+ />+ {/snippet}+</ResponsiveDialog.Root>diff --git a/frontend/src/lib/components/sheets/swarm-kv-form-sheet.svelte b/frontend/src/lib/components/sheets/swarm-kv-form-sheet.sveltenew file mode 100644index 000000000..3aa06f0bc--- /dev/null+++ b/frontend/src/lib/components/sheets/swarm-kv-form-sheet.svelte@@ -0,0 +1,189 @@+<script lang="ts">+ import { untrack } from 'svelte';+ import { toast } from 'svelte-sonner';++ import KeyValueEditor from '#lib/components/form/key-value-editor.svelte';+ import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';+ import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';+ import * as Alert from '#lib/components/ui/alert/index.js';+ import { Label } from '#lib/components/ui/label/index.js';+ import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';+ import { Textarea } from '#lib/components/ui/textarea/index.js';+ import { InfoIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { swarmService } from '#lib/services/swarm-service.js';+ import type { SwarmKvSummary } from '#lib/types/swarm.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { keyValueRowsToRecord, recordToKeyValueRows } from '#lib/utils/form-parsers.js';+ import { formatRelativeTime } from '#lib/utils/formatting.js';+ import { preventDefault } from '#lib/utils/settings.svelte.js';+ import { decodeBase64ToText, encodeTextToBase64, type SwarmKvResource } from '#lib/utils/swarm-kv.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ let {+ open = $bindable(false),+ resource,+ environmentId,+ existing,+ onSaved+ }: {+ open: boolean;+ resource: SwarmKvResource;+ environmentId: string;+ existing: SwarmKvSummary | null;+ onSaved: () => Promise<void>;+ } = $props();++ const isSecret = $derived(resource.kind === 'secrets');+ const canManage = $derived(hasPermission(resource.permission, environmentId));++ const initial = untrack(() => existing?.spec);+ let name = $state(initial?.Name ?? '');+ let data = $state(decodeBase64ToText(initial?.Data ?? ''));+ let labels = $state(recordToKeyValueRows(initial?.Labels));+ let submitting = $state(false);++ const description = $derived(+ existing+ ? [+ existing.spec.Name,+ existing.spec.Driver?.Name,+ `${m.common_created()} ${formatRelativeTime(existing.createdAt) || m.common_unknown()}`,+ `${m.common_updated()} ${formatRelativeTime(existing.updatedAt) || m.common_unknown()}`+ ]+ .filter(Boolean)+ .join(' · ')+ : resource.subtitle()+ );++ async function handleSubmit() {+ if (existing) {+ const resourceName = `${resource.resource()} "${existing.spec.Name}"`;+ submitting = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(+ swarmService.updateKvItem(+ resource.kind,+ existing.id,+ {+ version: existing.version.Index ?? 0,+ labels: keyValueRowsToRecord(labels)+ },+ environmentId+ )+ ),+ message: m.common_update_failed({ resource: resourceName }),+ setLoadingState: (value) => (submitting = value),+ onSuccess: async () => {+ toast.success(m.common_update_success({ resource: resourceName }));+ await onSaved();+ }+ });+ return;+ }++ const trimmedName = name.trim();+ if (!trimmedName) {+ toast.error(resource.nameRequired());+ return;+ }+ submitting = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(+ swarmService.createKvItem(+ resource.kind,+ {+ spec: {+ Name: trimmedName,+ Labels: keyValueRowsToRecord(labels),+ Data: encodeTextToBase64(data)+ }+ },+ environmentId+ )+ ),+ message: resource.createFailed(),+ setLoadingState: (value) => (submitting = value),+ onSuccess: async () => {+ toast.success(resource.createSuccess(trimmedName));+ await onSaved();+ }+ });+ }+</script>++<ResponsiveDialog.Root+ bind:open+ variant="sheet"+ title={existing ? resource.editTitle() : resource.createLabel()}+ {description}+ contentClass="sm:max-w-150"+>+ {#snippet children()}+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">+ <TextInputWithLabel+ id="swarm-kv-name"+ label={m.common_name()}+ placeholder={resource.namePlaceholder()}+ bind:value={name}+ helpText={existing ? resource.nameLocked() : undefined}+ disabled={!!existing || submitting || !canManage}+ required={!existing}+ />++ <div class="space-y-2.5">+ <div>+ <Label>{m.common_labels()}</Label>+ <p class="mt-0.5 text-xs text-muted-foreground">{m.common_labels_description({ resource: resource.resource() })}</p>+ </div>+ <KeyValueEditor+ bind:rows={labels}+ keyPlaceholder={m.swarm_secrets_label_key_placeholder()}+ valuePlaceholder={m.swarm_secrets_label_value_placeholder()}+ addLabel={m.add_label()}+ disabled={submitting || !canManage}+ />+ </div>++ {#if existing && isSecret}+ <Alert.Root variant="primary-subtle">+ <InfoIcon class="size-4" />+ <Alert.Description>{resource.immutableNotice()}</Alert.Description>+ </Alert.Root>+ {:else}+ <div class="space-y-2.5">+ <Label for="swarm-kv-data">{isSecret ? m.value() : m.swarm_configs_content_label()}</Label>+ <Textarea+ id="swarm-kv-data"+ rows={isSecret ? 6 : 14}+ mono+ size="sm"+ bind:value={data}+ placeholder={isSecret ? m.swarm_secrets_data_placeholder() : m.swarm_configs_data_placeholder()}+ readonly={!!existing || !canManage}+ disabled={submitting}+ />+ {#if existing}+ <p class="text-xs text-muted-foreground">{resource.immutableNotice()}</p>+ {:else if isSecret}+ <p class="text-xs text-muted-foreground">{m.swarm_secrets_value_help()}</p>+ {/if}+ </div>+ {/if}+ </form>+ {/snippet}++ {#snippet footer()}+ <SheetFooterActions+ bind:open+ cancelDisabled={submitting}+ showSubmit={canManage}+ submitAction={existing ? 'save' : 'create'}+ onSubmit={handleSubmit}+ submitDisabled={submitting}+ submitLoading={submitting}+ submitLabel={existing ? m.common_save_changes() : resource.createLabel()}+ />+ {/snippet}+</ResponsiveDialog.Root>diff --git a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelteindex 06eb0eff7..59992856e 100644--- a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte+++ b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte@@ -1,15 +1,18 @@<script lang="ts">+ import { Badge } from '#lib/components/ui/badge/index.js';import * as Sidebar from '#lib/components/ui/sidebar/index.js';import { EnvironmentsIcon, RemoteEnvironmentIcon, EdgeConnectionIcon, ArrowsUpDownIcon } from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';import settingsStore from '#lib/stores/config-store.svelte.js';import { allEnvironmentsPreview, environmentStore } from '#lib/stores/environment.store.svelte.js';+ import type { PodmanStatus } from '#lib/types/podman.js';type Props = {onOpenDialog?: () => void;+ podmanStatus?: PodmanStatus | null;};- let { onOpenDialog }: Props = $props();+ let { onOpenDialog, podmanStatus = null }: Props = $props();function getConnectionString(): string {if (!environmentStore.selected) return '';@@ -43,8 +46,13 @@{/if}</div><div class="grid flex-1 text-left text-sm leading-tight">- <span class="truncate font-medium">- {environmentStore.selected.name}+ <span class="flex min-w-0 items-center gap-1.5">+ <span class="truncate font-medium">+ {environmentStore.selected.name}+ </span>+ {#if podmanStatus?.detected}+ <Badge variant="purple" size="xs">{m.podman()}</Badge>+ {/if}</span><span class="truncate text-xs">{getConnectionString()}diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelteindex b61e6b209..c5848bab5 100644--- a/frontend/src/lib/components/sidebar/sidebar.svelte+++ b/frontend/src/lib/components/sidebar/sidebar.svelte@@ -3,6 +3,7 @@navigationItems,getManagementItems,getSwarmNavigationItems,+ getPodmanNavigationItems,filterByPermissions} from '#lib/config/navigation-config.js';</script>@@ -20,6 +21,7 @@import { environmentStore } from '#lib/stores/environment.store.svelte.js';import userStore from '#lib/stores/user-store.svelte.js';import type { PermissionsManifest, User } from '#lib/types/auth.js';+ import type { PodmanStatus } from '#lib/types/podman.js';import type { AppVersionInformation } from '#lib/types/settings.js';import SidebarEnvSwitcher from './sidebar-env-switcher.svelte';@@ -36,12 +38,14 @@user,versionInformation,swarmEnabled,+ podmanStatuses = {},permissionsManifest = null,...restProps}: ComponentProps<typeof Sidebar.Root> & {versionInformation: AppVersionInformation;user?: User | null;swarmEnabled?: boolean;+ podmanStatuses?: Record<string, PodmanStatus>;permissionsManifest?: PermissionsManifest | null;} = $props();@@ -68,6 +72,14 @@filterByPermissions(navigationItems.resourceItems, effectiveUser ?? null, currentEnvId, permissionsManifest));const swarmItems = $derived(filterByPermissions(swarmItemsRaw, effectiveUser ?? null, currentEnvId, permissionsManifest));+ const podmanItems = $derived(+ filterByPermissions(+ getPodmanNavigationItems(podmanStatuses, currentEnvId),+ effectiveUser ?? null,+ currentEnvId,+ permissionsManifest+ )+ );const settingsItems = $derived(filterByPermissions(navigationItems.settingsItems, effectiveUser ?? null, currentEnvId, permissionsManifest));@@ -99,10 +111,10 @@</div>{#if isCollapsed}<div class="flex justify-center px-1">- <SidebarEnvSwitcher onOpenDialog={() => (envSwitcherOpen = true)} />+ <SidebarEnvSwitcher onOpenDialog={() => (envSwitcherOpen = true)} podmanStatus={podmanStatuses[currentEnvId]} /></div>{:else}- <SidebarEnvSwitcher onOpenDialog={() => (envSwitcherOpen = true)} />+ <SidebarEnvSwitcher onOpenDialog={() => (envSwitcherOpen = true)} podmanStatus={podmanStatuses[currentEnvId]} />{/if}{#if isCollapsed}<div class="flex justify-center px-1 pt-1">@@ -128,6 +140,9 @@{#if swarmItems.length > 0}<SidebarItemGroup label={m.swarm()} items={swarmItems} />{/if}+ {#if podmanItems.length > 0}+ <SidebarItemGroup label={m.podman()} items={podmanItems} />+ {/if}{#if settingsItems.length > 0}<SidebarItemGroup label={m.sidebar_administration()} items={settingsItems} />{/if}diff --git a/frontend/src/lib/components/swarm/swarm-kv-page.svelte b/frontend/src/lib/components/swarm/swarm-kv-page.svelteindex 66a5f1a44..92b7aa642 100644--- a/frontend/src/lib/components/swarm/swarm-kv-page.svelte+++ b/frontend/src/lib/components/swarm/swarm-kv-page.svelte@@ -1,297 +1,114 @@<script lang="ts">- import { onMount, type Component } from 'svelte';- import { toast } from 'svelte-sonner';-- import { ArcaneButton } from '#lib/components/arcane-button/index.js';- import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';- import IfPermitted from '#lib/components/if-permitted.svelte';- import * as Card from '#lib/components/ui/card/index.js';- import { CopyButton } from '#lib/components/ui/copy-button/index.js';- import { Input } from '#lib/components/ui/input/index.js';- import { Textarea } from '#lib/components/ui/textarea/index.js';+ import SwarmKvFormSheet from '#lib/components/sheets/swarm-kv-form-sheet.svelte';import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';- import { TrashIcon } from '#lib/icons/index.js';- import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';+ import { ResourcePageLayout, type StatCardConfig } from '#lib/layouts/index.js';import { m } from '#lib/paraglide/messages.js';- import { handleApiResultWithCallbacks } from '#lib/utils/api.js';- import { decodeBase64ToText, encodeTextToBase64, formatSwarmTimestamp, getSwarmSpecName } from '#lib/utils/swarm-kv.js';+ import { swarmService } from '#lib/services/swarm-service.js';+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';+ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';+ import type { SwarmKvSummary } from '#lib/types/swarm.js';+ import { handleApiResultWithCallbacks, simpleRefresh } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { createRefreshActionButtons } from '#lib/utils/resource-actions.js';+ import type { SwarmKvResource } from '#lib/utils/swarm-kv.js';import { tryCatch } from '#lib/utils/try-catch.js';- export type SwarmKvItem = {- id: string;- spec?: Record<string, unknown> | null;- updatedAt: string;- };- type LoadingState = {- refresh: boolean;- create: boolean;- delete: boolean;- };- type SwarmKvMessages = {- pageTitle: string;- pageSubtitle: string;- statTitle: string;- createTitle: string;- createSubtitle: string;- namePlaceholder: string;- dataPlaceholder: string;- createButton: string;- listTitle: string;- listSubtitle: string;- empty: string;- immutableNotice: string;- deleteButton: string;- nameRequired: string;- createFailed: string;- createSuccess: (name: string) => string;- deleteConfirm: (name: string) => string;- deleteFailed: (name: string) => string;- deleteSuccess: (name: string) => string;- };+ import SwarmKvTable from './swarm-kv-table.svelte';let {- icon,- permission,- resourceLabel,- canManage,- messages,- loadItems,- createItem,- removeItem+ resource,+ initialItems,+ initialRequestOptions}: {- icon: Component;- permission: string;- resourceLabel: string;- canManage: boolean;- messages: SwarmKvMessages;- loadItems: () => Promise<SwarmKvItem[]>;- createItem: (spec: Record<string, unknown>) => Promise<SwarmKvItem>;- removeItem: (id: string) => Promise<unknown>;+ resource: SwarmKvResource;+ initialItems: Paginated<SwarmKvSummary>;+ initialRequestOptions: SearchPaginationSortRequest;} = $props();- let items = $state<SwarmKvItem[]>([]);- let selectedId = $state('');- let createName = $state('');- let createData = $state('');- let editName = $state('');- let editData = $state('');- let isLoading = $state<LoadingState>({- refresh: false,- create: false,- delete: false- });-- function selectItem(item: SwarmKvItem) {- selectedId = item.id;- const spec = (item.spec ?? {}) as Record<string, unknown>;- editName = typeof spec['Name'] === 'string' ? spec['Name'] : '';- editData = typeof spec['Data'] === 'string' ? decodeBase64ToText(spec['Data']) : '';- }-- function clearSelectedItem() {- selectedId = '';- editName = '';- editData = '';- }-- function toggleItem(item: SwarmKvItem) {- if (selectedId === item.id) {- clearSelectedItem();- return;- }-- selectItem(item);- }+ let items = $derived(initialItems);+ let requestOptions = $derived(initialRequestOptions);+ let refreshing = $state(false);+ let isSheetOpen = $state(false);+ let sheetSession = $state(0);+ let itemToEdit = $state<SwarmKvSummary | null>(null);+ let sheetEnvironmentId = $state('');async function refresh() {- isLoading.refresh = true;- try {- items = await loadItems();- if (selectedId && !items.some((item) => item.id === selectedId)) {- clearSelectedItem();- }- } finally {- isLoading.refresh = false;- }+ await simpleRefresh(+ () => swarmService.getKvItems(resource.kind, requestOptions),+ (data) => (items = data),+ m.common_refresh_failed({ resource: resource.title() }),+ (loading) => (refreshing = loading)+ );}- useEnvironmentRefresh(refresh);-- onMount(() => {- void refresh();+ useEnvironmentRefresh(async () => {+ isSheetOpen = false;+ await refresh();});- async function handleCreate() {- const name = createName.trim();- if (!name) {- toast.error(messages.nameRequired);- return;- }- const spec: Record<string, unknown> = {- Name: name,- Data: encodeTextToBase64(createData)- };+ function openSheet(item: SwarmKvSummary | null, environmentId: string) {+ itemToEdit = item;+ sheetEnvironmentId = environmentId;+ sheetSession += 1;+ isSheetOpen = true;+ }- isLoading.create = true;+ async function openEditSheet(item: SwarmKvSummary) {+ const environmentId = await environmentStore.getCurrentEnvironmentId();+ const result = await tryCatch(swarmService.getKvItem(resource.kind, item.id, environmentId));+ if ((await environmentStore.getCurrentEnvironmentId()) !== environmentId) return;await handleApiResultWithCallbacks({- result: await tryCatch(createItem(spec)),- message: messages.createFailed,- setLoadingState: (value) => (isLoading.create = value),- onSuccess: async (created) => {- toast.success(messages.createSuccess(getSwarmSpecName(created.spec, created.id)));- createName = '';- createData = '';- await refresh();- selectItem(created);- }+ result,+ message: m.common_load_failed({ resource: `${resource.resource()} "${item.spec.Name}"` }),+ onSuccess: (latest) => openSheet(latest, environmentId)});}- function handleRemove(item: SwarmKvItem) {- const name = getSwarmSpecName(item.spec, item.id);- openConfirmDialog({- title: m.common_delete_title({ resource: resourceLabel }),- message: messages.deleteConfirm(name),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.delete = true;- await handleApiResultWithCallbacks({- result: await tryCatch(removeItem(item.id)),- message: messages.deleteFailed(name),- setLoadingState: (value) => (isLoading.delete = value),- onSuccess: async () => {- toast.success(messages.deleteSuccess(name));- await refresh();- }- });- }- }- });+ async function handleSaved() {+ isSheetOpen = false;+ await refresh();}- const actionButtons: ActionButton[] = $derived([- {- id: 'refresh',- action: 'refresh',- placement: 'secondary',- iconOnly: true,- label: m.common_refresh(),- onclick: refresh,- loading: isLoading.refresh,- disabled: isLoading.refresh- }- ]);+ const actionButtons = $derived(+ createRefreshActionButtons({+ create: {+ allowed: hasPermission(resource.permission, environmentStore.selected?.id),+ label: resource.createLabel(),+ onclick: async () => openSheet(null, await environmentStore.getCurrentEnvironmentId())+ },+ refreshLabel: m.common_refresh(),+ onRefresh: refresh,+ refreshing+ })+ );const statCards: StatCardConfig[] = $derived([{- title: messages.statTitle,- value: items.length,- icon,+ title: resource.title(),+ value: items.pagination?.totalItems ?? items.data.length,+ icon: resource.icon,iconColor: 'text-info'}]);</script>-<ResourcePageLayout- title={messages.pageTitle}- subtitle={messages.pageSubtitle}- {icon}- {actionButtons}- {statCards}- environmentPicker->+<ResourcePageLayout title={resource.title()} subtitle={resource.subtitle()} {actionButtons} {statCards} environmentPicker>{#snippet mainContent()}- <div class={canManage ? 'grid gap-4 lg:grid-cols-2' : 'grid gap-4'}>- {#if canManage}- <Card.Root>- <Card.Header>- <Card.Title>{messages.createTitle}</Card.Title>- <Card.Description>{messages.createSubtitle}</Card.Description>- </Card.Header>- <Card.Content>- <div class="flex flex-col gap-3">- <Input placeholder={messages.namePlaceholder} bind:value={createName} />- <Textarea rows={10} bind:value={createData} placeholder={messages.dataPlaceholder} mono size="sm" />- <IfPermitted perm={permission}>- <ArcaneButton- action="create"- customLabel={messages.createButton}- onclick={handleCreate}- disabled={isLoading.create}- loading={isLoading.create}- />- </IfPermitted>- </div>- </Card.Content>- </Card.Root>- {/if}-- <div class="space-y-4">- <Card.Root>- <Card.Header>- <Card.Title>{messages.listTitle}</Card.Title>- <Card.Description>{messages.listSubtitle}</Card.Description>- </Card.Header>- <Card.Content>- <div class="flex flex-col gap-3">- {#if items.length === 0}- <div class="py-8 text-center text-sm text-muted-foreground">{messages.empty}</div>- {:else}- {#each items as item (item.id)}- <Card.Root class="overflow-hidden">- <button- type="button"- class={`w-full px-4 py-3 text-left transition-colors ${selectedId === item.id ? 'bg-muted/50' : 'hover:bg-muted/40'}`}- onclick={() => toggleItem(item)}- >- <div class="flex items-center justify-between gap-2">- <div class="min-w-0">- <div class="truncate font-medium">{getSwarmSpecName(item.spec, item.id)}</div>- <div class="font-mono text-xs text-muted-foreground">{item.id}</div>- </div>- <div class="shrink-0 text-xs text-muted-foreground">{formatSwarmTimestamp(item.updatedAt)}</div>- </div>- </button>+ <SwarmKvTable {resource} bind:items bind:requestOptions onEdit={openEditSheet} />+ {/snippet}- {#if selectedId === item.id}- <div class="space-y-3 border-t px-4 pt-4 pb-5">- <div class="flex items-center gap-2">- <div class="font-mono text-xs text-muted-foreground">{item.id}</div>- <CopyButton text={item.id} />- </div>- <p class="text-sm text-muted-foreground">{messages.immutableNotice}</p>- <Input placeholder={messages.namePlaceholder} bind:value={editName} readonly />- <Textarea- rows={12}- bind:value={editData}- placeholder={messages.dataPlaceholder}- mono- size="sm"- readonly- />- {#if canManage}- <div class="flex flex-wrap items-center gap-2 pt-1">- <ArcaneButton- action="remove"- customLabel={messages.deleteButton}- icon={TrashIcon}- onclick={() => handleRemove(item)}- disabled={isLoading.delete}- loading={isLoading.delete}- />- </div>- {/if}- </div>- {/if}- </Card.Root>- {/each}- {/if}- </div>- </Card.Content>- </Card.Root>- </div>- </div>+ {#snippet additionalContent()}+ {#if sheetSession > 0}+ {#key sheetSession}+ <SwarmKvFormSheet+ bind:open={isSheetOpen}+ {resource}+ environmentId={sheetEnvironmentId}+ existing={itemToEdit}+ onSaved={handleSaved}+ />+ {/key}+ {/if}{/snippet}</ResourcePageLayout>diff --git a/frontend/src/lib/components/swarm/swarm-kv-table.svelte b/frontend/src/lib/components/swarm/swarm-kv-table.sveltenew file mode 100644index 000000000..30d0822a7--- /dev/null+++ b/frontend/src/lib/components/swarm/swarm-kv-table.svelte@@ -0,0 +1,158 @@+<script lang="ts">+ import { toast } from 'svelte-sonner';++ import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';+ import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table/index.js';+ import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';+ import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';+ import { LabelBadges } from '#lib/components/badges/index.js';+ import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';+ import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';+ import { CalendarIcon, EditIcon, TrashIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { swarmService } from '#lib/services/swarm-service.js';+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';+ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';+ import type { SwarmKvSummary } from '#lib/types/swarm.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { formatRelativeTime } from '#lib/utils/formatting.js';+ import type { SwarmKvResource } from '#lib/utils/swarm-kv.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ let {+ resource,+ items = $bindable(),+ requestOptions = $bindable(),+ onEdit+ }: {+ resource: SwarmKvResource;+ items: Paginated<SwarmKvSummary>;+ requestOptions: SearchPaginationSortRequest;+ onEdit: (item: SwarmKvSummary) => void;+ } = $props();++ let isDeleting = $state(false);+ let mobileFieldVisibility = $state<Record<string, boolean>>({});++ const canManage = $derived(hasPermission(resource.permission, environmentStore.selected?.id));++ async function reload(options: SearchPaginationSortRequest = requestOptions) {+ items = await swarmService.getKvItems(resource.kind, options);+ return items;+ }++ function handleDelete(item: SwarmKvSummary) {+ const name = item.spec.Name;+ openConfirmDialog({+ title: m.common_delete_title({ resource: resource.resource() }),+ message: resource.deleteConfirm(name),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ isDeleting = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.removeKvItem(resource.kind, item.id)),+ message: resource.deleteFailed(name),+ setLoadingState: (value) => (isDeleting = value),+ onSuccess: async () => {+ toast.success(resource.deleteSuccess(name));+ await reload();+ }+ });+ }+ }+ });+ }++ const columns = $derived([+ { accessorKey: 'id', title: m.common_id(), hidden: true },+ { id: 'name', accessorFn: (item) => item.spec.Name, title: m.common_name(), sortable: true, cell: NameCell },+ ...(resource.kind === 'secrets'+ ? [+ {+ id: 'driver',+ accessorFn: (item: SwarmKvSummary) => item.spec.Driver?.Name ?? '',+ title: m.common_driver(),+ cell: DriverCell+ }+ ]+ : []),+ { id: 'labels', accessorFn: (item) => item.spec.Labels, title: m.common_labels(), cell: LabelsCell },+ { accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: TimeCell },+ { accessorKey: 'updatedAt', title: m.common_updated(), sortable: true, cell: TimeCell }+ ] satisfies ColumnSpec<SwarmKvSummary>[]);++ const mobileFields = [+ { id: 'labels', label: m.common_labels(), defaultVisible: true },+ { id: 'createdAt', label: m.common_created(), defaultVisible: true }+ ];+</script>++{#snippet NameCell({ item }: { item: SwarmKvSummary })}+ <button type="button" class="font-medium hover:underline" onclick={() => onEdit(item)}>{item.spec.Name}</button>+{/snippet}++{#snippet DriverCell({ item }: { item: SwarmKvSummary })}+ <span class="text-sm text-muted-foreground">{item.spec.Driver?.Name || '-'}</span>+{/snippet}++{#snippet LabelsCell({ item }: { item: SwarmKvSummary })}+ <LabelBadges labels={item.spec.Labels} />+{/snippet}++{#snippet TimeCell({ value }: { value: unknown })}+ <span class="text-sm">{formatRelativeTime(String(value ?? '')) || m.common_unknown()}</span>+{/snippet}++{#snippet MobileCard({ item, mobileFieldVisibility }: { item: SwarmKvSummary; mobileFieldVisibility: MobileFieldVisibility })}+ <UniversalMobileCard+ {item}+ icon={{ component: resource.icon, variant: 'purple' }}+ title={(item: SwarmKvSummary) => item.spec.Name}+ subtitle={(item: SwarmKvSummary) =>+ (mobileFieldVisibility['labels'] ?? true) ? Object.keys(item.spec.Labels ?? {}).join(', ') || null : null}+ footer={(mobileFieldVisibility['createdAt'] ?? true)+ ? {+ label: m.common_created(),+ getValue: (item: SwarmKvSummary) => formatRelativeTime(item.createdAt) || m.common_unknown(),+ icon: CalendarIcon+ }+ : undefined}+ rowActions={RowActions}+ onclick={() => onEdit(item)}+ />+{/snippet}++{#snippet RowActions({ item }: { item: SwarmKvSummary })}+ <RowActionsMenu>+ <DropdownMenu.Item onclick={() => onEdit(item)}>+ <EditIcon class="size-4" />+ {m.common_edit()}+ </DropdownMenu.Item>+ {#if canManage}+ <DropdownMenu.Separator />+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isDeleting}>+ <TrashIcon class="size-4" />+ {m.common_delete()}+ </DropdownMenu.Item>+ {/if}+ </RowActionsMenu>+{/snippet}++<ArcaneTable+ persistKey={resource.persistKey}+ {items}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => {+ requestOptions = options;+ return reload(options);+ }}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={MobileCard}+/>diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.tsindex ab767dbca..be06d4f56 100644--- a/frontend/src/lib/config/navigation-config.ts+++ b/frontend/src/lib/config/navigation-config.ts@@ -26,13 +26,16 @@ import {UpdateIcon,VariableIcon,ActivityIcon,- BackupIcon+ BackupIcon,+ BoxIcon,+ FileTextIcon} from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';import { environmentStore } from '#lib/stores/environment.store.svelte.js';import { featureStore } from '#lib/stores/features.store.svelte.js';import type { PermissionsManifest, User } from '#lib/types/auth.js';import type { FeatureID } from '#lib/types/features.js';+import type { PodmanStatus } from '#lib/types/podman.js';import { canReachShownAccessSurface } from '#lib/utils/auth.js';import type { ShortcutKey } from '#lib/utils/navigation.js';@@ -55,6 +58,7 @@ export type NavigationSections = {managementItems: NavigationItem[];resourceItems: NavigationItem[];swarmItems: NavigationItem[];+ podmanItems: NavigationItem[];settingsItems: NavigationItem[];};@@ -145,6 +149,18 @@ export const navigationItems: NavigationSections = {{ title: 'Configs', url: '/swarm/configs', icon: TemplateIcon, accessSurfaceId: 'route.swarm.configs' },{ title: 'Secrets', url: '/swarm/secrets', icon: LockIcon, accessSurfaceId: 'route.swarm.secrets' }],+ podmanItems: [+ { title: m.podman_pods_title(), url: '/podman/pods', icon: BoxIcon, accessSurfaceId: 'route.podman' },+ { title: m.podman_quadlets_title(), url: '/podman/quadlets', icon: FileTextIcon, accessSurfaceId: 'route.podman.quadlets' },+ { title: m.podman_kube_title(), url: '/podman/kube', icon: LayersIcon, accessSurfaceId: 'route.podman.kube' },+ { title: m.podman_secrets_title(), url: '/podman/secrets', icon: LockIcon, accessSurfaceId: 'route.podman.secrets' },+ {+ title: m.auto_update(),+ url: '/podman/autoupdate',+ icon: UpdateIcon,+ accessSurfaceId: 'route.podman.autoupdate'+ }+ ],settingsItems: [{title: m.events_title(),@@ -382,6 +398,18 @@ export function getSwarmNavigationItems(swarmEnabled: boolean | undefined, currereturn navigationItems.swarmItems.filter((item) => item.url === '/swarm/cluster');}+const podmanListUrls = ['/podman/pods', '/podman/quadlets'];++export function getPodmanNavigationItems(statuses: Record<string, PodmanStatus>, currentEnvId: string): NavigationItem[] {+ const shown = environmentStore.shown.flatMap((env) => statuses[env.id] ?? []);+ if (shown.length === 0) return [];+ const selected = statuses[currentEnvId];+ return navigationItems.podmanItems.filter((item) => {+ if (item.url === '/podman/quadlets') return shown.some((status) => status.quadletsSupported);+ return !!selected || podmanListUrls.includes(item.url);+ });+}+export const DEFAULT_LANDING_PAGE = '/dashboard';/**@@ -403,6 +431,7 @@ export type MobileNavigationSettings = {export function getAvailableMobileNavItems(options?: {swarmEnabled?: boolean;+ podmanStatuses?: Record<string, PodmanStatus>;user?: User | null;currentEnvId?: string;accessManifest?: PermissionsManifest | null;@@ -421,6 +450,8 @@ export function getAvailableMobileNavItems(options?: {flatItems.push(...swarmItems);}+ flatItems.push(...getPodmanNavigationItems(options?.podmanStatuses ?? {}, options?.currentEnvId ?? '0'));+if (navigationItems.settingsItems) {const settingsTopLevel = navigationItems.settingsItems.filter((item) => !item.items);flatItems.push(...settingsTopLevel);diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex fe340d166..9abbe9360 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -23,6 +23,20 @@ export const queryKeys = {['swarm', environmentId, 'join-candidates', user?.id ?? null, stableSerialize(user?.permissionsByEnv)] as const,serviceTasks: (environmentId: string, serviceId: string) => ['swarm', environmentId, 'service-tasks', serviceId] as const},+ podman: {+ environment: (environmentId: string) => ['podman', environmentId] as const,+ status: (environmentId: string) => ['podman', environmentId, 'status'] as const,+ pods: (scope: string, options: SearchPaginationSortRequest) => ['podman-pods', scope, stableSerialize(options)] as const,+ quadlets: (scope: string, options: SearchPaginationSortRequest) =>+ ['podman-quadlets', scope, stableSerialize(options)] as const,+ secrets: (scope: string, options: SearchPaginationSortRequest) =>+ ['podman-secrets', scope, stableSerialize(options)] as const,+ pod: (environmentId: string, podId: string) => ['podman', environmentId, 'pods', podId] as const,+ podStats: (environmentId: string, podName: string) => ['podman', environmentId, 'pods', podName, 'stats'] as const,+ podTop: (environmentId: string, podId: string) => ['podman', environmentId, 'pods', podId, 'top'] as const,+ quadlet: (environmentId: string, name: string) => ['podman', environmentId, 'quadlets', name] as const,+ quadletFile: (environmentId: string, name: string) => ['podman', environmentId, 'quadlets', name, 'file'] as const+ },jobs: {list: (environmentId: string) => ['environment-jobs', environmentId] as const,runs: (environmentId: string, jobId: string, page: number) => ['job-runs', environmentId, jobId, page] as const,diff --git a/frontend/src/lib/services/podman-service.ts b/frontend/src/lib/services/podman-service.tsnew file mode 100644index 000000000..8c4be600b--- /dev/null+++ b/frontend/src/lib/services/podman-service.ts@@ -0,0 +1,208 @@+import { environmentStore } from '#lib/stores/environment.store.svelte.js';+import type {+ PodmanAutoUpdateOptions,+ PodmanAutoUpdateResult,+ PodmanInfo,+ PodmanKubeDownReport,+ PodmanKubeDownRequest,+ PodmanKubeGenerateRequest,+ PodmanKubeGenerateResponse,+ PodmanKubePlayReport,+ PodmanKubePlayRequest,+ PodmanPod,+ PodmanPodActionRequest,+ PodmanPodCreateRequest,+ PodmanPodCreateResponse,+ PodmanPodInspect,+ PodmanPodPruneReport,+ PodmanPodStats,+ PodmanPodTop,+ PodmanQuadletDetail,+ PodmanQuadletFile,+ PodmanQuadletInstallReport,+ PodmanQuadletInstallRequest,+ PodmanQuadletRemoveReport,+ PodmanQuadletUpdateRequest,+ PodmanSecret,+ PodmanSecretCreateRequest,+ PodmanSecretCreateResponse,+ PodmanSecretUpdateRequest,+ PodmanStatus,+ PodmanUnitStatus+} from '#lib/types/podman.js';+import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';+import { transformPaginationParams } from '#lib/utils/tables.js';++import BaseAPIService, { type APIRequestConfig } from './api-service';++export type PodmanPodAction = 'start' | 'stop' | 'restart' | 'pause' | 'unpause' | 'kill';+export type PodmanQuadletAction = 'start' | 'stop' | 'restart';++class PodmanService extends BaseAPIService {+ private async environmentId(environmentId?: string): Promise<string> {+ return environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ }++ async getStatus(environmentId?: string, config?: APIRequestConfig): Promise<PodmanStatus> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/status`, config));+ }++ async getInfo(environmentId?: string, config?: APIRequestConfig): Promise<PodmanInfo> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/info`, config));+ }++ async runAutoUpdate(options: PodmanAutoUpdateOptions = {}): Promise<PodmanAutoUpdateResult> {+ const envId = await this.environmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/autoupdate`, options));+ }++ async getPods(scope: string, options?: SearchPaginationSortRequest, config?: APIRequestConfig): Promise<Paginated<PodmanPod>> {+ const res = await this.api.get(`/environments/${scope}/podman/pods`, {+ ...config,+ params: transformPaginationParams(options)+ });+ return res.data;+ }++ async getPod(podId: string, environmentId?: string): Promise<PodmanPodInspect> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/pods/${encodeURIComponent(podId)}`));+ }++ async getPodStats(names: string[], environmentId?: string): Promise<PodmanPodStats[]> {+ const envId = await this.environmentId(environmentId);+ const params = names.length > 0 ? { names: names.join(',') } : undefined;+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/pods/stats`, { params }));+ }++ async getPodTop(podId: string, environmentId?: string): Promise<PodmanPodTop> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/pods/${encodeURIComponent(podId)}/top`));+ }++ async createPod(request: PodmanPodCreateRequest, environmentId?: string): Promise<PodmanPodCreateResponse> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/pods`, request));+ }++ async prunePods(environmentId?: string): Promise<PodmanPodPruneReport[]> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/pods/prune`, {}));+ }++ async podAction(+ podId: string,+ action: PodmanPodAction,+ environmentId?: string,+ request: PodmanPodActionRequest = {}+ ): Promise<void> {+ const envId = await this.environmentId(environmentId);+ await this.handleResponse(+ this.api.post(`/environments/${envId}/podman/pods/${encodeURIComponent(podId)}/${action}`, request)+ );+ }++ async removePod(podId: string, force = false, environmentId?: string): Promise<void> {+ const envId = await this.environmentId(environmentId);+ await this.handleResponse(+ this.api.delete(`/environments/${envId}/podman/pods/${encodeURIComponent(podId)}`, { params: { force } })+ );+ }++ async getQuadlets(+ scope: string,+ options?: SearchPaginationSortRequest,+ config?: APIRequestConfig+ ): Promise<Paginated<PodmanQuadletDetail>> {+ const res = await this.api.get(`/environments/${scope}/podman/quadlets`, {+ ...config,+ params: transformPaginationParams(options)+ });+ return res.data;+ }++ async getQuadlet(name: string, environmentId?: string): Promise<PodmanQuadletDetail> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/quadlets/${encodeURIComponent(name)}`));+ }++ async getQuadletFile(name: string, environmentId?: string): Promise<PodmanQuadletFile> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/quadlets/${encodeURIComponent(name)}/file`));+ }++ async installQuadlet(request: PodmanQuadletInstallRequest): Promise<PodmanQuadletInstallReport> {+ const envId = await this.environmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/quadlets`, request));+ }++ async updateQuadlet(+ name: string,+ request: PodmanQuadletUpdateRequest,+ environmentId?: string+ ): Promise<PodmanQuadletInstallReport> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.put(`/environments/${envId}/podman/quadlets/${encodeURIComponent(name)}`, request));+ }++ async removeQuadlet(name: string, environmentId?: string): Promise<PodmanQuadletRemoveReport> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.delete(`/environments/${envId}/podman/quadlets/${encodeURIComponent(name)}`));+ }++ async quadletAction(name: string, action: PodmanQuadletAction, environmentId?: string): Promise<PodmanUnitStatus> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/quadlets/${encodeURIComponent(name)}/${action}`, {}));+ }++ async kubePlay(request: PodmanKubePlayRequest): Promise<PodmanKubePlayReport> {+ const envId = await this.environmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/kube/play`, request));+ }++ async kubeDown(request: PodmanKubeDownRequest, environmentId?: string): Promise<PodmanKubeDownReport> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/kube/down`, request));+ }++ async kubeGenerate(request: PodmanKubeGenerateRequest): Promise<PodmanKubeGenerateResponse> {+ const envId = await this.environmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/kube/generate`, request));+ }++ async getSecrets(+ scope: string,+ options?: SearchPaginationSortRequest,+ config?: APIRequestConfig+ ): Promise<Paginated<PodmanSecret>> {+ const res = await this.api.get(`/environments/${scope}/podman/secrets`, {+ ...config,+ params: transformPaginationParams(options)+ });+ return res.data;+ }++ async getSecret(name: string, environmentId?: string): Promise<PodmanSecret> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/podman/secrets/${encodeURIComponent(name)}`));+ }++ async createSecret(request: PodmanSecretCreateRequest, environmentId?: string): Promise<PodmanSecretCreateResponse> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.post(`/environments/${envId}/podman/secrets`, request));+ }++ async updateSecret(name: string, request: PodmanSecretUpdateRequest, environmentId?: string): Promise<PodmanSecret> {+ const envId = await this.environmentId(environmentId);+ return this.handleResponse(this.api.put(`/environments/${envId}/podman/secrets/${encodeURIComponent(name)}`, request));+ }++ async removeSecret(secretId: string, environmentId?: string): Promise<void> {+ const envId = await this.environmentId(environmentId);+ await this.handleResponse(this.api.delete(`/environments/${envId}/podman/secrets/${encodeURIComponent(secretId)}`));+ }+}++export const podmanService = new PodmanService();diff --git a/frontend/src/lib/services/swarm-service.ts b/frontend/src/lib/services/swarm-service.tsindex 425bf7958..551dd3f96 100644--- a/frontend/src/lib/services/swarm-service.ts+++ b/frontend/src/lib/services/swarm-service.ts@@ -33,10 +33,10 @@ import type {SwarmJoinTokensResponse,SwarmRotateJoinTokensRequest,SwarmUpdateRequest,- SwarmConfigSummary,- SwarmSecretSummary,- SwarmConfigCreateRequest,- SwarmSecretCreateRequest,+ SwarmKvCreateRequest,+ SwarmKvKind,+ SwarmKvSummary,+ SwarmKvUpdateRequest,SwarmJoinCandidate,SwarmJoinEnvironmentsRequest,SwarmJoinEnvironmentsResponse@@ -272,34 +272,35 @@ class SwarmService extends BaseAPIService {await this.handleResponse(this.api.put(`/environments/${envId}/swarm/spec`, request));}- async getConfigs(): Promise<SwarmConfigSummary[]> {+ async getKvItems(kind: SwarmKvKind, options?: SearchPaginationSortRequest): Promise<Paginated<SwarmKvSummary>> {const envId = await environmentStore.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/swarm/configs`));- }-- async createConfig(request: SwarmConfigCreateRequest): Promise<SwarmConfigSummary> {- const envId = await environmentStore.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/swarm/configs`, request));+ const res = await this.api.get(`/environments/${envId}/swarm/${kind}`, { params: transformPaginationParams(options) });+ return res.data;}- async removeConfig(configId: string): Promise<void> {- const envId = await environmentStore.getCurrentEnvironmentId();- await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/configs/${configId}`));+ async getKvItem(kind: SwarmKvKind, id: string, environmentId?: string): Promise<SwarmKvSummary> {+ const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/${kind}/${encodeURIComponent(id)}`));}- async getSecrets(): Promise<SwarmSecretSummary[]> {- const envId = await environmentStore.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/swarm/secrets`));+ async createKvItem(kind: SwarmKvKind, request: SwarmKvCreateRequest, environmentId?: string): Promise<SwarmKvSummary> {+ const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/${kind}`, request));}- async createSecret(request: SwarmSecretCreateRequest): Promise<SwarmSecretSummary> {- const envId = await environmentStore.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/swarm/secrets`, request));+ async updateKvItem(+ kind: SwarmKvKind,+ id: string,+ request: SwarmKvUpdateRequest,+ environmentId?: string+ ): Promise<SwarmKvSummary> {+ const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ return this.handleResponse(this.api.put(`/environments/${envId}/swarm/${kind}/${encodeURIComponent(id)}`, request));}- async removeSecret(secretId: string): Promise<void> {+ async removeKvItem(kind: SwarmKvKind, id: string): Promise<void> {const envId = await environmentStore.getCurrentEnvironmentId();- await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/secrets/${secretId}`));+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/${kind}/${encodeURIComponent(id)}`));}}diff --git a/frontend/src/lib/stores/environment.store.svelte.ts b/frontend/src/lib/stores/environment.store.svelte.tsindex a91b90445..a71ab1dde 100644--- a/frontend/src/lib/stores/environment.store.svelte.ts+++ b/frontend/src/lib/stores/environment.store.svelte.ts@@ -25,7 +25,7 @@ function getResourceListPage(): string | null {// Check if route has a dynamic segment (contains [...] pattern)// and is a resource detail page (not settings, environments management, etc.)- const resourcePrefixes = ['/containers', '/images', '/projects', '/networks', '/volumes'];+ const resourcePrefixes = ['/containers', '/images', '/projects', '/networks', '/volumes', '/podman/pods', '/podman/quadlets'];for (const prefix of resourcePrefixes) {// Match routes like /containers/[containerId] or /(app)/containers/[containerId]diff --git a/frontend/src/lib/types/podman.ts b/frontend/src/lib/types/podman.tsnew file mode 100644index 000000000..bca6da215--- /dev/null+++ b/frontend/src/lib/types/podman.ts@@ -0,0 +1,452 @@+export const PODMAN_SYSTEMD_UNIT_LABEL = 'PODMAN_SYSTEMD_UNIT';++export type PodmanAutoUpdateMode = 'rest' | 'systemd' | 'unavailable';+export type PodmanSystemdScope = 'system' | 'user';+export type PodmanQuadletType = 'container' | 'pod' | 'kube' | 'network' | 'volume' | 'image' | 'build' | 'artifact';+export type PodmanKubeGenerateType = 'pod' | 'service' | 'deployment' | 'daemonset' | 'job';++export const PODMAN_QUADLET_TYPES: PodmanQuadletType[] = [+ 'container',+ 'pod',+ 'kube',+ 'network',+ 'volume',+ 'image',+ 'build',+ 'artifact'+];+export const PODMAN_KUBE_GENERATE_TYPES: PodmanKubeGenerateType[] = ['pod', 'service', 'deployment', 'daemonset', 'job'];++export interface PodmanStatus {+ detected: boolean;+ version?: string;+ apiVersion?: string;+ rootless: boolean;+ quadletsSupported: boolean;+ quadletAppsSupported: boolean;+ autoUpdateMode: PodmanAutoUpdateMode;+ systemdAvailable: boolean;+ systemdScope?: PodmanSystemdScope;+ systemdReason?: string;+}++export interface PodmanInfoIdMap {+ container_id: number;+ host_id: number;+ size: number;+}++export interface PodmanInfoHelperBinary {+ executable?: string;+ package?: string;+ version?: string;+}++export interface PodmanInfoHost {+ arch?: string;+ buildahVersion?: string;+ cgroupManager?: string;+ cgroupVersion?: string;+ cgroupControllers?: string[];+ conmon: { package?: string; path?: string; version?: string };+ cpus: number;+ databaseBackend?: string;+ distribution: { distribution?: string; variant?: string; version?: string; codename?: string };+ eventLogger?: string;+ hostname?: string;+ idMappings: { uidmap?: PodmanInfoIdMap[]; gidmap?: PodmanInfoIdMap[] };+ kernel?: string;+ logDriver?: string;+ memFree: number;+ memTotal: number;+ networkBackend?: string;+ networkBackendInfo: {+ backend?: string;+ version?: string;+ package?: string;+ path?: string;+ dns: { version?: string; package?: string; path?: string };+ defaultNetwork?: string;+ };+ ociRuntime: { name?: string; package?: string; path?: string; version?: string };+ os?: string;+ remoteSocket: { path?: string; exists: boolean };+ rootlessNetworkCmd?: string;+ serviceIsRemote: boolean;+ security: {+ rootless: boolean;+ selinuxEnabled: boolean;+ apparmorEnabled: boolean;+ seccompEnabled: boolean;+ seccompProfilePath?: string;+ capabilities?: string;+ };+ slirp4netns: PodmanInfoHelperBinary;+ pasta: PodmanInfoHelperBinary;+ swapFree: number;+ swapTotal: number;+ uptime?: string;+}++export interface PodmanInfoStore {+ configFile?: string;+ containerStore: { number: number; paused: number; running: number; stopped: number };+ graphDriverName?: string;+ graphRoot?: string;+ graphStatus?: Record<string, string>;+ imageStore: { number: number };+ runRoot?: string;+ volumePath?: string;+}++export interface PodmanInfo {+ host: PodmanInfoHost;+ store: PodmanInfoStore;+ registries: { search?: string[] };+ plugins: { network?: string[]; volume?: string[]; log?: string[] };+ version: {+ apiVersion?: string;+ version?: string;+ goVersion?: string;+ gitCommit?: string;+ builtTime?: string;+ osArch?: string;+ };+}++export interface PodmanUnitStatus {+ name: string;+ description?: string;+ loadState: string;+ activeState: string;+ subState: string;+}++export interface PodmanPodContainer {+ id: string;+ names: string;+ status: string;+ restartCount: number;+}++export interface PodmanPod {+ id: string;+ name: string;+ namespace?: string;+ status: string;+ created: string;+ infraId?: string;+ cgroup?: string;+ labels?: Record<string, string>;+ networks?: string[];+ containers: PodmanPodContainer[] | null;+}++export interface PodmanPodPortBinding {+ hostIp?: string;+ hostPort: string;+}++export interface PodmanPodInfraConfig {+ portBindings?: Record<string, PodmanPodPortBinding[]>;+ hostNetwork: boolean;+ networks?: string[];+}++export interface PodmanPodInspectContainer {+ id: string;+ name: string;+ state: string;+}++export interface PodmanPodInspect {+ id: string;+ name: string;+ namespace?: string;+ created: string;+ state: string;+ hostname?: string;+ labels?: Record<string, string>;+ createInfra: boolean;+ infraContainerId?: string;+ infraConfig?: PodmanPodInfraConfig;+ sharedNamespaces?: string[];+ numContainers: number;+ containers: PodmanPodInspectContainer[] | null;+}++export interface PodmanPodPortMapping {+ containerPort: number;+ hostPort?: number;+ hostIp?: string;+ protocol?: string;+ range?: number;+}++export interface PodmanPodNetwork {+ name: string;+ aliases?: string[];+ staticIps?: string[];+ staticMac?: string;+ interfaceName?: string;+}++export interface PodmanPodVolume {+ source: string;+ destination: string;+ options?: string[];+}++export interface PodmanPodDeviceLimit {+ device: string;+ value: string;+}++export type PodmanPodExitPolicy = 'continue' | 'stop';+export type PodmanPodRestartPolicy = 'no' | 'always' | 'on-failure' | 'unless-stopped';++export interface PodmanPodCreateRequest {+ name: string;+ hostname?: string;+ labels?: Record<string, string>;+ exitPolicy?: PodmanPodExitPolicy;+ restartPolicy?: PodmanPodRestartPolicy;+ restartRetries?: number;+ noInfra?: boolean;+ infraImage?: string;+ infraCommand?: string[];+ infraName?: string;+ infraConmonPidFile?: string;+ sharedNamespaces?: string[];+ shareParent?: boolean;+ pid?: string;+ ipc?: string;+ uts?: string;+ userns?: string;+ uidMap?: string[];+ gidMap?: string[];+ networkMode?: string;+ networkOptions?: string[];+ networks?: PodmanPodNetwork[];+ portMappings?: PodmanPodPortMapping[];+ dnsServers?: string[];+ dnsSearch?: string[];+ dnsOptions?: string[];+ noManageResolvConf?: boolean;+ addHosts?: string[];+ noHosts?: boolean;+ noHostname?: boolean;+ hostsFile?: string;+ cgroupParent?: string;+ cpus?: number;+ cpuShares?: number;+ cpusetCpus?: string;+ cpusetMems?: string;+ memory?: string;+ memorySwap?: string;+ blkioWeight?: number;+ blkioWeightDevices?: PodmanPodDeviceLimit[];+ deviceReadBps?: PodmanPodDeviceLimit[];+ deviceWriteBps?: PodmanPodDeviceLimit[];+ devices?: string[];+ gpus?: string[];+ volumes?: PodmanPodVolume[];+ volumesFrom?: string[];+ shmSize?: string;+ shmSizeSystemd?: string;+ securityOpt?: string[];+ sysctl?: Record<string, string>;+}++export interface PodmanPodActionRequest {+ timeout?: number;+ signal?: string;+}++export interface PodmanPodCreateResponse {+ id: string;+}++export interface PodmanPodStats {+ pod: string;+ cid: string;+ name: string;+ cpu: string;+ memUsage: string;+ memUsageBytes: string;+ mem: string;+ netIo: string;+ blockIo: string;+ pids: string;+}++export interface PodmanPodTop {+ titles: string[] | null;+ processes: string[][] | null;+}++export interface PodmanPodPruneReport {+ id: string;+}++export interface PodmanContainer {+ id: string;+ names: string[];+ image: string;+ imageId?: string;+ state: string;+ status?: string;+ created: string;+ startedAt?: number;+ exitCode: number;+ exited: boolean;+ labels?: Record<string, string>;+ pod?: string;+ podName?: string;+ isInfra: boolean;+}++export interface PodmanQuadletFile {+ name: string;+ content: string;+}++export interface PodmanQuadletInstallRequest {+ name: string;+ content: string;+ extraFiles?: PodmanQuadletFile[];+ app?: string;+}++export interface PodmanQuadletUpdateRequest {+ content: string;+ extraFiles?: PodmanQuadletFile[];+}++export interface PodmanQuadletDetail {+ name: string;+ unitName: string;+ path: string;+ status: string;+ app?: string;+ type: PodmanQuadletType;+ template: boolean;+ unitStatus?: PodmanUnitStatus;+ containers?: PodmanContainer[];+}++export interface PodmanQuadletInstallReport {+ installedQuadlets: Record<string, string> | null;+ quadletErrors: Record<string, string> | null;+}++export interface PodmanQuadletRemoveReport {+ removed: string[] | null;+ errors: Record<string, string> | null;+}++export interface PodmanKubePlayRequest {+ yaml: string;+ start?: boolean;+ replace?: boolean;+ networks?: string[];+}++export interface PodmanKubeDownRequest {+ yaml: string;+ force?: boolean;+}++export interface PodmanKubeGenerateRequest {+ names: string[];+ type?: PodmanKubeGenerateType;+ service?: boolean;+}++export interface PodmanKubeGenerateResponse {+ yaml: string;+}++export interface PodmanKubePlayPod {+ id: string;+ containers: string[] | null;+ initContainers: string[] | null;+ logs: string[] | null;+ containerErrors: string[] | null;+}++export interface PodmanKubePlayVolume {+ name: string;+}++export interface PodmanKubePlayReport {+ pods: PodmanKubePlayPod[] | null;+ volumes: PodmanKubePlayVolume[] | null;+ serviceContainerId?: string;+ exitCode?: number;+}++export interface PodmanKubeDownPod {+ id: string;+}++export interface PodmanKubeDownReport {+ stopReport: PodmanKubeDownPod[] | null;+ rmReport: PodmanKubeDownPod[] | null;+}++export interface PodmanSecretDriver {+ name: string;+ options?: Record<string, string>;+}++export interface PodmanSecretSpec {+ name: string;+ driver: PodmanSecretDriver;+ labels?: Record<string, string>;+}++export interface PodmanSecret {+ id: string;+ createdAt: string;+ updatedAt: string;+ spec: PodmanSecretSpec;+}++export interface PodmanSecretCreateRequest {+ name: string;+ data: string;+ driver?: string;+ driverOptions?: Record<string, string>;+ labels?: Record<string, string>;+}++export type PodmanSecretUpdateRequest = Omit<PodmanSecretCreateRequest, 'name'>;++export interface PodmanSecretCreateResponse {+ id: string;+}++export interface PodmanAutoUpdateOptions {+ dryRun?: boolean;+ rollback?: boolean;+ tlsVerify?: boolean;+ authfile?: string;+ filters?: Record<string, string[]>;+}++export interface PodmanAutoUpdateReport {+ containerId: string;+ containerName: string;+ imageName: string;+ policy: string;+ systemdUnit: string;+ updated: string;+}++export interface PodmanAutoUpdateResult {+ mode: PodmanAutoUpdateMode;+ reports: PodmanAutoUpdateReport[] | null;+ errors: string[] | null;+ unit?: PodmanUnitStatus;+}diff --git a/frontend/src/lib/types/shared.ts b/frontend/src/lib/types/shared.tsindex cad6eca9c..b6fee1566 100644--- a/frontend/src/lib/types/shared.ts+++ b/frontend/src/lib/types/shared.ts@@ -234,6 +234,7 @@ export interface DashboardSnapshot {actionItems: DashboardActionItems;settings: DashboardSnapshotSettings;versionInfo?: AppVersionInformation;+ podCount?: number;}export type DashboardStreamEventType = 'snapshot' | 'error' | 'pending' | 'heartbeat';@@ -259,6 +260,7 @@ export interface DashboardEnvironmentOverview {actionItems: DashboardActionItems;settings: DashboardSnapshotSettings;versionInfo?: AppVersionInformation;+ podCount?: number;snapshotState: EnvironmentDashboardSnapshotState;snapshotError?: string;}@@ -277,6 +279,8 @@ export interface DashboardOverviewSummary {totalVolumes: number;volumesInUse: number;volumesUnused: number;+ podmanEnvironments: number;+ totalPods: number;}export interface DashboardEnvironmentCardState {diff --git a/frontend/src/lib/types/swarm.ts b/frontend/src/lib/types/swarm.tsindex 8d7adafc4..bb8921943 100644--- a/frontend/src/lib/types/swarm.ts+++ b/frontend/src/lib/types/swarm.ts@@ -488,28 +488,30 @@ export interface SwarmUpdateRequest {rotateManagerUnlockKey?: boolean;}-export interface SwarmConfigSummary {- id: string;- version: { index?: number; Index?: number };- createdAt: string;- updatedAt: string;- spec: Record<string, unknown>;+export type SwarmKvKind = 'secrets' | 'configs';++export interface SwarmKvSpec {+ Name: string;+ Labels?: Record<string, string> | null;+ Data?: string | null;+ Driver?: { Name: string; Options?: Record<string, string> | null } | null;}-export interface SwarmSecretSummary {+export interface SwarmKvSummary {id: string;- version: { index?: number; Index?: number };+ version: { Index?: number };createdAt: string;updatedAt: string;- spec: Record<string, unknown>;+ spec: SwarmKvSpec;}-export interface SwarmConfigCreateRequest {- spec: Record<string, unknown>;+export interface SwarmKvCreateRequest {+ spec: SwarmKvSpec;}-export interface SwarmSecretCreateRequest {- spec: Record<string, unknown>;+export interface SwarmKvUpdateRequest {+ version: number;+ labels: Record<string, string>;}// --- Compose projects ---diff --git a/frontend/src/lib/utils/auth.ts b/frontend/src/lib/utils/auth.tsindex 4a0361259..805eca4e2 100644--- a/frontend/src/lib/utils/auth.ts+++ b/frontend/src/lib/utils/auth.ts@@ -74,6 +74,7 @@ const PROTECTED_PREFIXES = ['/projects','/volumes','/networks',+ '/podman','/ports','/settings','/swarm',diff --git a/frontend/src/lib/utils/environments.ts b/frontend/src/lib/utils/environments.tsindex 5f4010ad6..1b1cdbaaf 100644--- a/frontend/src/lib/utils/environments.ts+++ b/frontend/src/lib/utils/environments.ts@@ -93,12 +93,16 @@ export async function resolveDetailEnvironmentId(url: URL): Promise<string> {}/**- * Destination for a create: the picked shown environment that grants `permission`, else the selected- * one, else the first shown environment that grants it. With one shown environment this is the selected one.+ * Destination for a create: the picked environment among `environments` that grants `permission`, else the+ * selected one, else the first that grants it. With one shown environment this is the selected one.*/-export function destinationEnvironmentId(picked: string, permission: string): string {+export function destinationEnvironmentId(+ picked: string,+ permission: string,+ environments: EnvironmentRef[] = environmentStore.shown+): string {const selected = environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID;- const permitted = environmentStore.shown.filter((env) => hasPermission(permission, env.id)).map((env) => env.id);+ const permitted = environments.filter((env) => hasPermission(permission, env.id)).map((env) => env.id);const candidate = permitted.includes(picked) ? picked : selected;return permitted.includes(candidate) ? candidate : (permitted[0] ?? candidate);}diff --git a/frontend/src/lib/utils/form-parsers.ts b/frontend/src/lib/utils/form-parsers.tsindex edaeb4907..f269f2f6b 100644--- a/frontend/src/lib/utils/form-parsers.ts+++ b/frontend/src/lib/utils/form-parsers.ts@@ -1,3 +1,5 @@+import type { KeyValueRow } from '#lib/components/form/key-value-editor.svelte';+/** Splits textarea content into trimmed, non-empty lines. */export function parseLines(text: string): string[] {return splitAndTrim(text, '\n');@@ -36,3 +38,11 @@ export function parseKeyValuePairs(text: string): Record<string, string> {return result;}++export function keyValueRowsToRecord(rows: KeyValueRow[]): Record<string, string> {+ return Object.fromEntries(rows.filter((row) => row.key.trim()).map((row) => [row.key.trim(), row.value]));+}++export function recordToKeyValueRows(record: Record<string, string> | null | undefined): KeyValueRow[] {+ return Object.entries(record ?? {}).map(([key, value]) => ({ key, value }));+}diff --git a/frontend/src/lib/utils/podman.ts b/frontend/src/lib/utils/podman.tsnew file mode 100644index 000000000..9c3318105--- /dev/null+++ b/frontend/src/lib/utils/podman.ts@@ -0,0 +1,28 @@+import { environmentStore, type EnvironmentRef } from '#lib/stores/environment.store.svelte.js';+import { PODMAN_SYSTEMD_UNIT_LABEL, type PodmanStatus } from '#lib/types/podman.js';+import { environmentHref } from '#lib/utils/environments.js';++export type PodmanStateVariant = 'green' | 'red' | 'amber' | 'gray';++export function podmanStateVariant(state: string | undefined): PodmanStateVariant {+ const normalized = (state ?? '').toLowerCase();+ if (normalized === 'running' || normalized === 'active') return 'green';+ if (['exited', 'stopped', 'dead', 'failed', 'error', 'inactive'].includes(normalized)) return 'red';+ if (!normalized || normalized === 'unknown' || normalized.startsWith('not loaded')) return 'gray';+ return 'amber';+}++export function quadletUnitHref(labels: Record<string, string> | null | undefined, environmentId: string): string | undefined {+ const unit = labels?.[PODMAN_SYSTEMD_UNIT_LABEL];+ return unit ? environmentHref(`/podman/quadlets?unit=${encodeURIComponent(unit)}`, environmentId) : undefined;+}++export function shownPodmanEnvironments(+ statuses: Record<string, PodmanStatus>,+ supports: (status: PodmanStatus) => boolean = () => true+): EnvironmentRef[] {+ return environmentStore.shown.filter((env) => {+ const status = statuses[env.id];+ return status !== undefined && supports(status);+ });+}diff --git a/frontend/src/lib/utils/swarm-kv.ts b/frontend/src/lib/utils/swarm-kv.tsindex 928fff1f1..a86ddfc92 100644--- a/frontend/src/lib/utils/swarm-kv.ts+++ b/frontend/src/lib/utils/swarm-kv.ts@@ -1,10 +1,70 @@+import { LockIcon, TemplateIcon, type IconType } from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';-import { formatRelativeTime } from '#lib/utils/formatting.js';+import type { SwarmKvKind } from '#lib/types/swarm.js';-export function getSwarmSpecName(spec: Record<string, unknown> | null | undefined, fallback: string): string {- const name = spec && typeof spec === 'object' ? spec['Name'] : undefined;- return typeof name === 'string' && name.trim() ? name : fallback.slice(0, 12);-}+export type SwarmKvResource = {+ kind: SwarmKvKind;+ persistKey: string;+ permission: string;+ icon: IconType;+ resource: () => string;+ title: () => string;+ subtitle: () => string;+ createLabel: () => string;+ editTitle: () => string;+ namePlaceholder: () => string;+ nameLocked: () => string;+ nameRequired: () => string;+ immutableNotice: () => string;+ createSuccess: (name: string) => string;+ createFailed: () => string;+ deleteConfirm: (name: string) => string;+ deleteSuccess: (name: string) => string;+ deleteFailed: (name: string) => string;+};++export const swarmKvResources: Record<SwarmKvKind, SwarmKvResource> = {+ secrets: {+ kind: 'secrets',+ persistKey: 'arcane-swarm-secrets-table',+ permission: 'swarm:secrets',+ icon: LockIcon,+ resource: m.swarm_secret,+ title: m.swarm_secrets_title,+ subtitle: m.swarm_secrets_subtitle,+ createLabel: m.create_secret,+ editTitle: m.swarm_secrets_edit_title,+ namePlaceholder: m.swarm_secrets_name_placeholder,+ nameLocked: m.swarm_secrets_name_locked,+ nameRequired: m.swarm_secrets_name_required,+ immutableNotice: m.swarm_secrets_immutable_notice,+ createSuccess: (name) => m.swarm_secrets_create_success({ name }),+ createFailed: m.swarm_secrets_create_failed,+ deleteConfirm: (name) => m.swarm_secrets_delete_confirm({ name }),+ deleteSuccess: (name) => m.swarm_secrets_delete_success({ name }),+ deleteFailed: (name) => m.swarm_secrets_delete_failed({ name })+ },+ configs: {+ kind: 'configs',+ persistKey: 'arcane-swarm-configs-table',+ permission: 'swarm:configs',+ icon: TemplateIcon,+ resource: m.swarm_config,+ title: m.swarm_configs_title,+ subtitle: m.swarm_configs_subtitle,+ createLabel: m.create_config,+ editTitle: m.swarm_configs_edit_title,+ namePlaceholder: m.swarm_configs_name_placeholder,+ nameLocked: m.swarm_configs_name_locked,+ nameRequired: m.swarm_configs_name_required,+ immutableNotice: m.swarm_configs_immutable_notice,+ createSuccess: (name) => m.swarm_configs_create_success({ name }),+ createFailed: m.swarm_configs_create_failed,+ deleteConfirm: (name) => m.swarm_configs_delete_confirm({ name }),+ deleteSuccess: (name) => m.swarm_configs_delete_success({ name }),+ deleteFailed: (name) => m.swarm_configs_delete_failed({ name })+ }+};export function decodeBase64ToText(base64Value: string): string {try {@@ -24,8 +84,3 @@ export function encodeTextToBase64(value: string): string {}return btoa(binary);}--export function formatSwarmTimestamp(timestamp: string): string {- if (!timestamp) return m.common_unknown();- return formatRelativeTime(timestamp) || m.common_unknown();-}diff --git a/frontend/src/lib/utils/workspace-files.ts b/frontend/src/lib/utils/workspace-files.tsindex 1e8cacba8..a87198078 100644--- a/frontend/src/lib/utils/workspace-files.ts+++ b/frontend/src/lib/utils/workspace-files.ts@@ -275,7 +275,15 @@ const WORKSPACE_LANGUAGE_EXTENSIONS: Partial<Record<string, CodeLanguage>> = {cjs: 'javascript',md: 'markdown',markdown: 'markdown',- mdx: 'markdown'+ mdx: 'markdown',+ container: 'systemd',+ pod: 'systemd',+ kube: 'systemd',+ network: 'systemd',+ volume: 'systemd',+ image: 'systemd',+ build: 'systemd',+ artifact: 'systemd'};export function workspaceFileLanguage(relativePath: string): CodeLanguage {diff --git a/frontend/src/routes/(app)/+layout.svelte b/frontend/src/routes/(app)/+layout.svelteindex 8469a4ceb..9332de8a7 100644--- a/frontend/src/routes/(app)/+layout.svelte+++ b/frontend/src/routes/(app)/+layout.svelte@@ -36,6 +36,7 @@const permissionsManifest = $derived(data.permissionsManifest);const permissionsManifestLoadFailed = $derived(data.permissionsManifestLoadFailed);const swarmEnabled = $derived(data.swarmEnabled);+ const podmanStatuses = $derived(data.podmanStatuses);const canReadActivities = $derived(userHasPermissionInAnyEnvironment(user, 'activities:read'));const isMobile = new IsMobile();@@ -154,7 +155,7 @@<Sidebar.Provider class={isMobile.current ? 'h-auto min-h-dvh' : undefined}>{#if !isMobile.current}- <AppSidebar {versionInformation} {user} {swarmEnabled} {permissionsManifest} />+ <AppSidebar {versionInformation} {user} {swarmEnabled} {podmanStatuses} {permissionsManifest} />{/if}<main class={cn('relative z-(--arcane-z-content)', isMobile.current ? 'flex-1' : 'h-dvh flex-1')}>@@ -179,7 +180,7 @@</main>{#if isMobile.current}- <MobileNav {user} {versionInformation} {swarmEnabled} {permissionsManifest} />+ <MobileNav {user} {versionInformation} {swarmEnabled} {podmanStatuses} {permissionsManifest} />{/if}</Sidebar.Provider>diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelteindex a56be3a00..82cbd4ec9 100644--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte@@ -47,6 +47,7 @@import { calculateMemoryUsage, getCustomHostname, getThemedIconUrl } from '#lib/utils/docker.js';import { environmentHref, listScopes } from '#lib/utils/environments.js';import { bytes } from '#lib/utils/formatting.js';+ import { quadletUnitHref } from '#lib/utils/podman.js';import { tryCatch } from '#lib/utils/try-catch.js';import ContainerCommitDialog from '../components/container-commit-dialog.svelte';@@ -276,6 +277,7 @@const project = $derived(data?.project ?? null);const composeInfo = $derived(container?.composeInfo ?? null);+ const quadletHref = $derived(quadletUnitHref(container?.labels, currentEnvId));const composeServiceName = $derived(composeInfo?.serviceName ?? '');const rootComposeFilename = $derived.by(() => {const cf = composeInfo?.configFiles;@@ -472,6 +474,11 @@{#if updateInfo?.hasUpdate}<Badge variant="amber" minWidth="20">{m.sidebar_update_available()}</Badge>{/if}+ {#if quadletHref}+ <Badge variant="purple" size="sm" href={quadletHref} title={m.podman_quadlet_update_disabled()}>+ {m.podman_managed_by_quadlet()}+ </Badge>+ {/if}{#if project && composeInfo}<Badgevariant="gray"diff --git a/frontend/src/routes/(app)/containers/components/container-table.svelte b/frontend/src/routes/(app)/containers/components/container-table.svelteindex 0d6f06b34..7aa3525c0 100644--- a/frontend/src/routes/(app)/containers/components/container-table.svelte+++ b/frontend/src/routes/(app)/containers/components/container-table.svelte@@ -69,6 +69,7 @@type EnvironmentRow} from '#lib/utils/environments.js';import { formatDateTimeShort, truncateImageDigest } from '#lib/utils/formatting.js';+ import { quadletUnitHref } from '#lib/utils/podman.js';import { createContainerActions } from '../container-table.actions';import {@@ -678,6 +679,7 @@{@const displayName = getContainerDisplayName(item)}{@const iconUrl = getThemedIconUrl(item, mode.current)}{@const projectLabel = item.labels?.[COMPOSE_PROJECT_LABEL]}+ {@const quadletHref = quadletUnitHref(item.labels, item.environmentId)}<div class="flex items-center gap-2"><IconImage src={iconUrl} alt={displayName} fallback={BoxIcon} class="size-6" containerClass="size-8 shrink-0" /><a class="min-w-0 truncate font-medium hover:underline" href={environmentHref(`/containers/${item.id}`, item.environmentId)}@@ -686,6 +688,11 @@{#if item.hidden}<Badge variant="gray" size="sm">{m.hidden()}</Badge>{/if}+ {#if quadletHref}+ <Badge variant="purple" size="sm" href={quadletHref}>+ {m.podman_managed_by_quadlet()}+ </Badge>+ {/if}{#if projectLabel && !groupByProject}<Badge variant="gray" size="sm" class="max-w-40" title={projectLabel}><span class="block min-w-0 truncate">diff --git a/frontend/src/routes/(app)/dashboard/components/all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/components/all-environments-view.svelteindex 6b7cb32ea..85ca1b7fe 100644--- a/frontend/src/routes/(app)/dashboard/components/all-environments-view.svelte+++ b/frontend/src/routes/(app)/dashboard/components/all-environments-view.svelte@@ -7,10 +7,11 @@import { type ActionButton } from '#lib/components/action-button-group/index.js';import { ArcaneButton } from '#lib/components/arcane-button/index.js';import * as ArcaneTooltip from '#lib/components/arcane-tooltip/index.js';- import DockerInfoDialog from '#lib/components/dialogs/docker-info-dialog.svelte';+ import DockerInfoDialog, { type EngineInfo } from '#lib/components/dialogs/docker-info-dialog.svelte';import PruneConfirmationDialog from '#lib/components/dialogs/prune-confirmation-dialog.svelte';import * as StatStrip from '#lib/components/stat-strip/index.js';import {+ BoxIcon,ContainersIcon,EnvironmentsIcon,ImagesIcon,@@ -23,6 +24,7 @@LayoutListIcon} from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';+ import { podmanService } from '#lib/services/podman-service.js';import { settingsService } from '#lib/services/settings-service.js';import { systemService } from '#lib/services/system-service.js';import { activityStore } from '#lib/stores/activity.store.svelte.js';@@ -32,7 +34,6 @@import userStore from '#lib/stores/user-store.svelte.js';import type { Activity } from '#lib/types/activity.type.js';import type { PruneType, SystemPruneRequest } from '#lib/types/automation.js';- import type { DockerInfo } from '#lib/types/docker.js';import type { Environment } from '#lib/types/environment.js';import type { AppVersionInformation, Settings } from '#lib/types/settings.js';import type {@@ -109,12 +110,13 @@let upgradeDialogOpenById = $state<Record<string, boolean>>({});let upgradeDialogUpgradingById = $state<Record<string, boolean>>({});- let dockerInfoOpen = $state(false);- let dockerInfoData = $state<DockerInfo | null>(null);- let dockerInfoPromise = $state<Promise<DockerInfo> | null>(null);- let dockerInfoError = $state<string | null>(null);- let dockerInfoByEnvironmentId = $state<Record<string, DockerInfo | undefined>>({});- let dockerInfoPromiseByEnvironmentId = $state<Record<string, Promise<DockerInfo> | undefined>>({});+ let engineInfoOpen = $state(false);+ let engineInfoEngine = $state<EngineInfo['engine']>('docker');+ let engineInfoData = $state<EngineInfo | null>(null);+ let engineInfoPromise = $state<Promise<EngineInfo> | null>(null);+ let engineInfoError = $state<string | null>(null);+ let engineInfoByEnvironmentId = $state<Record<string, EngineInfo | undefined>>({});+ let engineInfoPromiseByEnvironmentId = $state<Record<string, Promise<EngineInfo> | undefined>>({});const availableEnvironments = $derived.by(() => {if (!userStore.current) {@@ -230,42 +232,54 @@}}- async function loadDockerInfo(environment: Environment): Promise<DockerInfo> {+ async function fetchEngineInfo(environmentId: string, podCount: number | undefined): Promise<EngineInfo> {+ if (podCount === undefined) {+ return { engine: 'docker', docker: await systemService.getDockerInfoForEnvironment(environmentId) };+ }++ const [podman, status] = await Promise.all([podmanService.getInfo(environmentId), podmanService.getStatus(environmentId)]);+ return { engine: 'podman', podman, status, podCount };+ }++ async function loadEngineInfo(environmentId: string, podCount: number | undefined): Promise<EngineInfo> {try {- const info = await systemService.getDockerInfoForEnvironment(environment.id);- dockerInfoByEnvironmentId[environment.id] = info;- dockerInfoData = info;+ const info = await fetchEngineInfo(environmentId, podCount);+ engineInfoByEnvironmentId[environmentId] = info;+ engineInfoData = info;return info;} finally {- delete dockerInfoPromiseByEnvironmentId[environment.id];- dockerInfoPromise = null;+ delete engineInfoPromiseByEnvironmentId[environmentId];+ engineInfoPromise = null;}}- function openDockerInfo(environment: Environment) {- dockerInfoError = null;- dockerInfoOpen = true;- dockerInfoData = dockerInfoByEnvironmentId[environment.id] ?? null;- if (dockerInfoData) {- dockerInfoPromise = null;+ function openEngineInfo(item: DashboardEnvironmentOverview) {+ const environmentId = item.environment.id;+ const podCount = hasPermission('podman:read', environmentId) ? item.podCount : undefined;+ engineInfoError = null;+ engineInfoOpen = true;+ engineInfoEngine = podCount === undefined ? 'docker' : 'podman';+ engineInfoData = engineInfoByEnvironmentId[environmentId] ?? null;+ if (engineInfoData) {+ engineInfoPromise = null;return;}- dockerInfoPromise = dockerInfoPromiseByEnvironmentId[environment.id] ?? null;- if (dockerInfoPromise) {+ engineInfoPromise = engineInfoPromiseByEnvironmentId[environmentId] ?? null;+ if (engineInfoPromise) {return;}- dockerInfoPromise = tryCatch(loadDockerInfo(environment)).then((result) => {+ engineInfoPromise = tryCatch(loadEngineInfo(environmentId, podCount)).then((result) => {if (result.error) {const error: Error = result.error;- dockerInfoError = extractApiErrorMessage(error);+ engineInfoError = extractApiErrorMessage(error);throw error;}return result.data;});- dockerInfoPromiseByEnvironmentId[environment.id] = dockerInfoPromise;+ engineInfoPromiseByEnvironmentId[environmentId] = engineInfoPromise;}const environmentCards = $derived.by((): DashboardEnvironmentCardState[] => {@@ -325,6 +339,7 @@},settings: snapshot.settings,versionInfo: snapshot.versionInfo,+ podCount: snapshot.podCount,snapshotState: 'ready',snapshotError: state.streamError ? resolveSnapshotErrorMessage(state) : undefined};@@ -502,7 +517,7 @@action: 'base',label: m.common_inspect(),disabled: !shouldLoadEnvironment(item.environment),- onclick: () => openDockerInfo(item.environment),+ onclick: () => openEngineInfo(item),icon: InfoIcon});@@ -547,6 +562,7 @@running: loadedItem.containers.runningContainers,total: loadedItem.containers.totalContainers,images: loadedItem.imageUsageCounts.totalImages,+ podCount: loadedItem.podCount ?? null,updates: actionItemCount('image_updates'),vulnerabilities: actionItemCount('actionable_vulnerabilities'),cpu: getCpuMetric(stats),@@ -630,7 +646,19 @@label: m.resource_volumes_cap(),value: summary.totalVolumes,context: formatVolumeOverviewLabel(summary)- }+ },+ ...(summary.podmanEnvironments > 0+ ? [+ {+ key: 'pods',+ href: '/podman/pods',+ icon: BoxIcon,+ label: m.podman_pods_title(),+ value: summary.totalPods,+ context: m.dashboard_all_podman_environments({ count: summary.podmanEnvironments })+ }+ ]+ : [])];});@@ -770,7 +798,7 @@</header><section class="shrink-0">- <StatStrip.Root class="lg:grid-cols-4">+ <StatStrip.Root class={summaryTiles.length > 4 ? 'lg:grid-cols-5' : 'lg:grid-cols-4'}>{#each summaryTiles as tile (tile.key)}<StatStrip.Item label={tile.label} value={tile.value} icon={tile.icon} href={tile.href} loading={boardSummaryLoading}>{tile.context}@@ -829,4 +857,10 @@onCancel={closePruneDialog}/>-<DockerInfoDialog bind:open={dockerInfoOpen} dockerInfo={dockerInfoData} {dockerInfoPromise} errorMessage={dockerInfoError} />+<DockerInfoDialog+ bind:open={engineInfoOpen}+ engine={engineInfoEngine}+ info={engineInfoData}+ infoPromise={engineInfoPromise}+ errorMessage={engineInfoError}+/>diff --git a/frontend/src/routes/(app)/dashboard/components/environment-card.svelte b/frontend/src/routes/(app)/dashboard/components/environment-card.svelteindex 81c2b0dd0..b5ab33261 100644--- a/frontend/src/routes/(app)/dashboard/components/environment-card.svelte+++ b/frontend/src/routes/(app)/dashboard/components/environment-card.svelte@@ -80,6 +80,9 @@<div class="flex min-w-0 flex-wrap items-center gap-2"><div class="max-w-full min-w-0 text-base font-semibold tracking-tight break-words">{environment.name}</div><Badge variant={roleBadge.variant} size="sm">{roleBadge.text}</Badge>+ {#if overview.podCount !== undefined}+ <Badge variant="purple" size="sm">{m.podman()}</Badge>+ {/if}{#if versionInfo}<div class="flex items-center">{#if versionInfo.updateAvailable || debugUpgrade}@@ -186,6 +189,13 @@<span class="font-semibold text-foreground tabular-nums">{overview.imageUsageCounts.totalImages}</span>{String(m.images()).toLowerCase()}</span>+ {#if overview.podCount !== undefined}+ <span class="text-border">·</span>+ <span>+ <span class="font-semibold text-foreground tabular-nums">{overview.podCount}</span>+ {String(m.podman_pods_title()).toLowerCase()}+ </span>+ {/if}<span class="text-border">·</span><span><span class="font-semibold text-foreground tabular-nums">{overview.actionItems.items.length}</span>diff --git a/frontend/src/routes/(app)/dashboard/components/environments-table.svelte b/frontend/src/routes/(app)/dashboard/components/environments-table.svelteindex a85a40efc..636bdc4a6 100644--- a/frontend/src/routes/(app)/dashboard/components/environments-table.svelte+++ b/frontend/src/routes/(app)/dashboard/components/environments-table.svelte@@ -11,6 +11,7 @@running: number;total: number;images: number;+ podCount: number | null;updates: number;vulnerabilities: number;cpu: number | null;@@ -39,6 +40,7 @@let { rows }: { rows: EnvironmentTableRow[] } = $props();const showVulnerabilities = $derived(rows.some((row) => featureStore.isEnabled('vulnerabilityManagement', row.environment.id)));+ const showPods = $derived(rows.some((row) => row.podCount !== null));</script>{#snippet actionCount(count: number, href: string, icon: IconType, tone: 'amber' | 'red')}@@ -83,6 +85,7 @@<Table.Head>{m.common_status()}</Table.Head><Table.Head>{m.containers()}</Table.Head><Table.Head>{m.images()}</Table.Head>+ {#if showPods}<Table.Head>{m.podman_pods_title()}</Table.Head>{/if}<Table.Head>{m.updates()}</Table.Head>{#if showVulnerabilities}<Table.Head>{m.vuln_title()}</Table.Head>{/if}<Table.Head class="text-right">{m.cpu_usage()}</Table.Head>@@ -99,6 +102,9 @@<a class="truncate font-medium hover:underline" href="/environments/{row.environment.id}">{row.environment.name}</a>+ {#if row.podCount !== null}+ <Badge variant="purple" size="sm">{m.podman()}</Badge>+ {/if}{#if row.versionText}<Badge variant="gray" size="sm" mono>{row.versionText}@@ -116,10 +122,21 @@</span></Table.Cell>{#if row.loading}- <Table.Cell colspan={showVulnerabilities ? 7 : 6}><Skeleton class="h-4 w-full max-w-md" /></Table.Cell>+ <Table.Cell colspan={6 + Number(showVulnerabilities) + Number(showPods)}+ ><Skeleton class="h-4 w-full max-w-md" /></Table.Cell+ >{:else}<Table.Cell><span class="tabular-nums">{row.running}/{row.total}</span></Table.Cell><Table.Cell><span class="tabular-nums">{row.images}</span></Table.Cell>+ {#if showPods}+ <Table.Cell>+ {#if row.podCount === null}+ <span class="text-xs text-muted-foreground">—</span>+ {:else}+ <span class="tabular-nums">{row.podCount}</span>+ {/if}+ </Table.Cell>+ {/if}<Table.Cell>{@render actionCount(row.updates, '/updates', UpdateIcon, 'amber')}</Table.Cell>{#if showVulnerabilities}<Table.Cell>diff --git a/frontend/src/routes/(app)/dashboard/overview.helpers.ts b/frontend/src/routes/(app)/dashboard/overview.helpers.tsindex 565ffcaa9..6c88cb8df 100644--- a/frontend/src/routes/(app)/dashboard/overview.helpers.ts+++ b/frontend/src/routes/(app)/dashboard/overview.helpers.ts@@ -34,7 +34,9 @@ export function buildOverviewSummary(items: DashboardEnvironmentOverview[]): DasimagesUnused: items.reduce((total, item) => total + item.imageUsageCounts.imagesUnused, 0),totalVolumes: items.reduce((total, item) => total + (item.volumeUsageCounts?.total ?? 0), 0),volumesInUse: items.reduce((total, item) => total + (item.volumeUsageCounts?.inuse ?? 0), 0),- volumesUnused: items.reduce((total, item) => total + (item.volumeUsageCounts?.unused ?? 0), 0)+ volumesUnused: items.reduce((total, item) => total + (item.volumeUsageCounts?.unused ?? 0), 0),+ podmanEnvironments: items.filter((item) => item.podCount !== undefined).length,+ totalPods: items.reduce((total, item) => total + (item.podCount ?? 0), 0)};}diff --git a/frontend/src/routes/(app)/podman/autoupdate/+page.svelte b/frontend/src/routes/(app)/podman/autoupdate/+page.sveltenew file mode 100644index 000000000..41552526e--- /dev/null+++ b/frontend/src/routes/(app)/podman/autoupdate/+page.svelte@@ -0,0 +1,152 @@+<script lang="ts">+ import { toast } from 'svelte-sonner';++ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import LabeledSwitch from '#lib/components/form/labeled-switch.svelte';+ import { DetailSection, KeyValueCard, KeyValueGrid } from '#lib/components/resource-detail/index.js';+ import EmptyState from '#lib/components/states/empty-state.svelte';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import * as Card from '#lib/components/ui/card/index.js';+ import * as Table from '#lib/components/ui/table/index.js';+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';+ import { AlertIcon, InfoIcon, UpdateIcon } from '#lib/icons/index.js';+ import { ResourcePageLayout } from '#lib/layouts/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import type { PodmanAutoUpdateResult } from '#lib/types/podman.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { withOccurrenceKeys } from '#lib/utils/formatting.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ let { data } = $props();++ const status = $derived(data.podmanStatus);+ const mode = $derived(status?.autoUpdateMode ?? 'unavailable');++ let dryRun = $state(false);+ let rollback = $state(true);+ let running = $state(false);+ let result = $state<PodmanAutoUpdateResult | null>(null);+ let session = 0;++ useEnvironmentRefresh(() => {+ session += 1;+ result = null;+ });++ async function handleRun() {+ const started = session;+ running = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.runAutoUpdate(mode === 'rest' ? { dryRun, rollback } : {})),+ message: m.podman_autoupdate_failed(),+ setLoadingState: (value) => (running = value),+ onSuccess: (response) => {+ if ((response.errors ?? []).length > 0) {+ toast.error(m.podman_autoupdate_partial(), { description: response.errors?.join('\n') });+ } else {+ toast.success(m.podman_autoupdate_success());+ }+ if (started !== session) return;+ result = response;+ }+ });+ }+</script>++<ResourcePageLayout title={m.auto_update()} subtitle={m.podman_autoupdate_subtitle()} icon={UpdateIcon} environmentPicker>+ {#snippet mainContent()}+ {#if mode === 'unavailable'}+ <EmptyState+ icon={UpdateIcon}+ title={m.common_unavailable()}+ description={status?.systemdReason || m.podman_autoupdate_unavailable()}+ />+ {:else}+ <div class="space-y-4">+ <Card.Root>+ <Card.Header>+ <Card.Title>{m.podman_autoupdate_run()}</Card.Title>+ <Card.Description>+ {mode === 'rest' ? m.podman_autoupdate_rest_description() : m.podman_autoupdate_systemd_description()}+ </Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="space-y-4">+ {#if mode === 'rest'}+ <LabeledSwitch+ id="autoupdate-dry-run"+ label={m.podman_autoupdate_dry_run()}+ description={m.podman_autoupdate_dry_run_description()}+ bind:checked={dryRun}+ />+ <LabeledSwitch id="autoupdate-rollback" label={m.podman_autoupdate_rollback()} bind:checked={rollback} />+ {/if}+ <ArcaneButton+ action="update"+ customLabel={m.podman_autoupdate_run()}+ onclick={handleRun}+ loading={running}+ disabled={running}+ />+ </div>+ </Card.Content>+ </Card.Root>++ {#if result}+ {#if result.unit}+ <DetailSection title={m.podman_unit()} icon={InfoIcon}>+ <KeyValueGrid>+ <KeyValueCard label={m.podman_unit()}>{result.unit.name}</KeyValueCard>+ <KeyValueCard label={m.podman_unit_active_state()}>+ {result.unit.activeState} ({result.unit.subState})+ </KeyValueCard>+ </KeyValueGrid>+ </DetailSection>+ {/if}++ {#if (result.reports ?? []).length > 0}+ <div class="overflow-x-auto rounded-lg border">+ <Table.Root aria-label={m.auto_update()}>+ <Table.Header>+ <Table.Row>+ <Table.Head scope="col">{m.containers()}</Table.Head>+ <Table.Head scope="col">{m.common_image()}</Table.Head>+ <Table.Head scope="col">{m.podman_autoupdate_policy()}</Table.Head>+ <Table.Head scope="col">{m.podman_unit()}</Table.Head>+ <Table.Head scope="col">{m.common_status()}</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each result.reports ?? [] as report (report.containerId)}+ <Table.Row>+ <Table.Cell>{report.containerName}</Table.Cell>+ <Table.Cell><span class="font-mono text-xs">{report.imageName}</span></Table.Cell>+ <Table.Cell>{report.policy}</Table.Cell>+ <Table.Cell><span class="font-mono text-xs">{report.systemdUnit}</span></Table.Cell>+ <Table.Cell>+ <Badge variant={report.updated === 'true' ? 'green' : 'gray'} size="sm">{report.updated}</Badge>+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </div>+ {:else if result.mode === 'rest'}+ <EmptyState icon={UpdateIcon} title={m.podman_autoupdate_no_reports()} variant="plain" />+ {/if}++ {#if (result.errors ?? []).length > 0}+ <DetailSection title={m.common_error()} icon={AlertIcon}>+ <ul class="space-y-1 font-mono text-xs text-destructive">+ {#each withOccurrenceKeys(result.errors) as error (error.key)}+ <li>{error.value}</li>+ {/each}+ </ul>+ </DetailSection>+ {/if}+ {/if}+ </div>+ {/if}+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/podman/kube/+page.svelte b/frontend/src/routes/(app)/podman/kube/+page.sveltenew file mode 100644index 000000000..10f643643--- /dev/null+++ b/frontend/src/routes/(app)/podman/kube/+page.svelte@@ -0,0 +1,240 @@+<script lang="ts">+ import { useQueryClient } from '@tanstack/svelte-query';+ import { toast } from 'svelte-sonner';++ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import CodePanel from '#lib/components/code-panel.svelte';+ import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';+ import LabeledSwitch from '#lib/components/form/labeled-switch.svelte';+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';+ import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';+ import * as Card from '#lib/components/ui/card/index.js';+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';+ import { LayersIcon } from '#lib/icons/index.js';+ import { ResourcePageLayout } from '#lib/layouts/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { queryKeys } from '#lib/query/query-keys.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';+ import { PODMAN_KUBE_GENERATE_TYPES, type PodmanKubeGenerateType } from '#lib/types/podman.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { parseList } from '#lib/utils/form-parsers.js';+ import { withOccurrenceKeys } from '#lib/utils/formatting.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ const queryClient = useQueryClient();++ let yaml = $state('');+ let start = $state(true);+ let replace = $state(false);+ let networks = $state('');+ let generateNames = $state('');+ let generateType = $state<PodmanKubeGenerateType>('pod');+ let generateService = $state(false);+ let generated = $state('');+ let resultLines = $state<string[]>([]);+ let loading = $state({ play: false, down: false, generate: false });+ let session = 0;++ useEnvironmentRefresh(() => {+ session += 1;+ resultLines = [];+ generated = '';+ });++ async function invalidatePods() {+ await queryClient.invalidateQueries({ queryKey: queryKeys.podman.environment(environmentStore.selected?.id ?? '0') });+ }++ async function handlePlay() {+ const started = session;+ if (!yaml.trim()) {+ toast.error(m.common_field_required({ field: m.podman_kube_yaml() }));+ return;+ }+ const networkList = parseList(networks);+ loading.play = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(+ podmanService.kubePlay({ yaml, start, replace, networks: networkList.length > 0 ? networkList : undefined })+ ),+ message: m.podman_kube_play_failed(),+ setLoadingState: (value) => (loading.play = value),+ onSuccess: async (report) => {+ if (started !== session) return;+ resultLines = [+ ...(report.pods ?? []).flatMap((pod) => [+ m.podman_kube_pod_created({ id: pod.id.slice(0, 12), count: pod.containers?.length ?? 0 }),+ ...(pod.containerErrors ?? [])+ ]),+ ...(report.volumes ?? []).map((volume) => volume.name)+ ];+ if ((report.pods ?? []).some((pod) => (pod.containerErrors ?? []).length > 0)) {+ toast.error(m.podman_kube_play_partial({ count: report.pods?.length ?? 0 }));+ } else {+ toast.success(m.podman_kube_play_success({ count: report.pods?.length ?? 0 }));+ }+ await invalidatePods();+ }+ });+ }++ async function handleDown() {+ if (!yaml.trim()) {+ toast.error(m.common_field_required({ field: m.podman_kube_yaml() }));+ return;+ }+ const started = session;+ const environmentId = await environmentStore.getCurrentEnvironmentId();+ const downYaml = yaml;+ openConfirmDialog({+ title: m.common_down(),+ message: m.podman_kube_down_confirm(),+ checkboxes: [{ id: 'force', label: m.podman_kube_force_description() }],+ confirm: {+ label: m.common_down(),+ destructive: true,+ action: async (checkboxStates) => {+ if (started !== session) return;+ loading.down = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(+ podmanService.kubeDown({ yaml: downYaml, force: checkboxStates['force'] === true }, environmentId)+ ),+ message: m.podman_kube_down_failed(),+ setLoadingState: (value) => (loading.down = value),+ onSuccess: async (report) => {+ if (started !== session) return;+ resultLines = (report.rmReport ?? []).map((pod) => m.podman_kube_pod_removed({ id: pod.id.slice(0, 12) }));+ toast.success(m.podman_kube_down_success({ count: report.rmReport?.length ?? 0 }));+ await invalidatePods();+ }+ });+ }+ }+ });+ }++ async function handleGenerate() {+ const started = session;+ const names = parseList(generateNames);+ if (names.length === 0) {+ toast.error(m.common_field_required({ field: m.podman_kube_generate_names() }));+ return;+ }+ loading.generate = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.kubeGenerate({ names, type: generateType, service: generateService || undefined })),+ message: m.podman_kube_generate_failed(),+ setLoadingState: (value) => (loading.generate = value),+ onSuccess: (response) => {+ if (started !== session) return;+ generated = response.yaml;+ }+ });+ }+</script>++<ResourcePageLayout title={m.podman_kube_title()} subtitle={m.podman_kube_subtitle()} icon={LayersIcon} environmentPicker>+ {#snippet mainContent()}+ <div class="grid gap-4 xl:grid-cols-2">+ <div class="space-y-4">+ <CodePanel title={m.podman_kube_yaml()} language="yaml" validationMode="none" bind:value={yaml} autoHeight />+ <Card.Root>+ <Card.Header>+ <Card.Title>{m.podman_kube_play()}</Card.Title>+ <Card.Description>{m.podman_kube_play_description()}</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="space-y-4">+ <LabeledSwitch id="kube-start" label={m.podman_kube_start()} bind:checked={start} />+ <LabeledSwitch id="kube-replace" label={m.podman_kube_replace()} bind:checked={replace} />+ <TextInputWithLabel+ id="kube-networks"+ label={m.resource_networks_cap()}+ description={m.podman_comma_separated()}+ bind:value={networks}+ />+ <div class="flex flex-wrap gap-2">+ <ArcaneButton+ action="deploy"+ customLabel={m.podman_kube_play()}+ onclick={handlePlay}+ loading={loading.play}+ disabled={loading.play || loading.down}+ />+ <ArcaneButton+ action="remove"+ customLabel={m.common_down()}+ onclick={handleDown}+ loading={loading.down}+ disabled={loading.play || loading.down}+ />+ </div>+ {#if resultLines.length > 0}+ <ul class="space-y-1 rounded-lg border p-3 font-mono text-xs">+ {#each withOccurrenceKeys(resultLines) as line (line.key)}+ <li>{line.value}</li>+ {/each}+ </ul>+ {/if}+ </div>+ </Card.Content>+ </Card.Root>+ </div>++ <div class="space-y-4">+ <Card.Root>+ <Card.Header>+ <Card.Title>{m.podman_kube_generate()}</Card.Title>+ <Card.Description>{m.podman_kube_generate_description()}</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="space-y-4">+ <TextInputWithLabel+ id="kube-generate-names"+ label={m.podman_kube_generate_names()}+ description={m.podman_comma_separated()}+ bind:value={generateNames}+ />+ <SelectWithLabel+ id="kube-generate-type"+ label={m.common_type()}+ bind:value={() => generateType, (value) => (generateType = value as PodmanKubeGenerateType)}+ options={PODMAN_KUBE_GENERATE_TYPES.map((type) => ({ label: type, value: type }))}+ />+ <LabeledSwitch id="kube-generate-service" label={m.podman_kube_generate_service()} bind:checked={generateService} />+ <div class="flex flex-wrap gap-2">+ <ArcaneButton+ action="create"+ customLabel={m.podman_kube_generate()}+ onclick={handleGenerate}+ loading={loading.generate}+ disabled={loading.generate}+ />+ {#if generated}+ <ArcaneButton+ action="base"+ tone="outline"+ customLabel={m.podman_kube_use_generated()}+ onclick={() => (yaml = generated)}+ />+ {/if}+ </div>+ </div>+ </Card.Content>+ </Card.Root>+ {#if generated}+ <CodePanel+ title={m.podman_kube_generated()}+ language="yaml"+ validationMode="none"+ value={generated}+ readOnly+ autoHeight+ />+ {/if}+ </div>+ </div>+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/podman/pods/+page.svelte b/frontend/src/routes/(app)/podman/pods/+page.sveltenew file mode 100644index 000000000..8f332f05a--- /dev/null+++ b/frontend/src/routes/(app)/podman/pods/+page.svelte@@ -0,0 +1,186 @@+<script lang="ts">+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';+ import { untrack } from 'svelte';+ import { toast } from 'svelte-sonner';++ import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';+ import CreatePodSheet from '#lib/components/sheets/create-pod-sheet.svelte';+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';+ import { BoxIcon } from '#lib/icons/index.js';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { queryKeys } from '#lib/query/query-keys.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import type { PodmanPodCreateRequest } from '#lib/types/podman.js';+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { acrossEnvironmentsNote, fetchAcrossEnvironments, settleAcrossEnvironments } from '#lib/utils/environments.js';+ import { shownPodmanEnvironments } from '#lib/utils/podman.js';+ import { ResourceListPageState } from '#lib/utils/resource-list-page.svelte.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ import PodsTable from './components/pods-table.svelte';++ let { data } = $props();+ const queryClient = useQueryClient();++ const pageState = new ResourceListPageState(untrack(() => data.requestOptions));+ const podmanEnvironments = $derived(shownPodmanEnvironments(data.podmanStatuses));+ const manageableEnvironments = $derived(podmanEnvironments.filter((env) => hasPermission('podman:pods', env.id)));+ let isLoading = $state({ create: false, prune: false });++ const podsQuery = createQuery(() => {+ const queryScope = pageState.scope;+ const environments = podmanEnvironments;+ const options = pageState.requestOptions;+ return {+ queryKey: queryKeys.podman.pods(queryScope, options),+ queryFn: () =>+ fetchAcrossEnvironments(environments, options, (id, request, config) => podmanService.getPods(id, request, config)),+ placeholderData: (previous, query) => {+ if (query?.queryKey[1] === queryScope) return previous;+ return undefined;+ },+ select: (value) => ({ envId: queryScope, value })+ };+ });++ const resourcesReady = $derived(podsQuery.data?.envId === pageState.scope);+ const pods = $derived(podsQuery.data?.value ?? data.pods);++ async function loadPods(options: SearchPaginationSortRequest = pageState.requestOptions, requestedScope = pageState.scope) {+ const environments = podmanEnvironments;+ pageState.requestOptions = options;+ await queryClient.query({+ queryKey: queryKeys.podman.pods(requestedScope, options),+ staleTime: 0,+ queryFn: () =>+ fetchAcrossEnvironments(environments, options, (id, request, config) => podmanService.getPods(id, request, config))+ });+ }++ async function refresh() {+ await handleApiResultWithCallbacks({+ result: await tryCatch(loadPods()),+ message: m.common_refresh_failed({ resource: m.podman_pods_title() })+ });+ }++ useEnvironmentRefresh(() => {+ pageState.isCreateDialogOpen = false;+ });++ async function handleCreate(request: PodmanPodCreateRequest, environmentId: string) {+ isLoading.create = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.createPod(request, environmentId)),+ message: m.common_create_failed({ resource: request.name }),+ setLoadingState: (value) => (isLoading.create = value),+ onSuccess: async () => {+ toast.success(m.common_create_success({ resource: request.name }));+ pageState.isCreateDialogOpen = false;+ await refresh();+ }+ });+ }++ function handlePrune() {+ const environments = manageableEnvironments;+ openConfirmDialog({+ title: m.podman_pods_prune(),+ message: `${m.podman_pods_prune_confirm()} ${acrossEnvironmentsNote(environments)}`.trim(),+ confirm: {+ label: m.podman_pods_prune(),+ destructive: true,+ action: async () => {+ isLoading.prune = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(settleAcrossEnvironments(environments, (id) => podmanService.prunePods(id))),+ message: m.podman_pods_prune_failed(),+ setLoadingState: (value) => (isLoading.prune = value),+ onSuccess: async (results) => {+ const count = results.reduce((total, { value }) => total + (value?.length ?? 0), 0);+ toast.success(m.podman_pods_prune_success({ count }));+ await refresh();+ }+ });+ }+ }+ });+ }++ const isRefreshing = $derived(podsQuery.isFetching && !podsQuery.isPending);++ const actionButtons: ActionButton[] = $derived.by(() => {+ const buttons: ActionButton[] = [];+ if (manageableEnvironments.length > 0) {+ buttons.push(+ {+ id: 'create',+ action: 'create',+ placement: 'primary',+ label: m.common_create_button({ resource: m.podman_pod() }),+ onclick: () => (pageState.isCreateDialogOpen = true),+ loading: isLoading.create,+ disabled: !resourcesReady || isLoading.create+ },+ {+ id: 'prune',+ action: 'prune',+ placement: 'secondary',+ label: m.podman_pods_prune(),+ onclick: handlePrune,+ loading: isLoading.prune,+ disabled: isLoading.prune+ }+ );+ }+ buttons.push({+ id: 'refresh',+ action: 'refresh',+ placement: 'secondary',+ iconOnly: true,+ label: m.common_refresh(),+ onclick: refresh,+ loading: isRefreshing,+ disabled: podsQuery.isFetching+ });+ return buttons;+ });++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.podman_pods_total(),+ value: resourcesReady ? (pods.pagination?.totalItems ?? pods.data.length) : 0,+ icon: BoxIcon,+ iconColor: 'text-info'+ }+ ]);+</script>++<ResourcePageLayout title={m.podman_pods_title()} subtitle={m.podman_pods_subtitle()} {actionButtons} {statCards}>+ {#snippet mainContent()}+ {#if resourcesReady}+ {#key pageState.scope}+ <PodsTable+ bind:pods={+ () => pods,+ (value) => queryClient.setQueryData(queryKeys.podman.pods(pageState.scope, pageState.requestOptions), value)+ }+ bind:requestOptions={pageState.requestOptions}+ onRefreshData={loadPods}+ />+ {/key}+ {/if}+ {/snippet}++ {#snippet additionalContent()}+ <CreatePodSheet+ bind:open={pageState.isCreateDialogOpen}+ isLoading={isLoading.create}+ environments={manageableEnvironments}+ onSubmit={handleCreate}+ />+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/podman/pods/+page.ts b/frontend/src/routes/(app)/podman/pods/+page.tsnew file mode 100644index 000000000..749278115--- /dev/null+++ b/frontend/src/routes/(app)/podman/pods/+page.ts@@ -0,0 +1,45 @@+import { m } from '#lib/paraglide/messages.js';+import { queryKeys } from '#lib/query/query-keys.js';+import { podmanService } from '#lib/services/podman-service.js';+import { environmentStore } from '#lib/stores/environment.store.svelte.js';+import type { SearchPaginationSortRequest } from '#lib/types/shared.js';+import { throwPageLoadError } from '#lib/utils/api.js';+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';+import { shownPodmanEnvironments } from '#lib/utils/podman.js';+import { resolveInitialTableRequest } from '#lib/utils/tables.js';+import { tryCatch } from '#lib/utils/try-catch.js';++import type { PageLoad } from './$types';++export const load: PageLoad = async ({ parent }) => {+ const { queryClient, podmanStatuses } = await parent();+ const environments = shownPodmanEnvironments(podmanStatuses);+ const scope = environmentStore.shownKey;++ const requestOptions = resolveInitialTableRequest('arcane-podman-pods-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'name',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ const pods = await tryCatch(+ queryClient.query({+ queryKey: queryKeys.podman.pods(scope, requestOptions),+ queryFn: () =>+ fetchAcrossEnvironments(environments, requestOptions, (id, request, config) => podmanService.getPods(id, request, config))+ })+ );+ if (pods.error !== null) {+ throwPageLoadError(pods.error, m.common_load_failed({ resource: m.podman_pods_title() }));+ }++ return {+ pods: pods.data,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/podman/pods/[id]/+error.svelte b/frontend/src/routes/(app)/podman/pods/[id]/+error.sveltenew file mode 100644index 000000000..63a6029fc--- /dev/null+++ b/frontend/src/routes/(app)/podman/pods/[id]/+error.svelte@@ -0,0 +1,10 @@+<script lang="ts">+ import ResourceErrorPage from '#lib/components/resource-error-page.svelte';+ import { m } from '#lib/paraglide/messages.js';+</script>++<ResourceErrorPage+ fallbackTitle={m.error_generic()}+ backLabel={m.common_back_to({ resource: m.podman_pods_title() })}+ backHref="/podman/pods"+/>diff --git a/frontend/src/routes/(app)/podman/pods/[id]/+page.svelte b/frontend/src/routes/(app)/podman/pods/[id]/+page.sveltenew file mode 100644index 000000000..c4f644c5e--- /dev/null+++ b/frontend/src/routes/(app)/podman/pods/[id]/+page.svelte@@ -0,0 +1,242 @@+<script lang="ts">+ import { goto } from '$app/navigation';+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';++ import type { ActionButton } from '#lib/components/action-button-group/types.js';+ import { DetailSection, KeyValueCard, KeyValueGrid } from '#lib/components/resource-detail/index.js';+ import EmptyState from '#lib/components/states/empty-state.svelte';+ import * as Alert from '#lib/components/ui/alert/index.js';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import * as Table from '#lib/components/ui/table/index.js';+ import MonoCell from '#lib/components/vulnerability/mono-cell.svelte';+ import { AlertTriangleIcon, ContainersIcon, InfoIcon, LayoutListIcon, StatsIcon } from '#lib/icons/index.js';+ import { ResourceDetailLayout } from '#lib/layouts/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { queryKeys } from '#lib/query/query-keys.js';+ import { podmanService, type PodmanPodAction } from '#lib/services/podman-service.js';+ import { extractApiErrorMessage } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { environmentHref } from '#lib/utils/environments.js';+ import { formatDateTime, withOccurrenceKeys } from '#lib/utils/formatting.js';+ import { podmanStateVariant } from '#lib/utils/podman.js';++ import { confirmRemovePod, podActionLabels, runPodAction } from '../pod-actions';++ let { data } = $props();++ const queryClient = useQueryClient();+ const envId = $derived(data.envId);+ const podQuery = createQuery(() => ({+ queryKey: queryKeys.podman.pod(envId, data.pod.id),+ queryFn: () => podmanService.getPod(data.pod.id, envId),+ initialData: data.pod,+ refetchInterval: 10000,+ retry: false+ }));+ const pod = $derived(podQuery.data ?? data.pod);+ const members = $derived(pod.containers ?? []);+ const isRunning = $derived(pod.state.toLowerCase() === 'running');+ const canManage = $derived(hasPermission('podman:pods', envId));++ const statsQuery = createQuery(() => ({+ queryKey: queryKeys.podman.podStats(envId, pod.name),+ queryFn: () => podmanService.getPodStats([pod.name], envId),+ enabled: isRunning,+ refetchInterval: 5000,+ retry: false+ }));++ const topQuery = createQuery(() => ({+ queryKey: queryKeys.podman.podTop(envId, pod.id),+ queryFn: () => podmanService.getPodTop(pod.id, envId),+ enabled: isRunning,+ refetchInterval: 5000,+ retry: false+ }));++ let pendingAction = $state<PodmanPodAction | null>(null);++ async function refresh() {+ await queryClient.invalidateQueries({ queryKey: queryKeys.podman.environment(envId) });+ }++ function lifecycleButton(action: PodmanPodAction, placement: 'primary' | 'secondary' | 'menu'): ActionButton {+ return {+ id: action,+ action,+ group: 'lifecycle',+ placement,+ label: podActionLabels[action](),+ loading: pendingAction === action,+ disabled: pendingAction !== null,+ onclick: () =>+ runPodAction({ ...pod, environmentId: envId }, action, refresh, (loading) => (pendingAction = loading ? action : null))+ };+ }++ const actions: ActionButton[] = $derived(+ canManage+ ? [+ isRunning ? lifecycleButton('stop', 'primary') : lifecycleButton('start', 'primary'),+ lifecycleButton('restart', 'secondary'),+ pod.state.toLowerCase() === 'paused' ? lifecycleButton('unpause', 'menu') : lifecycleButton('pause', 'menu'),+ lifecycleButton('kill', 'menu'),+ {+ id: 'remove',+ action: 'remove',+ group: 'danger',+ destructive: true,+ placement: 'menu',+ label: m.common_remove(),+ onclick: () => confirmRemovePod({ ...pod, environmentId: envId }, () => goto('/podman/pods'))+ }+ ]+ : []+ );++ const portBindings = $derived(+ Object.entries(pod.infraConfig?.portBindings ?? {}).flatMap(([containerPort, bindings]) =>+ (bindings ?? []).map((binding) => `${binding.hostIp ? `${binding.hostIp}:` : ''}${binding.hostPort} → ${containerPort}`)+ )+ );+</script>++<ResourceDetailLayout+ backUrl="/podman/pods"+ backLabel={m.podman_pods_title()}+ title={pod.name}+ subtitle={`${m.common_id()}: ${pod.id.slice(0, 12)}`}+ {actions}+>+ {#snippet badges()}+ <Badge variant={podmanStateVariant(pod.state)} minWidth="20">{pod.state}</Badge>+ {/snippet}++ {#if podQuery.isError}+ <Alert.Root variant="destructive">+ <AlertTriangleIcon class="size-4" />+ <Alert.Title>{m.podman_updates_paused()}</Alert.Title>+ <Alert.Description>{extractApiErrorMessage(podQuery.error)}</Alert.Description>+ </Alert.Root>+ {/if}++ <DetailSection title={m.common_overview()} icon={InfoIcon}>+ <KeyValueGrid>+ <KeyValueCard label={m.common_id()}>{pod.id}</KeyValueCard>+ <KeyValueCard label={m.common_created()}>{formatDateTime(pod.created) || pod.created}</KeyValueCard>+ {#if pod.hostname}+ <KeyValueCard label={m.hostname()}>{pod.hostname}</KeyValueCard>+ {/if}+ <KeyValueCard label={m.podman_pod_infra()}>{pod.createInfra ? m.common_yes() : m.common_no()}</KeyValueCard>+ {#if pod.sharedNamespaces?.length}+ <KeyValueCard label={m.podman_pod_shared_namespaces()}>{pod.sharedNamespaces.join(', ')}</KeyValueCard>+ {/if}+ {#if pod.infraConfig?.networks?.length}+ <KeyValueCard label={m.resource_networks_cap()}>{pod.infraConfig.networks.join(', ')}</KeyValueCard>+ {/if}+ {#if portBindings.length > 0}+ <KeyValueCard label={m.common_ports()}>{portBindings.join(', ')}</KeyValueCard>+ {/if}+ </KeyValueGrid>+ </DetailSection>++ <DetailSection title={m.containers()} icon={ContainersIcon}>+ {#if members.length === 0}+ <EmptyState icon={ContainersIcon} title={m.podman_pod_no_containers()} variant="plain" />+ {:else}+ <div class="divide-y rounded-lg border">+ {#each members as member (member.id)}+ <div class="flex items-center justify-between gap-3 p-3">+ <a class="min-w-0 truncate font-medium hover:underline" href={environmentHref(`/containers/${member.id}`, envId)}+ >{member.name}</a+ >+ <div class="flex items-center gap-2">+ {#if member.id === pod.infraContainerId}+ <Badge variant="gray" size="sm">{m.podman_pod_infra()}</Badge>+ {/if}+ <Badge variant={podmanStateVariant(member.state)} size="sm">{member.state}</Badge>+ </div>+ </div>+ {/each}+ </div>+ {/if}+ </DetailSection>++ <DetailSection title={m.containers_resource_metrics()} icon={StatsIcon}>+ {#if !isRunning}+ <EmptyState icon={StatsIcon} title={m.common_unavailable()} description={m.podman_pod_not_running()} variant="plain" />+ {:else if statsQuery.isError}+ <EmptyState+ icon={StatsIcon}+ title={m.common_load_failed({ resource: m.containers_resource_metrics() })}+ description={extractApiErrorMessage(statsQuery.error)}+ actionLabel={m.common_retry()}+ onAction={() => statsQuery.refetch()}+ variant="plain"+ />+ {:else}+ <div class="overflow-x-auto rounded-lg border">+ <Table.Root aria-label={m.containers_resource_metrics()}>+ <Table.Header>+ <Table.Row>+ <Table.Head scope="col">{m.common_name()}</Table.Head>+ <Table.Head scope="col">{m.cpu_usage()}</Table.Head>+ <Table.Head scope="col">{m.memory_usage()}</Table.Head>+ <Table.Head scope="col">{m.containers_block_io()}</Table.Head>+ <Table.Head scope="col">{m.containers_network_io()}</Table.Head>+ <Table.Head scope="col">{m.podman_pids()}</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each statsQuery.data ?? [] as stat (stat.cid)}+ <Table.Row>+ <Table.Cell>{stat.name}</Table.Cell>+ <Table.Cell><MonoCell value={stat.cpu} /></Table.Cell>+ <Table.Cell><MonoCell value={stat.memUsage} /></Table.Cell>+ <Table.Cell><MonoCell value={stat.blockIo} /></Table.Cell>+ <Table.Cell><MonoCell value={stat.netIo} /></Table.Cell>+ <Table.Cell><MonoCell value={stat.pids} /></Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </div>+ {/if}+ </DetailSection>++ <DetailSection title={m.containers_processes_title()} icon={LayoutListIcon}>+ {#if !isRunning}+ <EmptyState icon={LayoutListIcon} title={m.common_unavailable()} description={m.podman_pod_not_running()} variant="plain" />+ {:else if topQuery.isError}+ <EmptyState+ icon={LayoutListIcon}+ title={m.common_load_failed({ resource: m.containers_processes_title() })}+ description={extractApiErrorMessage(topQuery.error)}+ actionLabel={m.common_retry()}+ onAction={() => topQuery.refetch()}+ variant="plain"+ />+ {:else if topQuery.data}+ <div class="overflow-x-auto rounded-lg border">+ <Table.Root aria-label={m.containers_processes_title()}>+ <Table.Header>+ <Table.Row>+ {#each withOccurrenceKeys(topQuery.data.titles) as title (title.key)}+ <Table.Head scope="col">{title.value}</Table.Head>+ {/each}+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each topQuery.data.processes ?? [] as cells (JSON.stringify(cells))}+ <Table.Row>+ {#each withOccurrenceKeys(cells) as cell (cell.key)}+ <Table.Cell><MonoCell value={cell.value} /></Table.Cell>+ {/each}+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </div>+ {/if}+ </DetailSection>+</ResourceDetailLayout>diff --git a/frontend/src/routes/(app)/podman/pods/[id]/+page.ts b/frontend/src/routes/(app)/podman/pods/[id]/+page.tsnew file mode 100644index 000000000..9c2d96d08--- /dev/null+++ b/frontend/src/routes/(app)/podman/pods/[id]/+page.ts@@ -0,0 +1,23 @@+import { m } from '#lib/paraglide/messages.js';+import { queryKeys } from '#lib/query/query-keys.js';+import { podmanService } from '#lib/services/podman-service.js';+import { throwPageLoadError } from '#lib/utils/api.js';+import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';+import { tryCatch } from '#lib/utils/try-catch.js';++import type { PageLoad } from './$types';++export const load: PageLoad = async ({ params, parent, url }) => {+ const { queryClient } = await parent();+ const envId = await resolveDetailEnvironmentId(url);+ const result = await tryCatch(+ queryClient.query({+ queryKey: queryKeys.podman.pod(envId, params.id),+ queryFn: () => podmanService.getPod(params.id, envId)+ })+ );+ if (result.error !== null) {+ throwPageLoadError(result.error, m.common_load_failed({ resource: m.podman_pod() }));+ }+ return { envId, pod: result.data };+};diff --git a/frontend/src/routes/(app)/podman/pods/components/pods-table.svelte b/frontend/src/routes/(app)/podman/pods/components/pods-table.sveltenew file mode 100644index 000000000..96008daa9--- /dev/null+++ b/frontend/src/routes/(app)/podman/pods/components/pods-table.svelte@@ -0,0 +1,162 @@+<script lang="ts">+ import { goto } from '$app/navigation';++ import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';+ import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table/index.js';+ import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';+ import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';+ import { BoxIcon, CalendarIcon, ContainersIcon, InspectIcon, TrashIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import type { PodmanPodAction } from '#lib/services/podman-service.js';+ import userStore from '#lib/stores/user-store.svelte.js';+ import type { PodmanPod } from '#lib/types/podman.js';+ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { environmentHref, hasShownPermission, type EnvironmentPage, type EnvironmentRow } from '#lib/utils/environments.js';+ import { formatDateTimeShort } from '#lib/utils/formatting.js';+ import { podmanStateVariant } from '#lib/utils/podman.js';++ import { confirmRemovePod, podActionLabels, runPodAction } from '../pod-actions';++ type PodRow = EnvironmentRow<PodmanPod>;++ let {+ pods = $bindable(),+ requestOptions = $bindable(),+ onRefreshData+ }: {+ pods: EnvironmentPage<Paginated<PodmanPod>>;+ requestOptions: SearchPaginationSortRequest;+ onRefreshData: (options: SearchPaginationSortRequest) => Promise<void>;+ } = $props();++ const canManagePods = $derived.by(() => {+ userStore.current;+ return hasShownPermission('podman:pods');+ });+ const lifecycleActions: PodmanPodAction[] = ['start', 'stop', 'restart', 'pause', 'unpause', 'kill'];++ let mobileFieldVisibility = $state<Record<string, boolean>>({});++ const podHref = (pod: PodRow) => environmentHref(`/podman/pods/${encodeURIComponent(pod.id)}`, pod.environmentId);++ const columns = $derived([+ ...environmentColumns<PodRow>(),+ { accessorKey: 'id', title: m.common_id(), hidden: true },+ { accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },+ { accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },+ { accessorKey: 'containers', title: m.containers(), cell: ContainersCell },+ { accessorKey: 'networks', title: m.resource_networks_cap(), cell: NetworksCell },+ { accessorKey: 'created', title: m.common_created(), sortable: true, cell: CreatedCell }+ ] satisfies ColumnSpec<PodRow>[]);++ const mobileFields = [+ { id: 'id', label: m.common_id(), defaultVisible: false },+ { id: 'status', label: m.common_status(), defaultVisible: true },+ { id: 'containers', label: m.containers(), defaultVisible: true },+ { id: 'created', label: m.common_created(), defaultVisible: true }+ ];+</script>++{#snippet NameCell({ item }: { item: PodRow })}+ <a class="font-medium hover:underline" href={podHref(item)}>{item.name}</a>+{/snippet}++{#snippet StatusCell({ item }: { item: PodRow })}+ <Badge variant={podmanStateVariant(item.status)} minWidth="20">{item.status}</Badge>+{/snippet}++{#snippet ContainersCell({ item }: { item: PodRow })}+ {item.containers?.length ?? 0}+{/snippet}++{#snippet NetworksCell({ item }: { item: PodRow })}+ {item.networks?.join(', ') || '-'}+{/snippet}++{#snippet CreatedCell({ item }: { item: PodRow })}+ {formatDateTimeShort(item.created)}+{/snippet}++{#snippet PodMobileCard({ item, mobileFieldVisibility }: { item: PodRow; mobileFieldVisibility: MobileFieldVisibility })}+ <UniversalMobileCard+ {item}+ icon={{ component: BoxIcon, variant: podmanStateVariant(item.status) === 'green' ? 'emerald' : 'gray' }}+ title={(item: PodRow) => item.name}+ subtitle={(item: PodRow) => ((mobileFieldVisibility['id'] ?? false) ? item.id : null)}+ badges={(mobileFieldVisibility['status'] ?? true)+ ? [(item: PodRow) => ({ variant: podmanStateVariant(item.status), text: item.status })]+ : []}+ fields={[+ {+ label: m.containers(),+ getValue: (item: PodRow) => String(item.containers?.length ?? 0),+ icon: ContainersIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['containers'] ?? true+ }+ ]}+ footer={(mobileFieldVisibility['created'] ?? true)+ ? {+ label: m.common_created(),+ getValue: (item: PodRow) => formatDateTimeShort(item.created),+ icon: CalendarIcon+ }+ : undefined}+ rowActions={RowActions}+ onclick={() => goto(podHref(item))}+ />+{/snippet}++{#snippet RowActions({ item }: { item: PodRow })}+ <RowActionsMenu>+ <DropdownMenu.Item onclick={() => goto(podHref(item))}>+ <InspectIcon class="size-4" />+ {m.common_inspect()}+ </DropdownMenu.Item>+ {#if canManagePods && hasPermission('podman:pods', item.environmentId)}+ <DropdownMenu.Separator />+ {#each lifecycleActions as action (action)}+ <DropdownMenu.Item+ onclick={() =>+ runPodAction(item, action, async () => {+ await onRefreshData(requestOptions);+ })}+ >+ {podActionLabels[action]()}+ </DropdownMenu.Item>+ {/each}+ <DropdownMenu.Separator />+ <DropdownMenu.Item+ variant="destructive"+ onclick={() =>+ confirmRemovePod(item, async () => {+ await onRefreshData(requestOptions);+ })}+ >+ <TrashIcon class="size-4" />+ {m.common_remove()}+ </DropdownMenu.Item>+ {/if}+ </RowActionsMenu>+{/snippet}++<ArcaneTable+ persistKey="arcane-podman-pods-table"+ items={pods}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => {+ requestOptions = options;+ await onRefreshData(options);+ return pods;+ }}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={PodMobileCard}+/>diff --git a/frontend/src/routes/(app)/podman/pods/pod-actions.ts b/frontend/src/routes/(app)/podman/pods/pod-actions.tsnew file mode 100644index 000000000..0e47dddf7--- /dev/null+++ b/frontend/src/routes/(app)/podman/pods/pod-actions.ts@@ -0,0 +1,58 @@+import { toast } from 'svelte-sonner';++import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';+import { m } from '#lib/paraglide/messages.js';+import { podmanService, type PodmanPodAction } from '#lib/services/podman-service.js';+import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+import { tryCatch } from '#lib/utils/try-catch.js';++type PodTarget = { id: string; name: string; environmentId: string };++export const podActionLabels: Record<PodmanPodAction, () => string> = {+ start: m.common_start,+ stop: m.common_stop,+ restart: m.common_restart,+ pause: m.common_pause,+ unpause: m.common_unpause,+ kill: m.common_kill+};++export async function runPodAction(+ pod: PodTarget,+ action: PodmanPodAction,+ onDone: () => void | Promise<void>,+ setLoading: (loading: boolean) => void = () => {}+) {+ setLoading(true);+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.podAction(pod.id, action, pod.environmentId)),+ message: m.common_action_failed_with_type({ action: podActionLabels[action](), type: pod.name }),+ setLoadingState: setLoading,+ onSuccess: async () => {+ toast.success(m.podman_action_success({ action: podActionLabels[action](), name: pod.name }));+ await onDone();+ }+ });+}++export function confirmRemovePod(pod: PodTarget, onDone: () => void | Promise<void>) {+ openConfirmDialog({+ title: m.common_remove_title({ resource: m.podman_pod() }),+ message: m.common_remove_confirm({ resource: pod.name }),+ checkboxes: [{ id: 'force', label: m.podman_force_remove() }],+ confirm: {+ label: m.common_remove(),+ destructive: true,+ action: async (checkboxStates) => {+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.removePod(pod.id, checkboxStates['force'] === true, pod.environmentId)),+ message: m.common_remove_failed({ resource: pod.name }),+ onSuccess: async () => {+ toast.success(m.common_remove_success({ resource: pod.name }));+ await onDone();+ }+ });+ }+ }+ });+}diff --git a/frontend/src/routes/(app)/podman/quadlets/+page.svelte b/frontend/src/routes/(app)/podman/quadlets/+page.sveltenew file mode 100644index 000000000..ccc869690--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/+page.svelte@@ -0,0 +1,127 @@+<script lang="ts">+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';+ import { untrack } from 'svelte';++ import * as Alert from '#lib/components/ui/alert/index.js';+ import { AlertTriangleIcon, FileTextIcon } from '#lib/icons/index.js';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { queryKeys } from '#lib/query/query-keys.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { fetchAcrossEnvironments } from '#lib/utils/environments.js';+ import { shownPodmanEnvironments } from '#lib/utils/podman.js';+ import { ResourceListPageState } from '#lib/utils/resource-list-page.svelte.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ import QuadletsTable from './components/quadlets-table.svelte';++ let { data } = $props();+ const queryClient = useQueryClient();++ const pageState = new ResourceListPageState(untrack(() => data.requestOptions));+ const quadletEnvironments = $derived(shownPodmanEnvironments(data.podmanStatuses, (status) => status.quadletsSupported));+ const canInstall = $derived(hasPermission('podman:quadlets', pageState.envId) && !!data.podmanStatus?.quadletsSupported);++ const quadletsQuery = createQuery(() => {+ const queryScope = pageState.scope;+ const environments = quadletEnvironments;+ const options = pageState.requestOptions;+ return {+ queryKey: queryKeys.podman.quadlets(queryScope, options),+ queryFn: () =>+ fetchAcrossEnvironments(environments, options, (id, request, config) => podmanService.getQuadlets(id, request, config)),+ placeholderData: (previous, query) => {+ if (query?.queryKey[1] === queryScope) return previous;+ return undefined;+ },+ select: (value) => ({ envId: queryScope, value })+ };+ });++ const resourcesReady = $derived(quadletsQuery.data?.envId === pageState.scope);+ const quadlets = $derived(quadletsQuery.data?.value ?? data.quadlets);++ async function loadQuadlets(options: SearchPaginationSortRequest = pageState.requestOptions, requestedScope = pageState.scope) {+ const environments = quadletEnvironments;+ pageState.requestOptions = options;+ await queryClient.query({+ queryKey: queryKeys.podman.quadlets(requestedScope, options),+ staleTime: 0,+ queryFn: () =>+ fetchAcrossEnvironments(environments, options, (id, request, config) => podmanService.getQuadlets(id, request, config))+ });+ }++ async function refresh() {+ await handleApiResultWithCallbacks({+ result: await tryCatch(loadQuadlets()),+ message: m.common_refresh_failed({ resource: m.podman_quadlets_title() })+ });+ }++ const isRefreshing = $derived(quadletsQuery.isFetching && !quadletsQuery.isPending);++ const actionButtons: ActionButton[] = $derived.by(() => {+ const buttons: ActionButton[] = [];+ if (canInstall) {+ buttons.push({+ id: 'create',+ action: 'create',+ placement: 'primary',+ label: m.podman_quadlet_install(),+ href: '/podman/quadlets/new'+ });+ }+ buttons.push({+ id: 'refresh',+ action: 'refresh',+ placement: 'secondary',+ iconOnly: true,+ label: m.common_refresh(),+ onclick: refresh,+ loading: isRefreshing,+ disabled: quadletsQuery.isFetching+ });+ return buttons;+ });++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.podman_quadlets_total(),+ value: resourcesReady ? (quadlets.pagination?.totalItems ?? quadlets.data.length) : 0,+ icon: FileTextIcon,+ iconColor: 'text-info'+ }+ ]);+</script>++<ResourcePageLayout title={m.podman_quadlets_title()} subtitle={m.podman_quadlets_subtitle()} {actionButtons} {statCards}>+ {#snippet mainContent()}+ <div class="space-y-4">+ {#if quadletEnvironments.length === 0}+ <Alert.Root variant="warning-subtle">+ <AlertTriangleIcon class="size-4 text-warning" />+ <Alert.Title>{m.common_unavailable()}</Alert.Title>+ <Alert.Description>{m.podman_quadlets_unsupported()}</Alert.Description>+ </Alert.Root>+ {/if}++ {#if resourcesReady}+ {#key pageState.scope}+ <QuadletsTable+ bind:quadlets={+ () => quadlets,+ (value) => queryClient.setQueryData(queryKeys.podman.quadlets(pageState.scope, pageState.requestOptions), value)+ }+ bind:requestOptions={pageState.requestOptions}+ podmanStatuses={data.podmanStatuses}+ onRefreshData={loadQuadlets}+ />+ {/key}+ {/if}+ </div>+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/podman/quadlets/+page.ts b/frontend/src/routes/(app)/podman/quadlets/+page.tsnew file mode 100644index 000000000..5d619d7a6--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/+page.ts@@ -0,0 +1,57 @@+import { redirect } from '@sveltejs/kit';++import { m } from '#lib/paraglide/messages.js';+import { queryKeys } from '#lib/query/query-keys.js';+import { podmanService } from '#lib/services/podman-service.js';+import { environmentStore } from '#lib/stores/environment.store.svelte.js';+import type { SearchPaginationSortRequest } from '#lib/types/shared.js';+import { throwPageLoadError } from '#lib/utils/api.js';+import { environmentHref, fetchAcrossEnvironments, resolveDetailEnvironmentId } from '#lib/utils/environments.js';+import { shownPodmanEnvironments } from '#lib/utils/podman.js';+import { resolveInitialTableRequest } from '#lib/utils/tables.js';+import { tryCatch } from '#lib/utils/try-catch.js';++import type { PageLoad } from './$types';++export const load: PageLoad = async ({ url, parent }) => {+ const { queryClient, podmanStatuses } = await parent();+ const environments = shownPodmanEnvironments(podmanStatuses, (status) => status.quadletsSupported);+ const scope = environmentStore.shownKey;++ const unit = url.searchParams.get('unit');+ if (unit) {+ const envId = await resolveDetailEnvironmentId(url);+ const match = await tryCatch(podmanService.getQuadlets(envId, { search: unit, pagination: { page: 1, limit: -1 } }));+ const quadlet = match.data?.data.find((item) => item.unitName === unit);+ if (quadlet) redirect(307, environmentHref(`/podman/quadlets/${encodeURIComponent(quadlet.name)}`, envId));+ }++ const requestOptions = resolveInitialTableRequest('arcane-podman-quadlets-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'name',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ const quadlets = await tryCatch(+ queryClient.query({+ queryKey: queryKeys.podman.quadlets(scope, requestOptions),+ queryFn: () =>+ fetchAcrossEnvironments(environments, requestOptions, (id, request, config) =>+ podmanService.getQuadlets(id, request, config)+ )+ })+ );+ if (quadlets.error !== null) {+ throwPageLoadError(quadlets.error, m.common_load_failed({ resource: m.podman_quadlets_title() }));+ }++ return {+ quadlets: quadlets.data,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/podman/quadlets/[name]/+error.svelte b/frontend/src/routes/(app)/podman/quadlets/[name]/+error.sveltenew file mode 100644index 000000000..852f7b82a--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/[name]/+error.svelte@@ -0,0 +1,10 @@+<script lang="ts">+ import ResourceErrorPage from '#lib/components/resource-error-page.svelte';+ import { m } from '#lib/paraglide/messages.js';+</script>++<ResourceErrorPage+ fallbackTitle={m.error_generic()}+ backLabel={m.common_back_to({ resource: m.podman_quadlets_title() })}+ backHref="/podman/quadlets"+/>diff --git a/frontend/src/routes/(app)/podman/quadlets/[name]/+page.svelte b/frontend/src/routes/(app)/podman/quadlets/[name]/+page.sveltenew file mode 100644index 000000000..094b21ed7--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/[name]/+page.svelte@@ -0,0 +1,248 @@+<script lang="ts">+ import { goto } from '$app/navigation';+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';+ import { toast } from 'svelte-sonner';++ import type { ActionButton } from '#lib/components/action-button-group/types.js';+ import CodePanel from '#lib/components/code-panel.svelte';+ import { DetailSection, KeyValueCard, KeyValueGrid } from '#lib/components/resource-detail/index.js';+ import EmptyState from '#lib/components/states/empty-state.svelte';+ import * as Alert from '#lib/components/ui/alert/index.js';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import * as Card from '#lib/components/ui/card/index.js';+ import { AlertTriangleIcon, BoxIcon, ContainersIcon, InfoIcon } from '#lib/icons/index.js';+ import { ResourceDetailLayout } from '#lib/layouts/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { queryKeys } from '#lib/query/query-keys.js';+ import { podmanService, type PodmanQuadletAction } from '#lib/services/podman-service.js';+ import type { PodmanQuadletFile } from '#lib/types/podman.js';+ import { extractApiErrorMessage, handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { environmentHref } from '#lib/utils/environments.js';+ import { podmanStateVariant } from '#lib/utils/podman.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ import ContainerLogsPanel from '../../../containers/components/container-logs-panel.svelte';+ import QuadletExtraFiles from '../components/quadlet-extra-files.svelte';+ import { confirmRemoveQuadlet, quadletActionLabels, runQuadletAction } from '../quadlet-actions';++ let { data } = $props();++ const queryClient = useQueryClient();+ const envId = $derived(data.envId);+ const status = $derived(data.podmanStatuses[data.envId]);+ const systemdAvailable = $derived(status?.systemdAvailable === true);++ const quadletQuery = createQuery(() => ({+ queryKey: queryKeys.podman.quadlet(envId, data.quadlet.name),+ queryFn: () => podmanService.getQuadlet(data.quadlet.name, envId),+ initialData: data.quadlet,+ refetchInterval: 10000,+ retry: false+ }));+ const quadlet = $derived(quadletQuery.data ?? data.quadlet);+ const containers = $derived(quadlet.containers ?? []);+ const podNames = $derived([+ ...new Set(containers.map((container) => container.podName).filter((name): name is string => !!name))+ ]);++ const canEdit = $derived(hasPermission('podman:quadlets', envId));+ const canLifecycle = $derived(hasPermission('podman:quadlets:lifecycle', envId) && !quadlet.template);++ let content = $derived(data.file.content);+ let extraFiles = $state<PodmanQuadletFile[]>([]);+ let saving = $state(false);+ let pendingAction = $state<PodmanQuadletAction | null>(null);+ let selectedContainerId = $state('');+ let autoScrollLogs = $state(true);+ const selectedContainer = $derived(containers.find((container) => container.id === selectedContainerId) ?? containers[0]);++ async function refresh() {+ await queryClient.invalidateQueries({ queryKey: queryKeys.podman.quadlet(envId, quadlet.name) });+ }++ async function handleSave() {+ const files = extraFiles.filter((file) => file.name.trim());+ saving = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(+ podmanService.updateQuadlet(quadlet.name, { content, extraFiles: files.length > 0 ? files : undefined }, envId)+ ),+ message: m.common_update_failed({ resource: quadlet.name }),+ setLoadingState: (value) => (saving = value),+ onSuccess: async (report) => {+ const errors = Object.entries(report.quadletErrors ?? {});+ if (errors.length > 0) {+ toast.error(m.common_update_failed({ resource: quadlet.name }), {+ description: errors.map(([name, error]) => `${name}: ${error}`).join('\n')+ });+ return;+ }+ toast.success(m.common_update_success({ resource: quadlet.name }));+ extraFiles = [];+ await refresh();+ }+ });+ }++ function lifecycleButton(action: PodmanQuadletAction, placement: 'primary' | 'secondary'): ActionButton {+ return {+ id: action,+ action,+ group: 'lifecycle',+ placement,+ label: quadletActionLabels[action](),+ loading: pendingAction === action,+ disabled: pendingAction !== null || !systemdAvailable,+ disabledReason: systemdAvailable ? undefined : status?.systemdReason,+ onclick: () =>+ runQuadletAction(quadlet.name, action, envId, refresh, (loading) => (pendingAction = loading ? action : null))+ };+ }++ const isActive = $derived(podmanStateVariant(quadlet.unitStatus?.activeState ?? quadlet.status) === 'green');++ const actions: ActionButton[] = $derived([+ ...(canLifecycle+ ? [+ isActive ? lifecycleButton('stop', 'primary') : lifecycleButton('start', 'primary'),+ lifecycleButton('restart', 'secondary')+ ]+ : []),+ ...(canEdit+ ? [+ {+ id: 'save',+ action: 'save' as const,+ placement: 'secondary' as const,+ label: m.common_save(),+ loading: saving,+ disabled: saving,+ onclick: handleSave+ },+ {+ id: 'remove',+ action: 'remove' as const,+ group: 'danger' as const,+ destructive: true,+ placement: 'menu' as const,+ label: m.common_remove(),+ onclick: () => confirmRemoveQuadlet(quadlet.name, envId, () => goto('/podman/quadlets'))+ }+ ]+ : [])+ ]);+</script>++<ResourceDetailLayout+ backUrl="/podman/quadlets"+ backLabel={m.podman_quadlets_title()}+ title={quadlet.name}+ subtitle={quadlet.path}+ {actions}+>+ {#snippet badges()}+ <Badge variant={podmanStateVariant(quadlet.status)} minWidth="20">{quadlet.status}</Badge>+ <Badge variant="gray" size="sm">.{quadlet.type}</Badge>+ {#if quadlet.template}+ <Badge variant="gray" size="sm">{m.podman_quadlet_template()}</Badge>+ {/if}+ {#if quadlet.app}+ <Badge variant="blue" size="sm">{quadlet.app}</Badge>+ {/if}+ {#each podNames as podName (podName)}+ <Badge variant="purple" size="sm" href={environmentHref(`/podman/pods/${encodeURIComponent(podName)}`, envId)}+ >{podName}</Badge+ >+ {/each}+ {/snippet}++ {#if quadletQuery.isError}+ <Alert.Root variant="destructive">+ <AlertTriangleIcon class="size-4" />+ <Alert.Title>{m.podman_updates_paused()}</Alert.Title>+ <Alert.Description>{extractApiErrorMessage(quadletQuery.error)}</Alert.Description>+ </Alert.Root>+ {/if}++ {#if canLifecycle && !systemdAvailable && status?.systemdReason}+ <p class="text-sm text-muted-foreground">{status.systemdReason}</p>+ {/if}++ <DetailSection title={m.podman_unit()} icon={InfoIcon}>+ <KeyValueGrid>+ <KeyValueCard label={m.podman_unit()}>{quadlet.unitName || '-'}</KeyValueCard>+ {#if quadlet.unitStatus}+ <KeyValueCard label={m.podman_unit_load_state()}>{quadlet.unitStatus.loadState}</KeyValueCard>+ <KeyValueCard label={m.podman_unit_active_state()}>+ {quadlet.unitStatus.activeState} ({quadlet.unitStatus.subState})+ </KeyValueCard>+ {#if quadlet.unitStatus.description}+ <KeyValueCard label={m.common_description()}>{quadlet.unitStatus.description}</KeyValueCard>+ {/if}+ {/if}+ </KeyValueGrid>+ </DetailSection>++ <CodePanel title={quadlet.name} language="systemd" validationMode="none" bind:value={content} readOnly={!canEdit} autoHeight />++ {#if canEdit}+ <Card.Root>+ <Card.Header>+ <Card.Title>{m.podman_quadlet_extra_files()}</Card.Title>+ <Card.Description>{m.podman_quadlet_update_files_description()}</Card.Description>+ </Card.Header>+ <Card.Content>+ <QuadletExtraFiles bind:files={extraFiles} disabled={saving} />+ </Card.Content>+ </Card.Root>+ {/if}++ <DetailSection title={m.containers()} icon={ContainersIcon}>+ {#if containers.length === 0}+ <EmptyState icon={ContainersIcon} title={m.podman_quadlet_no_containers()} variant="plain" />+ {:else}+ <div class="divide-y rounded-lg border">+ {#each containers as container (container.id)}+ <div class="flex items-center justify-between gap-3 p-3">+ <button+ type="button"+ class="min-w-0 truncate text-left font-medium hover:underline"+ onclick={() => (selectedContainerId = container.id)}+ >+ {container.names[0] ?? container.id.slice(0, 12)}+ </button>+ <div class="flex items-center gap-2">+ {#if container.podName}+ <Badge+ variant="purple"+ size="sm"+ href={environmentHref(`/podman/pods/${encodeURIComponent(container.podName)}`, envId)}+ >+ <BoxIcon class="size-3" />+ {container.podName}+ </Badge>+ {/if}+ <Badge variant={podmanStateVariant(container.state)} size="sm">{container.state}</Badge>+ <a+ class="text-xs text-muted-foreground hover:underline"+ href={environmentHref(`/containers/${container.id}`, envId)}>{m.common_inspect()}</a+ >+ </div>+ </div>+ {/each}+ </div>+ {/if}+ </DetailSection>++ {#if selectedContainer && hasPermission('containers:logs', envId)}+ {#key selectedContainer.id}+ <ContainerLogsPanel+ containerId={selectedContainer.id}+ environmentId={envId}+ isRunning={selectedContainer.state === 'running'}+ bind:autoScroll={autoScrollLogs}+ />+ {/key}+ {/if}+</ResourceDetailLayout>diff --git a/frontend/src/routes/(app)/podman/quadlets/[name]/+page.ts b/frontend/src/routes/(app)/podman/quadlets/[name]/+page.tsnew file mode 100644index 000000000..a8a719422--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/[name]/+page.ts@@ -0,0 +1,30 @@+import { m } from '#lib/paraglide/messages.js';+import { queryKeys } from '#lib/query/query-keys.js';+import { podmanService } from '#lib/services/podman-service.js';+import { throwPageLoadError } from '#lib/utils/api.js';+import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';+import { tryCatch } from '#lib/utils/try-catch.js';++import type { PageLoad } from './$types';++export const load: PageLoad = async ({ params, parent, url }) => {+ const { queryClient } = await parent();+ const envId = await resolveDetailEnvironmentId(url);+ const result = await tryCatch(+ Promise.all([+ queryClient.query({+ queryKey: queryKeys.podman.quadlet(envId, params.name),+ queryFn: () => podmanService.getQuadlet(params.name, envId)+ }),+ queryClient.query({+ queryKey: queryKeys.podman.quadletFile(envId, params.name),+ queryFn: () => podmanService.getQuadletFile(params.name, envId)+ })+ ])+ );+ if (result.error !== null) {+ throwPageLoadError(result.error, m.common_load_failed({ resource: m.podman_quadlet() }));+ }+ const [quadlet, file] = result.data;+ return { envId, quadlet, file };+};diff --git a/frontend/src/routes/(app)/podman/quadlets/components/quadlet-extra-files.svelte b/frontend/src/routes/(app)/podman/quadlets/components/quadlet-extra-files.sveltenew file mode 100644index 000000000..10dc75dcf--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/components/quadlet-extra-files.svelte@@ -0,0 +1,32 @@+<script lang="ts">+ import CodePanel from '#lib/components/code-panel.svelte';+ import RowListEditor from '#lib/components/form/row-list-editor.svelte';+ import { Input } from '#lib/components/ui/input/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import type { PodmanQuadletFile } from '#lib/types/podman.js';+ import { workspaceFileLanguage } from '#lib/utils/workspace-files.js';++ let {+ files = $bindable([]),+ disabled = false+ }: {+ files?: PodmanQuadletFile[];+ disabled?: boolean;+ } = $props();+</script>++<RowListEditor bind:rows={files} createRow={() => ({ name: '', content: '' })} {disabled} addLabel={m.podman_quadlet_add_file()}>+ {#snippet children(file)}+ <div class="min-w-0 flex-1 space-y-2">+ <Input placeholder={m.podman_quadlet_file_name_placeholder()} bind:value={file.name} {disabled} />+ <CodePanel+ title={file.name || m.podman_quadlet_extra_file()}+ language={workspaceFileLanguage(file.name)}+ validationMode="none"+ bind:value={file.content}+ readOnly={disabled}+ autoHeight+ />+ </div>+ {/snippet}+</RowListEditor>diff --git a/frontend/src/routes/(app)/podman/quadlets/components/quadlets-table.svelte b/frontend/src/routes/(app)/podman/quadlets/components/quadlets-table.sveltenew file mode 100644index 000000000..49ddc9a85--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/components/quadlets-table.svelte@@ -0,0 +1,187 @@+<script lang="ts">+ import { goto } from '$app/navigation';++ import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';+ import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table/index.js';+ import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';+ import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';+ import { FileTextIcon, InspectIcon, TrashIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import userStore from '#lib/stores/user-store.svelte.js';+ import type { PodmanQuadletDetail, PodmanStatus } from '#lib/types/podman.js';+ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { environmentHref, hasShownPermission, type EnvironmentPage, type EnvironmentRow } from '#lib/utils/environments.js';+ import { podmanStateVariant } from '#lib/utils/podman.js';++ import { confirmRemoveQuadlet, quadletActionLabels, quadletActions, runQuadletAction } from '../quadlet-actions';++ type QuadletRow = EnvironmentRow<PodmanQuadletDetail> & { id: string };++ let {+ quadlets = $bindable(),+ requestOptions = $bindable(),+ podmanStatuses,+ onRefreshData+ }: {+ quadlets: EnvironmentPage<Paginated<PodmanQuadletDetail>>;+ requestOptions: SearchPaginationSortRequest;+ podmanStatuses: Record<string, PodmanStatus>;+ onRefreshData: (options: SearchPaginationSortRequest) => Promise<void>;+ } = $props();++ const canManageQuadlets = $derived.by(() => {+ userStore.current;+ return hasShownPermission('podman:quadlets');+ });+ const canRunLifecycle = $derived.by(() => {+ userStore.current;+ return hasShownPermission('podman:quadlets:lifecycle');+ });++ let mobileFieldVisibility = $state<Record<string, boolean>>({});++ function withRowIds(page: EnvironmentPage<Paginated<PodmanQuadletDetail>>) {+ return { ...page, data: page.data.map((quadlet): QuadletRow => ({ ...quadlet, id: quadlet.name })) };+ }++ const rows = $derived(withRowIds(quadlets));++ const quadletHref = (quadlet: QuadletRow) =>+ environmentHref(`/podman/quadlets/${encodeURIComponent(quadlet.name)}`, quadlet.environmentId);++ const columns = $derived([+ ...environmentColumns<QuadletRow>(),+ { accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },+ { accessorKey: 'type', title: m.common_type(), sortable: true, cell: TypeCell },+ { accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },+ { accessorKey: 'unitName', title: m.podman_unit(), sortable: true, cell: UnitCell },+ { accessorKey: 'app', title: m.podman_quadlet_app(), sortable: true, cell: AppCell }+ ] satisfies ColumnSpec<QuadletRow>[]);++ const mobileFields = [+ { id: 'status', label: m.common_status(), defaultVisible: true },+ { id: 'type', label: m.common_type(), defaultVisible: true },+ { id: 'unitName', label: m.podman_unit(), defaultVisible: true },+ { id: 'app', label: m.podman_quadlet_app(), defaultVisible: false }+ ];+</script>++{#snippet NameCell({ item }: { item: QuadletRow })}+ <div class="flex items-center gap-2">+ <a class="font-medium hover:underline" href={quadletHref(item)}>{item.name}</a>+ {#if item.template}+ <Badge variant="gray" size="sm">{m.podman_quadlet_template()}</Badge>+ {/if}+ </div>+{/snippet}++{#snippet TypeCell({ item }: { item: QuadletRow })}+ <Badge variant="gray" size="sm">.{item.type}</Badge>+{/snippet}++{#snippet StatusCell({ item }: { item: QuadletRow })}+ <Badge variant={podmanStateVariant(item.status)} minWidth="20">{item.status}</Badge>+{/snippet}++{#snippet UnitCell({ item }: { item: QuadletRow })}+ <span class="font-mono text-xs text-muted-foreground">{item.unitName || '-'}</span>+{/snippet}++{#snippet AppCell({ item }: { item: QuadletRow })}+ {item.app || '-'}+{/snippet}++{#snippet QuadletMobileCard({ item, mobileFieldVisibility }: { item: QuadletRow; mobileFieldVisibility: MobileFieldVisibility })}+ <UniversalMobileCard+ {item}+ icon={{ component: FileTextIcon, variant: podmanStateVariant(item.status) === 'green' ? 'emerald' : 'gray' }}+ title={(item: QuadletRow) => item.name}+ badges={(mobileFieldVisibility['status'] ?? true)+ ? [(item: QuadletRow) => ({ variant: podmanStateVariant(item.status), text: item.status })]+ : []}+ fields={[+ {+ label: m.common_type(),+ getValue: (item: QuadletRow) => `.${item.type}`,+ icon: FileTextIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['type'] ?? true+ },+ {+ label: m.podman_unit(),+ getValue: (item: QuadletRow) => item.unitName || '-',+ icon: FileTextIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['unitName'] ?? true+ },+ {+ label: m.podman_quadlet_app(),+ getValue: (item: QuadletRow) => item.app || '-',+ icon: FileTextIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['app'] ?? false+ }+ ]}+ rowActions={RowActions}+ onclick={() => goto(quadletHref(item))}+ />+{/snippet}++{#snippet RowActions({ item }: { item: QuadletRow })}+ <RowActionsMenu>+ <DropdownMenu.Item onclick={() => goto(quadletHref(item))}>+ <InspectIcon class="size-4" />+ {m.common_inspect()}+ </DropdownMenu.Item>+ {#if canRunLifecycle && hasPermission('podman:quadlets:lifecycle', item.environmentId) && !item.template}+ {@const status = podmanStatuses[item.environmentId]}+ <DropdownMenu.Separator />+ {#each quadletActions as action (action)}+ <DropdownMenu.Item+ disabled={!status?.systemdAvailable}+ title={status?.systemdAvailable ? undefined : status?.systemdReason}+ onclick={() =>+ runQuadletAction(item.name, action, item.environmentId, async () => {+ await onRefreshData(requestOptions);+ })}+ >+ {quadletActionLabels[action]()}+ </DropdownMenu.Item>+ {/each}+ {/if}+ {#if canManageQuadlets && hasPermission('podman:quadlets', item.environmentId)}+ <DropdownMenu.Separator />+ <DropdownMenu.Item+ variant="destructive"+ onclick={() =>+ confirmRemoveQuadlet(item.name, item.environmentId, async () => {+ await onRefreshData(requestOptions);+ })}+ >+ <TrashIcon class="size-4" />+ {m.common_remove()}+ </DropdownMenu.Item>+ {/if}+ </RowActionsMenu>+{/snippet}++<ArcaneTable+ persistKey="arcane-podman-quadlets-table"+ items={rows}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => {+ requestOptions = options;+ await onRefreshData(options);+ return withRowIds(quadlets);+ }}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={QuadletMobileCard}+/>diff --git a/frontend/src/routes/(app)/podman/quadlets/new/+page.svelte b/frontend/src/routes/(app)/podman/quadlets/new/+page.sveltenew file mode 100644index 000000000..cfdcb56c2--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/new/+page.svelte@@ -0,0 +1,174 @@+<script lang="ts">+ import { goto } from '$app/navigation';+ import { toast } from 'svelte-sonner';++ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import CodePanel from '#lib/components/code-panel.svelte';+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';+ import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';+ import EmptyState from '#lib/components/states/empty-state.svelte';+ import * as Card from '#lib/components/ui/card/index.js';+ import { ArrowLeftIcon, FileTextIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import { PODMAN_QUADLET_TYPES, type PodmanQuadletFile, type PodmanQuadletType } from '#lib/types/podman.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ import QuadletExtraFiles from '../components/quadlet-extra-files.svelte';++ let { data } = $props();++ const status = $derived(data.podmanStatus);+ const appsSupported = $derived(status?.quadletAppsSupported === true);++ const templates: Record<PodmanQuadletType, string> = {+ container: '[Unit]\nDescription=\n\n[Container]\nImage=\n\n[Install]\nWantedBy=default.target\n',+ pod: '[Pod]\nPodName=\n',+ kube: '[Kube]\nYaml=\n\n[Install]\nWantedBy=default.target\n',+ network: '[Network]\n',+ volume: '[Volume]\n',+ image: '[Image]\nImage=\n',+ build: '[Build]\nImageTag=\nSetWorkingDirectory=unit\n',+ artifact: '[Artifact]\nArtifact=\n'+ };++ let baseName = $state('');+ let quadletType = $state<PodmanQuadletType>('container');+ let content = $state(templates.container);+ let kubeYaml = $state('');+ let app = $state('');+ let extraFiles = $state<PodmanQuadletFile[]>([]);+ let submitting = $state(false);++ const fileName = $derived(`${baseName.trim()}.${quadletType}`);+ const kubeFileName = $derived(`${baseName.trim()}.yaml`);++ function handleTypeChange(value: string) {+ const next = value as PodmanQuadletType;+ if (content === templates[quadletType]) content = templates[next];+ quadletType = next;+ }++ async function handleSubmit() {+ if (!baseName.trim()) {+ toast.error(m.common_field_required({ field: m.common_name() }));+ return;+ }+ const files = [+ ...(quadletType === 'kube' && kubeYaml.trim() ? [{ name: kubeFileName, content: kubeYaml }] : []),+ ...(appsSupported ? extraFiles.filter((file) => file.name.trim()) : [])+ ];+ submitting = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(+ podmanService.installQuadlet({+ name: fileName,+ content,+ extraFiles: files.length > 0 ? files : undefined,+ app: appsSupported && app.trim() ? app.trim() : undefined+ })+ ),+ message: m.podman_quadlet_install_failed({ name: fileName }),+ setLoadingState: (value) => (submitting = value),+ onSuccess: async (report) => {+ const errors = Object.entries(report.quadletErrors ?? {});+ if (errors.length > 0) {+ toast.error(m.podman_quadlet_install_failed({ name: fileName }), {+ description: errors.map(([name, error]) => `${name}: ${error}`).join('\n')+ });+ return;+ }+ toast.success(m.podman_quadlet_install_success({ name: fileName }));+ await goto(`/podman/quadlets/${encodeURIComponent(fileName)}`);+ }+ });+ }+</script>++<div class="flex min-h-0 flex-col bg-background">+ <div class="sticky top-0 z-10 border-b bg-background">+ <div class="mx-auto flex h-16 w-full max-w-full items-center gap-4 px-6">+ <ArcaneButton+ action="base"+ tone="ghost"+ size="sm"+ href="/podman/quadlets"+ class="gap-2 bg-transparent"+ icon={ArrowLeftIcon}+ customLabel={m.common_back()}+ />+ <div class="hidden h-4 w-px bg-border sm:block"></div>+ <h1 class="flex-1 text-base font-semibold">{m.podman_quadlet_install()}</h1>+ {#if status?.quadletsSupported}+ <ArcaneButton+ action="create"+ customLabel={m.podman_quadlet_install()}+ onclick={handleSubmit}+ loading={submitting}+ disabled={submitting}+ />+ {/if}+ </div>+ </div>++ <div class="mx-auto w-full max-w-full space-y-6 px-6 py-6">+ {#if !status?.quadletsSupported}+ <EmptyState icon={FileTextIcon} title={m.common_unavailable()} description={m.podman_quadlets_unsupported()} />+ {:else}+ <Card.Root>+ <Card.Header>+ <Card.Title>{m.common_details_title({ resource: m.podman_quadlet() })}</Card.Title>+ <Card.Description>{m.podman_quadlet_install_description()}</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="grid gap-4 md:grid-cols-2">+ <TextInputWithLabel+ id="quadlet-name"+ label={m.common_name()}+ helpText={fileName}+ bind:value={baseName}+ required+ disabled={submitting}+ />+ <SelectWithLabel+ id="quadlet-type"+ label={m.common_type()}+ value={quadletType}+ options={PODMAN_QUADLET_TYPES.map((type) => ({ label: `.${type}`, value: type }))}+ onValueChange={handleTypeChange}+ disabled={submitting}+ />+ {#if appsSupported}+ <TextInputWithLabel+ id="quadlet-app"+ label={m.podman_quadlet_app()}+ description={m.podman_quadlet_app_description()}+ bind:value={app}+ disabled={submitting}+ />+ {/if}+ </div>+ </Card.Content>+ </Card.Root>++ <CodePanel title={fileName} language="systemd" validationMode="none" bind:value={content} autoHeight />++ {#if quadletType === 'kube'}+ <CodePanel title={kubeFileName} language="yaml" validationMode="none" bind:value={kubeYaml} autoHeight />+ {/if}++ {#if appsSupported}+ <Card.Root>+ <Card.Header>+ <Card.Title>{m.podman_quadlet_extra_files()}</Card.Title>+ <Card.Description>{m.podman_quadlet_extra_files_description()}</Card.Description>+ </Card.Header>+ <Card.Content>+ <QuadletExtraFiles bind:files={extraFiles} disabled={submitting} />+ </Card.Content>+ </Card.Root>+ {/if}+ {/if}+ </div>+</div>diff --git a/frontend/src/routes/(app)/podman/quadlets/quadlet-actions.ts b/frontend/src/routes/(app)/podman/quadlets/quadlet-actions.tsnew file mode 100644index 000000000..ec03dc13c--- /dev/null+++ b/frontend/src/routes/(app)/podman/quadlets/quadlet-actions.ts@@ -0,0 +1,57 @@+import { toast } from 'svelte-sonner';++import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';+import { m } from '#lib/paraglide/messages.js';+import { podmanService, type PodmanQuadletAction } from '#lib/services/podman-service.js';+import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+import { tryCatch } from '#lib/utils/try-catch.js';++export const quadletActionLabels: Record<PodmanQuadletAction, () => string> = {+ start: m.common_start,+ stop: m.common_stop,+ restart: m.common_restart+};++export const quadletActions: PodmanQuadletAction[] = ['start', 'stop', 'restart'];++export async function runQuadletAction(+ name: string,+ action: PodmanQuadletAction,+ environmentId: string,+ onDone: () => void | Promise<void>,+ setLoading: (loading: boolean) => void = () => {}+) {+ setLoading(true);+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.quadletAction(name, action, environmentId)),+ message: m.common_action_failed_with_type({ action: quadletActionLabels[action](), type: name }),+ setLoadingState: setLoading,+ onSuccess: async (unit) => {+ toast.success(m.podman_action_success({ action: quadletActionLabels[action](), name }), {+ description: `${unit.name}: ${unit.activeState} (${unit.subState})`+ });+ await onDone();+ }+ });+}++export function confirmRemoveQuadlet(name: string, environmentId: string, onDone: () => void | Promise<void>) {+ openConfirmDialog({+ title: m.common_remove_title({ resource: m.podman_quadlet() }),+ message: m.common_remove_confirm({ resource: name }),+ confirm: {+ label: m.common_remove(),+ destructive: true,+ action: async () => {+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.removeQuadlet(name, environmentId)),+ message: m.common_remove_failed({ resource: name }),+ onSuccess: async () => {+ toast.success(m.common_remove_success({ resource: name }));+ await onDone();+ }+ });+ }+ }+ });+}diff --git a/frontend/src/routes/(app)/podman/secrets/+page.svelte b/frontend/src/routes/(app)/podman/secrets/+page.sveltenew file mode 100644index 000000000..f402a456e--- /dev/null+++ b/frontend/src/routes/(app)/podman/secrets/+page.svelte@@ -0,0 +1,158 @@+<script lang="ts">+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';+ import { untrack } from 'svelte';++ import PodmanSecretFormSheet from '#lib/components/sheets/podman-secret-form-sheet.svelte';+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';+ import { LockIcon } from '#lib/icons/index.js';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { queryKeys } from '#lib/query/query-keys.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import type { PodmanSecret } from '#lib/types/podman.js';+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { fetchAcrossEnvironments, type EnvironmentRow } from '#lib/utils/environments.js';+ import { shownPodmanEnvironments } from '#lib/utils/podman.js';+ import { ResourceListPageState } from '#lib/utils/resource-list-page.svelte.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ import SecretsTable from './components/secrets-table.svelte';++ let { data } = $props();+ const queryClient = useQueryClient();++ const pageState = new ResourceListPageState(untrack(() => data.requestOptions));+ const podmanEnvironments = $derived(shownPodmanEnvironments(data.podmanStatuses));+ const canCreate = $derived(podmanEnvironments.some((env) => hasPermission('podman:secrets', env.id)));+ let isSheetOpen = $state(false);+ let sheetSession = $state(0);+ let secretToEdit = $state<EnvironmentRow<PodmanSecret> | null>(null);++ const secretsQuery = createQuery(() => {+ const queryScope = pageState.scope;+ const environments = podmanEnvironments;+ const options = pageState.requestOptions;+ return {+ queryKey: queryKeys.podman.secrets(queryScope, options),+ queryFn: () =>+ fetchAcrossEnvironments(environments, options, (id, request, config) => podmanService.getSecrets(id, request, config)),+ placeholderData: (previous, query) => {+ if (query?.queryKey[1] === queryScope) return previous;+ return undefined;+ },+ select: (value) => ({ envId: queryScope, value })+ };+ });++ const resourcesReady = $derived(secretsQuery.data?.envId === pageState.scope);+ const secrets = $derived(secretsQuery.data?.value ?? data.secrets);++ async function loadSecrets(options: SearchPaginationSortRequest = pageState.requestOptions, requestedScope = pageState.scope) {+ const environments = podmanEnvironments;+ pageState.requestOptions = options;+ await queryClient.query({+ queryKey: queryKeys.podman.secrets(requestedScope, options),+ staleTime: 0,+ queryFn: () =>+ fetchAcrossEnvironments(environments, options, (id, request, config) => podmanService.getSecrets(id, request, config))+ });+ }++ async function refresh() {+ await handleApiResultWithCallbacks({+ result: await tryCatch(loadSecrets()),+ message: m.common_refresh_failed({ resource: m.podman_secrets_title() })+ });+ }++ function openSheet(secret: EnvironmentRow<PodmanSecret> | null) {+ secretToEdit = secret;+ sheetSession += 1;+ isSheetOpen = true;+ }++ async function openEditSheet(secret: EnvironmentRow<PodmanSecret>) {+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.getSecret(secret.spec.name, secret.environmentId)),+ message: m.common_load_failed({ resource: `${m.swarm_secret()} "${secret.spec.name}"` }),+ onSuccess: (latest) => openSheet({ ...secret, ...latest })+ });+ }++ useEnvironmentRefresh(() => {+ isSheetOpen = false;+ });++ async function handleSaved() {+ isSheetOpen = false;+ await refresh();+ }++ const isRefreshing = $derived(secretsQuery.isFetching && !secretsQuery.isPending);++ const actionButtons: ActionButton[] = $derived.by(() => {+ const buttons: ActionButton[] = [];+ if (canCreate) {+ buttons.push({+ id: 'create',+ action: 'create',+ placement: 'primary',+ label: m.create_secret(),+ onclick: () => openSheet(null)+ });+ }+ buttons.push({+ id: 'refresh',+ action: 'refresh',+ placement: 'secondary',+ iconOnly: true,+ label: m.common_refresh(),+ onclick: refresh,+ loading: isRefreshing,+ disabled: secretsQuery.isFetching+ });+ return buttons;+ });++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.podman_secrets_title(),+ value: resourcesReady ? (secrets.pagination?.totalItems ?? secrets.data.length) : 0,+ icon: LockIcon,+ iconColor: 'text-info'+ }+ ]);+</script>++<ResourcePageLayout title={m.podman_secrets_title()} subtitle={m.podman_secrets_subtitle()} {actionButtons} {statCards}>+ {#snippet mainContent()}+ {#if resourcesReady}+ {#key pageState.scope}+ <SecretsTable+ bind:secrets={+ () => secrets,+ (value) => queryClient.setQueryData(queryKeys.podman.secrets(pageState.scope, pageState.requestOptions), value)+ }+ bind:requestOptions={pageState.requestOptions}+ onRefreshData={loadSecrets}+ onEdit={openEditSheet}+ />+ {/key}+ {/if}+ {/snippet}++ {#snippet additionalContent()}+ {#if sheetSession > 0}+ {#key sheetSession}+ <PodmanSecretFormSheet+ bind:open={isSheetOpen}+ environments={podmanEnvironments}+ existing={secretToEdit}+ onSaved={handleSaved}+ />+ {/key}+ {/if}+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/podman/secrets/+page.ts b/frontend/src/routes/(app)/podman/secrets/+page.tsnew file mode 100644index 000000000..9102141c5--- /dev/null+++ b/frontend/src/routes/(app)/podman/secrets/+page.ts@@ -0,0 +1,47 @@+import { m } from '#lib/paraglide/messages.js';+import { queryKeys } from '#lib/query/query-keys.js';+import { podmanService } from '#lib/services/podman-service.js';+import { environmentStore } from '#lib/stores/environment.store.svelte.js';+import type { SearchPaginationSortRequest } from '#lib/types/shared.js';+import { throwPageLoadError } from '#lib/utils/api.js';+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';+import { shownPodmanEnvironments } from '#lib/utils/podman.js';+import { resolveInitialTableRequest } from '#lib/utils/tables.js';+import { tryCatch } from '#lib/utils/try-catch.js';++import type { PageLoad } from './$types';++export const load: PageLoad = async ({ parent }) => {+ const { queryClient, podmanStatuses } = await parent();+ const environments = shownPodmanEnvironments(podmanStatuses);+ const scope = environmentStore.shownKey;++ const requestOptions = resolveInitialTableRequest('arcane-podman-secrets-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'name',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ const secrets = await tryCatch(+ queryClient.query({+ queryKey: queryKeys.podman.secrets(scope, requestOptions),+ queryFn: () =>+ fetchAcrossEnvironments(environments, requestOptions, (id, request, config) =>+ podmanService.getSecrets(id, request, config)+ )+ })+ );+ if (secrets.error !== null) {+ throwPageLoadError(secrets.error, m.common_load_failed({ resource: m.podman_secrets_title() }));+ }++ return {+ secrets: secrets.data,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/podman/secrets/components/secrets-table.svelte b/frontend/src/routes/(app)/podman/secrets/components/secrets-table.sveltenew file mode 100644index 000000000..cf27d7228--- /dev/null+++ b/frontend/src/routes/(app)/podman/secrets/components/secrets-table.svelte@@ -0,0 +1,157 @@+<script lang="ts">+ import { toast } from 'svelte-sonner';++ import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';+ import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table/index.js';+ import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';+ import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';+ import { LabelBadges } from '#lib/components/badges/index.js';+ import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';+ import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';+ import { CalendarIcon, EditIcon, LockIcon, TrashIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { podmanService } from '#lib/services/podman-service.js';+ import userStore from '#lib/stores/user-store.svelte.js';+ import type { PodmanSecret } from '#lib/types/podman.js';+ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';+ import { hasPermission } from '#lib/utils/auth.js';+ import { hasShownPermission, type EnvironmentPage, type EnvironmentRow } from '#lib/utils/environments.js';+ import { formatRelativeTime } from '#lib/utils/formatting.js';+ import { tryCatch } from '#lib/utils/try-catch.js';++ type SecretRow = EnvironmentRow<PodmanSecret>;++ let {+ secrets = $bindable(),+ requestOptions = $bindable(),+ onRefreshData,+ onEdit+ }: {+ secrets: EnvironmentPage<Paginated<PodmanSecret>>;+ requestOptions: SearchPaginationSortRequest;+ onRefreshData: (options: SearchPaginationSortRequest) => Promise<void>;+ onEdit: (secret: SecretRow) => void;+ } = $props();++ let isDeleting = $state(false);+ let mobileFieldVisibility = $state<Record<string, boolean>>({});++ const canManageSecrets = $derived.by(() => {+ userStore.current;+ return hasShownPermission('podman:secrets');+ });++ function handleDelete(secret: SecretRow) {+ const name = secret.spec.name;+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_secret() }),+ message: m.swarm_secrets_delete_confirm({ name }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ isDeleting = true;+ await handleApiResultWithCallbacks({+ result: await tryCatch(podmanService.removeSecret(name, secret.environmentId)),+ message: m.swarm_secrets_delete_failed({ name }),+ setLoadingState: (value) => (isDeleting = value),+ onSuccess: async () => {+ toast.success(m.swarm_secrets_delete_success({ name }));+ await onRefreshData(requestOptions);+ }+ });+ }+ }+ });+ }++ const columns = $derived([+ ...environmentColumns<SecretRow>(),+ { accessorKey: 'id', title: m.common_id(), hidden: true },+ { id: 'name', accessorFn: (item) => item.spec.name, title: m.common_name(), sortable: true, cell: NameCell },+ { id: 'driver', accessorFn: (item) => item.spec.driver.name, title: m.common_driver(), sortable: true },+ { id: 'labels', accessorFn: (item) => item.spec.labels, title: m.common_labels(), cell: LabelsCell },+ { accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: TimeCell },+ { accessorKey: 'updatedAt', title: m.common_updated(), sortable: true, cell: TimeCell }+ ] satisfies ColumnSpec<SecretRow>[]);++ const mobileFields = [+ { id: 'id', label: m.common_id(), defaultVisible: false },+ { id: 'driver', label: m.common_driver(), defaultVisible: true },+ { id: 'createdAt', label: m.common_created(), defaultVisible: true }+ ];+</script>++{#snippet NameCell({ item }: { item: SecretRow })}+ <button type="button" class="font-medium hover:underline" onclick={() => onEdit(item)}>{item.spec.name}</button>+{/snippet}++{#snippet LabelsCell({ item }: { item: SecretRow })}+ <LabelBadges labels={item.spec.labels} />+{/snippet}++{#snippet TimeCell({ value }: { value: unknown })}+ <span class="text-sm">{formatRelativeTime(String(value ?? '')) || m.common_unknown()}</span>+{/snippet}++{#snippet SecretMobileCard({ item, mobileFieldVisibility }: { item: SecretRow; mobileFieldVisibility: MobileFieldVisibility })}+ <UniversalMobileCard+ {item}+ icon={{ component: LockIcon, variant: 'purple' }}+ title={(item: SecretRow) => item.spec.name}+ subtitle={(item: SecretRow) => ((mobileFieldVisibility['id'] ?? false) ? item.id : null)}+ fields={[+ {+ label: m.common_driver(),+ getValue: (item: SecretRow) => item.spec.driver.name,+ icon: LockIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['driver'] ?? true+ }+ ]}+ footer={(mobileFieldVisibility['createdAt'] ?? true)+ ? {+ label: m.common_created(),+ getValue: (item: SecretRow) => formatRelativeTime(item.createdAt) || m.common_unknown(),+ icon: CalendarIcon+ }+ : undefined}+ rowActions={RowActions}+ onclick={() => onEdit(item)}+ />+{/snippet}++{#snippet RowActions({ item }: { item: SecretRow })}+ <RowActionsMenu>+ <DropdownMenu.Item onclick={() => onEdit(item)}>+ <EditIcon class="size-4" />+ {m.common_edit()}+ </DropdownMenu.Item>+ {#if canManageSecrets && hasPermission('podman:secrets', item.environmentId)}+ <DropdownMenu.Separator />+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isDeleting}>+ <TrashIcon class="size-4" />+ {m.common_delete()}+ </DropdownMenu.Item>+ {/if}+ </RowActionsMenu>+{/snippet}++<ArcaneTable+ persistKey="arcane-podman-secrets-table"+ items={secrets}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => {+ requestOptions = options;+ await onRefreshData(options);+ return secrets;+ }}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={SecretMobileCard}+/>diff --git a/frontend/src/routes/(app)/swarm/configs/+page.svelte b/frontend/src/routes/(app)/swarm/configs/+page.svelteindex 06d77e051..61ad527a9 100644--- a/frontend/src/routes/(app)/swarm/configs/+page.svelte+++ b/frontend/src/routes/(app)/swarm/configs/+page.svelte@@ -1,44 +1,8 @@<script lang="ts">import SwarmKvPage from '#lib/components/swarm/swarm-kv-page.svelte';- import { TemplateIcon } from '#lib/icons/index.js';- import { m } from '#lib/paraglide/messages.js';- import { swarmService } from '#lib/services/swarm-service.js';- import { environmentStore } from '#lib/stores/environment.store.svelte.js';- import { hasPermission } from '#lib/utils/auth.js';+ import { swarmKvResources } from '#lib/utils/swarm-kv.js';- const currentEnvId = $derived(environmentStore.selected?.id);- const canManageConfigs = $derived(hasPermission('swarm:configs', currentEnvId));-- const messages = {- pageTitle: m.swarm_configs_title(),- pageSubtitle: m.swarm_configs_subtitle(),- statTitle: m.swarm_configs_title(),- createTitle: m.create_config(),- createSubtitle: m.swarm_configs_create_subtitle(),- namePlaceholder: m.swarm_configs_name_placeholder(),- dataPlaceholder: m.swarm_configs_data_placeholder(),- createButton: m.create_config(),- listTitle: m.swarm_configs_list_title(),- listSubtitle: m.select_one_to_edit_or_remove(),- empty: m.swarm_configs_empty(),- immutableNotice: m.swarm_configs_immutable_notice(),- deleteButton: m.swarm_configs_delete_button(),- nameRequired: m.swarm_configs_name_required(),- createFailed: m.swarm_configs_create_failed(),- createSuccess: (name: string) => m.swarm_configs_create_success({ name }),- deleteConfirm: (name: string) => m.swarm_configs_delete_confirm({ name }),- deleteFailed: (name: string) => m.swarm_configs_delete_failed({ name }),- deleteSuccess: (name: string) => m.swarm_configs_delete_success({ name })- };+ let { data } = $props();</script>-<SwarmKvPage- icon={TemplateIcon}- permission="swarm:configs"- resourceLabel={m.swarm_config()}- canManage={canManageConfigs}- {messages}- loadItems={() => swarmService.getConfigs()}- createItem={(spec) => swarmService.createConfig({ spec })}- removeItem={(id) => swarmService.removeConfig(id)}-/>+<SwarmKvPage resource={swarmKvResources.configs} initialItems={data.items} initialRequestOptions={data.requestOptions} />diff --git a/frontend/src/routes/(app)/swarm/configs/+page.ts b/frontend/src/routes/(app)/swarm/configs/+page.tsnew file mode 100644index 000000000..09ce05272--- /dev/null+++ b/frontend/src/routes/(app)/swarm/configs/+page.ts@@ -0,0 +1,26 @@+import { m } from '#lib/paraglide/messages.js';+import { swarmService } from '#lib/services/swarm-service.js';+import { throwPageLoadError } from '#lib/utils/api.js';+import { swarmKvResources } from '#lib/utils/swarm-kv.js';+import { resolveInitialListPageRequest } from '#lib/utils/tables.js';+import { tryCatch } from '#lib/utils/try-catch.js';++import type { PageLoad } from './$types';++export const load: PageLoad = async () => {+ const resource = swarmKvResources.configs;+ const requestOptions = resolveInitialListPageRequest(resource.persistKey, {+ column: 'name',+ direction: 'asc'+ });++ const items = await tryCatch(swarmService.getKvItems(resource.kind, requestOptions));+ if (items.error !== null) {+ throwPageLoadError(items.error, m.common_load_failed({ resource: resource.title() }));+ }++ return {+ items: items.data,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/swarm/secrets/+page.svelte b/frontend/src/routes/(app)/swarm/secrets/+page.svelteindex cce5f84ef..f9d25bc71 100644--- a/frontend/src/routes/(app)/swarm/secrets/+page.svelte+++ b/frontend/src/routes/(app)/swarm/secrets/+page.svelte@@ -1,44 +1,8 @@<script lang="ts">import SwarmKvPage from '#lib/components/swarm/swarm-kv-page.svelte';- import { LockIcon } from '#lib/icons/index.js';- import { m } from '#lib/paraglide/messages.js';- import { swarmService } from '#lib/services/swarm-service.js';- import { environmentStore } from '#lib/stores/environment.store.svelte.js';- import { hasPermission } from '#lib/utils/auth.js';+ import { swarmKvResources } from '#lib/utils/swarm-kv.js';- const currentEnvId = $derived(environmentStore.selected?.id);- const canManageSecrets = $derived(hasPermission('swarm:secrets', currentEnvId));-- const messages = {- pageTitle: m.swarm_secrets_title(),- pageSubtitle: m.swarm_secrets_subtitle(),- statTitle: m.swarm_secrets_title(),- createTitle: m.create_secret(),- createSubtitle: m.swarm_secrets_create_subtitle(),- namePlaceholder: m.swarm_secrets_name_placeholder(),- dataPlaceholder: m.swarm_secrets_data_placeholder(),- createButton: m.create_secret(),- listTitle: m.swarm_secrets_list_title(),- listSubtitle: m.select_one_to_edit_or_remove(),- empty: m.swarm_secrets_empty(),- immutableNotice: m.swarm_secrets_immutable_notice(),- deleteButton: m.swarm_secrets_delete_button(),- nameRequired: m.swarm_secrets_name_required(),- createFailed: m.swarm_secrets_create_failed(),- createSuccess: (name: string) => m.swarm_secrets_create_success({ name }),- deleteConfirm: (name: string) => m.swarm_secrets_delete_confirm({ name }),- deleteFailed: (name: string) => m.swarm_secrets_delete_failed({ name }),- deleteSuccess: (name: string) => m.swarm_secrets_delete_success({ name })- };+ let { data } = $props();</script>-<SwarmKvPage- icon={LockIcon}- permission="swarm:secrets"- resourceLabel={m.swarm_secret()}- canManage={canManageSecrets}- {messages}- loadItems={() => swarmService.getSecrets()}- createItem={(spec) => swarmService.createSecret({ spec })}- removeItem={(id) => swarmService.removeSecret(id)}-/>+<SwarmKvPage resource={swarmKvResources.secrets} initialItems={data.items} initialRequestOptions={data.requestOptions} />diff --git a/frontend/src/routes/(app)/swarm/secrets/+page.ts b/frontend/src/routes/(app)/swarm/secrets/+page.tsnew file mode 100644index 000000000..a7c7c8fb1--- /dev/null+++ b/frontend/src/routes/(app)/swarm/secrets/+page.ts@@ -0,0 +1,26 @@+import { m } from '#lib/paraglide/messages.js';+import { swarmService } from '#lib/services/swarm-service.js';+import { throwPageLoadError } from '#lib/utils/api.js';+import { swarmKvResources } from '#lib/utils/swarm-kv.js';+import { resolveInitialListPageRequest } from '#lib/utils/tables.js';+import { tryCatch } from '#lib/utils/try-catch.js';++import type { PageLoad } from './$types';++export const load: PageLoad = async () => {+ const resource = swarmKvResources.secrets;+ const requestOptions = resolveInitialListPageRequest(resource.persistKey, {+ column: 'name',+ direction: 'asc'+ });++ const items = await tryCatch(swarmService.getKvItems(resource.kind, requestOptions));+ if (items.error !== null) {+ throwPageLoadError(items.error, m.common_load_failed({ resource: resource.title() }));+ }++ return {+ items: items.data,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/updates/components/container-updates-table.svelte b/frontend/src/routes/(app)/updates/components/container-updates-table.svelteindex cb8365866..89dc5b511 100644--- a/frontend/src/routes/(app)/updates/components/container-updates-table.svelte+++ b/frontend/src/routes/(app)/updates/components/container-updates-table.svelte@@ -42,6 +42,7 @@type EnvironmentRow} from '#lib/utils/environments.js';import { formatImageUpdateCheckedAt, formatImageUpdateValue } from '#lib/utils/image-updates.js';+ import { quadletUnitHref } from '#lib/utils/podman.js';import { tryCatch } from '#lib/utils/try-catch.js';import { getContainerDisplayName } from '../../containers/container-table.helpers';@@ -61,6 +62,7 @@/** Automatic installation is off; checks and notifications still run. */autoUpdateDisabled: boolean;labelControlled: boolean;+ quadletHref?: string;/** False when the agent omitted `autoUpdateEnabled`; toggling is then unavailable. */statusAvailable: boolean;autoUpdateTitle: string;@@ -112,11 +114,14 @@function mapContainerRow(container: ContainerRow): ContainerUpdateRow {const name = getContainerDisplayName(container);const labelControlled = isAutoUpdateLabelDisabled(container.labels);+ const quadletHref = quadletUnitHref(container.labels, container.environmentId);const statusAvailable = typeof container.autoUpdateEnabled === 'boolean';const autoUpdateDisabled = container.autoUpdateEnabled === false;let autoUpdateTitle = m.updates_disable_auto_update_description();if (!statusAvailable) {autoUpdateTitle = m.auto_update_status_unavailable();+ } else if (quadletHref) {+ autoUpdateTitle = m.podman_quadlet_update_disabled();} else if (labelControlled) {autoUpdateTitle = m.auto_update_controlled_by_label_checks_continue({ label: `${UPDATE_CHECK_LABEL}=false` });} else if (autoUpdateDisabled) {@@ -135,6 +140,7 @@checkedAt: container.updateInfo?.checkTime ?? '',autoUpdateDisabled,labelControlled,+ quadletHref,statusAvailable,autoUpdateTitle,updateInfo: container.updateInfo,@@ -275,6 +281,11 @@{m.updates_auto_update_disabled()}</Badge>{/if}+ {#if item.quadletHref}+ <Badge variant="purple" href={item.quadletHref} title={m.podman_quadlet_update_disabled()}>+ {m.podman_managed_by_quadlet()}+ </Badge>+ {/if}</div>{/snippet}diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.tsindex 3ecbf8bc3..d7343713c 100644--- a/frontend/src/routes/+layout.ts+++ b/frontend/src/routes/+layout.ts@@ -1,4 +1,5 @@import { browser } from '$app/env';+import { invalidate } from '$app/navigation';import { navigating, page } from '$app/state';import { error, redirect } from '@sveltejs/kit';import { QueryClient } from '@tanstack/svelte-query';@@ -7,6 +8,7 @@ import { queryKeys } from '#lib/query/query-keys.js';import { isSessionCancelledError } from '#lib/services/api-service.js';import { authService } from '#lib/services/auth-service.js';import { environmentManagementService } from '#lib/services/env-mgmt-service.js';+import { podmanService } from '#lib/services/podman-service.js';import { roleService } from '#lib/services/role-service.js';import { settingsService } from '#lib/services/settings-service.js';import { swarmService } from '#lib/services/swarm-service.js';@@ -19,6 +21,7 @@ import userStore from '#lib/stores/user-store.svelte.js';import { versionStore } from '#lib/stores/version.store.svelte.js';import type { PermissionsManifest, User } from '#lib/types/auth.js';import type { Environment } from '#lib/types/environment.js';+import type { PodmanStatus } from '#lib/types/podman.js';import type { AppVersionInformation, Settings } from '#lib/types/settings.js';import { isAuthRejectionError } from '#lib/utils/api.js';import { getAuthRedirectPath, shownEnvironmentForRoute, userHasPermission } from '#lib/utils/auth.js';@@ -55,6 +58,9 @@ let telemetryAwaited = false;// Navigations reuse root data for this long; a refresh of the page on screen always refetches.const ROOT_STALE_TIME = 30_000;+const SECONDARY_DISCOVERY_TIMEOUT = 1_500;+const PODMAN_STATUS_DEPENDENCY = 'app:podman-status';+const slowPodmanStatuses = new Map<string, PodmanStatus>();// Query results last pushed into the stores, so a cached repeat never overwrites newer local or streamed state.let appliedUser: User | undefined;let appliedEnvironments: Environment[] | undefined;@@ -76,7 +82,8 @@ export const load: LayoutLoad = async (event) => {}};-async function loadRoot({ url }: Parameters<LayoutLoad>[0], releaseSelection: (() => void) | undefined) {+async function loadRoot({ url, depends }: Parameters<LayoutLoad>[0], releaseSelection: (() => void) | undefined) {+ depends(PODMAN_STATUS_DEPENDENCY);// Logout must not wait on, or be triggered by, authenticated requests; preloading runs this too.if (url.pathname === '/logout') {return {@@ -86,7 +93,9 @@ async function loadRoot({ url }: Parameters<LayoutLoad>[0], releaseSelection: ((permissionsManifestLoadFailed: false,versionInformation: versionStore.current ?? toAppVersionInformation({}),queryClient,- swarmEnabled: undefined+ swarmEnabled: undefined,+ podmanStatus: null,+ podmanStatuses: {}};}@@ -139,6 +148,8 @@ async function loadRoot({ url }: Parameters<LayoutLoad>[0], releaseSelection: ((let settings = null;let swarmEnabled: boolean | undefined;+ let podmanStatus: PodmanStatus | null = null;+ let podmanStatuses: Record<string, PodmanStatus> = {};let permissionsManifest: PermissionsManifest | null = null;let permissionsManifestLoadFailed = false;if (user) {@@ -227,9 +238,46 @@ async function loadRoot({ url }: Parameters<LayoutLoad>[0], releaseSelection: ((})): Promise.resolve(null);- const [loadedSettings, loadedSwarmStatus, loadedPermissionsManifest] = await Promise.all([+ const podmanEnvironmentIds = [...new Set([currentEnvironmentId, ...environmentStore.shown.map((env) => env.id)])].filter(+ (id) => userHasPermission(user, 'podman:read', id)+ );+ const podmanStatusRequest = Promise.all(+ podmanEnvironmentIds.map(async (id) => {+ const request = dataOrNull(+ queryClient.query({+ ...rootQuery,+ queryKey: queryKeys.podman.status(id),+ queryFn: () => podmanService.getStatus(id, { suppressAccessDeniedToast: true })+ })+ );+ if (id === currentEnvironmentId) return [id, await request] as const;+ const known = slowPodmanStatuses.get(id);+ if (known) {+ void request.then((refreshed) => {+ if (JSON.stringify(refreshed) === JSON.stringify(known)) return;+ if (refreshed?.detected) slowPodmanStatuses.set(id, refreshed);+ else slowPodmanStatuses.delete(id);+ void invalidate(PODMAN_STATUS_DEPENDENCY);+ });+ return [id, known] as const;+ }+ const status = await Promise.race([+ request,+ new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), SECONDARY_DISCOVERY_TIMEOUT))+ ]);+ if (status !== 'pending') return [id, status] as const;+ void request.then((discovered) => {+ if (!discovered?.detected) return;+ slowPodmanStatuses.set(id, discovered);+ void invalidate(PODMAN_STATUS_DEPENDENCY);+ });+ return [id, null] as const;+ })+ );+ const [loadedSettings, loadedSwarmStatus, loadedPodmanStatuses, loadedPermissionsManifest] = await Promise.all([settingsRequest,swarmStatusRequest,+ podmanStatusRequest,permissionsManifestRequest]);// Keep recovery/settings pages reachable while a selected agent is offline.@@ -244,6 +292,10 @@ async function loadRoot({ url }: Parameters<LayoutLoad>[0], releaseSelection: (());await featuresRequest;swarmEnabled = loadedSwarmStatus?.enabled;+ podmanStatuses = Object.fromEntries(+ loadedPodmanStatuses.filter((entry): entry is readonly [string, PodmanStatus] => entry[1]?.detected === true)+ );+ podmanStatus = podmanStatuses[currentEnvironmentId] ?? null;permissionsManifest = loadedPermissionsManifest;permissionsManifestLoadFailed = loadedPermissionsManifest === null;} else {@@ -306,6 +358,8 @@ async function loadRoot({ url }: Parameters<LayoutLoad>[0], releaseSelection: ((permissionsManifestLoadFailed,versionInformation,queryClient,- swarmEnabled+ swarmEnabled,+ podmanStatus,+ podmanStatuses};}diff --git a/tests/spec/dashboard.spec.ts b/tests/spec/dashboard.spec.tsindex 9bf34556f..d1cae7991 100644--- a/tests/spec/dashboard.spec.ts+++ b/tests/spec/dashboard.spec.ts@@ -75,7 +75,10 @@ test.describe('Dashboard system stats websocket', () => {await expect(page.getByText('7 CPUs', { exact: true })).toBeVisible();await expect(page.getByText('512 MB / 1 GB', { exact: true })).toBeVisible();await expect(page.getByText('256 MB / 1 GB', { exact: true })).toBeVisible();- await expect(page.locator('main').getByText('Local Docker', { exact: true })).toBeVisible();+ const environmentResponse = await page.request.get('/api/environments/0');+ expect(environmentResponse.ok()).toBeTruthy();+ const { data: environment }: { data: { name: string } } = await environmentResponse.json();+ await expect(page.locator('main').getByText(environment.name, { exact: true })).toBeVisible();});test('keeps skeletons until the deadline when the stream opens without a sample', async ({diff --git a/types/dashboard/dashboard.go b/types/dashboard/dashboard.goindex 99263d30a..d02a49ef9 100644--- a/types/dashboard/dashboard.go+++ b/types/dashboard/dashboard.go@@ -132,6 +132,8 @@ type Snapshot struct {//// Required: falseVersionInfo *versiontypes.Info `json:"versionInfo,omitempty"`++ PodCount *int `json:"podCount,omitempty"`}type StreamEvent struct {diff --git a/types/podman/autoupdate.go b/types/podman/autoupdate.gonew file mode 100644index 000000000..a5772d5c1--- /dev/null+++ b/types/podman/autoupdate.go@@ -0,0 +1,33 @@+package podman++type AutoUpdateMode string++const (+ AutoUpdateModeREST AutoUpdateMode = "rest"+ AutoUpdateModeSystemd AutoUpdateMode = "systemd"+ AutoUpdateModeUnavailable AutoUpdateMode = "unavailable"+)++type AutoUpdateOptions struct {+ DryRun bool `json:"dryRun,omitempty"`+ Rollback *bool `json:"rollback,omitempty"`+ TLSVerify *bool `json:"tlsVerify,omitempty"`+ Authfile string `json:"authfile,omitempty"`+ Filters map[string][]string `json:"filters,omitempty"`+}++type AutoUpdateReport struct {+ ContainerID string `json:"containerId"`+ ContainerName string `json:"containerName"`+ ImageName string `json:"imageName"`+ Policy string `json:"policy"`+ SystemdUnit string `json:"systemdUnit"`+ Updated string `json:"updated"`+}++type AutoUpdateResult struct {+ Mode AutoUpdateMode `json:"mode"`+ Reports []AutoUpdateReport `json:"reports"`+ Errors []string `json:"errors"`+ Unit *UnitStatus `json:"unit,omitempty"`+}diff --git a/types/podman/kube.go b/types/podman/kube.gonew file mode 100644index 000000000..dd3190539--- /dev/null+++ b/types/podman/kube.go@@ -0,0 +1,61 @@+package podman++type KubeGenerateType string++const (+ KubeGenerateTypePod KubeGenerateType = "pod"+ KubeGenerateTypeService KubeGenerateType = "service"+ KubeGenerateTypeDeployment KubeGenerateType = "deployment"+ KubeGenerateTypeDaemonSet KubeGenerateType = "daemonset"+ KubeGenerateTypeJob KubeGenerateType = "job"+)++type KubePlayRequest struct {+ YAML string `json:"yaml" minLength:"1" doc:"Kubernetes YAML to play"`+ Start *bool `json:"start,omitempty" doc:"Start the pods after creating them"`+ Replace bool `json:"replace,omitempty" doc:"Replace existing pods and containers"`+ Networks []string `json:"networks,omitempty" doc:"Networks to attach the pods to"`+}++type KubeDownRequest struct {+ YAML string `json:"yaml" minLength:"1" doc:"Kubernetes YAML to tear down"`+ Force bool `json:"force,omitempty" doc:"Also remove volumes created by the YAML"`+}++type KubeGenerateRequest struct {+ Names []string `json:"names" minItems:"1" doc:"Pods, containers, or volumes to include"`+ Type KubeGenerateType `json:"type,omitempty" enum:"pod,service,deployment,daemonset,job" doc:"Kubernetes kind to generate"`+ Service bool `json:"service,omitempty" doc:"Also generate a Kubernetes service"`+}++type KubeGenerateResponse struct {+ YAML string `json:"yaml"`+}++type KubePlayPod struct {+ ID string `json:"id"`+ Containers []string `json:"containers"`+ InitContainers []string `json:"initContainers"`+ Logs []string `json:"logs"`+ ContainerErrors []string `json:"containerErrors"`+}++type KubePlayVolume struct {+ Name string `json:"name"`+}++type KubePlayReport struct {+ Pods []KubePlayPod `json:"pods"`+ Volumes []KubePlayVolume `json:"volumes"`+ ServiceContainerID string `json:"serviceContainerId,omitempty"`+ ExitCode *int32 `json:"exitCode,omitempty"`+}++type KubeDownPod struct {+ ID string `json:"id"`+}++type KubeDownReport struct {+ StopReport []KubeDownPod `json:"stopReport"`+ RmReport []KubeDownPod `json:"rmReport"`+}diff --git a/types/podman/labels.go b/types/podman/labels.gonew file mode 100644index 000000000..5205f35e9--- /dev/null+++ b/types/podman/labels.go@@ -0,0 +1,3 @@+package podman++const SystemdUnitLabel = "PODMAN_SYSTEMD_UNIT"diff --git a/types/podman/pod.go b/types/podman/pod.gonew file mode 100644index 000000000..84017779a--- /dev/null+++ b/types/podman/pod.go@@ -0,0 +1,190 @@+package podman++import (+ "time"++ "github.com/getarcaneapp/arcane/types/v2/base"+)++type PodContainer struct {+ ID string `json:"id"`+ Names string `json:"names"`+ Status string `json:"status"`+ RestartCount uint `json:"restartCount"`+}++type Pod struct {+ base.EnvironmentTag++ ID string `json:"id"`+ Name string `json:"name"`+ Namespace string `json:"namespace,omitempty"`+ Status string `json:"status"`+ Created time.Time `json:"created"`+ InfraID string `json:"infraId,omitempty"`+ Cgroup string `json:"cgroup,omitempty"`+ Labels map[string]string `json:"labels,omitempty"`+ Networks []string `json:"networks,omitempty"`+ Containers []PodContainer `json:"containers"`+}++type PodPortBinding struct {+ HostIP string `json:"hostIp,omitempty"`+ HostPort string `json:"hostPort"`+}++type PodInfraConfig struct {+ PortBindings map[string][]PodPortBinding `json:"portBindings,omitempty"`+ HostNetwork bool `json:"hostNetwork"`+ Networks []string `json:"networks,omitempty"`+}++type PodInspectContainer struct {+ ID string `json:"id"`+ Name string `json:"name"`+ State string `json:"state"`+}++type PodInspect struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Namespace string `json:"namespace,omitempty"`+ Created time.Time `json:"created"`+ State string `json:"state"`+ Hostname string `json:"hostname,omitempty"`+ Labels map[string]string `json:"labels,omitempty"`+ CreateInfra bool `json:"createInfra"`+ InfraContainerID string `json:"infraContainerId,omitempty"`+ InfraConfig *PodInfraConfig `json:"infraConfig,omitempty"`+ SharedNamespaces []string `json:"sharedNamespaces,omitempty"`+ NumContainers uint `json:"numContainers"`+ Containers []PodInspectContainer `json:"containers"`+}++type PodPortMapping struct {+ ContainerPort uint16 `json:"containerPort" minimum:"1" doc:"Port inside the pod"`+ HostPort uint16 `json:"hostPort,omitempty" doc:"Port on the host"`+ HostIP string `json:"hostIp,omitempty" doc:"Host IP to bind"`+ Protocol string `json:"protocol,omitempty" doc:"tcp, udp, or sctp"`+ Range uint16 `json:"range,omitempty" doc:"Number of consecutive ports to map"`+}++type PodNetwork struct {+ Name string `json:"name" minLength:"1" doc:"Network to join"`+ Aliases []string `json:"aliases,omitempty" doc:"Network-scoped aliases"`+ StaticIPs []string `json:"staticIps,omitempty" doc:"Static IPv4 or IPv6 addresses"`+ StaticMAC string `json:"staticMac,omitempty" doc:"Static MAC address"`+ InterfaceName string `json:"interfaceName,omitempty" doc:"Interface name inside the pod"`+}++type PodVolume struct {+ Source string `json:"source" minLength:"1" doc:"Absolute host path or named volume"`+ Destination string `json:"destination" minLength:"1" doc:"Path inside the pod"`+ Options []string `json:"options,omitempty" doc:"Mount options such as ro, z, Z, or U"`+}++type PodDeviceLimit struct {+ Device string `json:"device" minLength:"1" doc:"Block device as MAJOR:MINOR"`+ Value string `json:"value" minLength:"1" doc:"Weight (10-1000) for weight limits, or a rate such as 1mb for throughput limits"`+}++type PodCreateRequest struct {+ Name string `json:"name" minLength:"1" doc:"Pod name"`+ Hostname string `json:"hostname,omitempty" doc:"Pod hostname"`+ Labels map[string]string `json:"labels,omitempty" doc:"Pod labels"`+ ExitPolicy string `json:"exitPolicy,omitempty" enum:"continue,stop" doc:"Behaviour when the last container exits"`+ RestartPolicy string `json:"restartPolicy,omitempty" enum:"no,always,on-failure,unless-stopped" doc:"Restart policy for containers in the pod"`+ RestartRetries *uint `json:"restartRetries,omitempty" doc:"Restart attempts for the on-failure policy"`+ NoInfra bool `json:"noInfra,omitempty" doc:"Create the pod without an infra container"`+ InfraImage string `json:"infraImage,omitempty" doc:"Image for the infra container"`+ InfraCommand []string `json:"infraCommand,omitempty" doc:"Entrypoint of the infra container"`+ InfraName string `json:"infraName,omitempty" doc:"Name of the infra container"`+ InfraConmonPidFile string `json:"infraConmonPidFile,omitempty" doc:"Path that receives the infra container's conmon PID"`+ SharedNamespaces []string `json:"sharedNamespaces,omitempty" doc:"Namespaces shared between pod members"`+ ShareParent *bool `json:"shareParent,omitempty" doc:"Use the pod's cgroup as the cgroup parent of its containers"`+ Pid string `json:"pid,omitempty" doc:"PID namespace: host, private, ns:<path>, or container:<id>"`+ Ipc string `json:"ipc,omitempty" doc:"IPC namespace: host, private, shareable, none, ns:<path>, or container:<id>"`+ Uts string `json:"uts,omitempty" doc:"UTS namespace: host, private, ns:<path>, or container:<id>"`+ Userns string `json:"userns,omitempty" doc:"User namespace, for example auto, keep-id, keep-id:uid=1000, host, or ns:<path>"`+ UIDMap []string `json:"uidMap,omitempty" doc:"UID mappings as CONTAINER:HOST:SIZE"`+ GIDMap []string `json:"gidMap,omitempty" doc:"GID mappings as CONTAINER:HOST:SIZE"`+ NetworkMode string `json:"networkMode,omitempty" doc:"bridge, host, none, private, slirp4netns, pasta, or ns:<path>"`+ NetworkOptions []string `json:"networkOptions,omitempty" doc:"Options for the slirp4netns or pasta network mode"`+ Networks []PodNetwork `json:"networks,omitempty" doc:"Networks to join"`+ PortMappings []PodPortMapping `json:"portMappings,omitempty" doc:"Published ports"`+ DNSServers []string `json:"dnsServers,omitempty" doc:"DNS servers"`+ DNSSearch []string `json:"dnsSearch,omitempty" doc:"DNS search domains"`+ DNSOptions []string `json:"dnsOptions,omitempty" doc:"DNS resolver options"`+ NoManageResolvConf bool `json:"noManageResolvConf,omitempty" doc:"Use the image's /etc/resolv.conf"`+ AddHosts []string `json:"addHosts,omitempty" doc:"Extra /etc/hosts entries as HOST:IP"`+ NoHosts bool `json:"noHosts,omitempty" doc:"Use the image's /etc/hosts"`+ NoHostname bool `json:"noHostname,omitempty" doc:"Use the image's /etc/hostname"`+ HostsFile string `json:"hostsFile,omitempty" doc:"Base file for /etc/hosts, or image or none"`+ CgroupParent string `json:"cgroupParent,omitempty" doc:"Parent cgroup of the pod"`+ CPUs float64 `json:"cpus,omitempty" minimum:"0" doc:"Number of CPUs"`+ CPUShares uint64 `json:"cpuShares,omitempty" doc:"Relative CPU weight"`+ CPUSetCPUs string `json:"cpusetCpus,omitempty" doc:"CPUs allowed to run the pod, for example 0-3"`+ CPUSetMems string `json:"cpusetMems,omitempty" doc:"Memory nodes allowed to run the pod, for example 0,1"`+ Memory string `json:"memory,omitempty" doc:"Memory limit such as 512m or 2g"`+ MemorySwap string `json:"memorySwap,omitempty" doc:"Memory plus swap limit such as 1g, or -1 for unlimited swap"`+ BlkioWeight uint16 `json:"blkioWeight,omitempty" minimum:"10" maximum:"1000" doc:"Relative block IO weight"`+ BlkioWeightDevices []PodDeviceLimit `json:"blkioWeightDevices,omitempty" doc:"Per-device block IO weights"`+ DeviceReadBps []PodDeviceLimit `json:"deviceReadBps,omitempty" doc:"Per-device read rate limits"`+ DeviceWriteBps []PodDeviceLimit `json:"deviceWriteBps,omitempty" doc:"Per-device write rate limits"`+ Devices []string `json:"devices,omitempty" doc:"Host devices as HOST[:CONTAINER[:PERMISSIONS]]"`+ GPUs []string `json:"gpus,omitempty" doc:"NVIDIA GPUs to add through CDI, or all"`+ Volumes []PodVolume `json:"volumes,omitempty" doc:"Bind mounts and named volumes"`+ VolumesFrom []string `json:"volumesFrom,omitempty" doc:"Containers to mount volumes from, as CONTAINER[:OPTIONS]"`+ ShmSize string `json:"shmSize,omitempty" doc:"Size of /dev/shm such as 64m"`+ ShmSizeSystemd string `json:"shmSizeSystemd,omitempty" doc:"Size of systemd tmpfs mounts such as 64m"`+ SecurityOpt []string `json:"securityOpt,omitempty" doc:"Security options such as label=disable"`+ Sysctl map[string]string `json:"sysctl,omitempty" doc:"Namespaced kernel parameters"`+}++type PodActionRequest struct {+ Timeout *int `json:"timeout,omitempty" doc:"Seconds to wait before killing the pod on stop"`+ Signal string `json:"signal,omitempty" doc:"Signal sent on kill"`+}++type PodCreateResponse struct {+ ID string `json:"id"`+}++type PodStats struct {+ Pod string `json:"pod"`+ CID string `json:"cid"`+ Name string `json:"name"`+ CPU string `json:"cpu"`+ MemUsage string `json:"memUsage"`+ MemUsageBytes string `json:"memUsageBytes"`+ Mem string `json:"mem"`+ NetIO string `json:"netIo"`+ BlockIO string `json:"blockIo"`+ PIDS string `json:"pids"`+}++type PodTop struct {+ Titles []string `json:"titles"`+ Processes [][]string `json:"processes"`+}++type PodPruneReport struct {+ ID string `json:"id"`+}++type Container struct {+ ID string `json:"id"`+ Names []string `json:"names"`+ Image string `json:"image"`+ ImageID string `json:"imageId,omitempty"`+ State string `json:"state"`+ Status string `json:"status,omitempty"`+ Created time.Time `json:"created"`+ StartedAt int64 `json:"startedAt,omitempty"`+ ExitCode int32 `json:"exitCode"`+ Exited bool `json:"exited"`+ Labels map[string]string `json:"labels,omitempty"`+ Pod string `json:"pod,omitempty"`+ PodName string `json:"podName,omitempty"`+ IsInfra bool `json:"isInfra"`+}diff --git a/types/podman/quadlet.go b/types/podman/quadlet.gonew file mode 100644index 000000000..82e5af704--- /dev/null+++ b/types/podman/quadlet.go@@ -0,0 +1,65 @@+package podman++import "github.com/getarcaneapp/arcane/types/v2/base"++type QuadletType string++const (+ QuadletTypeContainer QuadletType = "container"+ QuadletTypePod QuadletType = "pod"+ QuadletTypeKube QuadletType = "kube"+ QuadletTypeNetwork QuadletType = "network"+ QuadletTypeVolume QuadletType = "volume"+ QuadletTypeImage QuadletType = "image"+ QuadletTypeBuild QuadletType = "build"+ QuadletTypeArtifact QuadletType = "artifact"+)++type Quadlet struct {+ Name string `json:"name"`+ UnitName string `json:"unitName,omitempty"`+ Path string `json:"path"`+ Status string `json:"status"`+ App string `json:"app,omitempty"`+}++type QuadletFile struct {+ Name string `json:"name"`+ Content string `json:"content"`+}++type QuadletInstallRequest struct {+ Name string `json:"name" minLength:"1" doc:"Quadlet file name including its extension"`+ Content string `json:"content" minLength:"1" doc:"Quadlet file contents"`+ ExtraFiles []QuadletFile `json:"extraFiles,omitempty" doc:"Additional files installed beside the quadlet"`+ App string `json:"app,omitempty" doc:"Application the quadlet belongs to"`+}++type QuadletUpdateRequest struct {+ Content string `json:"content" minLength:"1" doc:"Quadlet file contents"`+ ExtraFiles []QuadletFile `json:"extraFiles,omitempty" doc:"Additional files installed beside the quadlet"`+}++type QuadletDetail struct {+ base.EnvironmentTag++ Name string `json:"name"`+ UnitName string `json:"unitName"`+ Path string `json:"path"`+ Status string `json:"status"`+ App string `json:"app,omitempty"`+ Type QuadletType `json:"type"`+ Template bool `json:"template"`+ UnitStatus *UnitStatus `json:"unitStatus,omitempty"`+ Containers []Container `json:"containers,omitempty"`+}++type QuadletInstallReport struct {+ InstalledQuadlets map[string]string `json:"installedQuadlets"`+ QuadletErrors map[string]string `json:"quadletErrors"`+}++type QuadletRemoveReport struct {+ Removed []string `json:"removed"`+ Errors map[string]string `json:"errors"`+}diff --git a/types/podman/secret.go b/types/podman/secret.gonew file mode 100644index 000000000..c4f4e76d2--- /dev/null+++ b/types/podman/secret.go@@ -0,0 +1,46 @@+package podman++import (+ "time"++ "github.com/getarcaneapp/arcane/types/v2/base"+)++type SecretDriver struct {+ Name string `json:"name"`+ Options map[string]string `json:"options,omitempty"`+}++type SecretSpec struct {+ Name string `json:"name"`+ Driver SecretDriver `json:"driver"`+ Labels map[string]string `json:"labels,omitempty"`+}++type Secret struct {+ base.EnvironmentTag++ ID string `json:"id"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ Spec SecretSpec `json:"spec"`+}++type SecretCreateRequest struct {+ Name string `json:"name" minLength:"1" doc:"Secret name"`+ Data string `json:"data" minLength:"1" doc:"Secret value"`+ Driver string `json:"driver,omitempty" doc:"Secret driver"`+ DriverOptions map[string]string `json:"driverOptions,omitempty" doc:"Secret driver options"`+ Labels map[string]string `json:"labels,omitempty" doc:"Secret labels"`+}++type SecretCreateResponse struct {+ ID string `json:"id"`+}++type SecretUpdateRequest struct {+ Data string `json:"data" minLength:"1" doc:"New secret value; Podman replaces the whole secret"`+ Driver string `json:"driver,omitempty" doc:"Secret driver"`+ DriverOptions map[string]string `json:"driverOptions,omitempty" doc:"Secret driver options"`+ Labels map[string]string `json:"labels,omitempty" doc:"Secret labels"`+}diff --git a/types/podman/status.go b/types/podman/status.gonew file mode 100644index 000000000..343c67ba5--- /dev/null+++ b/types/podman/status.go@@ -0,0 +1,199 @@+package podman++type SystemdScope string++const (+ SystemdScopeSystem SystemdScope = "system"+ SystemdScopeUser SystemdScope = "user"+)++type Status struct {+ Detected bool `json:"detected"`+ Version string `json:"version,omitempty"`+ APIVersion string `json:"apiVersion,omitempty"`+ Rootless bool `json:"rootless"`+ QuadletsSupported bool `json:"quadletsSupported"`+ QuadletAppsSupported bool `json:"quadletAppsSupported"`+ AutoUpdateMode AutoUpdateMode `json:"autoUpdateMode"`+ SystemdAvailable bool `json:"systemdAvailable"`+ SystemdScope SystemdScope `json:"systemdScope,omitempty"`+ SystemdReason string `json:"systemdReason,omitempty"`+}++type SystemdAvailability struct {+ Available bool `json:"available"`+ Scope SystemdScope `json:"scope,omitempty"`+ Reason string `json:"reason,omitempty"`+}++type UnitStatus struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ LoadState string `json:"loadState"`+ ActiveState string `json:"activeState"`+ SubState string `json:"subState"`+}++type VersionComponent struct {+ Name string `json:"name"`+ Version string `json:"version"`+}++type Version struct {+ Version string `json:"version"`+ APIVersion string `json:"apiVersion"`+ MinAPIVersion string `json:"minApiVersion,omitempty"`+ GitCommit string `json:"gitCommit,omitempty"`+ GoVersion string `json:"goVersion,omitempty"`+ Os string `json:"os,omitempty"`+ Arch string `json:"arch,omitempty"`+ KernelVersion string `json:"kernelVersion,omitempty"`+ Components []VersionComponent `json:"components,omitempty"`+}++type InfoSecurity struct {+ Rootless bool `json:"rootless"`+ SELinuxEnabled bool `json:"selinuxEnabled"`+ AppArmorEnabled bool `json:"apparmorEnabled"`+ SeccompEnabled bool `json:"seccompEnabled"`+ SeccompProfilePath string `json:"seccompProfilePath,omitempty"`+ Capabilities string `json:"capabilities,omitempty"`+}++type InfoDistribution struct {+ Distribution string `json:"distribution,omitempty"`+ Variant string `json:"variant,omitempty"`+ Version string `json:"version,omitempty"`+ Codename string `json:"codename,omitempty"`+}++type InfoOCIRuntime struct {+ Name string `json:"name,omitempty"`+ Package string `json:"package,omitempty"`+ Path string `json:"path,omitempty"`+ Version string `json:"version,omitempty"`+}++type InfoConmon struct {+ Package string `json:"package,omitempty"`+ Path string `json:"path,omitempty"`+ Version string `json:"version,omitempty"`+}++type InfoHelperBinary struct {+ Executable string `json:"executable,omitempty"`+ Package string `json:"package,omitempty"`+ Version string `json:"version,omitempty"`+}++type InfoNetworkDNS struct {+ Version string `json:"version,omitempty"`+ Package string `json:"package,omitempty"`+ Path string `json:"path,omitempty"`+}++type InfoNetworkBackend struct {+ Backend string `json:"backend,omitempty"`+ Version string `json:"version,omitempty"`+ Package string `json:"package,omitempty"`+ Path string `json:"path,omitempty"`+ DNS InfoNetworkDNS `json:"dns"`+ DefaultNetwork string `json:"defaultNetwork,omitempty"`+}++type InfoIDMap struct {+ ContainerID int64 `json:"container_id"`+ HostID int64 `json:"host_id"`+ Size int64 `json:"size"`+}++type InfoIDMappings struct {+ UIDMap []InfoIDMap `json:"uidmap,omitempty"`+ GIDMap []InfoIDMap `json:"gidmap,omitempty"`+}++type InfoRemoteSocket struct {+ Path string `json:"path,omitempty"`+ Exists bool `json:"exists"`+}++type InfoHost struct {+ Arch string `json:"arch,omitempty"`+ BuildahVersion string `json:"buildahVersion,omitempty"`+ CgroupManager string `json:"cgroupManager,omitempty"`+ CgroupVersion string `json:"cgroupVersion,omitempty"`+ CgroupControllers []string `json:"cgroupControllers,omitempty"`+ Conmon InfoConmon `json:"conmon"`+ CPUs int `json:"cpus"`+ DatabaseBackend string `json:"databaseBackend,omitempty"`+ Distribution InfoDistribution `json:"distribution"`+ EventLogger string `json:"eventLogger,omitempty"`+ Hostname string `json:"hostname,omitempty"`+ IDMappings InfoIDMappings `json:"idMappings"`+ Kernel string `json:"kernel,omitempty"`+ LogDriver string `json:"logDriver,omitempty"`+ MemFree int64 `json:"memFree"`+ MemTotal int64 `json:"memTotal"`+ NetworkBackend string `json:"networkBackend,omitempty"`+ NetworkBackendInfo InfoNetworkBackend `json:"networkBackendInfo"`+ OCIRuntime InfoOCIRuntime `json:"ociRuntime"`+ Os string `json:"os,omitempty"`+ RemoteSocket InfoRemoteSocket `json:"remoteSocket"`+ RootlessNetworkCmd string `json:"rootlessNetworkCmd,omitempty"`+ ServiceIsRemote bool `json:"serviceIsRemote"`+ Security InfoSecurity `json:"security"`+ Slirp4netns InfoHelperBinary `json:"slirp4netns"`+ Pasta InfoHelperBinary `json:"pasta"`+ SwapFree int64 `json:"swapFree"`+ SwapTotal int64 `json:"swapTotal"`+ Uptime string `json:"uptime,omitempty"`+}++type InfoContainerStore struct {+ Number int `json:"number"`+ Paused int `json:"paused"`+ Running int `json:"running"`+ Stopped int `json:"stopped"`+}++type InfoImageStore struct {+ Number int `json:"number"`+}++type InfoStore struct {+ ConfigFile string `json:"configFile,omitempty"`+ ContainerStore InfoContainerStore `json:"containerStore"`+ GraphDriverName string `json:"graphDriverName,omitempty"`+ GraphRoot string `json:"graphRoot,omitempty"`+ GraphStatus map[string]string `json:"graphStatus,omitempty"`+ ImageStore InfoImageStore `json:"imageStore"`+ RunRoot string `json:"runRoot,omitempty"`+ VolumePath string `json:"volumePath,omitempty"`+}++type InfoRegistries struct {+ Search []string `json:"search,omitempty"`+}++type InfoPlugins struct {+ Network []string `json:"network,omitempty"`+ Volume []string `json:"volume,omitempty"`+ Log []string `json:"log,omitempty"`+}++type InfoVersion struct {+ APIVersion string `json:"apiVersion,omitempty"`+ Version string `json:"version,omitempty"`+ GoVersion string `json:"goVersion,omitempty"`+ GitCommit string `json:"gitCommit,omitempty"`+ BuiltTime string `json:"builtTime,omitempty"`+ OsArch string `json:"osArch,omitempty"`+}++type Info struct {+ Host InfoHost `json:"host"`+ Store InfoStore `json:"store"`+ Registries InfoRegistries `json:"registries"`+ Plugins InfoPlugins `json:"plugins"`+ Version InfoVersion `json:"version"`+}diff --git a/types/swarm/config_secret.go b/types/swarm/config_secret.goindex 4222c0324..e77cfca42 100644--- a/types/swarm/config_secret.go+++ b/types/swarm/config_secret.go@@ -66,3 +66,13 @@ func NewSecretSummary(secret swarm.Secret) SecretSummary {Spec: secret.Spec,}}++type ConfigUpdateRequest struct {+ Version uint64 `json:"version" doc:"Current config version, used to reject stale updates"`+ Labels map[string]string `json:"labels" doc:"Replacement labels; config data is immutable"`+}++type SecretUpdateRequest struct {+ Version uint64 `json:"version" doc:"Current secret version, used to reject stale updates"`+ Labels map[string]string `json:"labels" doc:"Replacement labels; secret data is immutable"`+}