Skip to content
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Releases are cut with `scripts/release.sh <version> [notes]`, which patches `int

**Sharing** (`internal/share/manager.go`, `alios share`): exposes a project publicly through a Cloudflare Tunnel. A `cloudflared` container on `alios_internal` sends traffic to Caddy over plain HTTP, and a `<project>.share.caddyfile` vhost matching the exact public host proxies it on to the project. That vhost file is the only record of a share's URL, mode and auth. The tunnel containers carry `alios.share.*` labels only so leftovers can be found and removed, and they're deliberately not global services, so `global restart` doesn't bounce them. Quick mode (default) runs one `alios_share_<project>` container per share with a random trycloudflare.com URL. Named mode (`ALIOS_SHARE_TUNNEL_TOKEN` + `ALIOS_SHARE_DOMAIN`) runs one shared `alios_share` container whose `*.<domain>` ingress is configured in the Cloudflare dashboard. See `docs/SHARING.md`.

**Scale to zero** (`internal/idle`, `cmd/alios-idle`, `alios idle`): the `alios_idle` global service stops project containers that have been idle for `ALIOS_IDLE_TIMEOUT` (default 30m; the per-project `alios.project.idle` label overrides it) and starts them again when Caddy can't reach them. Every project and share vhost ends with `import alios_wake <project>`, a snippet in the base Caddyfile that sends 502/503/504 errors to the waker, which starts the container and 307-redirects back to the same URL. `alios stop` swaps that line for `import alios_stopped <project>` (a "stopped" page), so a project stopped by hand stays down until `alios start`; the vhost is the only record of which state a project is in (`ssl.SetProjectStopped`). Idle means no network traffic, no CPU and no exec'd processes over the timeout (`idle.Tracker`, unit-tested). `alios_idle` is deliberately not a compose service or in `GlobalServices`: it's optional, and compose aborts the whole `up` when one image can't be pulled (`services/idle.go`). The service runs from its own image (`Dockerfile.idle`, pushed by `scripts/release.sh` as `ghcr.io/aliasproject/alios-idle:<version>`), and it is the one place that talks to the Docker Engine API over the socket directly instead of through `docker.Client`, because its scratch image has no docker CLI. See `docs/IDLE.md`.

**Networking**: all alios containers share one Docker bridge network (`alios_internal`, see `config.GetNetworkConfig()`). The `alios_dns` container resolves `*.test` to the host so `https://<project>.test` reaches Caddy, which reverse-proxies to `alios_php_<project>` by container name (Caddy resolves Docker container names on the shared network natively — no explicit resolver directive needed). Project containers get `alios_dns`'s live container IP injected as their DNS server (resolved at container-creation time, not hardcoded) so they can resolve other `.test` domains from inside.

**Self-update** (`internal/updater/updater.go`): checks GitHub Releases (private repo, needs `GITHUB_TOKEN`) first, then falls back to a public S3/R2-hosted `manifest.json`. Replaces the running binary atomically, escalating to `sudo`/Windows UAC if the install path isn't writable.
Expand Down
17 changes: 17 additions & 0 deletions Dockerfile.idle
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# The alios_idle global service (cmd/alios-idle). Published as
# ghcr.io/aliasproject/alios-idle:<version> by scripts/release.sh, tagged with
# the CLI version so a CLI always runs the service it was built against.
FROM golang:1.23-alpine AS build
WORKDIR /src
COPY go.mod ./
COPY cmd/alios-idle ./cmd/alios-idle
COPY internal/idle ./internal/idle
ARG TARGETOS TARGETARCH
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -trimpath -ldflags="-s -w" -o /alios-idle ./cmd/alios-idle

FROM scratch
COPY --from=build /alios-idle /alios-idle
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s CMD ["/alios-idle", "healthcheck"]
ENTRYPOINT ["/alios-idle"]
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ labels.
pulled image — per project, switchable any time
- Per-project env vars injected into the container, same as production
- Pause/resume everything with one command
- Scale to zero: idle projects are stopped and start again on the next
visit (see [docs/IDLE.md](docs/IDLE.md))

## Installation

Expand Down Expand Up @@ -121,6 +123,21 @@ alios global restart
alios global status
```

### Scale to zero

Projects nobody is using are stopped after 30 minutes (`ALIOS_IDLE_TIMEOUT`),
and the next request to one starts it again. The first page load takes a
second or two longer. `exec`, `shell` and `share` start a sleeping project
too. A project stopped with `alios stop` stays down until `alios start`. See
[docs/IDLE.md](docs/IDLE.md) for how idle is detected.

```
alios idle # show this project's setting
alios idle off # never stop it (e.g. it runs a queue worker)
alios idle 2h # its own timeout
alios idle on # back to ALIOS_IDLE_TIMEOUT
```

### Pause & resume

Stop everything at once to free up CPU/RAM, then bring back exactly what was
Expand Down Expand Up @@ -218,6 +235,9 @@ ALIOS_DNS_PORT DNS listener port (default: 53)
ALIOS_ENABLE_SSL Enable/disable SSL setup (default: true)
ALIOS_ENABLE_DNS Enable/disable DNS setup (default: true)
ALIOS_AUTO_START_GLOBAL Auto-start global services (default: true)
ALIOS_IDLE_TIMEOUT Stop projects idle this long, e.g. 30m, 2h, or
off (default: 30m; applied by 'global restart',
kept when unset)
```

