Skip to content

Modern Docker Management, Designed for Everyone

fix: sort containers by live CPU and memory usage globally (#4099)

Kyle Mendell18e4e3f5b1b2
diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.go
index 372675558..f2bc0f2e1 100644
--- a/backend/internal/container/handler.go
+++ b/backend/internal/container/handler.go
@@ -45,11 +45,12 @@ type ContainerHandler struct {
// ContainerPaginatedResponse is the paginated list response for containers.
type ContainerPaginatedResponse struct {
- Success bool `json:"success"`
- Data []containertypes.Summary `json:"data"`
- Groups []containertypes.SummaryGroup `json:"groups,omitempty"`
- Counts containertypes.StatusCounts `json:"counts"`
- Pagination base.PaginationResponse `json:"pagination"`
+ Success bool `json:"success"`
+ Data []containertypes.Summary `json:"data"`
+ Groups []containertypes.SummaryGroup `json:"groups,omitempty"`
+ Counts containertypes.StatusCounts `json:"counts"`
+ Pagination base.PaginationResponse `json:"pagination"`
+ ResourceSortSupported bool `json:"resourceSortSupported"`
}
type ListContainersInput struct {
@@ -319,6 +320,10 @@ func RegisterContainers(api huma.API, containerSvc *ContainerService, dockerSvc
}
func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContainersInput) (*ListContainersOutput, error) {
+ if ps, _ := middleware.PermissionsFromContext(ctx); containerResourceSortPermissionDeniedInternal(ps, input.EnvironmentID, input.Sort) {
+ return nil, huma.Error403Forbidden("permission denied: " + authz.PermContainersRead)
+ }
+
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Updates != "" {
params.Filters["updates"] = input.Updates
@@ -337,11 +342,12 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContai
return &ListContainersOutput{
Body: ContainerPaginatedResponse{
- Success: true,
- Data: result.Items,
- Groups: result.Groups,
- Counts: result.Counts,
- Pagination: handlerutil.PaginationResponse(result.Pagination),
+ Success: true,
+ Data: result.Items,
+ Groups: result.Groups,
+ Counts: result.Counts,
+ Pagination: handlerutil.PaginationResponse(result.Pagination),
+ ResourceSortSupported: true,
},
}, nil
}
diff --git a/backend/internal/container/resource_stats.go b/backend/internal/container/resource_stats.go
new file mode 100644
index 000000000..e3ad5d43b
--- /dev/null
+++ b/backend/internal/container/resource_stats.go
@@ -0,0 +1,249 @@
+package container
+
+import (
+ "context"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
+ "log/slog"
+ "strings"
+ "sync"
+ "time"
+
+ "emperror.dev/errors"
+ "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/client"
+ "github.com/samber/hot"
+ containerstats "go.getarcane.app/streams/stats"
+ "golang.org/x/sync/errgroup"
+
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ containertypes "github.com/getarcaneapp/arcane/types/v2/container"
+)
+
+const (
+ containerResourceSampleTTL = 5 * time.Second
+ containerResourceSampleCacheSize = 4096
+ containerResourceCollectConcurrency = 16
+ containerResourceCollectTimeout = 3 * time.Second
+)
+
+func newResourceSampleCacheInternal(ttl time.Duration) *hot.HotCache[string, containertypes.ResourceSample] {
+ return hot.NewHotCache[string, containertypes.ResourceSample](hot.LRU, containerResourceSampleCacheSize).
+ WithTTL(ttl).
+ WithJanitor().
+ Build()
+}
+
+// resourceSampleCacheKeyInternal isolates cache and coalescing entries by
+// Docker daemon and container ID.
+func (s *ContainerService) resourceSampleCacheKeyInternal(containerID string) string {
+ return s.dockerService.DockerHost() + "\x00" + containerID
+}
+
+// containerResourceSortPermissionDeniedInternal enforces the extra
+// containers:read requirement on resource-sorted list requests.
+func containerResourceSortPermissionDeniedInternal(ps *authz.PermissionSet, envID, sort string) bool {
+ if !containertypes.IsResourceSort(sort) {
+ return false
+ }
+ return !ps.Allows(authz.PermContainersRead, envID)
+}
+
+// listContainersByResourceInternal applies search and filters, collects stats
+// for the matching containers, then sorts and paginates.
+func (s *ContainerService) listContainersByResourceInternal(
+ ctx context.Context,
+ config pagination.Config[containertypes.Summary],
+ items []containertypes.Summary,
+ counts containertypes.StatusCounts,
+ params pagination.QueryParams,
+) (ContainerListResult, error) {
+ filtered := make([]containertypes.Summary, 0, len(items))
+ for _, item := range items {
+ if config.MatchesSearchAndFilters(item, params) {
+ filtered = append(filtered, item)
+ }
+ }
+
+ samples, err := s.collectResourceSamplesInternal(ctx, filtered)
+ if err != nil {
+ return ContainerListResult{}, err
+ }
+ for i := range filtered {
+ filtered[i].ResourceSample = samples[filtered[i].ID]
+ }
+
+ page := config.OrderAndPaginate(filtered, params)
+ s.ApplySummaryIcons(ctx, page, nil)
+
+ return ContainerListResult{
+ Items: page,
+ Pagination: pagination.BuildResponse(int64(len(filtered)), int64(len(items)), params),
+ Counts: counts,
+ }, nil
+}
+
+// collectResourceSamplesInternal fetches one sample per running container.
+// Individual failures leave the container unsampled; a batch timeout or
+// cancellation fails the request so partial lists never sort as global.
+func (s *ContainerService) collectResourceSamplesInternal(ctx context.Context, items []containertypes.Summary) (map[string]*containertypes.ResourceSample, error) {
+ batchTimeout := s.resourceBatchTimeout
+ if batchTimeout <= 0 {
+ batchTimeout = timeouts.DefaultDockerAPI
+ }
+ batchCtx, cancel := context.WithTimeout(ctx, batchTimeout)
+ defer cancel()
+
+ g, groupCtx := errgroup.WithContext(batchCtx)
+ g.SetLimit(containerResourceCollectConcurrency)
+
+ samples := make(map[string]*containertypes.ResourceSample, len(items))
+ var mu sync.Mutex
+
+ for i := range items {
+ if items[i].State != string(container.StateRunning) {
+ continue
+ }
+ id := items[i].ID
+ g.Go(func() error {
+ sample, err := s.fetchResourceSampleInternal(groupCtx, id)
+ if err != nil {
+ if groupCtx.Err() != nil {
+ return groupCtx.Err()
+ }
+ slog.WarnContext(groupCtx, "Failed to collect container resource sample", "container_id", id, "error", err)
+ return nil
+ }
+ mu.Lock()
+ samples[id] = sample
+ mu.Unlock()
+ return nil
+ })
+ }
+
+ if err := g.Wait(); err != nil {
+ return nil, errors.WrapIf(err, "failed to collect container resource samples")
+ }
+ return samples, nil
+}
+
+// fetchResourceSampleInternal returns a cached sample when fresh and coalesces
+// concurrent fetches for the same container.
+func (s *ContainerService) fetchResourceSampleInternal(ctx context.Context, containerID string) (*containertypes.ResourceSample, error) {
+ key := s.resourceSampleCacheKeyInternal(containerID)
+ if s.resourceSampleCache != nil {
+ if sample, ok, _ := s.resourceSampleCache.Get(key); ok {
+ return &sample, nil
+ }
+ }
+
+ sampleTimeout := s.resourceSampleTimeout
+ if sampleTimeout <= 0 {
+ sampleTimeout = containerResourceCollectTimeout
+ }
+ ch := s.resourceSampleFlight.DoChan(key, func() (any, error) {
+ flightCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sampleTimeout)
+ defer cancel()
+ return s.collectResourceSampleInternal(flightCtx, containerID)
+ })
+
+ fetchCtx, cancel := context.WithTimeout(ctx, sampleTimeout)
+ defer cancel()
+
+ select {
+ case <-fetchCtx.Done():
+ return nil, fetchCtx.Err()
+ case res := <-ch:
+ if res.Err != nil {
+ return nil, res.Err
+ }
+ sample, ok := res.Val.(*containertypes.ResourceSample)
+ if !ok {
+ return nil, errors.New("resource sample flight returned unexpected type")
+ }
+ return sample, nil
+ }
+}
+
+// collectResourceSampleInternal performs the non-streaming Docker stats call.
+// IncludePreviousSample gives the CPU delta a valid previous sample.
+func (s *ContainerService) collectResourceSampleInternal(ctx context.Context, containerID string) (*containertypes.ResourceSample, error) {
+ dockerClient, err := s.dockerService.GetClient(ctx)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to connect to Docker")
+ }
+
+ stats, err := dockerClient.ContainerStats(ctx, containerID, client.ContainerStatsOptions{Stream: false, IncludePreviousSample: true})
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to fetch container stats")
+ }
+ defer func() { _ = stats.Body.Close() }()
+
+ var statsData container.StatsResponse
+ if err := json.UnmarshalDecode(jsontext.NewDecoder(stats.Body), &statsData); err != nil {
+ return nil, errors.WrapIf(err, "failed to decode container stats")
+ }
+
+ built := containerstats.BuildSample(statsData)
+ sample := &containertypes.ResourceSample{
+ CPUPercent: float64(built.CPUTenths) / 10,
+ MemoryUsageBytes: built.MemoryUsageBytes,
+ MemoryLimitBytes: statsData.MemoryStats.Limit,
+ SampleTime: statsData.Read,
+ }
+ if sample.SampleTime.IsZero() {
+ sample.SampleTime = time.Now()
+ }
+
+ if s.resourceSampleCache != nil {
+ s.resourceSampleCache.Set(s.resourceSampleCacheKeyInternal(containerID), *sample)
+ }
+ return sample, nil
+}
+
+// containerResourceSampleSortInternal orders summaries by their collected
+// sample value, keeping unsampled containers last in both directions and
+// breaking ties by name, then ID. Valid zero values sort as zero, not as
+// unavailable.
+func containerResourceSampleSortInternal(sort string, descending bool) pagination.SortOption[containertypes.Summary] {
+ var value func(*containertypes.ResourceSample) float64
+ if sort == containertypes.SortCPUUsage {
+ value = func(sample *containertypes.ResourceSample) float64 { return sample.CPUPercent }
+ } else {
+ value = func(sample *containertypes.ResourceSample) float64 { return float64(sample.MemoryUsageBytes) }
+ }
+
+ tieBreak := func(a, b containertypes.Summary) int {
+ if c := compareContainerNamesForSortInternal(a, b); c != 0 {
+ return c
+ }
+ return strings.Compare(a.ID, b.ID)
+ }
+
+ return func(a, b containertypes.Summary) int {
+ if a.ResourceSample == nil && b.ResourceSample == nil {
+ return tieBreak(a, b)
+ }
+ if a.ResourceSample == nil {
+ return 1
+ }
+ if b.ResourceSample == nil {
+ return -1
+ }
+
+ valueA, valueB := value(a.ResourceSample), value(b.ResourceSample)
+ if valueA == valueB {
+ return tieBreak(a, b)
+ }
+ less := valueA < valueB
+ if descending {
+ less = !less
+ }
+ if less {
+ return -1
+ }
+ return 1
+ }
+}
diff --git a/backend/internal/container/resource_stats_test.go b/backend/internal/container/resource_stats_test.go
new file mode 100644
index 000000000..94497574d
--- /dev/null
+++ b/backend/internal/container/resource_stats_test.go
@@ -0,0 +1,420 @@
+package container
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/docker"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ containertypes "github.com/getarcaneapp/arcane/types/v2/container"
+ "github.com/moby/moby/api/types/container"
+ "github.com/stretchr/testify/require"
+)
+
+type resourceStatsServerInternal struct {
+ mu sync.Mutex
+ containers []container.Summary
+ stats map[string]container.StatsResponse
+ statsStatus map[string]int
+ statsCalls map[string]int
+ delay time.Duration
+ slowIDs map[string]bool
+
+ current atomic.Int32
+ maxSeen atomic.Int32
+}
+
+func newResourceStatsServerInternal() *resourceStatsServerInternal {
+ return &resourceStatsServerInternal{
+ stats: map[string]container.StatsResponse{},
+ statsStatus: map[string]int{},
+ statsCalls: map[string]int{},
+ slowIDs: map[string]bool{},
+ }
+}
+
+func (f *resourceStatsServerInternal) addContainer(id, name, state string, labels ...map[string]string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var l map[string]string
+ if len(labels) > 0 {
+ l = labels[0]
+ }
+ f.containers = append(f.containers, container.Summary{ID: id, Names: []string{"/" + name}, State: container.ContainerState(state), Image: "img:latest", Labels: l})
+}
+
+func (f *resourceStatsServerInternal) setStats(id string, cpuPercent float64, memoryUsage, memoryLimit uint64) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ // cpuPercent maps to cpuDelta/systemDelta*100 with a fixed systemDelta of 1000.
+ f.stats[id] = container.StatsResponse{
+ CPUStats: container.CPUStats{
+ CPUUsage: container.CPUUsage{TotalUsage: uint64(1000 + cpuPercent*10)},
+ SystemUsage: 2000,
+ },
+ PreCPUStats: container.CPUStats{
+ CPUUsage: container.CPUUsage{TotalUsage: 1000},
+ SystemUsage: 1000,
+ },
+ MemoryStats: container.MemoryStats{
+ Usage: memoryUsage,
+ Limit: memoryLimit,
+ },
+ Read: time.Now(),
+ }
+}
+
+func (f *resourceStatsServerInternal) callsFor(id string) int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.statsCalls[id]
+}
+
+func (f *resourceStatsServerInternal) handler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ path := dockerTestPathInternal(r.URL.Path)
+ switch {
+ case path == "/containers/json":
+ f.mu.Lock()
+ list := append([]container.Summary{}, f.containers...)
+ f.mu.Unlock()
+ _ = json.NewEncoder(w).Encode(list)
+ case strings.HasPrefix(path, "/containers/") && strings.HasSuffix(path, "/stats"):
+ id := strings.TrimSuffix(strings.TrimPrefix(path, "/containers/"), "/stats")
+ cur := f.current.Add(1)
+ for {
+ seen := f.maxSeen.Load()
+ if cur <= seen || f.maxSeen.CompareAndSwap(seen, cur) {
+ break
+ }
+ }
+ defer f.current.Add(-1)
+
+ f.mu.Lock()
+ f.statsCalls[id]++
+ stats, hasStats := f.stats[id]
+ status, hasStatus := f.statsStatus[id]
+ delay := f.delay
+ slow := f.slowIDs[id]
+ f.mu.Unlock()
+
+ wait := delay
+ if slow {
+ wait = time.Second
+ }
+ if wait > 0 {
+ select {
+ case <-time.After(wait):
+ case <-r.Context().Done():
+ return
+ }
+ }
+ if hasStatus {
+ w.WriteHeader(status)
+ return
+ }
+ if !hasStats {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(stats)
+ default:
+ http.NotFound(w, r)
+ }
+ })
+}
+
+func newResourceSortServiceInternal(t *testing.T, fixture *resourceStatsServerInternal) *ContainerService {
+ t.Helper()
+ server := httptest.NewServer(fixture.handler())
+ t.Cleanup(server.Close)
+
+ return NewContainerService(
+ nil,
+ docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClientInternal(t, server)),
+ nil,
+ nil,
+ nil,
+ )
+}
+
+func resourceSortParamsInternal(sort, order string, start, limit int) pagination.QueryParams {
+ return pagination.QueryParams{
+ SortParams: pagination.SortParams{Sort: sort, Order: pagination.SortOrder(order)},
+ Params: pagination.Params{Start: start, Limit: limit},
+ Filters: map[string]string{},
+ }
+}
+
+func summaryIDsInternal(items []containertypes.Summary) []string {
+ ids := make([]string, 0, len(items))
+ for _, item := range items {
+ ids = append(ids, item.ID)
+ }
+ return ids
+}
+
+func listResourceSortedInternal(t *testing.T, svc *ContainerService, params pagination.QueryParams) ContainerListResult {
+ t.Helper()
+ result, err := svc.ListContainersPaginated(t.Context(), params, true, true, true, "")
+ require.NoError(t, err)
+ return result
+}
+
+func TestResourceSortRanksMemoryByBytesNotPercent(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ // high-percent: 800 of 1000 bytes (80%); high-bytes: 900 of 10000 (9%).
+ fixture.addContainer("high-percent", "high-percent", "running")
+ fixture.setStats("high-percent", 10, 800, 1000)
+ fixture.addContainer("high-bytes", "high-bytes", "running")
+ fixture.setStats("high-bytes", 10, 900, 10000)
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ result := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20))
+ require.Equal(t, []string{"high-bytes", "high-percent"}, summaryIDsInternal(result.Items))
+
+ result = listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "asc", 0, 20))
+ require.Equal(t, []string{"high-percent", "high-bytes"}, summaryIDsInternal(result.Items))
+}
+
+func TestResourceSortOrdersAcrossPages(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ memoryByID := map[string]uint64{"c1": 100, "c2": 200, "c3": 300, "c4": 400, "c5": 500}
+ for id, memory := range memoryByID {
+ fixture.addContainer(id, id, "running")
+ fixture.setStats(id, 0, memory, 10000)
+ }
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ tests := []struct {
+ name string
+ order string
+ start int
+ want []string
+ }{
+ {name: "desc page 1", order: "desc", start: 0, want: []string{"c5", "c4"}},
+ {name: "desc page 2", order: "desc", start: 2, want: []string{"c3", "c2"}},
+ {name: "desc page 3", order: "desc", start: 4, want: []string{"c1"}},
+ {name: "asc page 1", order: "asc", start: 0, want: []string{"c1", "c2"}},
+ {name: "asc page 2", order: "asc", start: 2, want: []string{"c3", "c4"}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, tt.order, tt.start, 2))
+ require.Equal(t, tt.want, summaryIDsInternal(result.Items))
+ require.Equal(t, int64(5), result.Pagination.TotalItems)
+ })
+ }
+}
+
+func TestResourceSortOrdersByCPUPercent(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("busy", "busy", "running")
+ fixture.setStats("busy", 90, 100, 1000)
+ fixture.addContainer("idle", "idle", "running")
+ fixture.setStats("idle", 5, 100, 1000)
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ result := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortCPUUsage, "desc", 0, 20))
+ require.Equal(t, []string{"busy", "idle"}, summaryIDsInternal(result.Items))
+ require.InDelta(t, 90, result.Items[0].ResourceSample.CPUPercent, 0.2)
+ require.InDelta(t, 5, result.Items[1].ResourceSample.CPUPercent, 0.2)
+}
+
+func TestResourceSortAppliesSearchAndFiltersBeforeCollectingStats(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("web", "web", "running", map[string]string{"team": "backend"})
+ fixture.setStats("web", 10, 100, 1000)
+ fixture.addContainer("db", "db", "running")
+ fixture.setStats("db", 20, 200, 1000)
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ params := resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20)
+ params.Search = "web"
+ result := listResourceSortedInternal(t, svc, params)
+ require.Equal(t, []string{"web"}, summaryIDsInternal(result.Items))
+ require.Equal(t, 1, fixture.callsFor("web"))
+ require.Equal(t, 0, fixture.callsFor("db"), "filtered-out containers must not trigger stats collection")
+
+ params = resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20)
+ params.Filters["label"] = "team=backend"
+ result = listResourceSortedInternal(t, svc, params)
+ require.Equal(t, []string{"web"}, summaryIDsInternal(result.Items))
+ require.Equal(t, 0, fixture.callsFor("db"))
+}
+
+func TestResourceSortHandlesZeroUnavailableStoppedAndTies(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("zero", "zero", "running")
+ fixture.setStats("zero", 0, 0, 1000)
+ fixture.addContainer("tie-b", "alpha", "running")
+ fixture.setStats("tie-b", 0, 100, 1000)
+ fixture.addContainer("tie-a", "alpha", "running")
+ fixture.setStats("tie-a", 0, 100, 1000)
+ fixture.addContainer("broken", "broken", "running")
+ fixture.statsStatus["broken"] = http.StatusInternalServerError
+ fixture.addContainer("stopped", "stopped", "exited")
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ asc := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "asc", 0, 20))
+ require.Equal(t, []string{"zero", "tie-a", "tie-b", "broken", "stopped"}, summaryIDsInternal(asc.Items),
+ "zeros first, unavailable and stopped last, ties by name then ID")
+ require.NotNil(t, asc.Items[0].ResourceSample, "zero usage is a valid sample, not unavailable")
+ require.Nil(t, asc.Items[3].ResourceSample)
+ require.Nil(t, asc.Items[4].ResourceSample)
+
+ desc := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20))
+ require.Equal(t, []string{"tie-a", "tie-b", "zero", "broken", "stopped"}, summaryIDsInternal(desc.Items),
+ "unavailable stays last in descending order too")
+
+ require.Equal(t, 0, fixture.callsFor("stopped"), "stopped containers must not trigger stats collection")
+}
+
+func TestResourceSortCachesSamples(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("web", "web", "running")
+ fixture.setStats("web", 10, 100, 1000)
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ for range 2 {
+ listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20))
+ }
+ require.Equal(t, 1, fixture.callsFor("web"), "second list within the TTL must reuse the cached sample")
+}
+
+func TestResourceSortCacheExpires(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("web", "web", "running")
+ fixture.setStats("web", 10, 100, 1000)
+ svc := newResourceSortServiceInternal(t, fixture)
+ svc.resourceSampleCache = newResourceSampleCacheInternal(50 * time.Millisecond)
+
+ listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20))
+ time.Sleep(100 * time.Millisecond)
+ listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20))
+ require.Equal(t, 2, fixture.callsFor("web"), "expired entries must be refetched")
+}
+
+func TestResourceSortCoalescesConcurrentFetches(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("web", "web", "running")
+ fixture.setStats("web", 10, 100, 1000)
+ fixture.delay = 100 * time.Millisecond
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ const callers = 8
+ var wg sync.WaitGroup
+ errs := make([]error, callers)
+ for i := range callers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, err := svc.fetchResourceSampleInternal(t.Context(), "web")
+ errs[i] = err
+ }()
+ }
+ wg.Wait()
+ for _, err := range errs {
+ require.NoError(t, err)
+ }
+ require.Equal(t, 1, fixture.callsFor("web"), "concurrent fetches for the same container must coalesce")
+}
+
+func TestResourceSortBoundsCollectionConcurrency(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.delay = 50 * time.Millisecond
+ for i := range 32 {
+ id := fmt.Sprintf("c%02d", i)
+ fixture.addContainer(id, id, "running")
+ fixture.setStats(id, 0, uint64(i), 10000)
+ }
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ result := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 40))
+ require.Len(t, result.Items, 32)
+ require.LessOrEqual(t, fixture.maxSeen.Load(), int32(containerResourceCollectConcurrency))
+}
+
+func TestResourceSortBatchTimeoutFailsRequest(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("slow", "slow", "running")
+ fixture.setStats("slow", 10, 100, 1000)
+ fixture.delay = time.Second
+ svc := newResourceSortServiceInternal(t, fixture)
+ svc.resourceBatchTimeout = 50 * time.Millisecond
+
+ _, err := svc.ListContainersPaginated(t.Context(), resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20), true, true, true, "")
+ require.Error(t, err, "batch timeout must fail the refresh instead of presenting a partial sort")
+}
+
+func TestResourceSortPerContainerTimeoutMarksUnavailable(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("fast", "fast", "running")
+ fixture.setStats("fast", 10, 100, 1000)
+ fixture.addContainer("slow", "slow", "running")
+ fixture.setStats("slow", 10, 200, 1000)
+ fixture.slowIDs["slow"] = true
+ svc := newResourceSortServiceInternal(t, fixture)
+ svc.resourceSampleTimeout = 50 * time.Millisecond
+
+ result := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20))
+ require.Equal(t, []string{"fast", "slow"}, summaryIDsInternal(result.Items))
+ require.NotNil(t, result.Items[0].ResourceSample)
+ require.Nil(t, result.Items[1].ResourceSample, "per-container timeout leaves the sample unavailable")
+}
+
+func TestResourceSortCancelledContextFailsRequest(t *testing.T) {
+ fixture := newResourceStatsServerInternal()
+ fixture.addContainer("web", "web", "running")
+ fixture.setStats("web", 10, 100, 1000)
+ fixture.delay = time.Second
+ svc := newResourceSortServiceInternal(t, fixture)
+
+ ctx, cancel := context.WithCancel(t.Context())
+ go func() {
+ time.Sleep(50 * time.Millisecond)
+ cancel()
+ }()
+
+ _, err := svc.ListContainersPaginated(ctx, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20), true, true, true, "")
+ require.Error(t, err)
+}
+
+func TestResourceSortPermissionCheck(t *testing.T) {
+ listOnly := authz.NewPermissionSet()
+ listOnly.AddEnv("env-1", authz.PermContainersList)
+ full := authz.NewPermissionSet()
+ full.AddEnv("env-1", authz.PermContainersList, authz.PermContainersRead)
+
+ require.True(t, containerResourceSortPermissionDeniedInternal(listOnly, "env-1", containertypes.SortCPUUsage))
+ require.True(t, containerResourceSortPermissionDeniedInternal(listOnly, "env-1", containertypes.SortMemoryUsage))
+ require.False(t, containerResourceSortPermissionDeniedInternal(full, "env-1", containertypes.SortMemoryUsage))
+ require.False(t, containerResourceSortPermissionDeniedInternal(listOnly, "env-1", "name"),
+ "non-resource sorts keep the endpoint's containers:list requirement")
+ require.False(t, containerResourceSortPermissionDeniedInternal(authz.SudoPermissionSet(), "env-1", containertypes.SortCPUUsage))
+}
+
+func TestResourceSortComparatorKeepsUnavailableLast(t *testing.T) {
+ asc := containerResourceSampleSortInternal(containertypes.SortMemoryUsage, false)
+ desc := containerResourceSampleSortInternal(containertypes.SortMemoryUsage, true)
+ sampled := containertypes.Summary{ID: "b", Names: []string{"b"}, ResourceSample: &containertypes.ResourceSample{MemoryUsageBytes: 1}}
+ unsampled := containertypes.Summary{ID: "a", Names: []string{"a"}}
+
+ require.Equal(t, 1, asc(unsampled, sampled))
+ require.Equal(t, -1, asc(sampled, unsampled))
+ require.Equal(t, 1, desc(unsampled, sampled))
+ require.Equal(t, -1, desc(sampled, unsampled))
+
+ zero := containertypes.Summary{ID: "z", Names: []string{"z"}, ResourceSample: &containertypes.ResourceSample{MemoryUsageBytes: 0}}
+ require.Equal(t, -1, asc(zero, unsampled), "zero is a valid value, not unavailable")
+ require.Equal(t, -1, asc(zero, sampled))
+}
diff --git a/backend/internal/container/service.go b/backend/internal/container/service.go
index 89301a097..f5cbc8c9f 100644
--- a/backend/internal/container/service.go
+++ b/backend/internal/container/service.go
@@ -45,16 +45,21 @@ import (
"go.getarcane.app/updater"
"go.getarcane.app/updater/labels"
"go.getarcane.app/updater/pkg/utils/tagpolicy"
+ "golang.org/x/sync/singleflight"
)
type ContainerService struct {
- dockerService *docker.DockerClientService
- eventService *event.EventService
- imageService *image.ImageService
- settingsService *settings.SettingsService
- projectService *project.ProjectService
- statsHistory containerstats.Store
- iconMetaCache *hot.HotCache[string, projects.ArcaneComposeMetadata]
+ dockerService *docker.DockerClientService
+ eventService *event.EventService
+ imageService *image.ImageService
+ settingsService *settings.SettingsService
+ projectService *project.ProjectService
+ statsHistory containerstats.Store
+ iconMetaCache *hot.HotCache[string, projects.ArcaneComposeMetadata]
+ resourceSampleCache *hot.HotCache[string, containertypes.ResourceSample]
+ resourceSampleFlight singleflight.Group
+ resourceSampleTimeout time.Duration
+ resourceBatchTimeout time.Duration
}
const (
@@ -81,6 +86,9 @@ func NewContainerService(eventService *event.EventService, dockerService *docker
WithTTL(containerIconMetadataTTL).
WithJanitor().
Build(),
+ resourceSampleCache: newResourceSampleCacheInternal(containerResourceSampleTTL),
+ resourceSampleTimeout: containerResourceCollectTimeout,
+ resourceBatchTimeout: timeouts.DefaultDockerAPI,
}
}
@@ -1441,6 +1449,10 @@ func (s *ContainerService) ListContainersPaginated(
}, nil
}
+ if isContainerResourceSortRequestInternal(params, groupBy) {
+ return s.listContainersByResourceInternal(ctx, config, items, counts, params)
+ }
+
result := config.SearchOrderAndPaginate(items, params)
s.ApplySummaryIcons(ctx, result.Items, nil)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
@@ -1778,9 +1790,25 @@ func (s *ContainerService) buildContainerSortBindings() []pagination.SortBinding
return 0
},
},
+ {
+ Key: containertypes.SortCPUUsage,
+ Fn: containerResourceSampleSortInternal(containertypes.SortCPUUsage, false),
+ DescFn: containerResourceSampleSortInternal(containertypes.SortCPUUsage, true),
+ },
+ {
+ Key: containertypes.SortMemoryUsage,
+ Fn: containerResourceSampleSortInternal(containertypes.SortMemoryUsage, false),
+ DescFn: containerResourceSampleSortInternal(containertypes.SortMemoryUsage, true),
+ },
}
}
+// isContainerResourceSortRequestInternal limits resource sorting to the
+// ungrouped list: project-grouped mode keeps the existing group pagination.
+func isContainerResourceSortRequestInternal(params pagination.QueryParams, groupBy string) bool {
+ return groupBy != containerGroupByProject && containertypes.IsResourceSort(params.Sort)
+}
+
func compareContainerPortsForSortInternal(a, b containertypes.Summary) int {
hasPortsA, portA := lowestContainerPortSortValueInternal(a.Ports)
hasPortsB, portB := lowestContainerPortSortValueInternal(b.Ports)
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index eadea9882..5d627a933 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -24,6 +24,7 @@ import (
wsutil "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
+ containertypes "github.com/getarcaneapp/arcane/types/v2/container"
"github.com/getarcaneapp/arcane/types/v2/gitops"
volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/labstack/echo/v5"
@@ -273,6 +274,7 @@ func (m *EnvironmentMiddleware) proxyPermissionDenied(c *echo.Context, ps *authz
"path", suffix, "environment_id", envID, "error", err)
return true
}
+ required = withContainerResourceSortPermissionsInternal(required, c.Request(), method, suffix)
for _, operationPermission := range required {
if !ps.Allows(operationPermission, envID) {
slog.DebugContext(c.Request().Context(), "Denying proxied request: body-derived permission denied",
@@ -424,6 +426,18 @@ func proxiedGitOpsSyncPermissionsInternal(request *http.Request, method, suffix
return required, nil
}
+// withContainerResourceSortPermissionsInternal adds containers:read for
+// resource-sorted container lists, which collect per-container stats.
+func withContainerResourceSortPermissionsInternal(required []string, request *http.Request, method, suffix string) []string {
+ if request == nil || method != http.MethodGet || strings.Trim(suffix, "/") != "containers" {
+ return required
+ }
+ if containertypes.IsResourceSort(request.URL.Query().Get("sort")) {
+ return append(required, authz.PermContainersRead)
+ }
+ return required
+}
+
type proxiedReplayBodyInternal struct {
io.Reader
diff --git a/backend/internal/middleware/environment_middleware_authz_test.go b/backend/internal/middleware/environment_middleware_authz_test.go
index 7f2e6e3df..7b5b8e737 100644
--- a/backend/internal/middleware/environment_middleware_authz_test.go
+++ b/backend/internal/middleware/environment_middleware_authz_test.go
@@ -239,3 +239,30 @@ func TestProxyPermissionDeniedWSTerminalRequiresExec(t *testing.T) {
"expected WS terminal to be allowed with containers:exec")
}
+
+func TestProxyPermissionDeniedResourceSortRequiresRead(t *testing.T) {
+ m := newProxyAuthzMiddleware(containerMatcher())
+
+ listOnly := authz.NewPermissionSet()
+ listOnly.AddEnv(proxyTestEnvID, authz.PermContainersList)
+
+ for _, sort := range []string{"cpuUsage", "memoryUsage"} {
+ c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/containers?sort="+sort)
+ require.True(t, m.proxyPermissionDenied(c, listOnly, proxyTestEnvID),
+ "expected resource sort %q to be denied with only containers:list", sort)
+ }
+
+ c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/containers?sort=name")
+ require.False(t, m.proxyPermissionDenied(c, listOnly, proxyTestEnvID),
+ "expected non-resource sorts to stay allowed with containers:list")
+
+ c = newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/containers")
+ require.False(t, m.proxyPermissionDenied(c, listOnly, proxyTestEnvID),
+ "expected the plain list to stay allowed with containers:list")
+
+ withRead := authz.NewPermissionSet()
+ withRead.AddEnv(proxyTestEnvID, authz.PermContainersList, authz.PermContainersRead)
+ c = newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/containers?sort=memoryUsage&order=desc")
+ require.False(t, m.proxyPermissionDenied(c, withRead, proxyTestEnvID),
+ "expected resource sort to be allowed with containers:list and containers:read")
+}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 6854451af..17b6cd528 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -594,6 +594,8 @@
"containers_check_updates": "Update Containers",
"containers_check_updates_failed": "Failed to Check Containers for Updates",
"containers_check_updates_success": "Containers Updated Successfully.",
+ "containers_resource_sort_unsupported": "Sorting by CPU or memory usage needs a newer agent for this environment. Update the agent to sort by live resource usage.",
+ "containers_resource_refresh_failed": "Automatic refresh failed: {message}",
"update_container": "Update Container",
"standalone_containers": "Standalone containers",
"wrap_text": "Wrap text",
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelte
index 32283b546..1b4e2c362 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte
@@ -687,6 +687,11 @@
let lastPersistedSettings: string | null = null;
let persistTimeout: ReturnType<typeof setTimeout> | undefined;
+ export function persistSort(sort: SortState | undefined) {
+ if (!enablePersist || !prefs) return;
+ prefs.current = { ...prefs.current, s: encodeSort(sort) };
+ }
+
export function persistCustomSettings(settings: Record<string, unknown>) {
if (!preferencesReady || !prefs) return;
const settingsJson = JSON.stringify(settings);
diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.ts
index fd81ca7d2..a912693d6 100644
--- a/frontend/src/lib/services/container-service.ts
+++ b/frontend/src/lib/services/container-service.ts
@@ -18,6 +18,7 @@ import { tryCatch } from '#lib/utils/try-catch.js';
export type ContainersPaginatedResponse = Paginated<ContainerSummaryDto, ContainerStatusCounts> & {
groups?: ContainerSummaryGroupDto[];
+ resourceSortSupported?: boolean;
};
export type ContainerListRequestOptions = SearchPaginationSortRequest & {
groupByProject?: boolean;
diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.ts
index 2f9e604f5..bf2144cea 100644
--- a/frontend/src/lib/types/docker.ts
+++ b/frontend/src/lib/types/docker.ts
@@ -167,6 +167,13 @@ export interface ContainerEditConfigDto {
running: boolean;
}
+export interface ContainerResourceSample {
+ cpuPercent: number;
+ memoryUsageBytes: number;
+ memoryLimitBytes: number;
+ sampleTime: string;
+}
+
export interface ContainerSummaryDto extends BaseContainer {
updateStrategy?: string;
ports: ContainerPorts[];
@@ -176,6 +183,7 @@ export interface ContainerSummaryDto extends BaseContainer {
updateInfo?: ImageUpdateInfoDto;
redeployDisabled?: boolean;
hidden?: boolean;
+ resourceSample?: ContainerResourceSample | null;
}
export interface ContainerSummaryGroupDto {
diff --git a/frontend/src/routes/(app)/containers/components/container-resource-poller.svelte.ts b/frontend/src/routes/(app)/containers/components/container-resource-poller.svelte.ts
new file mode 100644
index 000000000..5d9f13882
--- /dev/null
+++ b/frontend/src/routes/(app)/containers/components/container-resource-poller.svelte.ts
@@ -0,0 +1,59 @@
+import { extractApiErrorMessage } from '#lib/utils/api.js';
+
+/**
+ * Owns the periodic refresh used while the table is sorted by live CPU or memory.
+ * Polling pauses while the tab is hidden and resumes on the next visibility change.
+ */
+export class ContainerResourcePoller {
+ error = $state<string | null>(null);
+
+ private timer: ReturnType<typeof setTimeout> | null = null;
+ private generation = 0;
+ private refresh: (() => Promise<unknown>) | null = null;
+ private readonly resume = () => {
+ if (!this.refresh || document.hidden) return;
+ this.clearTimer();
+ void this.poll(this.generation);
+ };
+
+ constructor(private readonly intervalMs: number) {}
+
+ start(refresh: () => Promise<unknown>): void {
+ this.stop();
+ this.refresh = refresh;
+ this.generation += 1;
+ this.timer = setTimeout(() => this.poll(this.generation), this.intervalMs);
+ document.addEventListener('visibilitychange', this.resume);
+ }
+
+ stop(): void {
+ if (!this.refresh) return;
+ this.refresh = null;
+ this.generation += 1;
+ this.clearTimer();
+ document.removeEventListener('visibilitychange', this.resume);
+ }
+
+ private clearTimer(): void {
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = null;
+ }
+
+ private async poll(generation: number): Promise<void> {
+ const refresh = this.refresh;
+ if (!refresh || generation !== this.generation) return;
+ if (document.hidden) {
+ this.timer = setTimeout(() => this.poll(generation), this.intervalMs);
+ return;
+ }
+ try {
+ await refresh();
+ if (generation === this.generation) this.error = null;
+ } catch (err) {
+ if (generation === this.generation) this.error = extractApiErrorMessage(err);
+ }
+ if (generation === this.generation) {
+ this.timer = setTimeout(() => this.poll(generation), this.intervalMs);
+ }
+ }
+}
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 4c792b539..6fdde614c 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -12,6 +12,7 @@
import { formatDateTimeShort, truncateImageDigest } from '#lib/utils/formatting.js';
import type { ContainerSummaryDto } from '#lib/types/docker.js';
import type { ColumnSpec, BulkAction } from '#lib/components/arcane-table/index.js';
+ import type { SortState } from '#lib/components/arcane-table/arcane-table.types.svelte';
import { m } from '#lib/paraglide/messages.js';
import { PortBadge } from '#lib/components/badges/index.js';
import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
@@ -28,8 +29,10 @@
import { ContainerStatsManager } from './components/container-stats-manager.svelte';
import ContainerStatsSync from './components/container-stats-sync.svelte';
import ContainerStatsCell from './components/container-stats-cell.svelte';
+ import { ContainerResourcePoller } from './components/container-resource-poller.svelte';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { hasPermission } from '#lib/utils/auth.js';
+ import * as Alert from '#lib/components/ui/alert/index.js';
import IconImage from '#lib/components/icon-image.svelte';
import { COMPOSE_PROJECT_LABEL, getContainerIpAddresses, getThemedIconUrl, parseImageRef } from '#lib/utils/docker.js';
import { hasAnyLoadingState } from '#lib/utils/bulk-actions.js';
@@ -60,7 +63,9 @@
RedeployIcon,
PauseIcon,
PlayIcon,
- ZapIcon
+ ZapIcon,
+ AlertTriangleIcon,
+ InfoIcon
} from '#lib/icons/index.js';
import KillContainerDialog from './components/kill-container-dialog.svelte';
@@ -97,6 +102,20 @@
const statsManager = new ContainerStatsManager();
+ const resourceSortSupported = $derived(containers.resourceSortSupported === true);
+ const resourceSortActive = $derived.by(() => {
+ if (groupByProject || !resourceSortSupported) return false;
+ return isResourceSort(requestOptions?.sort);
+ });
+
+ const resourceRefreshIntervalMs = 5000;
+ const resourcePoller = new ContainerResourcePoller(resourceRefreshIntervalMs);
+ const defaultSort: SortState = { column: 'created', direction: 'desc' };
+
+ function isResourceSort(sort: SearchPaginationSortRequest['sort']): boolean {
+ return sort?.column === 'cpuUsage' || sort?.column === 'memoryUsage';
+ }
+
function buildGroupedRequest(options: SearchPaginationSortRequest, grouped = groupByProject): ContainerListRequestOptions {
return {
...options,
@@ -104,14 +123,39 @@
};
}
+ async function fetchContainers(request: ContainerListRequestOptions): Promise<ContainersPaginatedResponse> {
+ return onRefreshData ? onRefreshData(request) : containerService.getContainers(request);
+ }
+
+ // Refreshes can overlap: a resource poll may still be in flight when the user changes
+ // the page or a filter, or when the parent refreshes the bound data itself. The
+ // generation orders requests started here; the identity check catches any other
+ // writer. Only a request that is newest on both counts may write table state.
+ let refreshGeneration = 0;
+
async function refreshContainers(options: SearchPaginationSortRequest, grouped = groupByProject) {
- const request = buildGroupedRequest(options, grouped);
- if (onRefreshData) {
- const result = await onRefreshData(request);
- containers = result;
- return result;
+ const generation = ++refreshGeneration;
+ const seen = containers;
+ const superseded = () => generation !== refreshGeneration || containers !== seen;
+ let request = buildGroupedRequest(options, grouped);
+ let result = await fetchContainers(request);
+ if (superseded()) return containers;
+
+ // Older agents cannot order by live CPU or memory and silently fall back to a name
+ // sort. Replace a persisted resource sort with the default so the request, the
+ // persisted preference, and the rendered order agree.
+ if (result.resourceSortSupported !== true && isResourceSort(request.sort)) {
+ request = { ...request, sort: defaultSort, pagination: { page: 1, limit: getCurrentLimit() } };
+ tablePreferences?.persistSort(defaultSort);
+ requestOptions = {
+ ...options,
+ sort: request.sort,
+ pagination: request.pagination
+ };
+ result = await fetchContainers(request);
+ if (superseded()) return containers;
}
- const result = await containerService.getContainers(request);
+
containers = result;
return result;
}
@@ -167,6 +211,7 @@
let mobileFieldVisibility = $state<Record<string, boolean>>({});
let tablePreferences = $state<{
persistCustomSettings(settings: Record<string, unknown>): void;
+ persistSort(sort: SortState | undefined): void;
}>();
let customSettings = $state<Record<string, unknown>>({});
let showInternal = $derived.by(() => {
@@ -187,7 +232,7 @@
);
const shouldConnect = $derived.by(() => {
- if (!resourcesCurrent) {
+ if (!resourcesCurrent || resourceSortActive) {
return new Set<string>();
}
const cpuVisible = columnVisibility['cpuUsage'] !== false;
@@ -204,6 +249,14 @@
const currentEnvId = $derived(environmentStore.selected?.id || '0');
const resourcesCurrent = $derived(environmentId === currentEnvId);
+
+ // Only the on/off state is tracked here. The callback reads requestOptions when
+ // it runs, so pagination or filter changes do not restart the poll cycle.
+ $effect(() => {
+ if (!resourceSortActive || !resourcesCurrent) return;
+ resourcePoller.start(() => refreshContainers(requestOptions));
+ return () => resourcePoller.stop();
+ });
const canUpdateContainers = $derived(hasPermission('containers:autoupdate', currentEnvId));
const canEditContainers = $derived(hasPermission('containers:edit', currentEnvId));
const canStartContainers = $derived(hasPermission('containers:start', currentEnvId));
@@ -331,17 +384,19 @@
cell: UpdatesCell
},
{
- accessorFn: (row) => statsManager.getCPUPercent(row.id) ?? -1,
id: 'cpuUsage',
+ // TanStack only treats accessor columns as sortable, so the sampled value is
+ // exposed even though ordering happens on the server.
+ accessorFn: (row) => row.resourceSample?.cpuPercent ?? null,
title: m.cpu_usage(),
- clientSort: !groupByProject,
+ sortable: !groupByProject && resourceSortSupported,
cell: CPUCell
},
{
- accessorFn: (row) => statsManager.getMemoryPercent(row.id) ?? -1,
id: 'memoryUsage',
+ accessorFn: (row) => row.resourceSample?.memoryUsageBytes ?? null,
title: m.memory_usage(),
- clientSort: !groupByProject,
+ sortable: !groupByProject && resourceSortSupported,
cell: MemoryCell
},
{ accessorKey: 'status', title: m.common_status() },
@@ -521,24 +576,43 @@
{/snippet}
{#snippet CPUCell({ item }: { item: ContainerSummaryDto })}
- <ContainerStatsCell
- value={statsManager.getCPUPercent(item.id)}
- loading={statsManager.isLoading(item.id) ?? false}
- unavailable={statsManager.hasError(item.id)}
- stopped={item.state !== 'running'}
- type="cpu"
- />
+ {#if resourceSortActive}
+ <ContainerStatsCell
+ value={item.resourceSample?.cpuPercent}
+ unavailable={!item.resourceSample}
+ stopped={item.state !== 'running'}
+ type="cpu"
+ />
+ {:else}
+ <ContainerStatsCell
+ value={statsManager.getCPUPercent(item.id)}
+ loading={statsManager.isLoading(item.id) ?? false}
+ unavailable={statsManager.hasError(item.id)}
+ stopped={item.state !== 'running'}
+ type="cpu"
+ />
+ {/if}
{/snippet}
{#snippet MemoryCell({ item }: { item: ContainerSummaryDto })}
- {@const memoryData = statsManager.getMemoryUsage(item.id)}
- <ContainerStatsCell
- value={memoryData?.usage}
- limit={memoryData?.limit}
- unavailable={statsManager.hasError(item.id)}
- stopped={item.state !== 'running'}
- type="memory"
- />
+ {#if resourceSortActive}
+ <ContainerStatsCell
+ value={item.resourceSample?.memoryUsageBytes}
+ limit={item.resourceSample?.memoryLimitBytes}
+ unavailable={!item.resourceSample}
+ stopped={item.state !== 'running'}
+ type="memory"
+ />
+ {:else}
+ {@const memoryData = statsManager.getMemoryUsage(item.id)}
+ <ContainerStatsCell
+ value={memoryData?.usage}
+ limit={memoryData?.limit}
+ unavailable={statsManager.hasError(item.id)}
+ stopped={item.state !== 'running'}
+ type="memory"
+ />
+ {/if}
{/snippet}
{#snippet PortsCell({ item }: { item: ContainerSummaryDto })}
@@ -717,8 +791,12 @@
{
label: m.cpu_usage(),
getValue: (item: ContainerSummaryDto) => {
- const cpu = statsManager.getCPUPercent(item.id);
if (item.state !== 'running') return m.common_na();
+ if (resourceSortActive) {
+ const cpu = item.resourceSample?.cpuPercent;
+ return cpu === undefined ? m.common_unavailable() : `${cpu.toFixed(1)}%`;
+ }
+ const cpu = statsManager.getCPUPercent(item.id);
if (cpu === undefined) return statsManager.hasError(item.id) ? m.common_unavailable() : '...';
return `${cpu.toFixed(1)}%`;
},
@@ -729,8 +807,12 @@
{
label: m.memory_usage(),
getValue: (item: ContainerSummaryDto) => {
- const memData = statsManager.getMemoryUsage(item.id);
if (item.state !== 'running') return m.common_na();
+ if (resourceSortActive) {
+ const usage = item.resourceSample?.memoryUsageBytes;
+ return usage === undefined ? m.common_unavailable() : `${(usage / 1024 / 1024).toFixed(0)} MB`;
+ }
+ const memData = statsManager.getMemoryUsage(item.id);
if (!memData?.usage) return statsManager.hasError(item.id) ? m.common_unavailable() : '...';
return `${(memData.usage / 1024 / 1024).toFixed(0)} MB`;
},
@@ -910,6 +992,20 @@
{/if}
{/snippet}
+{#if !resourceSortSupported && !groupByProject}
+ <Alert.Root class="mb-4">
+ <InfoIcon class="size-4" />
+ <Alert.Title>{m.containers_resource_sort_unsupported()}</Alert.Title>
+ </Alert.Root>
+{/if}
+
+{#if resourceSortActive && resourcePoller.error}
+ <Alert.Root variant="destructive" class="mb-4">
+ <AlertTriangleIcon class="size-4" />
+ <Alert.Title>{m.containers_resource_refresh_failed({ message: resourcePoller.error })}</Alert.Title>
+ </Alert.Root>
+{/if}
+
<ArcaneTable
bind:this={tablePreferences}
persistKey="arcane-container-table"
diff --git a/tests/spec/container-resource-sort.spec.ts b/tests/spec/container-resource-sort.spec.ts
new file mode 100644
index 000000000..487f9ccab
--- /dev/null
+++ b/tests/spec/container-resource-sort.spec.ts
@@ -0,0 +1,318 @@
+import { expect, test, type Page } from '../fixtures/test.fixture';
+
+type MockSample = {
+ cpuPercent: number;
+ memoryUsageBytes: number;
+ memoryLimitBytes: number;
+ sampleTime: string;
+};
+
+type MockContainer = {
+ id: string;
+ names: string[];
+ image: string;
+ imageId: string;
+ command: string;
+ created: number;
+ labels: Record<string, string>;
+ state: string;
+ status: string;
+ ports: [];
+ hostConfig: { networkMode: string };
+ networkSettings: { networks: Record<string, unknown> };
+ mounts: [];
+ resourceSample?: MockSample | null;
+};
+
+const MiB = 1024 * 1024;
+const GiB = 1024 * MiB;
+
+function createSortContainer(
+ id: string,
+ created: number,
+ sample: MockSample | null
+): MockContainer {
+ return {
+ id,
+ names: [`/${id}`],
+ image: 'misc:latest',
+ imageId: `image-${id}`,
+ command: '',
+ created,
+ labels: {},
+ state: 'running',
+ status: 'Up 5 minutes',
+ ports: [],
+ hostConfig: { networkMode: 'default' },
+ networkSettings: { networks: {} },
+ mounts: [],
+ resourceSample: sample
+ };
+}
+
+function sample(
+ cpuPercent: number,
+ memoryUsageBytes: number,
+ memoryLimitBytes: number
+): MockSample {
+ return { cpuPercent, memoryUsageBytes, memoryLimitBytes, sampleTime: new Date().toISOString() };
+}
+
+// Default order is created desc: small, high-percent, big-bytes, broken.
+// Memory-bytes desc: big-bytes (3GiB), high-percent (800MiB), small (100MiB), broken.
+// Memory-percent desc would put high-percent (80%) first: the two orders differ.
+function basicFixtures() {
+ return [
+ createSortContainer('small', 400, sample(5, 100 * MiB, 8 * GiB)),
+ createSortContainer('high-percent', 300, sample(50, 800 * MiB, 1 * GiB)),
+ createSortContainer('big-bytes', 200, sample(10, 3 * GiB, 4 * GiB)),
+ createSortContainer('broken', 100, null)
+ ];
+}
+
+// Twelve fixtures in created-desc order so page size 10 leaves the two
+// heaviest containers off the default first page: they enter it once sorted
+// by memory desc.
+function pagedFixtures() {
+ const items: MockContainer[] = [];
+ for (let i = 0; i < 10; i++) {
+ items.push(createSortContainer(`filler-${i}`, 20 - i, sample(i, (10 + i) * MiB, 8 * GiB)));
+ }
+ items.push(createSortContainer('offpage-heavy2', 2, sample(2, 4 * GiB, 8 * GiB)));
+ items.push(createSortContainer('offpage-heavy', 1, sample(1, 5 * GiB, 8 * GiB)));
+ return items;
+}
+
+type Scenario = {
+ supported: boolean;
+ fixtures: () => MockContainer[];
+ failList?: boolean;
+ requests: string[];
+};
+
+function installContainersMock(page: Page, scenario: Scenario) {
+ return page.context().route('**/containers**', async (route) => {
+ if (route.request().method() !== 'GET') {
+ await route.continue();
+ return;
+ }
+ const url = new URL(route.request().url());
+ if (!/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)) {
+ await route.continue();
+ return;
+ }
+ if (scenario.failList) {
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: false, data: { error: 'daemon exploded' } })
+ });
+ return;
+ }
+
+ scenario.requests.push(url.search);
+ const sort = url.searchParams.get('sort') ?? '';
+ const order = url.searchParams.get('order') ?? 'asc';
+ const start = Number(url.searchParams.get('start') ?? '0');
+ const limit = Number(url.searchParams.get('limit') ?? '20');
+
+ let items = scenario.fixtures();
+ const valueOf = (c: MockContainer) => {
+ if (!c.resourceSample) return null;
+ return sort === 'cpuUsage' ? c.resourceSample.cpuPercent : c.resourceSample.memoryUsageBytes;
+ };
+ if (sort === 'cpuUsage' || sort === 'memoryUsage') {
+ items = [...items].sort((a, b) => {
+ const va = valueOf(a);
+ const vb = valueOf(b);
+ if (va === null && vb === null) return a.id.localeCompare(b.id);
+ if (va === null) return 1;
+ if (vb === null) return -1;
+ if (va === vb) return a.id.localeCompare(b.id);
+ return order === 'desc' ? vb - va : va - vb;
+ });
+ }
+
+ const safeLimit = limit > 0 ? limit : items.length;
+ const pageItems = items.slice(start, start + safeLimit);
+
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: true,
+ data: pageItems,
+ counts: {
+ runningContainers: items.length,
+ stoppedContainers: 0,
+ totalContainers: items.length
+ },
+ pagination: {
+ totalPages: Math.max(1, Math.ceil(items.length / safeLimit)),
+ totalItems: items.length,
+ currentPage: Math.floor(start / safeLimit) + 1,
+ itemsPerPage: safeLimit,
+ grandTotalItems: items.length
+ },
+ ...(scenario.supported ? { resourceSortSupported: true } : {})
+ })
+ });
+ });
+}
+
+async function openContainers(page: Page) {
+ await page.addInitScript(() => {
+ localStorage.removeItem('selectedEnvironmentId');
+ localStorage.removeItem('arcane-container-table');
+ });
+ await page.goto('/containers');
+ await page.waitForLoadState('load');
+ await page.setViewportSize({ width: 1440, height: 900 });
+}
+
+function rowIds(page: Page) {
+ return page
+ .getByRole('row')
+ .filter({ has: page.locator('a[href^="/containers/"]') })
+ .locator('a[href^="/containers/"]')
+ .evaluateAll((els) => els.map((el) => el.getAttribute('href')?.split('/').pop() ?? ''));
+}
+
+async function setPageSize(page: Page, size: string) {
+ // The rows-per-page control is a bits-ui Select trigger, which renders as a plain
+ // button rather than a combobox.
+ await page.locator('[data-slot="select-trigger"]').filter({ visible: true }).first().click();
+ await page.getByRole('option', { name: size, exact: true }).click();
+}
+
+async function sortByHeader(page: Page, name: string, direction: 'asc' | 'desc') {
+ // The sortable header button opens a menu; the direction is chosen from it.
+ await page.getByRole('columnheader', { name, exact: true }).getByRole('button').click();
+ await page
+ .getByRole('menuitem', { name: direction === 'desc' ? 'Desc' : 'Asc', exact: true })
+ .click();
+}
+
+test('memory sort orders globally by bytes and renders matching samples', async ({ page }) => {
+ const scenario: Scenario = { supported: true, fixtures: basicFixtures, requests: [] };
+ await installContainersMock(page, scenario);
+ await openContainers(page);
+
+ await expect(page.getByRole('row').filter({ hasText: 'small' }).first()).toBeVisible();
+
+ await sortByHeader(page, 'Memory Usage', 'desc');
+
+ await expect
+ .poll(() => rowIds(page), { timeout: 10000 })
+ .toEqual(['big-bytes', 'high-percent', 'small', 'broken']);
+
+ const bigBytesRow = page
+ .getByRole('row')
+ .filter({ has: page.getByRole('link', { name: 'big-bytes' }) });
+ await expect(bigBytesRow.getByText('10.0%')).toBeVisible();
+ await expect(bigBytesRow.getByText('3 GB', { exact: true })).toBeVisible();
+
+ const brokenRow = page
+ .getByRole('row')
+ .filter({ has: page.getByRole('link', { name: 'broken' }) });
+ // Both the CPU and memory cells fall back to the unavailable label.
+ await expect(brokenRow.getByText('Unavailable', { exact: true })).toHaveCount(2);
+});
+
+test('sorted refresh pulls off-page containers into the first page', async ({ page }) => {
+ const scenario: Scenario = { supported: true, fixtures: pagedFixtures, requests: [] };
+ await installContainersMock(page, scenario);
+ await openContainers(page);
+
+ await setPageSize(page, '10');
+ await expect
+ .poll(() => rowIds(page), { timeout: 10000 })
+ .toEqual([
+ 'filler-0',
+ 'filler-1',
+ 'filler-2',
+ 'filler-3',
+ 'filler-4',
+ 'filler-5',
+ 'filler-6',
+ 'filler-7',
+ 'filler-8',
+ 'filler-9'
+ ]);
+
+ await sortByHeader(page, 'Memory Usage', 'desc');
+
+ await expect
+ .poll(() => rowIds(page), { timeout: 10000 })
+ .toEqual([
+ 'offpage-heavy',
+ 'offpage-heavy2',
+ 'filler-9',
+ 'filler-8',
+ 'filler-7',
+ 'filler-6',
+ 'filler-5',
+ 'filler-4',
+ 'filler-3',
+ 'filler-2'
+ ]);
+});
+
+test('resource sort polls, suspends in background tabs, and surfaces failures', async ({
+ page
+}) => {
+ test.setTimeout(60000);
+ const scenario: Scenario = { supported: true, fixtures: basicFixtures, requests: [] };
+ await installContainersMock(page, scenario);
+ await openContainers(page);
+
+ await sortByHeader(page, 'CPU Usage', 'desc');
+ await expect
+ .poll(() => rowIds(page), { timeout: 10000 })
+ .toEqual(['high-percent', 'big-bytes', 'small', 'broken']);
+
+ const initialRequests = scenario.requests.filter((q) => q.includes('sort=cpuUsage')).length;
+ await expect
+ .poll(() => scenario.requests.filter((q) => q.includes('sort=cpuUsage')).length, {
+ timeout: 15000
+ })
+ .toBeGreaterThan(initialRequests);
+
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'hidden', { value: true, configurable: true });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ const frozen = scenario.requests.length;
+ await page.waitForTimeout(6500);
+ expect(scenario.requests.length).toBe(frozen);
+
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'hidden', { value: false, configurable: true });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await expect.poll(() => scenario.requests.length, { timeout: 10000 }).toBeGreaterThan(frozen);
+
+ scenario.failList = true;
+ await expect(page.getByText('Automatic refresh failed: daemon exploded')).toBeVisible({
+ timeout: 15000
+ });
+
+ scenario.failList = false;
+ await expect(page.getByText('Automatic refresh failed: daemon exploded')).toBeHidden({
+ timeout: 15000
+ });
+});
+
+test('older agents disable resource sorting with an upgrade explanation', async ({ page }) => {
+ const scenario: Scenario = { supported: false, fixtures: basicFixtures, requests: [] };
+ await installContainersMock(page, scenario);
+ await openContainers(page);
+
+ await expect(page.getByText('needs a newer agent for this environment')).toBeVisible();
+ await expect(
+ page.getByRole('columnheader', { name: 'Memory Usage', exact: true }).getByRole('button')
+ ).toHaveCount(0);
+ await expect(
+ page.getByRole('columnheader', { name: 'CPU Usage', exact: true }).getByRole('button')
+ ).toHaveCount(0);
+});
diff --git a/types/container/container.go b/types/container/container.go
index a32a03395..2b1210fb4 100644
--- a/types/container/container.go
+++ b/types/container/container.go
@@ -790,6 +790,45 @@ type HostConfig struct {
Memory int64 `json:"memory,omitempty"`
}
+// Resource sort keys accepted by the container list endpoint. They are part of
+// the shared API contract: the manager's environment proxy inspects the sort
+// query parameter to enforce the additional containers:read permission before
+// forwarding resource-sorted requests to an agent.
+const (
+ SortCPUUsage = "cpuUsage"
+ SortMemoryUsage = "memoryUsage"
+)
+
+// IsResourceSort reports whether sort is a resource-based sort key.
+func IsResourceSort(sort string) bool {
+ return sort == SortCPUUsage || sort == SortMemoryUsage
+}
+
+// ResourceSample is a point-in-time resource usage sample for a container,
+// returned with resource-sorted list responses so ordering and displayed
+// values come from the same data.
+type ResourceSample struct {
+ // CPUPercent is the normalized CPU usage percentage (0-100 scale).
+ //
+ // Required: true
+ CPUPercent float64 `json:"cpuPercent"`
+
+ // MemoryUsageBytes is the memory usage in bytes.
+ //
+ // Required: true
+ MemoryUsageBytes uint64 `json:"memoryUsageBytes"`
+
+ // MemoryLimitBytes is the memory limit in bytes.
+ //
+ // Required: true
+ MemoryLimitBytes uint64 `json:"memoryLimitBytes"`
+
+ // SampleTime is when the sample was taken.
+ //
+ // Required: true
+ SampleTime time.Time `json:"sampleTime"`
+}
+
// Summary represents a container summary.
type Summary struct {
// ID is the unique identifier of the container.
@@ -884,6 +923,13 @@ type Summary struct {
//
// Required: false
Hidden bool `json:"hidden,omitempty"`
+
+ // ResourceSample holds the resource usage sample collected for a
+ // resource-sorted list request. Nil when the request was not resource-sorted
+ // or the sample was unavailable (stopped container or collection failure).
+ //
+ // Required: false
+ ResourceSample *ResourceSample `json:"resourceSample,omitempty"`
}
// ComposeInfo contains Docker Compose project information extracted from container labels.