Reverse proxy for sleepy stacks
  • Go 88.3%
  • Python 7%
  • Shell 4.7%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Adam Štrauch bb7a949286
All checks were successful
Test and deploy development proxy / verify (push) Successful in 2m11s
Production proxy deployment / deploy (release) Successful in 1m42s
Recheck sleeping Docker stacks after restart
2026-11-25 00:08:13 +01:00
.gitea/workflows Deploy production releases to all stack nodes with health verification 2026-11-02 00:58:43 +01:00
deploy Deploy production releases to all stack nodes with health verification 2026-11-02 00:58:43 +01:00
.gitignore Authenticate management listener with shared vm-api token 2026-10-31 19:32:20 +01:00
auth.go Persist observation checkpoints and publish restart recovery coverage 2026-11-01 02:57:11 +01:00
auth_test.go Persist observation checkpoints and publish restart recovery coverage 2026-11-01 02:57:11 +01:00
coverage.go Coordinate sleepy lifecycle and export complete node inventory metrics 2026-10-30 22:52:36 +01:00
coverage_test.go Coordinate sleepy lifecycle and export complete node inventory metrics 2026-10-30 22:52:36 +01:00
go.mod Implement on-demand Incus stack proxy with durable usage metering 2026-10-30 22:33:37 +01:00
go.sum Implement on-demand Incus stack proxy with durable usage metering 2026-10-30 22:33:37 +01:00
idle_timeout_test.go Cache Incus routing inventory and refresh on cache misses 2026-11-02 13:19:08 +01:00
incus_config.go Add v2 sleep mode that stops Docker containers inside running Incus stacks 2026-11-03 09:45:33 +01:00
incus_config_test.go Coordinate sleepy lifecycle and export complete node inventory metrics 2026-10-30 22:52:36 +01:00
incus_read.go Cache Incus routing inventory and refresh on cache misses 2026-11-02 13:19:08 +01:00
incus_read_test.go Cache Incus routing inventory and refresh on cache misses 2026-11-02 13:19:08 +01:00
inventory.go Add v2 sleep mode that stops Docker containers inside running Incus stacks 2026-11-03 09:45:33 +01:00
inventory_test.go Exclude unlabeled reference images from node stack inventory counts 2026-10-30 23:16:09 +01:00
lifecycle_lock_linux.go Coordinate sleepy lifecycle and export complete node inventory metrics 2026-10-30 22:52:36 +01:00
lifecycle_lock_test.go Coordinate sleepy lifecycle and export complete node inventory metrics 2026-10-30 22:52:36 +01:00
main.go Recheck sleeping Docker stacks after restart 2026-11-25 00:08:13 +01:00
main_test.go Cache Incus routing inventory and refresh on cache misses 2026-11-02 13:19:08 +01:00
performance_test.go Persist observation checkpoints and publish restart recovery coverage 2026-11-01 02:57:11 +01:00
README.md Recheck sleeping Docker stacks after restart 2026-11-25 00:08:13 +01:00
recovery.go Add v2 sleep mode that stops Docker containers inside running Incus stacks 2026-11-03 09:45:33 +01:00
recovery_test.go Persist observation checkpoints and publish restart recovery coverage 2026-11-01 02:57:11 +01:00
routing_cache.go Cache Incus routing inventory and refresh on cache misses 2026-11-02 13:19:08 +01:00
routing_cache_test.go Cache Incus routing inventory and refresh on cache misses 2026-11-02 13:19:08 +01:00
sleeping.go Recheck sleeping Docker stacks after restart 2026-11-25 00:08:13 +01:00
sleeping_test.go Recheck sleeping Docker stacks after restart 2026-11-25 00:08:13 +01:00
startup_test.go Keep proxy available when saved Docker containers are removed 2026-11-05 10:29:20 +01:00
tuning.go Wait for Docker container health before forwarding wake-up traffic 2026-11-03 11:48:51 +01:00
tuning_test.go Implement on-demand Incus stack proxy with durable usage metering 2026-10-30 22:33:37 +01:00
usage.go Add v2 sleep mode that stops Docker containers inside running Incus stacks 2026-11-03 09:45:33 +01:00
usage_test.go Implement on-demand Incus stack proxy with durable usage metering 2026-10-30 22:33:37 +01:00

sleepy-stacks

