Skip to content

Modern Docker Management, Designed for Everyone

refactor: move cgroup logic to go.getarcane.app/sys/cgroup (#3159)

Kyle Mendellc27ce9319790
diff --git a/backend/api/handlers/system.go b/backend/api/handlers/system.go
index f0f4184f4..6cce5b3a9 100644
--- a/backend/api/handlers/system.go
+++ b/backend/api/handlers/system.go
@@ -7,20 +7,21 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ dockersystem "github.com/moby/moby/api/types/system"
+ "github.com/moby/moby/client"
+
humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
- docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/types/v2/base"
containertypes "github.com/getarcaneapp/arcane/types/v2/container"
"github.com/getarcaneapp/arcane/types/v2/dockerinfo"
"github.com/getarcaneapp/arcane/types/v2/system"
- dockersystem "github.com/moby/moby/api/types/system"
- "github.com/moby/moby/client"
+ "go.getarcane.app/sys/cgroup"
updatertypes "go.getarcane.app/updater/types"
)
@@ -353,8 +354,8 @@ func (h *SystemHandler) GetDockerInfo(ctx context.Context, input *GetDockerInfoI
// daemon may report the physical machine's full capacity while the
// LXC guest has a smaller cgroup budget — apply those limits so the
// dashboard shows what Arcane's host actually has available.
- if !docker.IsDockerContainer() {
- if cgroupLimits, err := docker.DetectCgroupLimits(); err == nil {
+ if !cgroup.IsDockerContainer() {
+ if cgroupLimits, err := cgroup.DetectLimits(); err == nil {
if limit := cgroupLimits.MemoryLimit; limit > 0 {
limitInt := limit
if memTotal == 0 || limitInt < memTotal {
diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.go
index aed738bb0..f270b085a 100644
--- a/backend/api/ws/handler.go
+++ b/backend/api/ws/handler.go
@@ -14,21 +14,22 @@ import (
"sync/atomic"
"time"
+ "github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
+ "github.com/shirou/gopsutil/v4/cpu"
+ "github.com/shirou/gopsutil/v4/disk"
+ "github.com/shirou/gopsutil/v4/host"
+ "github.com/shirou/gopsutil/v4/mem"
+
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
- docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/system"
wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"
httputil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
systemtypes "github.com/getarcaneapp/arcane/types/v2/system"
- "github.com/gorilla/websocket"
- "github.com/labstack/echo/v4"
- "github.com/shirou/gopsutil/v4/cpu"
- "github.com/shirou/gopsutil/v4/disk"
- "github.com/shirou/gopsutil/v4/host"
- "github.com/shirou/gopsutil/v4/mem"
+ "go.getarcane.app/sys/cgroup"
)
const cgroupCacheTTL = 30 * time.Second
@@ -74,7 +75,7 @@ type WebSocketHandler struct {
running bool
}
containerStatsHubs sync.Map
- cgroupCache *system.CgroupCache
+ cgroupCache *cgroup.Cache
gpuMonitor *system.GPUMonitor
diskUsagePathCache struct {
@@ -230,7 +231,7 @@ func NewWebSocketHandler(
diagnosticsService: diagnosticsService,
wsMetrics: defaultWebSocketMetrics,
logStreams: make(map[string]*wsLogStream),
- cgroupCache: system.NewCgroupCache(cgroupCacheTTL),
+ cgroupCache: cgroup.NewCache(cgroupCacheTTL),
gpuMonitor: system.NewGPUMonitor(cfg.GPUMonitoringEnabled, cfg.GPUType),
wsUpgrader: websocket.Upgrader{
CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.GetAppURL()),
@@ -1167,7 +1168,7 @@ func (h *WebSocketHandler) getMemoryInfo() (uint64, uint64) {
// MemAvailable). Treat the reclaimable portion as cache, matching
// btop/htop, so the dashboard does not over-report usage on ZFS hosts.
used := memInfo.Used
- if arc := docker.ZFSARCReclaimable(); arc > 0 {
+ if arc := cgroup.ZFSARCReclaimable(); arc > 0 {
used -= min(used, arc)
}
return used, memInfo.Total
@@ -1188,7 +1189,7 @@ func (h *WebSocketHandler) getMemoryInfo() (uint64, uint64) {
// resources actually allocated to the LXC guest. The cgroup limits ARE the
// correct numbers to show.
func (h *WebSocketHandler) applyCgroupLimits(cpuCount int, memUsed, memTotal uint64) (int, uint64, uint64) {
- if docker.IsDockerContainer() {
+ if cgroup.IsDockerContainer() {
return cpuCount, memUsed, memTotal
}
cgroupLimits := h.getCachedCgroupLimitsInternal()
@@ -1296,7 +1297,7 @@ func (h *WebSocketHandler) storeCPUCacheValueInternal(value float64) {
h.cpuCache.Unlock()
}
-func (h *WebSocketHandler) getCachedCgroupLimitsInternal() *docker.CgroupLimits {
+func (h *WebSocketHandler) getCachedCgroupLimitsInternal() *cgroup.Limits {
if h.cgroupCache == nil {
return nil
}
diff --git a/backend/api/ws/handler_test.go b/backend/api/ws/handler_test.go
index a5d743879..a1d05c74c 100644
--- a/backend/api/ws/handler_test.go
+++ b/backend/api/ws/handler_test.go
@@ -12,13 +12,14 @@ import (
"testing"
"time"
- docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/system"
- wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"
- systemtypes "github.com/getarcaneapp/arcane/types/v2/system"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/system"
+ wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"
+ systemtypes "github.com/getarcaneapp/arcane/types/v2/system"
+ "go.getarcane.app/sys/cgroup"
)
func TestBroadcastContainerLogStreamErrorInternal_JSON(t *testing.T) {
@@ -108,7 +109,7 @@ func newTestWebSocketHandler() *WebSocketHandler {
return &WebSocketHandler{
wsMetrics: wshub.NewWebSocketMetrics(),
logStreams: make(map[string]*wsLogStream),
- cgroupCache: system.NewCgroupCache(cgroupCacheTTL),
+ cgroupCache: cgroup.NewCache(cgroupCacheTTL),
gpuMonitor: system.NewGPUMonitor(false, ""),
wsUpgrader: websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
@@ -579,15 +580,15 @@ func TestWebSocketHandler_GetCachedCgroupLimitsInternal_DeduplicatesRefresh(t *t
release := make(chan struct{})
// A fresh cache has a zero timestamp, so the first Get takes the refresh path
// and subsequent concurrent Gets dedupe behind the write lock.
- handler.cgroupCache = system.NewCgroupCacheWithDetector(cgroupCacheTTL, func() (*docker.CgroupLimits, error) {
+ handler.cgroupCache = cgroup.NewCacheWithDetector(cgroupCacheTTL, func() (*cgroup.Limits, error) {
calls.Add(1)
close(start)
<-release
- return &docker.CgroupLimits{CPUCount: 2}, nil
+ return &cgroup.Limits{CPUCount: 2}, nil
})
const goroutines = 8
- results := make(chan *docker.CgroupLimits, goroutines)
+ results := make(chan *cgroup.Limits, goroutines)
ready := make(chan struct{})
var entered sync.WaitGroup
entered.Add(goroutines)
diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.go
index 78a23f14b..bc819d50c 100644
--- a/backend/cli/upgrade/upgrade.go
+++ b/backend/cli/upgrade/upgrade.go
@@ -9,12 +9,14 @@ import (
"strings"
"time"
- docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/client"
"github.com/spf13/cobra"
+
+ docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
+ "go.getarcane.app/sys/cgroup"
updaterlabels "go.getarcane.app/updater/pkg/labels"
updaterlogs "go.getarcane.app/updater/pkg/logs"
)
@@ -127,7 +129,7 @@ func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (cont
return container.InspectResponse{}, err
}
- selfID, _ := docker.GetCurrentContainerID()
+ selfID, _ := cgroup.CurrentContainerID()
slog.Info("Searching for Arcane container", "selfID", selfID, "totalContainers", len(containers.Items))
now := time.Now()
diff --git a/backend/go.mod b/backend/go.mod
index d4e07b8d0..bd4d0419e 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -55,6 +55,7 @@ require (
github.com/wneessen/go-mail v0.7.3
go.getarcane.app/builds v0.1.0
go.getarcane.app/sys/atomic v0.1.0
+ go.getarcane.app/sys/cgroup v0.1.0
go.getarcane.app/updater v0.4.0
go.yaml.in/yaml/v4 v4.0.0-rc.6
golang.org/x/crypto v0.53.0
diff --git a/backend/go.sum b/backend/go.sum
index 7e804a1d1..cf3d48c84 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -539,6 +539,8 @@ go.getarcane.app/builds v0.1.0 h1:BOEFFFI35nQq/jowWs7+Uhi1XNoKIEKmNd7xnassCVg=
go.getarcane.app/builds v0.1.0/go.mod h1:3g7+969+qWH33EXnA+nu5MKhs72JYDPf9Q/OtYO6CIA=
go.getarcane.app/sys/atomic v0.1.0 h1:0HhUeGXYdKAmMW24O+OaqcjDZx6twAuYPBu9T91zKsk=
go.getarcane.app/sys/atomic v0.1.0/go.mod h1:QPb5eUXYKYG5acp9jJBAZ/PTbHbByDAQG6eDNAsZZ2w=
+go.getarcane.app/sys/cgroup v0.1.0 h1:SCAbuU+rZ/EjMU8kkVxmXZsMchiZp9eFdMQFnbU+asA=
+go.getarcane.app/sys/cgroup v0.1.0/go.mod h1:Paj4QOazrTXO/Ivhmvt1E/RjPJFTdKkxRgRDk4qBCUI=
go.getarcane.app/updater v0.4.0 h1:ZVXZ8N/sXDZq7/0VvB8JMwtbwNpGqrswLDjESimL8mw=
go.getarcane.app/updater v0.4.0/go.mod h1:Pqz4cI9nePA6abdZzfESZPxQC5jWVoiWKqcgX+pDkAk=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 1b5805110..a1394f04d 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -14,6 +14,12 @@ import (
"time"
composetypes "github.com/compose-spec/compose-go/v2/types"
+ "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/api/types/events"
+ "github.com/moby/moby/api/types/network"
+ "github.com/moby/moby/client"
+ "golang.org/x/sync/singleflight"
+
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
@@ -28,12 +34,8 @@ import (
containertypes "github.com/getarcaneapp/arcane/types/v2/container"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
- "github.com/moby/moby/api/types/container"
- "github.com/moby/moby/api/types/events"
- "github.com/moby/moby/api/types/network"
- "github.com/moby/moby/client"
+ "go.getarcane.app/sys/cgroup"
libupdater "go.getarcane.app/updater/pkg/labels"
- "golang.org/x/sync/singleflight"
)
type ContainerService struct {
@@ -593,7 +595,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st
wasRunning := containerInfo.State != nil && containerInfo.State.Running
apiVersion := libarcane.DetectDockerAPIVersion(ctx, dockerClient)
- currentContainerID, currentContainerErr := dockerutils.GetCurrentContainerID()
+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
if libupdater.ShouldDisableArcaneServerRedeploy(containerInfo.Config.Labels, containerInfo.ID, currentContainerID, currentContainerErr) {
err = &common.ArcaneSelfRedeployError{}
s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, models.JSON{
@@ -731,7 +733,7 @@ func (s *ContainerService) GetContainerDetails(ctx context.Context, id string) (
}
details := containertypes.NewDetails(containerInspect)
- currentContainerID, currentContainerErr := dockerutils.GetCurrentContainerID()
+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
details.RedeployDisabled = libupdater.ShouldDisableArcaneServerRedeploy(details.Labels, details.ID, currentContainerID, currentContainerErr)
s.applyContainerDetailsIconInternal(ctx, &details)
@@ -997,7 +999,7 @@ func (s *ContainerService) ListContainersPaginated(
dockerContainers = filterInternalContainers(dockerContainers, includeInternal)
imageIDs := collectImageIDs(dockerContainers)
updateInfoMap := s.getUpdateInfoMap(ctx, imageIDs)
- currentContainerID, currentContainerErr := dockerutils.GetCurrentContainerID()
+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
items := s.buildContainerSummaries(dockerContainers, updateInfoMap, currentContainerID, currentContainerErr)
config := s.buildContainerPaginationConfig()
diff --git a/backend/internal/services/dashboard_service.go b/backend/internal/services/dashboard_service.go
index 96e5da859..8df25e26a 100644
--- a/backend/internal/services/dashboard_service.go
+++ b/backend/internal/services/dashboard_service.go
@@ -7,6 +7,9 @@ import (
"sort"
"time"
+ dockercontainer "github.com/moby/moby/api/types/container"
+ "golang.org/x/sync/errgroup"
+
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
@@ -15,9 +18,8 @@ import (
dashboardtypes "github.com/getarcaneapp/arcane/types/v2/dashboard"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
versiontypes "github.com/getarcaneapp/arcane/types/v2/version"
- dockercontainer "github.com/moby/moby/api/types/container"
+ "go.getarcane.app/sys/cgroup"
libupdater "go.getarcane.app/updater/pkg/labels"
- "golang.org/x/sync/errgroup"
)
const defaultDashboardAPIKeyExpiryWindow = 14 * 24 * time.Hour
@@ -78,7 +80,7 @@ func (s *DashboardService) GetSnapshot(ctx context.Context, options DashboardAct
filteredContainers := filterInternalContainers(dockerContainers, false)
containerItems := make([]containertypes.Summary, 0, len(filteredContainers))
- currentContainerID, currentContainerErr := dockerutils.GetCurrentContainerID()
+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
if s.containerService != nil {
containerItems = s.containerService.buildContainerSummaries(filteredContainers, nil, currentContainerID, currentContainerErr)
} else {
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index 17b047db1..2a9b528dc 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -19,6 +19,10 @@ import (
"github.com/compose-spec/compose-go/v2/loader"
composetypes "github.com/compose-spec/compose-go/v2/types"
"github.com/docker/compose/v5/pkg/api"
+ "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/client"
+ "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/database"
@@ -36,11 +40,9 @@ import (
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
"github.com/getarcaneapp/arcane/types/v2/project"
- "github.com/moby/moby/api/types/container"
- "github.com/moby/moby/client"
buildtypes "go.getarcane.app/builds/types"
+ "go.getarcane.app/sys/cgroup"
libupdater "go.getarcane.app/updater/pkg/labels"
- "gorm.io/gorm"
)
type ProjectService struct {
@@ -892,7 +894,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strin
slog.Error("compose ps error", "projectName", composeProject.Name, "error", err)
return nil, fmt.Errorf("failed to get compose services status: %w", err)
}
- currentContainerID, currentContainerErr := dockerutil.GetCurrentContainerID()
+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
have := map[string]bool{}
var services []ProjectServiceInfo
@@ -2354,7 +2356,7 @@ func (s *ProjectService) projectRedeployDisabledInternal(ctx context.Context, pr
containersByProject := groupComposeContainersByProjectInternal(containers)
- currentContainerID, currentContainerErr := dockerutil.GetCurrentContainerID()
+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
for _, container := range lookupProjectContainers(proj, containersByProject) {
if libupdater.ShouldDisableArcaneServerRedeploy(container.Labels, container.ID, currentContainerID, currentContainerErr) {
return true
@@ -4466,7 +4468,7 @@ func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, pro
// 3. Map to DTOs
results := make([]project.Details, len(projectsList))
- currentContainerID, currentContainerErr := dockerutil.GetCurrentContainerID()
+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
for i, p := range projectsList {
results[i] = s.mapProjectToDto(ctx, projectsDir, p, containersByProject, currentContainerID, currentContainerErr)
}
diff --git a/backend/internal/services/system_upgrade_service.go b/backend/internal/services/system_upgrade_service.go
index c4108b6ec..5eadbf2f7 100644
--- a/backend/internal/services/system_upgrade_service.go
+++ b/backend/internal/services/system_upgrade_service.go
@@ -12,6 +12,10 @@ import (
"sync/atomic"
"time"
+ containertypes "github.com/moby/moby/api/types/container"
+ mounttypes "github.com/moby/moby/api/types/mount"
+ "github.com/moby/moby/client"
+
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
@@ -22,9 +26,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/projects"
"github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"
"github.com/getarcaneapp/arcane/types/v2/version"
- containertypes "github.com/moby/moby/api/types/container"
- mounttypes "github.com/moby/moby/api/types/mount"
- "github.com/moby/moby/client"
+ "go.getarcane.app/sys/cgroup"
libupdater "go.getarcane.app/updater/pkg/labels"
updatertypes "go.getarcane.app/updater/types"
)
@@ -197,7 +199,7 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo
return projects.GetHostPathForContainerPath(ctx, dockerClient, containerPath)
},
func() bool {
- _, err := dockerutils.GetCurrentContainerID()
+ _, err := cgroup.CurrentContainerID()
return err == nil
},
)
@@ -345,7 +347,7 @@ func resolveSystemUpgraderRuntimeOptionsInternal(
// getCurrentContainerID detects if we're running in Docker and returns container ID
func (s *SystemUpgradeService) getCurrentContainerIDInternal() (string, error) {
- id, err := dockerutils.GetCurrentContainerID()
+ id, err := cgroup.CurrentContainerID()
if err != nil {
return "", &common.NotRunningInDockerError{}
}
diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.go
index eaf8dd4ee..e3a0ce459 100644
--- a/backend/internal/services/updater_service.go
+++ b/backend/internal/services/updater_service.go
@@ -12,6 +12,9 @@ import (
"time"
"github.com/compose-spec/compose-go/v2/loader"
+ "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/client"
+
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
@@ -21,8 +24,7 @@ import (
projectspkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/types/v2/updater"
- "github.com/moby/moby/api/types/container"
- "github.com/moby/moby/client"
+ "go.getarcane.app/sys/cgroup"
moduleapi "go.getarcane.app/updater/api"
updaterdigest "go.getarcane.app/updater/pkg/digest"
"go.getarcane.app/updater/pkg/labels"
@@ -113,7 +115,7 @@ func (s *UpdaterService) configInternal() moduleapi.Config {
// the updater engine routes it through the CLI self-updater even when the
// container is missing the Arcane labels. Empty when not running in Docker.
func selfContainerIDInternal() string {
- id, err := dockerutil.GetCurrentContainerID()
+ id, err := cgroup.CurrentContainerID()
if err != nil {
return ""
}
diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.go
index f25a1edb5..96e8e6fac 100644
--- a/backend/internal/services/version_service.go
+++ b/backend/internal/services/version_service.go
@@ -11,16 +11,17 @@ import (
"time"
ref "github.com/distribution/reference"
+ containertypes "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/client"
+ "golang.org/x/mod/semver"
+
"github.com/getarcaneapp/arcane/backend/v2/buildables"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
- docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cache"
"github.com/getarcaneapp/arcane/types/v2/version"
- containertypes "github.com/moby/moby/api/types/container"
- "github.com/moby/moby/client"
+ "go.getarcane.app/sys/cgroup"
libupdater "go.getarcane.app/updater/pkg/labels"
- "golang.org/x/mod/semver"
)
const (
@@ -459,7 +460,7 @@ func (s *VersionService) normalizeImageRef(configImage string) string {
// getCurrentContainerID detects if we're running in Docker via cgroup, mountinfo, or hostname
func (s *VersionService) getCurrentContainerID() (string, error) {
- return docker.GetCurrentContainerID()
+ return cgroup.CurrentContainerID()
}
// extractTagFromImageRef extracts the tag from an image reference using distribution/reference
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
index dabc74bbf..a780517d4 100644
--- a/backend/internal/services/vulnerability_service.go
+++ b/backend/internal/services/vulnerability_service.go
@@ -20,6 +20,14 @@ import (
"time"
cerrdefs "github.com/containerd/errdefs"
+ "github.com/moby/moby/api/pkg/stdcopy"
+ containertypes "github.com/moby/moby/api/types/container"
+ imagetypes "github.com/moby/moby/api/types/image"
+ mounttypes "github.com/moby/moby/api/types/mount"
+ "github.com/moby/moby/client"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
@@ -31,14 +39,8 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/projects"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/types/v2/vulnerability"
- "github.com/moby/moby/api/pkg/stdcopy"
- containertypes "github.com/moby/moby/api/types/container"
- imagetypes "github.com/moby/moby/api/types/image"
- mounttypes "github.com/moby/moby/api/types/mount"
- "github.com/moby/moby/client"
+ "go.getarcane.app/sys/cgroup"
libupdater "go.getarcane.app/updater/pkg/labels"
- "gorm.io/gorm"
- "gorm.io/gorm/clause"
)
const (
@@ -1878,7 +1880,7 @@ func (s *VulnerabilityService) inspectCurrentArcaneContainerInternal(
return nil, errors.New("docker client is not available")
}
- if containerID, err := dockerutils.GetCurrentContainerID(); err == nil {
+ if containerID, err := cgroup.CurrentContainerID(); err == nil {
inspect, inspectErr := libarcane.ContainerInspectWithCompatibility(
ctx,
dockerClient,
@@ -1994,7 +1996,7 @@ func (s *VulnerabilityService) resolveTrivyRuntimeOptionsInternal(ctx context.Co
return projects.GetHostPathForContainerPath(ctx, dockerClient, containerPath)
},
func() bool {
- _, err := dockerutils.GetCurrentContainerID()
+ _, err := cgroup.CurrentContainerID()
return err == nil
},
)
diff --git a/backend/pkg/dockerutil/cgroup_utils.go b/backend/pkg/dockerutil/cgroup_utils.go
deleted file mode 100644
index 3d7810210..000000000
--- a/backend/pkg/dockerutil/cgroup_utils.go
+++ /dev/null
@@ -1,488 +0,0 @@
-package docker
-
-import (
- "bufio"
- "errors"
- "fmt"
- "io"
- "log/slog"
- "os"
- "path/filepath"
- "regexp"
- "strconv"
- "strings"
-
- "github.com/shirou/gopsutil/v4/host"
-)
-
-const unrestricted = 9223372036854771712
-
-type CgroupLimits struct {
- MemoryLimit int64
- MemoryUsage int64
- CPUQuota int64
- CPUPeriod int64
- CPUCount int
-}
-
-func DetectCgroupLimits() (*CgroupLimits, error) {
- limits := &CgroupLimits{
- MemoryLimit: -1,
- MemoryUsage: -1,
- CPUQuota: -1,
- CPUPeriod: -1,
- CPUCount: -1,
- }
-
- if !isInCgroup() {
- return nil, errors.New("not running in a cgroup")
- }
-
- if isCgroupV2() {
- return detectCgroupV2Limits(limits)
- }
-
- return detectCgroupV1Limits(limits)
-}
-
-func isInCgroup() bool {
- if info, err := host.Info(); err == nil {
- if info.VirtualizationSystem != "" && strings.EqualFold(info.VirtualizationRole, "guest") {
- return true
- }
- }
-
- return hasExplicitCgroupLimit()
-}
-
-func isCgroupV2() bool {
- _, err := os.Stat("/sys/fs/cgroup/cgroup.controllers")
- return err == nil
-}
-
-func hasExplicitCgroupLimit() bool {
- if isCgroupV2() {
- if limit, err := readCgroupV2Int64("/sys/fs/cgroup/memory.max"); err == nil && isFiniteLimit(limit) {
- return true
- }
-
- if quota, period := readCgroupV2CPU(); quota > 0 && period > 0 {
- return true
- }
-
- return false
- }
-
- cgroupPath, err := getCgroupV1Path()
- if err != nil || cgroupPath == "" {
- return false
- }
-
- memLimitPath := filepath.Join("/sys/fs/cgroup/memory", cgroupPath, "memory.limit_in_bytes")
- if limit, err := readCgroupV1Int64(memLimitPath); err == nil && isFiniteLimit(limit) {
- return true
- }
-
- if quota, err := readCgroupV1CPUControllerInt64(cgroupPath, "cpu.cfs_quota_us"); err == nil && quota > 0 {
- if period, err := readCgroupV1CPUControllerInt64(cgroupPath, "cpu.cfs_period_us"); err == nil && period > 0 {
- return true
- }
- }
-
- return false
-}
-
-func detectCgroupV2Limits(limits *CgroupLimits) (*CgroupLimits, error) {
- if memLimit, err := readCgroupV2Int64("/sys/fs/cgroup/memory.max"); err == nil {
- if memLimit != unrestricted {
- limits.MemoryLimit = memLimit
- }
- }
-
- if memUsage, err := readCgroupV2Int64("/sys/fs/cgroup/memory.current"); err == nil {
- // memory.current includes reclaimable page cache; subtract inactive_file
- // to match what `docker stats` reports as usage.
- if inactiveFile, err := readMemoryStatValue("/sys/fs/cgroup/memory.stat", "inactive_file"); err == nil {
- memUsage = max(memUsage-inactiveFile, 0)
- }
- limits.MemoryUsage = memUsage
- }
-
- if cpuMax, err := os.ReadFile("/sys/fs/cgroup/cpu.max"); err == nil {
- parts := strings.Fields(string(cpuMax))
- if len(parts) >= 2 {
- if parts[0] != "max" {
- if quota, err := strconv.ParseInt(parts[0], 10, 64); err == nil {
- limits.CPUQuota = quota
- }
- }
- if period, err := strconv.ParseInt(parts[1], 10, 64); err == nil {
- limits.CPUPeriod = period
- }
- }
- }
-
- if limits.CPUQuota > 0 && limits.CPUPeriod > 0 {
- limits.CPUCount = max(int((limits.CPUQuota+limits.CPUPeriod-1)/limits.CPUPeriod), 1)
- }
-
- return limits, nil
-}
-
-func detectCgroupV1Limits(limits *CgroupLimits) (*CgroupLimits, error) {
- cgroupPath, err := getCgroupV1Path()
- if err != nil {
- return limits, err
- }
-
- memoryLimitPath := filepath.Join("/sys/fs/cgroup/memory", cgroupPath, "memory.limit_in_bytes")
- if memLimit, err := readCgroupV1Int64(memoryLimitPath); err == nil {
- if memLimit < unrestricted {
- limits.MemoryLimit = memLimit
- }
- }
-
- memoryUsagePath := filepath.Join("/sys/fs/cgroup/memory", cgroupPath, "memory.usage_in_bytes")
- if memUsage, err := readCgroupV1Int64(memoryUsagePath); err == nil {
- // memory.usage_in_bytes includes reclaimable page cache; subtract
- // total_inactive_file (from memory.stat) to match `docker stats`.
- memoryStatPath := filepath.Join("/sys/fs/cgroup/memory", cgroupPath, "memory.stat")
- if inactiveFile, err := readMemoryStatValue(memoryStatPath, "total_inactive_file"); err == nil {
- memUsage = max(memUsage-inactiveFile, 0)
- }
- limits.MemoryUsage = memUsage
- }
-
- if cpuQuota, err := readCgroupV1CPUControllerInt64(cgroupPath, "cpu.cfs_quota_us"); err == nil {
- limits.CPUQuota = cpuQuota
- }
-
- if cpuPeriod, err := readCgroupV1CPUControllerInt64(cgroupPath, "cpu.cfs_period_us"); err == nil {
- limits.CPUPeriod = cpuPeriod
- }
-
- if limits.CPUQuota > 0 && limits.CPUPeriod > 0 {
- limits.CPUCount = max(int((limits.CPUQuota+limits.CPUPeriod-1)/limits.CPUPeriod), 1)
- }
-
- return limits, nil
-}
-
-func getCgroupV1Path() (string, error) {
- file, err := os.Open("/proc/self/cgroup")
- if err != nil {
- return "", err
- }
- defer func() { _ = file.Close() }()
-
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := scanner.Text()
- parts := strings.SplitN(line, ":", 3)
- if len(parts) == 3 {
- if strings.Contains(parts[1], "memory") || strings.Contains(parts[1], "cpu") {
- return strings.TrimPrefix(parts[2], "/"), nil
- }
- }
- }
-
- if err := scanner.Err(); err != nil {
- return "", fmt.Errorf("error scanning cgroup file: %w", err)
- }
-
- return "", errors.New("cgroup path not found")
-}
-
-func readCgroupV1Int64(path string) (int64, error) {
- data, err := os.ReadFile(path)
- if err != nil {
- return 0, err
- }
-
- value, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
- if err != nil {
- return 0, err
- }
-
- return value, nil
-}
-
-// readMemoryStatValue reads a single "key value" line from a cgroup memory.stat
-// file and returns the value for the given key.
-func readMemoryStatValue(path, key string) (int64, error) {
- file, err := os.Open(path)
- if err != nil {
- return 0, err
- }
- defer func() { _ = file.Close() }()
-
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- fields := strings.Fields(scanner.Text())
- if len(fields) < 2 || fields[0] != key {
- continue
- }
- return strconv.ParseInt(fields[1], 10, 64)
- }
- if err := scanner.Err(); err != nil {
- return 0, err
- }
-
- return 0, fmt.Errorf("key %q not found in %s", key, path)
-}
-
-func readCgroupV2Int64(path string) (int64, error) {
- data, err := os.ReadFile(path)
- if err != nil {
- return 0, err
- }
-
- content := strings.TrimSpace(string(data))
- if content == "max" {
- return unrestricted, nil
- }
-
- value, err := strconv.ParseInt(content, 10, 64)
- if err != nil {
- return 0, err
- }
-
- return value, nil
-}
-
-func readCgroupV2CPU() (int64, int64) {
- data, err := os.ReadFile("/sys/fs/cgroup/cpu.max")
- if err != nil {
- return -1, -1
- }
-
- parts := strings.Fields(string(data))
- if len(parts) < 2 {
- return -1, -1
- }
-
- var quota int64
- if parts[0] != "max" {
- if q, err := strconv.ParseInt(parts[0], 10, 64); err == nil {
- quota = q
- }
- }
-
- period, err := strconv.ParseInt(parts[1], 10, 64)
- if err != nil {
- return -1, -1
- }
-
- return quota, period
-}
-
-func isFiniteLimit(value int64) bool {
- return value > 0 && value < unrestricted
-}
-
-func readCgroupV1CPUControllerInt64(cgroupPath, filename string) (int64, error) {
- controllerBases := []string{
- "/sys/fs/cgroup/cpu,cpuacct",
- "/sys/fs/cgroup/cpu",
- "/sys/fs/cgroup/cpuacct",
- }
-
- var lastErr error
- for _, base := range controllerBases {
- value, err := readCgroupV1Int64(filepath.Join(base, cgroupPath, filename))
- if err == nil {
- return value, nil
- }
- lastErr = err
- }
-
- return 0, lastErr
-}
-
-// Container ID detection patterns for cgroup v1 and v2
-var (
- // cgroup v1: "12:memory:/docker/abc123..." or "12:memory:/kubepods/.../docker/abc123..."
- cgroupV1ContainerPattern = regexp.MustCompile(`/docker/([a-f0-9]{64})`)
- // cgroup v2: "0::/system.slice/docker-abc123.scope"
- cgroupV2ContainerPattern = regexp.MustCompile(`docker-([a-f0-9]{64})\.scope`)
-)
-
-// IsDockerContainer reports whether the current process is running inside a
-// Docker container (as opposed to an LXC container, a VM, or bare metal).
-//
-// The distinction matters for System Overview stats: in Docker the cgroup
-// limits (--cpus / --memory) are artificial constraints set by the operator
-// and should NOT be used as the host resource totals shown in the dashboard.
-// In LXC, by contrast, the cgroup limits represent the real hardware budget
-// assigned to the container — gopsutil reads the host's /proc values which are
-// higher, so the cgroup limits must be applied to show correct figures.
-//
-// Detection: Docker always creates /.dockerenv inside every container it
-// starts. LXC does not. We fall back to a /proc/self/cgroup pattern check
-// as a secondary signal.
-func IsDockerContainer() bool {
- if _, err := os.Stat("/.dockerenv"); err == nil {
- return true
- }
- data, err := os.ReadFile("/proc/self/cgroup")
- if err != nil {
- return false
- }
- return cgroupV1ContainerPattern.Match(data) || cgroupV2ContainerPattern.Match(data)
-}
-
-// GetCurrentContainerID detects the current container ID using multiple detection methods
-// It tries cgroup, mountinfo, and hostname in that order
-func GetCurrentContainerID() (string, error) {
- // Try cgroup first (works on cgroup v1 and cgroupns=host mode)
- if id, err := getContainerIDFromCgroup(); err == nil {
- slog.Debug("GetCurrentContainerID: found via cgroup", "containerId", id)
- return id, nil
- }
-
- // Try mountinfo (works when cgroup namespace is private)
- if id, err := getContainerIDFromMountinfo(); err == nil {
- slog.Debug("GetCurrentContainerID: found via mountinfo", "containerId", id)
- return id, nil
- }
-
- // Try hostname (Docker often sets hostname to container ID)
- if id, err := getContainerIDFromHostname(); err == nil {
- slog.Debug("GetCurrentContainerID: found via hostname", "containerId", id)
- return id, nil
- }
-
- return "", errors.New("no container ID found via cgroup, mountinfo, or hostname")
-}
-
-// getContainerIDFromCgroup tries to extract container ID from /proc/self/cgroup
-func getContainerIDFromCgroup() (string, error) {
- data, err := os.ReadFile("/proc/self/cgroup")
- if err != nil {
- return "", err
- }
-
- content := string(data)
-
- // Try cgroup v1 pattern
- if matches := cgroupV1ContainerPattern.FindStringSubmatch(content); len(matches) >= 2 {
- return matches[1], nil
- }
-
- // Try cgroup v2 pattern
- if matches := cgroupV2ContainerPattern.FindStringSubmatch(content); len(matches) >= 2 {
- return matches[1], nil
- }
-
- return "", errors.New("no container ID found in cgroup")
-}
-
-// getContainerIDFromMountinfo tries to extract container ID from /proc/self/mountinfo
-// This works even when cgroup namespace is private (cgroupns=private)
-func getContainerIDFromMountinfo() (string, error) {
- data, err := os.ReadFile("/proc/self/mountinfo")
- if err != nil {
- return "", err
- }
-
- content := string(data)
- lines := strings.SplitSeq(content, "\n")
-
- for line := range lines {
- // Look for Docker container paths in mountinfo
- if strings.Contains(line, "/docker/containers/") {
- parts := strings.Split(line, "/docker/containers/")
- if len(parts) > 1 {
- idParts := strings.Split(parts[1], "/")
- if len(idParts) > 0 && len(idParts[0]) >= 12 {
- id := idParts[0]
- if len(id) >= 64 {
- return id[:64], nil
- }
- return id, nil
- }
- }
- }
- }
-
- return "", errors.New("no container ID found in mountinfo")
-}
-
-// getContainerIDFromHostname tries to use hostname as container ID
-// Docker often sets the hostname to the container ID (12 or 64 hex chars)
-func getContainerIDFromHostname() (string, error) {
- hostname, err := os.Hostname()
- if err != nil {
- return "", err
- }
-
- // Docker often sets hostname to the short container ID (12 chars) or full ID (64 chars)
- if len(hostname) == 12 || len(hostname) == 64 {
- // Verify it looks like a hex string
- for _, c := range hostname {
- if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
- return "", errors.New("hostname doesn't match container ID pattern")
- }
- }
- return hostname, nil
- }
-
- return "", errors.New("hostname doesn't match expected container ID length")
-}
-
-// ZFSARCReclaimable returns the number of bytes of ZFS ARC (Adaptive
-// Replacement Cache) that the kernel counts as used memory but that can be
-// reclaimed under memory pressure.
-//
-// The kernel accounts ZFS ARC as used and excludes it from /proc/meminfo's
-// MemAvailable, so gopsutil's Used (= Total - MemAvailable) counts the whole
-// ARC as used. Tools like btop/htop instead treat ARC as reclaimable cache. We
-// subtract the reclaimable portion so the dashboard does not over-report usage
-// on ZFS hosts.
-//
-// The arcstats file only exists when the ZFS kernel module is loaded, so the
-// open fails cheaply on non-ZFS systems (including macOS dev machines) and this
-// returns 0 there.
-func ZFSARCReclaimable() uint64 {
- f, err := os.Open("/proc/spl/kstat/zfs/arcstats")
- if err != nil {
- return 0
- }
- defer func() { _ = f.Close() }()
- return parseARCStats(f)
-}
-
-// parseARCStats parses the kstat-format arcstats content and returns the
-// reclaimable ARC size in bytes: max(size-c_min, 0). The ARC cannot shrink
-// below c_min, so only the portion above c_min is genuinely reclaimable — a
-// slightly more conservative choice than btop's full-size treatment, which is
-// the right call for a "used" metric.
-//
-// Each kstat row is "name type data"; the value is the third column.
-func parseARCStats(r io.Reader) uint64 {
- var size, cMin uint64
- scanner := bufio.NewScanner(r)
- for scanner.Scan() {
- fields := strings.Fields(scanner.Text())
- if len(fields) < 3 {
- continue
- }
- switch fields[0] {
- case "size":
- if v, err := strconv.ParseUint(fields[2], 10, 64); err == nil {
- size = v
- }
- case "c_min":
- if v, err := strconv.ParseUint(fields[2], 10, 64); err == nil {
- cMin = v
- }
- }
- }
- if err := scanner.Err(); err != nil {
- slog.Error("failed to parse ARC stats", "error", err)
- }
- if size <= cMin {
- return 0
- }
- return size - cMin
-}
diff --git a/backend/pkg/dockerutil/cgroup_utils_test.go b/backend/pkg/dockerutil/cgroup_utils_test.go
deleted file mode 100644
index dc577a60c..000000000
--- a/backend/pkg/dockerutil/cgroup_utils_test.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package docker
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestReadMemoryStatValue(t *testing.T) {
- // Trimmed cgroup memory.stat: flat "key value" lines.
- const memoryStat = `anon 1048576
-file 2097152
-inactive_file 524288
-active_file 1572864
-total_inactive_file 786432
-`
- path := filepath.Join(t.TempDir(), "memory.stat")
- require.NoError(t, os.WriteFile(path, []byte(memoryStat), 0o600))
-
- // Exact key match: inactive_file must not be shadowed by total_inactive_file.
- value, err := readMemoryStatValue(path, "inactive_file")
- require.NoError(t, err)
- require.Equal(t, int64(524288), value)
-
- value, err = readMemoryStatValue(path, "total_inactive_file")
- require.NoError(t, err)
- require.Equal(t, int64(786432), value)
-}
-
-func TestReadMemoryStatValue_MissingKey(t *testing.T) {
- path := filepath.Join(t.TempDir(), "memory.stat")
- require.NoError(t, os.WriteFile(path, []byte("anon 1048576\n"), 0o600))
-
- _, err := readMemoryStatValue(path, "inactive_file")
- require.Error(t, err)
-}
-
-func TestParseARCStats(t *testing.T) {
- // Abbreviated kstat dump: rows are "name type data".
- const arcstats = `13 1 0x01 98 26656 5560875779 158279494432
-name type data
-hits 4 1234567
-misses 4 89012
-c_min 4 1073741824
-c_max 4 8589934592
-size 4 7516192768
-`
- // size (7 GiB) - c_min (1 GiB) = 6 GiB reclaimable.
- require.Equal(t, uint64(6442450944), parseARCStats(strings.NewReader(arcstats)))
-}
-
-func TestParseARCStats_ClampsAndHandlesMissing(t *testing.T) {
- // No arcstats content (non-ZFS host): nothing reclaimable.
- require.Equal(t, uint64(0), parseARCStats(strings.NewReader("")))
-
- // ARC already at its floor (size <= c_min): clamped to 0, never underflows.
- const atFloor = `size 4 1073741824
-c_min 4 1073741824
-`
- require.Equal(t, uint64(0), parseARCStats(strings.NewReader(atFloor)))
-}
diff --git a/backend/pkg/dockerutil/mount_utils.go b/backend/pkg/dockerutil/mount_utils.go
index 84b5655f8..f86ae7a39 100644
--- a/backend/pkg/dockerutil/mount_utils.go
+++ b/backend/pkg/dockerutil/mount_utils.go
@@ -5,10 +5,12 @@ import (
"os"
"strings"
- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
- containertypes "github.com/moby/moby/api/types/container"
- mounttypes "github.com/moby/moby/api/types/mount"
+ "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/api/types/mount"
"github.com/moby/moby/client"
+
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
+ "go.getarcane.app/sys/cgroup"
)
func getCurrentContainerInspectTargetInternal(currentContainerID func() (string, error), hostname func() (string, error)) (string, error) {
@@ -38,11 +40,11 @@ func getCurrentContainerInspectTargetInternal(currentContainerID func() (string,
// at target. Returns nil + no error if Arcane isn't running inside a
// container or no suitable mount is found — callers can fall back to a
// plain bind on containerPath in that case.
-func MountForCurrentContainerSubpath(ctx context.Context, dockerCli *client.Client, containerPath, target string) (*mounttypes.Mount, error) {
+func MountForCurrentContainerSubpath(ctx context.Context, dockerCli *client.Client, containerPath, target string) (*mount.Mount, error) {
if dockerCli == nil {
return nil, nil
}
- inspectTarget, err := getCurrentContainerInspectTargetInternal(GetCurrentContainerID, os.Hostname)
+ inspectTarget, err := getCurrentContainerInspectTargetInternal(cgroup.CurrentContainerID, os.Hostname)
if err != nil {
return nil, err
}
@@ -76,7 +78,7 @@ func MountForCurrentContainerSubpath(ctx context.Context, dockerCli *client.Clie
//
// Returns nil if no mount destination is a prefix of containerPath or if
// the matching mount is of an unsupported type.
-func MountForSubpath(mounts []containertypes.MountPoint, containerPath string, target string) *mounttypes.Mount {
+func MountForSubpath(mounts []container.MountPoint, containerPath string, target string) *mount.Mount {
if strings.TrimSpace(containerPath) == "" {
return nil
}
@@ -84,7 +86,7 @@ func MountForSubpath(mounts []containertypes.MountPoint, containerPath string, t
target = containerPath
}
- var best *containertypes.MountPoint
+ var best *container.MountPoint
for i := range mounts {
m := &mounts[i]
if m.Destination == "" {
@@ -105,7 +107,7 @@ func MountForSubpath(mounts []containertypes.MountPoint, containerPath string, t
readOnly := !best.RW
switch best.Type { //nolint:exhaustive // only bind and volume mounts are translatable; the default returns nil for the rest
- case mounttypes.TypeBind:
+ case mount.TypeBind:
if strings.TrimSpace(best.Source) == "" {
return nil
}
@@ -113,14 +115,14 @@ func MountForSubpath(mounts []containertypes.MountPoint, containerPath string, t
if relative != "" {
source = strings.TrimRight(source, "/") + "/" + relative
}
- return &mounttypes.Mount{Type: mounttypes.TypeBind, Source: source, Target: target, ReadOnly: readOnly}
- case mounttypes.TypeVolume:
+ return &mount.Mount{Type: mount.TypeBind, Source: source, Target: target, ReadOnly: readOnly}
+ case mount.TypeVolume:
if strings.TrimSpace(best.Name) == "" {
return nil
}
- m := &mounttypes.Mount{Type: mounttypes.TypeVolume, Source: best.Name, Target: target, ReadOnly: readOnly}
+ m := &mount.Mount{Type: mount.TypeVolume, Source: best.Name, Target: target, ReadOnly: readOnly}
if relative != "" {
- m.VolumeOptions = &mounttypes.VolumeOptions{Subpath: relative}
+ m.VolumeOptions = &mount.VolumeOptions{Subpath: relative}
}
return m
default:
@@ -144,7 +146,7 @@ func pathHasPrefixInternal(containerPath, prefix string) bool {
//
// It currently supports bind and named volume mounts. If target is empty, destination
// is used as the target.
-func MountForDestination(mounts []containertypes.MountPoint, destination string, target string) *mounttypes.Mount {
+func MountForDestination(mounts []container.MountPoint, destination string, target string) *mount.Mount {
if strings.TrimSpace(destination) == "" {
return nil
}
@@ -160,23 +162,23 @@ func MountForDestination(mounts []containertypes.MountPoint, destination string,
readOnly := !m.RW
switch m.Type {
- case mounttypes.TypeVolume:
+ case mount.TypeVolume:
if strings.TrimSpace(m.Name) == "" {
return nil
}
- return &mounttypes.Mount{Type: mounttypes.TypeVolume, Source: m.Name, Target: target, ReadOnly: readOnly}
- case mounttypes.TypeBind:
+ return &mount.Mount{Type: mount.TypeVolume, Source: m.Name, Target: target, ReadOnly: readOnly}
+ case mount.TypeBind:
if strings.TrimSpace(m.Source) == "" {
return nil
}
- return &mounttypes.Mount{Type: mounttypes.TypeBind, Source: m.Source, Target: target, ReadOnly: readOnly}
- case mounttypes.TypeTmpfs:
+ return &mount.Mount{Type: mount.TypeBind, Source: m.Source, Target: target, ReadOnly: readOnly}
+ case mount.TypeTmpfs:
return nil
- case mounttypes.TypeNamedPipe:
+ case mount.TypeNamedPipe:
return nil
- case mounttypes.TypeCluster:
+ case mount.TypeCluster:
return nil
- case mounttypes.TypeImage:
+ case mount.TypeImage:
return nil
default:
return nil
diff --git a/backend/pkg/libarcane/system/cgroup.go b/backend/pkg/libarcane/system/cgroup.go
deleted file mode 100644
index a5b336c5b..000000000
--- a/backend/pkg/libarcane/system/cgroup.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Package system encapsulates host-level resource probing used by the WebSocket system stats
-// endpoint: cgroup limits and GPU detection/stats. The types here own their own caching and
-// synchronization so handlers can hold them as plain fields.
-package system
-
-import (
- "sync"
- "time"
-
- docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
-)
-
-// CgroupCache memoizes the result of cgroup limit detection for a configurable TTL.
-// A single in-flight refresh is shared across concurrent callers (singleflight semantics
-// via the write lock), so a stampede of system-stats samplers never duplicates the work.
-type CgroupCache struct {
- mu sync.RWMutex
- value *docker.CgroupLimits
- detected bool
- timestamp time.Time
- ttl time.Duration
- detector func() (*docker.CgroupLimits, error)
-}
-
-// NewCgroupCache returns a cache that caches detection results for ttl using the
-// default docker.DetectCgroupLimits detector.
-func NewCgroupCache(ttl time.Duration) *CgroupCache {
- return NewCgroupCacheWithDetector(ttl, docker.DetectCgroupLimits)
-}
-
-// NewCgroupCacheWithDetector returns a cache backed by a custom detector. Useful when
-// callers (e.g. tests) need to control detection behaviour or simulate failures.
-func NewCgroupCacheWithDetector(ttl time.Duration, detector func() (*docker.CgroupLimits, error)) *CgroupCache {
- return &CgroupCache{ttl: ttl, detector: detector}
-}
-
-// Get returns the cached cgroup limits, refreshing if the entry is older than the TTL.
-// Returns nil when no cgroup limits have been detected (host is not running under cgroups).
-func (c *CgroupCache) Get() *docker.CgroupLimits {
- c.mu.RLock()
- value, detected, fresh := c.value, c.detected, time.Since(c.timestamp) < c.ttl
- c.mu.RUnlock()
- if fresh {
- if detected {
- return value
- }
- return nil
- }
-
- c.mu.Lock()
- defer c.mu.Unlock()
-
- if time.Since(c.timestamp) < c.ttl {
- if c.detected {
- return c.value
- }
- return nil
- }
-
- limits, err := c.detector()
- c.timestamp = time.Now()
- if err != nil {
- c.value = nil
- c.detected = false
- return nil
- }
- c.value = limits
- c.detected = true
- return c.value
-}
diff --git a/backend/pkg/projects/container_mounts.go b/backend/pkg/projects/container_mounts.go
index f616ca527..a967bc2fd 100644
--- a/backend/pkg/projects/container_mounts.go
+++ b/backend/pkg/projects/container_mounts.go
@@ -5,10 +5,11 @@ import (
"os"
"strings"
- dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
mounttypes "github.com/moby/moby/api/types/mount"
"github.com/moby/moby/client"
+
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
+ "go.getarcane.app/sys/cgroup"
)
// GetCurrentContainerMounts inspects Arcane's own container and returns its bind and
@@ -21,7 +22,7 @@ func GetCurrentContainerMounts(ctx context.Context, dockerCli *client.Client) ([
}
// Prefer robust current-container detection and fall back to hostname.
- inspectTarget, err := getCurrentContainerInspectTargetInternal(dockerutil.GetCurrentContainerID, os.Hostname)
+ inspectTarget, err := getCurrentContainerInspectTargetInternal(cgroup.CurrentContainerID, os.Hostname)
if err != nil {
return nil, err
}
diff --git a/backend/pkg/scheduler/auto_heal_job.go b/backend/pkg/scheduler/auto_heal_job.go
index b2a369efb..3fb72f819 100644
--- a/backend/pkg/scheduler/auto_heal_job.go
+++ b/backend/pkg/scheduler/auto_heal_job.go
@@ -7,14 +7,16 @@ import (
"sync"
"time"
- "github.com/getarcaneapp/arcane/backend/v2/internal/models"
- "github.com/getarcaneapp/arcane/backend/v2/internal/services"
- dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
"github.com/robfig/cron/v3"
"golang.org/x/sync/errgroup"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
+ "go.getarcane.app/sys/cgroup"
)
const AutoHealJobName = "auto-heal"
@@ -130,7 +132,7 @@ func (j *AutoHealJob) selfContainerIDInternal(ctx context.Context) string {
j.selfIDOnce.Do(func() {
detect := j.getSelfContainerID
if detect == nil {
- detect = dockerutil.GetCurrentContainerID
+ detect = cgroup.CurrentContainerID
}
id, err := detect()
if err != nil {
diff --git a/go.work.sum b/go.work.sum
index ef571572b..a934b24a6 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -2088,6 +2088,8 @@ go.etcd.io/gofail v0.2.0 h1:p19drv16FKK345a09a1iubchlw/vmRuksmRzgBIGjcA=
go.etcd.io/gofail v0.2.0/go.mod h1:nL3ILMGfkXTekKI3clMBNazKnjUZjYLKmBHzsVAnC1o=
go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ=
go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo=
+go.getarcane.app/sys/cgroup v0.1.0 h1:SCAbuU+rZ/EjMU8kkVxmXZsMchiZp9eFdMQFnbU+asA=
+go.getarcane.app/sys/cgroup v0.1.0/go.mod h1:Paj4QOazrTXO/Ivhmvt1E/RjPJFTdKkxRgRDk4qBCUI=
go.getarcane.app/updater v0.3.6 h1:+BqoycaRsHj+cLVSzcYQuqbHxUKbtmaozMNblz5bVSw=
go.getarcane.app/updater v0.3.6/go.mod h1:2ENitZR/lA5MuBn60OZYR5wvU3ZCE+pAgfrebfOlRDA=
go.getarcane.app/updater v0.3.7 h1:WqHsxudvt8gvCR7iSHdxdzwH0+hM0FAh64bSypBX9Mo=