## Supported versions
Expand Down
92 changes: 92 additions & 0 deletions cmd/alios-idle/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Command alios-idle is the alios_idle global service: it stops project
// containers that have gone idle and wakes them on the next request. It runs
// in its own container (see Dockerfile.idle); the CLI starts it with the other
// global services and configures it through environment variables.
package main

import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/aliasproject/alios-cli/internal/idle"
)

func main() {
logger := log.New(os.Stdout, "", log.LstdFlags)
listen := envOr("ALIOS_IDLE_LISTEN", ":8080")

// The image has no shell or wget for a Docker healthcheck, so the binary
// checks itself.
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
resp, err := http.Get("http://127.0.0.1" + listen + "/healthz")
if err != nil || resp.StatusCode != http.StatusNoContent {
os.Exit(1)
}
return
}

timeout := duration(logger, "ALIOS_IDLE_TIMEOUT", idle.DefaultTimeout)
engine := idle.NewSocketEngine(envOr("ALIOS_IDLE_DOCKER_SOCKET", "/var/run/docker.sock"))

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()

watcher := &idle.Watcher{
Engine: engine,
Tracker: idle.NewTracker(idle.DefaultThresholds),
Interval: duration(logger, "ALIOS_IDLE_INTERVAL", 30*time.Second),
Timeout: timeout,
BusyWarnAfter: duration(logger, "ALIOS_IDLE_BUSY_WARN", 2*time.Hour),
Log: logger,
}
if watcher.Interval <= 0 {
watcher.Interval = 30 * time.Second
}
go watcher.Run(ctx)

server := &http.Server{
Addr: listen,
Handler: &idle.Waker{
Engine: engine,
WakeTimeout: duration(logger, "ALIOS_IDLE_WAKE_TIMEOUT", 60*time.Second),
Log: logger,
},
ReadHeaderTimeout: 10 * time.Second,
}
go func() {
<-ctx.Done()
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(shutdown)
}()

if timeout > 0 {
logger.Printf("stopping projects after %s idle; waking them on %s", timeout, listen)
} else {
logger.Printf("idle stopping is off (except projects with their own timeout); waking projects on %s", listen)
}
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatal(err)
}
}

func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}

func duration(logger *log.Logger, key string, def time.Duration) time.Duration {
d, err := idle.ParseTimeout(os.Getenv(key), def)
if err != nil {
logger.Printf("ignoring invalid %s=%q, using %s", key, os.Getenv(key), def)
return def
}
return d
}
115 changes: 115 additions & 0 deletions docs/IDLE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Scale to zero

Projects that nobody is using are stopped, and the next request to one starts
it again. Only the projects you're actually working on use CPU and memory, so
you can keep many sites set up without running them all.

```
alios idle # show this project's setting
alios idle off # never stop it
alios idle 2h # stop it after 2h idle instead of the default
alios idle on # back to the default (ALIOS_IDLE_TIMEOUT)
```

The default is 30 minutes. To change it, set `ALIOS_IDLE_TIMEOUT` (for
example `1h`, or `off`) and run `alios global restart`. The service keeps that
value until a later global start runs with the variable set to something
else, so a terminal without it never resets the timeout. `alios status`,
`alios idle` and `alios doctor` report the value the service is actually
running with. `alios idle` stores a project's own setting in a container
label, the same way `alios env` does, so changing it recreates the container.

## How it works

A global service, `alios_idle`, runs next to Caddy and does two jobs.

**Stopping.** Every 30 seconds it reads each running project's counters from
the Docker API and treats the project as active if any of these is true:

- **Network:** more than about 8 KiB/min of traffic. Any page view, API call
or open dev-server connection counts, and so does an app talking to MySQL.
- **CPU:** more than 1% of a core. An idle FrankenPHP container uses about
0.1%.
- **Exec sessions:** any process that was exec'd into the container rather
than started by its server, seen in two samples in a row. That covers
`alios exec` and `alios shell` for as long as they're open, including an
idle shell, which uses no CPU or traffic. A health check that happens to be
running when a sample is taken doesn't count. Processes the server itself
starts, such as its workers or a supervisor's queue workers, aren't exec
sessions, so only their CPU and traffic count.

A project that stays quiet on all three for the timeout is stopped. Docker
remembers that it was stopped, so it stays stopped after a reboot, and only
the projects you were using come back.