A Go reverse proxy that starts Incus stacks on demand and stops idle stacks. Source lives in sleepy-stacks-proxy; the executable and systemd unit retain the sleepy-stacks name. It listens on :80, selects a container using the request's X-Stack-ID header and the container's user.stack-id, and forwards HTTP to the container's port 80. It waits for a routable address and an accepting TCP listener before forwarding the original request. Request bodies are not retried. When restoring Docker containers after sleep, it first waits for all saved containers to be running and for their configured health checks to pass. Go's reverse proxy supports streaming and WebSocket upgrades.

Build and run

Requires Go 1.24+, a C compiler (for the SQLite driver), and the incus CLI. Run on a host that can reach container IP addresses and whose service account can administer the selected Incus project. Port 80 requires root or CAP_NET_BIND_SERVICE.

go build -buildvcs=false -o sleepy-stacks .
incus config set my-container user.stack-id=stack-123
# TOKEN must match the existing vm-api node token (supply it privately).
export TOKEN
./sleepy-stacks -database /var/lib/sleepy-stacks/uptime.db
curl -H 'X-Stack-ID: stack-123' http://localhost/
# Use a private curl config/header file containing Authorization: Bearer <node-token>.
# Avoid putting the real token in command arguments or shell history.
curl --config /root/.config/sleepy-stacks/curl.conf http://localhost:8080/metrics

Create the database's parent directory before starting. Use a persistent local filesystem for the database and its SQLite WAL files. Only one sleepy-stacks process should manage a given set of containers.

A stack is stopped after 60 seconds without traffic, checked approximately once per second. Active HTTP requests and WebSockets keep it running; the idle window begins again when the last request completes. Containers already running at service startup receive a fresh idle window. Containers without a stack ID are ignored, except to finish restoring Docker after sleepy enrollment is removed. Stack IDs must be unique within the selected project.

An initial lifecycle sweep failure is logged and retried by the poller while the proxy and management listeners remain available. A broken stack's wake must not prevent other stacks from being served. Inventory remains unsuccessful until a complete sweep succeeds; saved Docker resume sets are retained on wake failure.

Sleeping modes

SLEEPING_MODE=v1 is the default: sleep stops the Incus container and a request starts it again. Set SLEEPING_MODE=v2 (or -sleeping-mode=v2) to keep Incus running and stop every currently running Docker container inside it, including mgm. This uses incus exec ... -- docker ps/stop/start directly, so wake-up does not depend on the management container. Docker must be available inside the Incus container. Invalid mode values prevent startup.

For systemd, add this to /etc/default/sleepy-stacks and restart the service:

SLEEPING_MODE=v2

Before stopping anything, the proxy persists full Docker container IDs in user.stack-sleep-containers as a JSON array and sets user.stack-sleep-state to stopping. After all stops succeed the state becomes sleeping. Wake sets waking, lists all existing Docker IDs, logs and skips saved IDs that were deleted (for example by a deployment), starts the remaining saved IDs, and waits until each is running and any configured Docker health check reports healthy, then clears both keys. Containers that were already stopped stay stopped; no Compose down/up or container removal is performed. Empty running sets are supported. Failed stops/starts retain the original resume set for retry, including after a proxy restart. Readiness failures also retain the waking state and resume set; subsequent requests or lifecycle polls retry the wake. Containers without health checks only need to be running. Stopped, paused, restarting, starting, and unhealthy containers block readiness until they recover or the timeout expires. Requests restore saved v2 sleep state even after changing the configured mode back to v1. Do not remove or edit these keys while a stack is asleep.

Active requests, idle timeouts and maintenance use the same policy in both modes. For stacks already marked asleep, the proxy checks running Incus containers at startup and every 10 minutes thereafter. If Docker has restarted any containers, the proxy stops them again and preserves the original set to restore on wake. The next poll wakes Docker for a maintenance lease or after switching the stack to a normal profile. Interrupted stops and wakes are retried by the poller. After a wake, HTTP still waits for port 80 readiness. Docker inspection runs only while restoring saved sleep state, not on every request to an awake stack. Health checks for all resumed containers must pass, including optional services.

Sleeping stacks and incomplete wakes do not accumulate observed uptime or count as awake in inventory metrics, even though Incus reports Running. The companion vm-api change maps these states to the existing logical Stopped API status in both stack detail and inventory, allowing admin's existing sleepy-stack UI to show Sleeping and avoid runtime calls to the stopped management container. Incus itself continues to show its actual physical status. Deploy the vm-api status mapping alongside v2; the admin frontend needs no change.

