Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Release per-tenant resource store handles on offboarding and shutdown
rcourtmand7f8e98912f8
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 3bc60f212d..8f6db856a4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -5818,3 +5818,16 @@ the metrics store, so a tenant monitor that has been stopped is guaranteed notto write into its data directory afterwards. Tenant offboarding and any callerthat removes a tenant directory can rely on `Stop` having quiesced disk writes,rather than racing a detached goroutine.+### Per-tenant resource stores are released on offboarding and shutdown++`ResourceHandlers.getStore` opens a SQLite handle per org and caches it for the+process lifetime. `CloseTenantStore` releases and evicts one org's handle and is+called from `Router.CleanupTenant` alongside the other per-tenant teardown;+`CloseStores`, exposed as `Router.ShutdownResourceStores`, releases all of them.+Without this an offboarded tenant kept its file descriptors and its+`unified_resources.db-wal`/`-shm` files alive and its directory could not be+fully removed. Closed stores are evicted from the cache so a later request opens+a fresh handle rather than using a closed one+(`TestResourceHandlers_CloseTenantStoreReleasesTheHandle`), and both entry points+are idempotent and nil-safe+(`TestResourceHandlers_CloseIsIdempotentAndNilSafe`).diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex c1de53031e..a98c7c9eab 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -8881,3 +8881,16 @@ together: `type Ping struct` in `internal/telemetry/telemetry.go`, theRetired columns stay in the live receiver database rather than being dropped:migrations only add, the columns hold real rows from the schema-v6 window, andnothing writes them once the receiver struct loses the fields.+### Per-tenant resource stores are released on offboarding and shutdown++`ResourceHandlers.getStore` opens a SQLite handle per org and caches it for the+process lifetime. `CloseTenantStore` releases and evicts one org's handle and is+called from `Router.CleanupTenant` alongside the other per-tenant teardown;+`CloseStores`, exposed as `Router.ShutdownResourceStores`, releases all of them.+Without this an offboarded tenant kept its file descriptors and its+`unified_resources.db-wal`/`-shm` files alive and its directory could not be+fully removed. Closed stores are evicted from the cache so a later request opens+a fresh handle rather than using a closed one+(`TestResourceHandlers_CloseTenantStoreReleasesTheHandle`), and both entry points+are idempotent and nil-safe+(`TestResourceHandlers_CloseIsIdempotentAndNilSafe`).diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 0dd9c16d52..53661cb076 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -2183,3 +2183,16 @@ most one tenant-local system-settings read; it must not scan tenants, readexternal logo files, call a licensing network service, or add per-route andper-component refetches. The response remains bounded to an enabled flag, one120-character display name, and the already size-limited inline image.+### Per-tenant resource stores are released on offboarding and shutdown++`ResourceHandlers.getStore` opens a SQLite handle per org and caches it for the+process lifetime. `CloseTenantStore` releases and evicts one org's handle and is+called from `Router.CleanupTenant` alongside the other per-tenant teardown;+`CloseStores`, exposed as `Router.ShutdownResourceStores`, releases all of them.+Without this an offboarded tenant kept its file descriptors and its+`unified_resources.db-wal`/`-shm` files alive and its directory could not be+fully removed. Closed stores are evicted from the cache so a later request opens+a fresh handle rather than using a closed one+(`TestResourceHandlers_CloseTenantStoreReleasesTheHandle`), and both entry points+are idempotent and nil-safe+(`TestResourceHandlers_CloseIsIdempotentAndNilSafe`).diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 4077f322f4..73b3872412 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -1938,3 +1938,16 @@ because it looks like data in the fleet aggregate.`audit_logging_persistent`, `audit_events_30d`, and`pulse_intelligence_patrol_autofixes_30d` so they cannot return under their oldnames.+### Per-tenant resource stores are released on offboarding and shutdown++`ResourceHandlers.getStore` opens a SQLite handle per org and caches it for the+process lifetime. `CloseTenantStore` releases and evicts one org's handle and is+called from `Router.CleanupTenant` alongside the other per-tenant teardown;+`CloseStores`, exposed as `Router.ShutdownResourceStores`, releases all of them.+Without this an offboarded tenant kept its file descriptors and its+`unified_resources.db-wal`/`-shm` files alive and its directory could not be+fully removed. Closed stores are evicted from the cache so a later request opens+a fresh handle rather than using a closed one+(`TestResourceHandlers_CloseTenantStoreReleasesTheHandle`), and both entry points+are idempotent and nil-safe+(`TestResourceHandlers_CloseIsIdempotentAndNilSafe`).diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 66c44ae96b..f2981b021b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -4984,3 +4984,16 @@ the 30-day telemetry window are excluded at count time by`CountAuditReadActivitySince`, so the derived signal stays "is using" ratherthan drifting into "has ever used"(`TestAuditReadsOutsideWindowAreNotCounted`).+### Per-tenant resource stores are released on offboarding and shutdown++`ResourceHandlers.getStore` opens a SQLite handle per org and caches it for the+process lifetime. `CloseTenantStore` releases and evicts one org's handle and is+called from `Router.CleanupTenant` alongside the other per-tenant teardown;+`CloseStores`, exposed as `Router.ShutdownResourceStores`, releases all of them.+Without this an offboarded tenant kept its file descriptors and its+`unified_resources.db-wal`/`-shm` files alive and its directory could not be+fully removed. Closed stores are evicted from the cache so a later request opens+a fresh handle rather than using a closed one+(`TestResourceHandlers_CloseTenantStoreReleasesTheHandle`), and both entry points+are idempotent and nil-safe+(`TestResourceHandlers_CloseIsIdempotentAndNilSafe`).diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 036c64fe49..12e2caea60 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -4395,3 +4395,16 @@ destructive migration is not. The boundary is only that fresh schema creationstops declaring dead tables.`internal/unifiedresources/store_test.go` pins this by failing if a freshstore's `sqlite_master` contains `resource_metadata`.++### Cached per-tenant resource stores must be releasable++`ResourceHandlers.getStore` opens a SQLite handle per org and caches it for the+process lifetime, so the cache needs an explicit release path or an offboarded+tenant keeps its handle, its file descriptors, and its+`unified_resources.db-wal`/`-shm` sidecars, and its directory cannot be removed.+`CloseTenantStore` releases one org, `CloseStores` releases all of them, and+`Router.CleanupTenant` calls the former alongside the rest of per-tenant+teardown. `TestCachedResourceStoresHaveATenantReleasePath` in+`internal/unifiedresources/code_standards_test.go` is a source-shape guard,+because the leak is invisible at runtime until a tenant is deleted or a data+directory is torn down.diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 7ba4fb90b9..e276aab932 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -22384,3 +22384,32 @@ func TestIssue1649StrandedDockerUpdateReconcilesWithoutRedispatch(t *testing.T)t.Fatalf("receipt=%#v update=%d lifecycle=%d raw=%d", receipt, len(agents.typedUpdateCalls), len(agents.typedCalls), len(agents.calls))}}++// Tenant offboarding must release every per-tenant resource the router holds.+// The resource store was the one that was missed: getStore caches a SQLite+// handle per org for the process lifetime, so a deleted tenant kept its handle+// and its directory could not be removed.+func TestCleanupTenantReleasesPerTenantResourceStore(t *testing.T) {+ routerSource, err := os.ReadFile("router.go")+ if err != nil {+ t.Fatalf("read router.go: %v", err)+ }+ src := string(routerSource)++ cleanupStart := strings.Index(src, "func (r *Router) CleanupTenant(")+ if cleanupStart < 0 {+ t.Fatal("CleanupTenant not found")+ }+ cleanupEnd := strings.Index(src[cleanupStart:], "\n}\n")+ if cleanupEnd < 0 {+ t.Fatal("could not bound CleanupTenant")+ }+ cleanup := src[cleanupStart : cleanupStart+cleanupEnd]++ if !strings.Contains(cleanup, "CloseTenantStore(orgID)") {+ t.Error("CleanupTenant must close the offboarded tenant's unified resource store")+ }+ if !strings.Contains(src, "func (r *Router) ShutdownResourceStores()") {+ t.Error("Router must expose ShutdownResourceStores for shutdown-time release")+ }+}diff --git a/internal/api/resources.go b/internal/api/resources.goindex 3179a8ac96..8ed17e9358 100644--- a/internal/api/resources.go+++ b/internal/api/resources.go@@ -4,6 +4,7 @@ import ("context""encoding/json""errors"+ "fmt""io""net/http""sort"@@ -1279,6 +1280,61 @@ func (h *ResourceHandlers) getStore(orgID string) (unified.ResourceStore, error)return store, nil}+// CloseTenantStore closes and evicts one org's cached resource store.+//+// getStore opens a SQLite handle per org and caches it for the process+// lifetime. Without this, offboarding a tenant left its handle open: the+// -wal and -shm files stay on disk, the file descriptors are never returned,+// and the tenant directory cannot be fully removed.+func (h *ResourceHandlers) CloseTenantStore(orgID string) error {+ if h == nil {+ return nil+ }+ key := cacheKey(orgID)++ h.storeMu.Lock()+ store, ok := h.stores[key]+ if ok {+ delete(h.stores, key)+ }+ h.storeMu.Unlock()++ h.invalidateCache(orgID)++ if !ok || store == nil {+ return nil+ }+ return store.Close()+}++// CloseStores closes and evicts every cached resource store. Used on shutdown+// so SQLite handles are released rather than left to process exit.+func (h *ResourceHandlers) CloseStores() error {+ if h == nil {+ return nil+ }++ h.storeMu.Lock()+ stores := make(map[string]unified.ResourceStore, len(h.stores))+ for key, store := range h.stores {+ stores[key] = store+ }+ h.stores = make(map[string]unified.ResourceStore)+ h.storeMu.Unlock()++ var errs []error+ for key, store := range stores {+ if store == nil {+ continue+ }+ if err := store.Close(); err != nil {+ errs = append(errs, fmt.Errorf("close resource store for %s: %w", key, err))+ }+ h.invalidateCache(key)+ }+ return errors.Join(errs...)+}+func (h *ResourceHandlers) invalidateCache(orgID string) {key := cacheKey(orgID)h.cacheMu.Lock()diff --git a/internal/api/resources_store_close_test.go b/internal/api/resources_store_close_test.gonew file mode 100644index 0000000000..f899c353b0--- /dev/null+++ b/internal/api/resources_store_close_test.go@@ -0,0 +1,105 @@+package api++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++// sqliteSidecarsPresent reports whether SQLite's -wal/-shm sidecars exist, which+// they only do while a connection is open. They are the observable signal that a+// store handle was or was not released.+func sqliteSidecarsPresent(t *testing.T, dataDir, orgID string) bool {+ t.Helper()+ base := filepath.Join(dataDir, "orgs", orgID, "resources", "unified_resources.db")+ for _, suffix := range []string{"-wal", "-shm"} {+ if _, err := os.Stat(base + suffix); err == nil {+ return true+ }+ }+ return false+}++// getStore opens a SQLite handle per org and caches it for the process+// lifetime. Offboarding a tenant must release it, or the handle, its file+// descriptors, and its -wal/-shm files outlive the tenant.+func TestResourceHandlers_CloseTenantStoreReleasesTheHandle(t *testing.T) {+ dataDir := t.TempDir()+ handlers := NewResourceHandlers(&config.Config{DataPath: dataDir})+ t.Cleanup(func() { _ = handlers.CloseStores() })++ if _, err := handlers.getStore("client-x"); err != nil {+ t.Fatalf("getStore: %v", err)+ }+ if !sqliteSidecarsPresent(t, dataDir, "client-x") {+ t.Skip("SQLite did not create -wal/-shm sidecars; nothing observable to assert")+ }++ if err := handlers.CloseTenantStore("client-x"); err != nil {+ t.Fatalf("CloseTenantStore: %v", err)+ }+ if sqliteSidecarsPresent(t, dataDir, "client-x") {+ t.Fatal("-wal/-shm survived CloseTenantStore; the handle was not released")+ }++ handlers.storeMu.Lock()+ _, cached := handlers.stores[cacheKey("client-x")]+ handlers.storeMu.Unlock()+ if cached {+ t.Fatal("closed store is still cached; a later request would use a closed handle")+ }+}++func TestResourceHandlers_CloseStoresReleasesEveryTenant(t *testing.T) {+ dataDir := t.TempDir()+ handlers := NewResourceHandlers(&config.Config{DataPath: dataDir})++ for _, orgID := range []string{"client-a", "client-b"} {+ if _, err := handlers.getStore(orgID); err != nil {+ t.Fatalf("getStore(%s): %v", orgID, err)+ }+ }+ if err := handlers.CloseStores(); err != nil {+ t.Fatalf("CloseStores: %v", err)+ }++ for _, orgID := range []string{"client-a", "client-b"} {+ if sqliteSidecarsPresent(t, dataDir, orgID) {+ t.Errorf("-wal/-shm survived CloseStores for %s", orgID)+ }+ }+ handlers.storeMu.Lock()+ remaining := len(handlers.stores)+ handlers.storeMu.Unlock()+ if remaining != 0 {+ t.Fatalf("%d store(s) still cached after CloseStores", remaining)+ }+}++// Closing must be safe to repeat and safe on a nil handler: the shutdown path+// runs before every dependency is guaranteed to be wired.+func TestResourceHandlers_CloseIsIdempotentAndNilSafe(t *testing.T) {+ var nilHandlers *ResourceHandlers+ if err := nilHandlers.CloseStores(); err != nil {+ t.Fatalf("nil handler CloseStores: %v", err)+ }+ if err := nilHandlers.CloseTenantStore("client-a"); err != nil {+ t.Fatalf("nil handler CloseTenantStore: %v", err)+ }++ handlers := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})+ if _, err := handlers.getStore("client-a"); err != nil {+ t.Fatalf("getStore: %v", err)+ }+ if err := handlers.CloseStores(); err != nil {+ t.Fatalf("first CloseStores: %v", err)+ }+ if err := handlers.CloseStores(); err != nil {+ t.Fatalf("second CloseStores must be a no-op: %v", err)+ }+ if err := handlers.CloseTenantStore("client-a"); err != nil {+ t.Fatalf("CloseTenantStore on an evicted org must be a no-op: %v", err)+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex 1d5968ce1b..841982b4e4 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -1039,6 +1039,12 @@ func (r *Router) CleanupTenant(ctx context.Context, orgID string) error {if r.licenseHandlers != nil {r.licenseHandlers.RemoveTenantService(orgID)}+ if r.resourceHandlers != nil {+ if err := r.resourceHandlers.CloseTenantStore(orgID); err != nil {+ errs = append(errs, fmt.Errorf("resource store cleanup: %w", err))+ }+ }+r.monitorAdapterMu.Lock()delete(r.monitorResourceAdapters, orgID)r.monitorAdapterMu.Unlock()@@ -2962,6 +2968,21 @@ func (r *Router) ShutdownAIIntelligence() {// ShutdownRBAC closes every organization RBAC store owned by this router and// clears the global manager only when it points at the same provider.+// ShutdownResourceStores closes every cached per-org unified resource store.+//+// getStore opens these lazily and caches them for the process lifetime, so+// without an explicit shutdown the SQLite handles and their -wal/-shm files+// outlive the router. Tests that build a Router against a temporary data+// directory must call this, or the open handles race directory cleanup.+func (r *Router) ShutdownResourceStores() {+ if r == nil || r.resourceHandlers == nil {+ return+ }+ if err := r.resourceHandlers.CloseStores(); err != nil {+ log.Warn().Err(err).Msg("failed to close unified resource stores")+ }+}+func (r *Router) ShutdownRBAC() {if r.rbacProvider == nil {returndiff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex ff775d49f3..845e3e5eae 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -2810,3 +2810,37 @@ func TestGuestRRDPointCarriesOnlyRecordedGuestColumns(t *testing.T) {}}}++// A per-tenant cache of SQLite resource stores must have a release path, and+// tenant teardown must use it.+//+// ResourceHandlers.getStore opens a handle per org and caches it for the+// process lifetime. Without an explicit release, offboarding a tenant leaves+// its handle, file descriptors, and -wal/-shm sidecars alive and its directory+// unremovable. This is a source-shape guard because the leak is invisible at+// runtime until a tenant is deleted or a data directory is torn down.+func TestCachedResourceStoresHaveATenantReleasePath(t *testing.T) {+ resources, err := os.ReadFile("../api/resources.go")+ if err != nil {+ t.Fatalf("read resources.go: %v", err)+ }+ for _, fragment := range []string{+ "func (h *ResourceHandlers) CloseTenantStore(orgID string) error",+ "func (h *ResourceHandlers) CloseStores() error",+ } {+ if !strings.Contains(string(resources), fragment) {+ t.Errorf("internal/api/resources.go must expose %q so cached per-tenant stores can be released", fragment)+ }+ }++ router, err := os.ReadFile("../api/router.go")+ if err != nil {+ t.Fatalf("read router.go: %v", err)+ }+ if !strings.Contains(string(router), "r.resourceHandlers.CloseTenantStore(orgID)") {+ t.Error("Router.CleanupTenant must release the offboarded tenant's resource store")+ }+ if !strings.Contains(string(router), "func (r *Router) ShutdownResourceStores()") {+ t.Error("Router must expose ShutdownResourceStores so every cached store can be released on shutdown")+ }+}