**Waking.** A project's vhost ends with `import alios_wake <project>`. When the
container is stopped, Caddy can't reach it, and the request goes to
`alios_idle` instead. It starts the container, waits until it accepts
connections (usually under a second), then replies with a `307` redirect to
the same URL so the browser tries again. With a `307` the browser resends the
original method and body, so a form POST or an API call is resubmitted, not
turned into a GET. The waker itself only ever sees a bodiless GET. Only
Caddy's own upstream failures (502, 503, 504) go to the waker, so an app's
error pages and a share's basic-auth prompt pass through untouched.

`alios_idle` is optional. It runs outside the compose group, so if its image
can't be pulled, `alios global start` warns and carries on. DNS, Caddy and
your projects still work, and nothing is stopped or woken. A stopped project
then shows Caddy's empty 502 until `alios_idle` is running again, and
`alios doctor` reports it. `alios pause` stops it before the projects, so a
request arriving mid-pause can't start one again.

`alios exec`, `alios shell` and `alios share` start a sleeping project
themselves. `alios list` and `alios status` show such a project as
"sleeping".

## Sleeping vs stopped

A project the watcher stopped for being idle is **sleeping**: the next visit
starts it. A project you stop with `alios stop` is **stopped**: it stays down
until `alios start`. A visit gets a short "stopped" page instead, and `exec`,
`shell` and `share` ask you to start it first. That way, a browser tab that
keeps polling the project can't undo the stop.

The difference is recorded in the project's vhost: `alios stop` swaps its
`import alios_wake <project>` line for `import alios_stopped <project>`, and
`alios start` swaps it back, and so do the other commands that start the
container (`restart`, `rebuild`, `php`, `image`). `alios pause`/`resume`,
`alios cert repair` and `alios cert remove` keep it.

## Busy without traffic

A project that keeps using CPU for 2 hours with no traffic at all is either
running a long job or stuck. (An open but idle `alios shell` keeps a project
awake without counting as busy.) `alios_idle` keeps it running
either way, and logs a `busy-warning` line, which `alios doctor` shows. Check
it with `alios logs` or `docker top alios_php_<project>`.

## When to turn it off

Use `alios idle off` for a project that has to keep running with no requests:
one with a queue worker or scheduler running inside its container, for
example. A worker the container's server starts isn't an exec session, so
only its CPU and traffic count, and its polling may be too light to register,
so the project can be stopped while the worker waits for jobs.

## Upgrading

Vhosts written by an older alios don't have the `import alios_wake` line, so
visiting one of those projects while it's stopped shows Caddy's error instead
of starting it. Each vhost is rewritten on that project's next `alios start`,
or run `alios cert repair` to update them all; it writes the base Caddyfile
with the snippet first. `alios global start` and `alios doctor` point out any
that are left. A shared project's share vhost picks up the snippet the next
time it's shared.

## Security

`alios_idle` mounts the Docker socket so that it can read stats and start and
stop containers. Mounting the socket gives a container root-equivalent access
to the host. The service only ever starts a container named
`alios_php_<project>` that carries the matching `alios.project.name` label.
Its waker listens only on the internal `alios_internal` network, with no port
published to the host. Rootless Docker isn't supported yet: the socket path is
fixed at `/var/run/docker.sock`, which Docker Desktop also provides on macOS
and Windows.
13 changes: 12 additions & 1 deletion internal/commands/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ func (h *Handler) handleDoctor() error {
h.doctorSSL(r)
h.doctorProject(r, tokenOK)
h.doctorShare(r)
h.doctorIdle(r)

return r.summary()
}
Expand Down Expand Up @@ -308,6 +309,9 @@ func (h *Handler) doctorServices(r *doctorReport) {
return
}
for _, svc := range svcs {
if svc.Container == services.IdleContainer {
continue // optional; checked in its own section (doctorIdle)
}
if svc.Status == "running" {
r.ok("%s running (%s)", svc.Name, svc.Container)
continue
Expand Down Expand Up @@ -408,8 +412,15 @@ func (h *Handler) doctorProject(r *doctorReport, registryOK bool) {
}

domain := proj.Name + ".test"
if _, err := h.docker.ReadFileFromVolume("alios_vhosts", proj.Name+".caddyfile"); err == nil {
if vhost, err := h.docker.ReadFileFromVolume("alios_vhosts", proj.Name+".caddyfile"); err == nil {
r.ok("Caddy vhost %s.caddyfile present", proj.Name)
switch {
case strings.Contains(vhost, "import alios_stopped"):
r.info("Stopped with 'alios stop': visits won't start it until 'alios start'")
case !strings.Contains(vhost, "import alios_wake"):
r.warn("Vhost predates scale to zero, so visiting the project while it's asleep won't start it",
"alios cert repair")
}
} else {
r.fail("Caddy vhost missing (https://"+domain+" will hit the 'No project here' page)", "alios cert repair")
}
Expand Down
Loading