Durable restart recovery

SQLite retains usage intervals and per-stack observation checkpoints in the same transaction. The checkpoint stores identity, last observation, running state and process generation. Startup restores the boundary but deliberately does not count the saved running state as evidence that a container ran while the proxy was down. A restart opens one proxy-offline interval from the last complete poll until the first successful complete poll, including repeated failed startups. A drained shutdown takes a fresh inventory observation and records a clean marker; failed shutdown observations leave the prior watermark intact. Cancelled observations are labelled observation-cancelled, not an Incus outage.

Authenticated, loopback-only GET /v1/coverage?after=0&limit=1000 provides a separate paginated stream: version, meter_id, nullable observed_from and observed_until, records, next_cursor, has_more, and open_gaps. Each closed record has cursor, started_at, ended_at, and reason. Its cursor is allocated when the gap closes, so a consumer cannot miss a closure after reading an open gap. Closed records are immutable. Existing closed diagnostic rows are migrated once without changing their timestamps. Use the final page's watermark and open gap list only after collecting all pages. The legacy /v1/usage and /v1/gaps formats remain available; their bounded diagnostics must not be mistaken for the complete new recovery stream.

The master records financial waiver decisions; this proxy reports evidence only. Keep the SQLite file and WAL on persistent local storage. Do not prune or edit usage/gap rows manually. Replacing the database creates a different meter ID, which the master must reconcile against its last durable collection, never its last posted charge. No new request-path network call or SQLite commit is added: the checkpoint update shares the existing observation transaction. Coverage pagination and reconciliation use the management/accounting path.

Metrics expose sleepy_stacks_observed_until_seconds, sleepy_stacks_open_gap_started_seconds, sleepy_stacks_open_gaps, and sleepy_stacks_closed_gaps_total. Alert when observations are stale for five minutes, an open gap lasts over an hour, or database writes fail. The master/admin must additionally monitor collection lag and financial conflicts; a current proxy watermark alone does not prove that central accounting collected it. Missing/empty/repeated headers return 400, unknown IDs return 404, duplicate IDs or Incus/startup failures return 503, and forwarding failures return 502.

Enable maintenance to prevent automatic shutdown (on-demand starts still work):

incus config set my-container user.stack-maintenance=1 user.stack-maintenance-until="$(date -u -d '+15 minutes' +%Y-%m-%dT%H:%M:%SZ)"
incus config set my-container user.stack-maintenance= user.stack-maintenance-until=

Configuration is refreshed before each shutdown, including inherited profile configuration. Explicit instance configuration takes precedence. Addresses must have global scope; IPv4 is preferred over IPv6. Only the configured -upstream-interface (default eth0) is considered. Nested Docker bridges and veth interfaces are never used as fallbacks. A missing or unusable configured interface makes readiness fail with 503.

Flag Environment variable Default Meaning
-listen SLEEPY_STACKS_LISTEN :80 HTTP listener
-metrics-listen SLEEPY_STACKS_METRICS_LISTEN :8080 Metrics listener
-database SLEEPY_STACKS_DATABASE sleepy-stacks.db SQLite file
-sleeping-mode SLEEPING_MODE v1 v1: stop Incus; v2: stop and restore running Docker containers inside Incus
-incus SLEEPY_STACKS_INCUS incus Incus CLI path
-incus-socket SLEEPY_STACKS_INCUS_SOCKET /var/lib/incus/unix.socket Local daemon socket for REST and CLI
-lock-dir SLEEPY_STACKS_LOCK_DIR /run/lock/sleepy-stacks Shared lifecycle lock directory; must match vm-api
-lock-poll-interval SLEEPY_STACKS_LOCK_POLL_INTERVAL 25ms Context-aware lock retry interval
-inventory-excluded-instances SLEEPY_STACKS_INVENTORY_EXCLUDED_INSTANCES stackimage0 Exact comma-separated unlabeled reference names excluded only from inventory; empty disables
-upstream-interface SLEEPY_STACKS_UPSTREAM_INTERFACE eth0 Host-facing interface; no fallback
-project SLEEPY_STACKS_PROJECT default Incus project
-idle-timeout SLEEPY_STACKS_IDLE_TIMEOUT 60s Idle shutdown delay
-ready-timeout SLEEPY_STACKS_READY_TIMEOUT 60s Shared wake-up, Docker health, and address/TCP readiness deadline
-poll-interval SLEEPY_STACKS_POLL_INTERVAL 1s Lifecycle polling and uptime checkpoint interval
-incus-timeout SLEEPY_STACKS_INCUS_TIMEOUT 90s Maximum duration of each CLI command or maintenance REST reconciliation
-probe-timeout SLEEPY_STACKS_PROBE_TIMEOUT 500ms One TCP port 80 probe timeout
-probe-interval SLEEPY_STACKS_PROBE_INTERVAL 200ms Delay between Docker health or TCP readiness probes
-connect-timeout SLEEPY_STACKS_CONNECT_TIMEOUT 10s Upstream connection timeout
-response-header-timeout SLEEPY_STACKS_RESPONSE_HEADER_TIMEOUT 60s Wait for upstream headers after writing request; 0 disables
-upstream-idle-timeout SLEEPY_STACKS_UPSTREAM_IDLE_TIMEOUT 90s Upstream keep-alive timeout; 0 disables
-read-header-timeout SLEEPY_STACKS_READ_HEADER_TIMEOUT 10s Client request header timeout; 0 disables
-read-timeout SLEEPY_STACKS_READ_TIMEOUT 0 Client request read timeout; 0 disables
-write-timeout SLEEPY_STACKS_WRITE_TIMEOUT 0 Client response write deadline; 0 disables
-client-idle-timeout SLEEPY_STACKS_CLIENT_IDLE_TIMEOUT 60s Client keep-alive timeout; 0 falls back to read-timeout
-shutdown-timeout SLEEPY_STACKS_SHUTDOWN_TIMEOUT 30s Graceful shutdown timeout
-read-buffer-size SLEEPY_STACKS_READ_BUFFER_SIZE 4096 Upstream read buffer bytes per connection
-write-buffer-size SLEEPY_STACKS_WRITE_BUFFER_SIZE 4096 Upstream write buffer bytes per connection
-copy-buffer-size SLEEPY_STACKS_COPY_BUFFER_SIZE 32768 Pooled response copy buffer bytes per active response
-max-header-bytes SLEEPY_STACKS_MAX_HEADER_BYTES 1048576 Client request header limit (Go also allows parser overhead)
-flush-interval SLEEPY_STACKS_FLUSH_INTERVAL 0 Normal flushing; positive duration for periodic flushing, negative for immediate flushing

Environment values supply defaults; explicit flags override them. Invalid values fail startup. Additional settings use the same prefix:

Flag Environment variable Default Meaning
-metrics-read-header-timeout SLEEPY_STACKS_METRICS_READ_HEADER_TIMEOUT 10s Metrics header deadline
-metrics-write-timeout SLEEPY_STACKS_METRICS_WRITE_TIMEOUT 10s Metrics response deadline
-metrics-idle-timeout SLEEPY_STACKS_METRICS_IDLE_TIMEOUT 60s Metrics keep-alive
-tcp-keep-alive SLEEPY_STACKS_TCP_KEEP_ALIVE 30s Upstream TCP keep-alive; negative disables
-tls-handshake-timeout SLEEPY_STACKS_TLS_HANDSHAKE_TIMEOUT 10s Transport TLS deadline
-expect-continue-timeout SLEEPY_STACKS_EXPECT_CONTINUE_TIMEOUT 1s Transport Expect Continue wait
-database-busy-timeout SLEEPY_STACKS_DATABASE_BUSY_TIMEOUT 5s SQLite lock wait

Maintenance leases use user.stack-maintenance-until in RFC3339 UTC. Missing or malformed expiry on a maintenance instance is assigned once to now + 15 minutes and persisted in Incus. An expired lease clears both local fields persistently. If persistence fails, idle shutdown is skipped and an error is logged. Lifecycle configuration is rechecked on every sweep; adding/removing user.stack-id enrolls or removes an instance without a proxy restart. Canonical master stack IDs are required, never billing IDs or backend names. Normal-profile field removal and starting a stopped Incus instance are the node API's responsibility; the proxy restores saved v2 Docker containers on the next poll.

The proxy caches the container enrollment list in an immutable in-memory snapshot. A request for an unknown stack ID triggers a configuration inventory refresh (GET /1.0/instances?recursion=1) without gathering every container's runtime state. Concurrent misses share that refresh; after each miss refresh, further misses reuse its result for one second, including failures and unknown IDs. This backoff is shared across IDs so random unknown IDs cannot force repeated scans. Waiting requests can cancel independently. A failed refresh returns 503 for unresolved requests while preserving known mappings for targeted validation.

There is no routing-only refresh timer or fixed expiry for known mappings. The lifecycle/accounting loop still reads inventory for its own work before and after each sweep; those successful observations also update the routing cache without additional queries. New stacks are therefore discovered on a cache miss or by the next lifecycle observation. A miss immediately following another miss refresh may wait for its one-second backoff to expire. Duplicate IDs fail closed when observed. Removed or reassigned mappings are also invalidated when targeted checks detect the change.

Cached status and addresses are never used to make lifecycle or routing decisions. Under the shared lifecycle lock, the proxy reads only the selected container’s current configuration and state through the local Incus Unix socket. Idle checks use the same targeted reads so normal-profile conversions, maintenance renewals, and timeout changes are checked before stopping a stack. Readiness retries fetch only that container, including after a cold start.

Every request waits for a successful TCP connection to the stack's port 80 before it is forwarded, including requests to containers already running. This tests whether the port accepts connections; it does not require a particular HTTP status or health-check path. A failed probe is retried until -ready-timeout, then the caller receives 503. One shared readiness deadline bounds wake-up (including start operations and Docker health checks), TCP probes, and Incus lookups during the wait. It excludes the initial container lookup and lifecycle lock wait; Incus commands also have their own timeout. Background Docker wakes use the same readiness timeout. Failures are logged with the blocking Docker container names/IDs and their last observed states. Client cancellation interrupts the readiness wait.

Buffer sizes are in bytes. Bodies stream without being fully buffered, so these sizes are not request/response body limits. The copy pool reuses response buffers. Go flushes streaming responses immediately regardless of a positive flush interval. See Go's reverse proxy documentation.

-idle-timeout controls stack shutdown; the client/upstream idle flags control HTTP keep-alive connections. Read/write timeouts are absolute deadlines, not per-chunk inactivity timeouts, and include time spent waiting for startup. Keep them at zero for unrestricted streaming or set them high enough to cover startup plus transfers. Metrics use separately configurable header/write/idle timeouts. If you raise -shutdown-timeout beyond 30s under systemd, increase the unit's TimeoutStopSec accordingly. Graceful shutdown flushes uptime without stopping stacks. No external deployment or Incus configuration is performed by the build.

For example:

./sleepy-stacks -idle-timeout=2m -ready-timeout=90s \
  -probe-interval=250ms -probe-timeout=1s \
  -read-buffer-size=16384 -write-buffer-size=16384 -copy-buffer-size=65536 \
  -connect-timeout=5s -response-header-timeout=2m

Uptime metrics

GET :8080/metrics returns Prometheus text format:

# HELP sleepy_stacks_uptime_seconds_total Observed container running time in seconds.
# TYPE sleepy_stacks_uptime_seconds_total counter
sleepy_stacks_uptime_seconds_total{stack_id="stack-123",container="my-container"} 123.456000

Uptime accumulates across starts and proxy restarts, separately for each stack ID/container name pair. Running maintenance containers count too. Values are checkpointed each polling cycle and at graceful shutdown. They represent running time observed by this process, starting with its first observation; time while the proxy is offline is not reconstructed. An abrupt termination can lose the time since the last checkpoint. External state changes are measured to polling precision. Deleted containers retain their historical counters in SQLite. This is operational monitoring, not exact billing accounting.

The management listener requires the same nonempty TOKEN environment variable as vm-api. The process refuses to start without it. Every route on port 8080, including /metrics, /v1/usage, /v1/gaps, unknown routes and unsupported methods, requires exactly one Authorization: Bearer <token> or Authorization: Token <token> header. Schemes are case insensitive; credential comparison uses constant-time SHA-256 digest comparison. Missing, malformed, duplicate or incorrect authorization returns 401 with no reflected credentials. Query-string tokens are never accepted. Journal routes additionally require a loopback TCP peer (forwarded headers do not bypass this restriction); remote authenticated journal access returns 403. Metrics allow authenticated node/master callers. Port 80 authentication and forwarding are unchanged.

Place the proxy behind a trusted ingress that supplies X-Stack-ID; clients able to choose this header can wake any mapped stack. Bind metrics to an internal address when appropriate. The Incus CLI is forced to the local daemon and uses the same configured Unix socket as maintenance REST calls. Remote CLI targets are unsupported. See the official Incus list reference and instance lifecycle guide.

Systemd

Copy the built binary to /usr/local/bin/sleepy-stacks, install deploy/sleepy-stacks.service in /etc/systemd/system/, then enable it. The supplied unit runs as root for local Incus access and port 80. Adjust its executable paths, project, and account for your host. It creates /var/lib/sleepy-stacks automatically.

Verify

go test -race ./...
go vet ./...

Tests use an in-memory Incus substitute, real temporary SQLite files, and an HTTP backend; they never operate on real containers. Test on a disposable Incus container before deploying to production.

Durable usage journal (non-charging telemetry)

GET :8080/v1/usage?after=0&limit=1000 returns:

{"version":1,"meter_id":"UUID","records":[{"cursor":1,"stack_id":"123","container":"web","started_at":"2026-10-30T12:00:00Z","ended_at":"2026-10-30T12:00:01Z","duration_ns":1000000000,"uptime_seconds":1}],"next_cursor":1,"has_more":false}

after is an exclusive nonnegative cursor; limit is 1..10000. Optional stack_id is an exact string filter. IDs in Incus and this JSON API are strings. A node adapter must convert numeric canonical IDs for a master API that expects integers. Records are immutable and ordered by cursor. Empty pages retain the requested cursor; has_more indicates another matching record. Never reuse a filtered cursor as a global ingestion cursor. Consumers deduplicate using node + meter_id + cursor. meter_id is a UUID stored in SQLite metadata, stable across restarts and new after database replacement. Restoring an old database backup can rewind its cursor with the same meter_id: restore procedures must rotate identity or reconcile against the consumer before resuming ingestion. No records are pruned automatically.

Integer duration_ns is authoritative and exactly equals ended_at minus started_at in UTC. uptime_seconds is compatibility telemetry. SQLite interval append and cumulative uptime update commit together (WAL, synchronous FULL). Consumers split intervals at timezone-aware day/month/hour boundaries for graphs, sum integer nanoseconds and round once at the approved billing boundary. Charges require separate explicit approval; this service never creates charges.

GET :8080/metrics also exposes persistent sleepy_stacks_requests_total{stack_id="123"}: one count per request that resolves to a uniquely enrolled stack, including readiness/startup/upstream failures. Malformed headers, unknown IDs and failed initial Incus lookups are not attributed. The uptime counter retains its existing stack_id/container labels. Enrollment removal or instance deletion preserves historical usage and request counters.

GET :8080/v1/gaps?after=0 returns up to 1000 diagnostic objects {cursor,started_at,ended_at,reason}. ended_at is null for an ongoing Incus outage. Reasons are proxy-offline, incus-unavailable and clock-adjustment. Diagnostic records can close after first retrieval; reread an open record with an earlier cursor. These node-wide diagnostic gaps are conservative and can overlap observed usage on healthy stacks or the final shutdown checkpoint. They are not billing records or proof of per-stack coverage. No gap means only that no gap was detected.

No usage is reconstructed for proxy downtime or failed Incus observations. Abrupt termination loses uncheckpointed time; downtime is recorded from the last persisted poll on reopening. State changes are accurate only to polling precision. Wall-clock elapsed time is compared with monotonic elapsed time; a difference over one second or a backwards wall clock produces a clock-adjustment gap and no usage interval. Backwards checkpoints wait for the prior timestamp to be reached. Smaller clock slews use timestamp elapsed time consistently. Maintenance uptime is included. Deleting or moving a stack must not block ingestion of unrelated historical rows; consumers should quarantine unresolved IDs while advancing their global cursor. The journal alone cannot prove exact billable uptime through outages or migration.

Both metrics and journal routes share the authenticated management listener. Restrict :8080 to trusted node/master/monitoring callers with host networking policy or a private listener address. Do not expose it publicly.

Deployment handoff and safeguards

Build and verify on Linux amd64 with Go 1.24+, a C compiler and compatible target libc (SQLite uses CGO):

go test -race ./...
go vet ./...
python3 -m unittest discover -s deploy -p 'test_*.py'
go build -buildvcs=false -o sleepy-stacks .
SSH_CONFIG=/home/cx/.ssh/config sh deploy/deploy.sh stack-node-dev-01.rosti.cz
systemctl is-active sleepy-stacks.service  # run on target

Deployment requires Python 3 and a running vmapi.service. Before replacing the proxy binary, deploy/sync-vmapi-token.py reads only TOKEN from the running vm-api process environment (/proc/<MainPID>/environ). This includes both inline systemd Environment= and environment-file configuration without evaluating or sourcing either. A PID recheck rejects concurrent vm-api restarts. Missing, empty, ambiguous or malformed tokens abort deployment without changing the binary. The helper atomically installs /etc/sleepy-stacks/token.env (root-only directory 0700, file 0600); it never prints credentials. Rotate vm-api credentials first, then redeploy the proxy to copy the new effective value and restart it.

The systemd unit reads optional /etc/default/sleepy-stacks followed by mandatory /etc/sleepy-stacks/token.env, so tuning cannot override the synchronized token. For manual installation, provision that root-only token file before starting. The unit defaults its database to /var/lib/sleepy-stacks/uptime.db. Set SLEEPY_STACKS_PROJECT and listener addresses there as required. Increase TimeoutStopSec when increasing shutdown timeout. The deployment script preserves existing systemd units managed by ansible-ng; it installs the bundled unit only when none exists. It enables/restarts the service without changing instance enrollment fields or existing database files. Before moving to the next node, deploy/verify-deployment.py waits up to two minutes for the running executable's SHA-256 to match the build, its token to match vm-api, and authenticated metrics to report a successful inventory less than 30 seconds old. Failure stops deployment before the next node. It does not automatically roll back a failed restart. Deployment is sequential across explicitly named allowlisted nodes.

The dev workflow tests PRs and main; only a push to main deploys, only to stack-node-dev-01.rosti.cz. It loads SSH_MASTER_KEY and installs the independently verified public host key in deploy/known_hosts.dev. Key rotation requires verifying and updating that checked-in key. CI still requires access to the organization SSH secret, reachable dev node, runner Go/CGO prerequisites and supported actions.

Production deploys published releases, or an explicit manual dispatch on main with boolean input deploy_production=true. Both require repository variable SLEEPY_PROXY_PRODUCTION_ENABLED=true. Publishing a release is the normal way to ship a new production version; ordinary pushes to main deploy development only. The checked-out revision must belong to main's history.

The production workflow tests and builds once on a [prod, amd64, debian12] runner, retaining compatibility with the oldest production host's glibc. Build logs record the Git revision and artifact checksum. The same artifact is then deployed to stack-node-01.rosti.cz, stack-node-02.rosti.cz and stack-node-03.rosti.cz, in that order. Concurrent production runs are serialized.

The workflow uses the organization SSH_MASTER_KEY and the repository SLEEPY_STACKS_KNOWN_HOSTS secret containing independently verified production host keys. Strict host-key checking remains enabled. It selects the production environment and sets ALLOW_PRODUCTION_DEPLOY=true for the allowlisted nodes. Repository write access, workflow changes and runner isolation remain deployment security boundaries because the runner holds a root deployment key.

Lifecycle synchronization and conditional maintenance writes

Proxy and vm-api must share the same host-visible lock directory. For each instance, the filename is lowercase hexadecimal SHA256 of its UTF-8 name plus .lock, with no project component. Both processes use Linux exclusive flock on that file and never unlink it. The proxy creates directories with mode 0770 and lockfiles with mode 0660, subject to umask; use the same service UID or provision a writable shared group and suitable umask. Different project instances with identical names safely serialize on the same file. Lock acquisition respects context cancellation.

The proxy acquires st.mu, then the cross-process lock, then refreshes Incus state. It holds both locks through start/readiness or maintenance reconciliation/stop. vm-api must hold the same flock around its full read/configure/wake/rollback operation for profile and maintenance changes. This prevents a stale sleepy snapshot from stopping an instance after conversion to a normal profile. Changing the lock directory on only one service breaks this guarantee.

Maintenance writes use a dependency-free HTTP client over the configured local Unix socket: GET /1.0/instances/<name>?project=<project>, compare the current canonical stack ID and maintenance lease to the expected snapshot, then PATCH only the two maintenance keys with the GET's exact ETag in If-Match. A changed snapshot, missing ETag, HTTP 412, unsupported response, deadline or API failure skips shutdown and leaves reconciliation for a later sweep. There is no unconditional write fallback or immediate retry against a renewed lease. This follows the official Incus conditional-update model and the instance PATCH handler's ETag check. CLI start/stop remain in use with --force-local and INCUS_SOCKET set to the same socket, ensuring that CLI and REST operations cannot address different daemons. Deploy only on the stack node hosting those instances.

Coverage envelope

Every usage page now adds the following version-1-compatible object:

{"coverage":{"observed_from":"2026-10-30T12:00:00Z","observed_until":"2026-10-30T12:01:00Z","gaps":[],"gaps_complete":true}}

observed_from is the persisted first fully successful sweep; observed_until is the persisted last fully successful sweep. Both are null before the first success, including an upgrade from a database without coverage metadata. Watermarks are advanced only after all instance refreshes, checkpoints and lifecycle reconciliations succeed. Failures keep the previous watermark and an open global diagnostic gap; recovery closes the gap and advances the watermark in one transaction. The additional sweep-incomplete gap reason covers lock, checkpoint, maintenance and action failures.

Coverage includes all diagnostic gaps as {started_at,ended_at,reason}, with a null end for ongoing gaps. At most 1000 are included; if any were truncated, gaps_complete is false. Journal records, meter identity and coverage are read from one SQLite snapshot so the coverage cannot race ahead of the returned journal page. Consumers must finish pagination, retain coverage intact and require sufficient history and complete gap information for the relevant rate epoch. First observation after epoch start, missing/null coverage, a failed page, an overlapping gap or a truncated gap list prevents treating missing usage as observed zero. Coverage does not remove the documented polling precision or enable charging in this service.

Maintenance PATCH accepts synchronous HTTP 200 and asynchronous HTTP 202 responses. For async responses, the returned local operation is awaited at /1.0/operations/<id>/wait?timeout=-1&project=<project> under the same original Incus reconciliation deadline. Only operation status_code 200 with an empty err is success. Failure, cancellation, malformed operation URLs and timeouts keep the sweep incomplete. The current upstream PATCH handler returns synchronous success; the vendored Incus UpdateInstance client uses asynchronous PUT. Supporting both response forms preserves compatibility without treating accepted work as completed. See Incus background operations.

Node inventory gauges

The metrics endpoint publishes these gauges after a fully successful sweep:

Metric Meaning
sleepy_stacks_stacks Normal and sleepy containers in the configured Incus project, excluding configured unlabeled reference instances
sleepy_stacks_sleepy_stacks Containers with nonempty effective user.stack-id
sleepy_stacks_awake_sleepy_stacks Awake sleepy stacks, excluding v2 sleep and incomplete wakes, including maintenance
sleepy_stacks_inventory_success 1 if the last entire sweep succeeded, otherwise 0
sleepy_stacks_inventory_last_success_timestamp_seconds Unix timestamp of the retained successful inventory snapshot

Inventory uses the configured project's normal and sleepy containers, except configured administrative/reference images. SLEEPY_STACKS_INVENTORY_EXCLUDED_INSTANCES (or -inventory-excluded-instances) defaults to the known Roští reference image stackimage0. Supply comma-separated exact names to replace the default; surrounding whitespace and empty entries are ignored. An explicitly empty value disables all exclusions. Names are case-sensitive, with no prefix or wildcard matching. An instance with a nonempty effective user.stack-id always overrides the exclusion and contributes to total, sleepy and (when logically awake) awake sleepy counts. Exclusions affect inventory only; routing, enrollment and lifecycle behavior are unchanged. Other normal containers without markers cannot be distinguished from administrative containers unless their names are configured in this list. VM instances are excluded. Awake means Incus Running, independent of active HTTP requests. The final inventory is read after lifecycle actions, so successful idle stops are reflected in that snapshot. On any sweep or final inventory failure, previous counts and their timestamp are retained and inventory_success becomes 0. Before the first success, count and timestamp samples are omitted and success is 0; no zero inventory is fabricated. Consumers should check success and timestamp age before treating the retained counts as current.

The real Incus acceptance test is SSH_CONFIG=/home/cx/.ssh/config sh deploy/smoke-test.sh. It is restricted to stack-node-dev-01.rosti.cz, creates a disposable project, transient proxy, and separate database, and cleans up its own resources. It requires the local rosti/stackimage/v2 image and pool0 storage on that node.