diff --git a/CLAUDE.md b/CLAUDE.md index 8dc0e94..8de81b5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,6 +40,8 @@ Releases are cut with `scripts/release.sh [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 `.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_` 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 `*.` 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 `, 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 ` (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:`), 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://.test` reaches Caddy, which reverse-proxies to `alios_php_` 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. diff --git a/Dockerfile.idle b/Dockerfile.idle new file mode 100644 index 0000000..5ab0d66 --- /dev/null +++ b/Dockerfile.idle @@ -0,0 +1,17 @@ +# The alios_idle global service (cmd/alios-idle). Published as +# ghcr.io/aliasproject/alios-idle: 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"] diff --git a/README.md b/README.md index b9a9e01..80bf11d 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 @@ -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 diff --git a/cmd/alios-idle/main.go b/cmd/alios-idle/main.go new file mode 100644 index 0000000..b589f67 --- /dev/null +++ b/cmd/alios-idle/main.go @@ -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 +} diff --git a/docs/IDLE.md b/docs/IDLE.md new file mode 100644 index 0000000..df36474 --- /dev/null +++ b/docs/IDLE.md @@ -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 `. 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 ` line for `import alios_stopped `, 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_`. + +## 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_` 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. diff --git a/internal/commands/doctor.go b/internal/commands/doctor.go index a50b7dc..43a59b1 100644 --- a/internal/commands/doctor.go +++ b/internal/commands/doctor.go @@ -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() } @@ -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 @@ -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") } diff --git a/internal/commands/handler.go b/internal/commands/handler.go index 097fa84..cc975fe 100644 --- a/internal/commands/handler.go +++ b/internal/commands/handler.go @@ -126,6 +126,8 @@ func (h *Handler) Execute(args []string) error { return h.handleImage(commandArgs) case "env": return h.handleEnv(commandArgs) + case "idle": + return h.handleIdle(commandArgs) case "share": return h.handleShare(commandArgs) @@ -192,6 +194,7 @@ func (h *Handler) handleGlobalCommand(args []string) error { return fmt.Errorf("failed to start services: %w", err) } fmt.Println(utils.Colorize("[SUCCESS]", utils.ColorGreen) + " Global services started successfully") + h.hintVhostsWithoutWake() return h.showServicesStatus() case "stop": @@ -211,6 +214,7 @@ func (h *Handler) handleGlobalCommand(args []string) error { return fmt.Errorf("failed to restart services: %w", err) } fmt.Println(utils.Colorize("[SUCCESS]", utils.ColorGreen) + " Global services restarted") + h.hintVhostsWithoutWake() return h.showServicesStatus() case "status": @@ -312,6 +316,13 @@ func (h *Handler) handleCertRepair() error { fmt.Printf(utils.Colorize("[RESTARTING]", utils.ColorCyan)+" Repairing SSL/vhost configuration for %d project(s)...\n", len(names)) + // The vhosts import the alios_wake snippet from the base Caddyfile; + // rewrite it first, or a base file from an older alios would leave Caddy + // unable to start on the new vhosts. + if err := h.services.WriteBaseConfig(); err != nil { + return fmt.Errorf("failed to write the base Caddyfile: %w", err) + } + repaired, repairErr := h.ssl.RepairVhosts(names) if repairErr != nil { fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: %v\n", repairErr) @@ -566,6 +577,22 @@ func (h *Handler) handleStart(args ...string) error { return fmt.Errorf("failed to start project: %w", err) } + // The vhost written below imports snippets from the base Caddyfile, and + // EnsureRunning skips rewriting it when services are already up - after + // an alios update that would leave Caddy unable to load the new vhost. + if err := h.services.WriteBaseConfig(); err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to update the base Caddyfile: %v\n", err) + } + + // The SSL setup below rewrites the vhost, which also clears an `alios + // stop`; without SSL, clear it directly (the base config was just + // written, so skip clearStopped's rewrite). + if !h.config.EnableSSL { + if err := h.ssl.SetProjectStopped(proj.Name, false); err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to re-enable waking for the project: %v\n", err) + } + } + // Setup SSL for project if h.config.EnableSSL { if err := h.ssl.SetupProjectSSL(proj.Name); err != nil { @@ -697,6 +724,7 @@ func (h *Handler) handleImage(args []string) error { return fmt.Errorf("failed to switch image: %w", err) } + h.clearStopped(proj.Name) fmt.Println(utils.Colorize("[SUCCESS]", utils.ColorGreen) + " Image switched successfully") updated, err := h.projects.GetCurrentProject() if err != nil { @@ -705,15 +733,18 @@ func (h *Handler) handleImage(args []string) error { return h.showProjectStatus(updated) } -// handleStop stops the current project and ends its share. +// handleStop stops the current project until the next `alios start`: it +// ends the share and marks the vhost stopped, so a visit doesn't start it +// again the way it would a project that went to sleep for being idle. func (h *Handler) handleStop() error { return h.stopProject(true) } -// stopProject stops the current project. A restart passes endShare=false: -// the tunnel points at Caddy, not the container, so the share keeps working -// (and keeps its URL) once the project is back up. -func (h *Handler) stopProject(endShare bool) error { +// stopProject stops the current project. A restart passes manual=false: the +// project is coming straight back, so its share keeps working (the tunnel +// points at Caddy, not the container, so it keeps its URL) and its vhost +// isn't marked stopped. +func (h *Handler) stopProject(manual bool) error { project, err := h.projects.GetCurrentProject() if err != nil { return err @@ -721,15 +752,32 @@ func (h *Handler) stopProject(endShare bool) error { fmt.Printf(utils.Colorize("[STOPPING]", utils.ColorYellow)+" Stopping project '%s'...\n", project.Name) - if err := h.projects.Stop(); err != nil { - return fmt.Errorf("failed to stop project: %w", err) + // Mark the vhost stopped before stopping the container: while the app + // shuts down Caddy's requests fail, and with the wake snippet still in + // place a polling tab would have the waker start it straight back up. + marked := false + if manual { + h.stopShareQuietly(project.Name) + if err := h.markStopped(project.Name, true); err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to mark the project stopped, so a visit may start it again: %v\n", err) + } else { + marked = true + } } - if endShare { - h.stopShareQuietly(project.Name) + if err := h.projects.Stop(); err != nil { + // Still running: don't leave it marked stopped, or once it next + // goes idle a visit would show the "stopped" page. + if marked { + h.ssl.SetProjectStopped(project.Name, false) + } + return fmt.Errorf("failed to stop project: %w", err) } fmt.Println(utils.Colorize("[SUCCESS]", utils.ColorGreen) + " Project stopped") + if marked { + fmt.Println(" It stays stopped until 'alios start'.") + } return nil } @@ -761,6 +809,7 @@ func (h *Handler) handleRebuild() error { return fmt.Errorf("failed to rebuild project: %w", err) } + h.clearStopped(project.Name) fmt.Printf(utils.Colorize("[SUCCESS]", utils.ColorGreen)+" '%s' rebuilt and running\n", project.Name) return nil } @@ -822,17 +871,28 @@ func (h *Handler) handleList() error { return nil } + // Telling asleep from stopped costs a throwaway container, so only look + // when some project is down and alios_idle could wake it. If the vhosts + // can't be read, call none of them asleep rather than all of them. + waking := false + var stopped map[string]bool + if h.docker.IsContainerRunning(services.IdleContainer) { + for _, proj := range projects { + if proj.Status == "stopped" { + if s, err := h.ssl.StoppedProjects(); err == nil { + waking, stopped = true, s + } + break + } + } + } fmt.Printf("Found %d project(s):\n\n", len(projects)) for _, proj := range projects { - status := utils.Colorize("[STOPPED]", utils.ColorRed) + " stopped" - if proj.Status == "running" { - status = utils.Colorize("[RUNNING]", utils.ColorGreen) + " running" - } - - fmt.Printf(" %s (%s)\n", proj.Name, status) + asleep := waking && !stopped[proj.Name] + fmt.Printf(" %s (%s)\n", proj.Name, h.formatProjectStatus(proj.Status, asleep)) fmt.Printf(" PHP: %s\n", proj.PHPVersion) fmt.Printf(" Path: %s\n", proj.Path) - if proj.Status == "running" { + if proj.Status == "running" || asleep { fmt.Printf(" URL: %s\n", proj.URL) } fmt.Println() @@ -884,6 +944,7 @@ func (h *Handler) handlePHPVersion(args []string) error { return fmt.Errorf("failed to change PHP version: %w", err) } + h.clearStopped(proj.Name) fmt.Printf(utils.Colorize("[SUCCESS]", utils.ColorGreen)+" PHP version changed to %s\n", newVersion) fmt.Println("Run 'alios start' to start with the new version") return nil @@ -1056,8 +1117,8 @@ func (h *Handler) handleContainerExec(command string, args []string) error { return fmt.Errorf("unknown command: %s (project not initialized)", command) } - if project.Status != "running" { - return fmt.Errorf("project container is not running. Run 'alios start' first") + if err := h.wakeForCommand(); err != nil { + return err } // Prepare command for execution @@ -1087,8 +1148,8 @@ func (h *Handler) handleExec(args []string) error { return fmt.Errorf("project not initialized. Run 'alios start' first") } - if project.Status != "running" { - return fmt.Errorf("project container is not running. Run 'alios start' first") + if err := h.wakeForCommand(); err != nil { + return err } err = h.projects.Exec(args, false) @@ -1118,8 +1179,8 @@ func (h *Handler) handleShell(args []string) error { return fmt.Errorf("project not initialized. Run 'alios start' first") } - if project.Status != "running" { - return fmt.Errorf("project container is not running. Run 'alios start' first") + if err := h.wakeForCommand(); err != nil { + return err } if *userFlag != "" { @@ -1408,10 +1469,12 @@ func (h *Handler) showStatus() error { fmt.Printf("\n" + utils.Colorize("[DIRECTORY]", utils.ColorCyan) + " Current Project:\n") fmt.Printf(" Name: %s\n", project.Name) fmt.Printf(" PHP: %s\n", project.PHPVersion) - fmt.Printf(" Status: %s\n", utils.FormatStatus(project.Status)) - if project.Status == "running" { + asleep := h.projectAsleep(project.Name, project.Status) + fmt.Printf(" Status: %s\n", h.formatProjectStatus(project.Status, asleep)) + if project.Status == "running" || asleep { fmt.Printf(" URL: %s\n", project.URL) } + fmt.Printf(" Idle: %s\n", h.describeIdle(project.Idle)) if sh, err := h.share.Get(project.Name); err == nil && sh != nil { fmt.Printf(" Shared: %s\n", formatShare(sh, h.share.TunnelRunning(sh))) } @@ -1488,7 +1551,7 @@ USAGE: COMMANDS: Project Management: start [version] Start project (with optional PHP version) - stop Stop the current project + stop Stop the current project until the next start restart Restart the current project rebuild Force-recreate the container from a fresh image (e.g. after editing a custom Dockerfile) @@ -1504,6 +1567,8 @@ COMMANDS: share [--auth u:p] Share the project at a public URL (Cloudflare Tunnel) share stop Stop sharing the current project share list List every active share + idle Show when the project is stopped for being idle + idle off|on| Never stop it / use ALIOS_IDLE_TIMEOUT / own timeout Machine Lifecycle: pause Stop every alios container (projects + global services) @@ -1550,6 +1615,7 @@ EXAMPLES: alios env unset APP_DEBUG # Remove an env var alios share # Get a public URL for the current project alios share --auth demo:secret # Same, behind a username/password + alios idle off # Keep a project with a queue worker running alios doctor # Diagnose why something isn't working alios check-update # Check for available updates alios update # Update to latest version diff --git a/internal/commands/idle.go b/internal/commands/idle.go new file mode 100644 index 0000000..4c2a34c --- /dev/null +++ b/internal/commands/idle.go @@ -0,0 +1,186 @@ +package commands + +import ( + "fmt" + "strings" + "time" + + "github.com/aliasproject/alios-cli/internal/idle" + "github.com/aliasproject/alios-cli/internal/project" + "github.com/aliasproject/alios-cli/internal/services" + "github.com/aliasproject/alios-cli/internal/utils" +) + +// handleIdle shows or changes the current project's scale-to-zero setting: +// +// alios idle show it +// alios idle off never stop this project (e.g. it runs a queue worker) +// alios idle on use the global ALIOS_IDLE_TIMEOUT again +// alios idle 2h stop it after its own idle timeout +func (h *Handler) handleIdle(args []string) error { + proj, err := h.projects.GetCurrentProject() + if err != nil { + return err + } + if proj.Status == "not initialized" { + return fmt.Errorf("project not initialized. Run 'alios start' first") + } + + if len(args) == 0 { + fmt.Printf("%s: %s\n", proj.Name, h.describeIdle(proj.Idle)) + if !h.docker.IsContainerRunning(services.IdleContainer) { + fmt.Println(utils.Colorize("[WARNING]", utils.ColorYellow) + " alios_idle isn't running, so nothing is stopped or woken. Run 'alios global start'.") + } + return nil + } + if len(args) > 1 { + return fmt.Errorf("usage: alios idle [on|off|]") + } + + setting := strings.TrimSpace(args[0]) + if setting == "on" || setting == "default" { + setting = "" + } + if setting == "never" { + setting = "off" + } + + // Changing the label recreates the container, which counts as a fresh + // start for the idle timer, so this never stops the project right away. + if err := h.projects.SetIdle(setting); err != nil { + return err + } + fmt.Printf(utils.Colorize("[SUCCESS]", utils.ColorGreen)+" %s: %s\n", proj.Name, h.describeIdle(setting)) + return nil +} + +// wakeForCommand starts the current project if it's asleep, for commands +// that need its container running: exec, shell, share. A project stopped +// with `alios stop` stays stopped. +func (h *Handler) wakeForCommand() error { + proj, err := h.projects.GetCurrentProject() + if err != nil { + return err + } + // Only a stop by hand is respected. If the vhosts can't be read, wake + // it: the command was asked for explicitly. + if proj.Status == "stopped" { + if stopped, err := h.ssl.StoppedProjects(); err == nil && stopped[proj.Name] { + return fmt.Errorf("project is stopped. Run 'alios start' first") + } + } + woke, err := h.projects.Wake() + if woke { + fmt.Println(utils.Colorize("[STARTING]", utils.ColorCyan) + " Project was asleep; started it") + } + return err +} + +// describeIdle explains a project setting against the timeout the running +// alios_idle service actually uses, not this shell's ALIOS_IDLE_TIMEOUT. +func (h *Handler) describeIdle(setting string) string { + global, _ := h.services.IdleTimeoutSetting() + return project.DescribeIdle(setting, global) +} + +// markStopped records an `alios stop` (or clears it) in the project's vhost. +// The base Caddyfile is rewritten first so the snippet the vhost will import +// exists even if services were started by an older alios. +func (h *Handler) markStopped(name string, stopped bool) error { + if err := h.services.WriteBaseConfig(); err != nil { + return err + } + return h.ssl.SetProjectStopped(name, stopped) +} + +// clearStopped makes a project wake on visits again, for commands that start +// it other than `alios start` (rebuild, php, image). +func (h *Handler) clearStopped(name string) { + if err := h.markStopped(name, false); err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to re-enable waking for the project: %v\n", err) + } +} + +// projectAsleep reports whether a stopped project starts again on the next +// visit: alios_idle is running and the project wasn't stopped with `alios +// stop`. +func (h *Handler) projectAsleep(name, status string) bool { + if status != "stopped" || !h.docker.IsContainerRunning(services.IdleContainer) { + return false + } + stopped, err := h.ssl.StoppedProjects() + return err == nil && !stopped[name] +} + +// formatProjectStatus shows a stopped project as sleeping when the next +// request to it starts it again. +func (h *Handler) formatProjectStatus(status string, asleep bool) string { + if status == "stopped" && asleep { + return utils.Colorize("[SLEEPING]", utils.ColorBlue) + " sleeping, starts on the next visit" + } + return utils.FormatStatus(status) +} + +// hintVhostsWithoutWake points out project vhosts written before scale to +// zero, which don't start a stopped project on a visit. Each is rewritten on +// that project's next `alios start`; `alios cert repair` does them all. +func (h *Handler) hintVhostsWithoutWake() { + output, err := h.docker.RunWithOutput("run", "--rm", "-v", "alios_vhosts:/vhosts:ro", "alpine:latest", + "sh", "-c", "cd /vhosts && grep -LE 'import alios_(wake|stopped)' *.caddyfile 2>/dev/null; true") + if err != nil { + return + } + // Output can include docker's own pull messages, so count only file + // names. Share vhosts are skipped: cert repair doesn't rewrite them (the + // next `alios share` does), so counting them would repeat the hint. + n := 0 + for _, line := range strings.Split(output, "\n") { + line = strings.TrimSpace(line) + if strings.HasSuffix(line, ".caddyfile") && !strings.HasSuffix(line, ".share.caddyfile") { + n++ + } + } + if n == 0 { + return + } + fmt.Printf(utils.Colorize("[INFO]", utils.ColorBlue)+" %d vhost(s) predate scale to zero, so those projects won't start on a visit. Run 'alios cert repair' to update them.\n", n) +} + +// doctorIdle checks the scale-to-zero service and reports projects it has +// flagged as busy for a long time with no traffic. +func (h *Handler) doctorIdle(r *doctorReport) { + r.section("SCALE TO ZERO") + + if _, err := idle.ParseTimeout(h.config.IdleTimeout, idle.DefaultTimeout); err != nil { + r.fail(fmt.Sprintf("ALIOS_IDLE_TIMEOUT=%q isn't a duration", h.config.IdleTimeout), + "set it to e.g. 30m or 2h, or off, then run 'alios global restart'") + } + + running, ok := h.services.IdleTimeoutSetting() + if !ok { + r.fail("alios_idle isn't running: idle projects aren't stopped, and stopped ones aren't started on a visit", + "alios global start (its output says why it couldn't start, e.g. the image couldn't be pulled)") + return + } + if h.config.IdleTimeout != "" && h.config.IdleTimeout != running { + r.warn(fmt.Sprintf("ALIOS_IDLE_TIMEOUT is %q here but alios_idle runs with %q", h.config.IdleTimeout, running), + "alios global restart, to apply this shell's value") + } + r.ok("alios_idle running (%s)", strings.TrimPrefix(h.describeIdle(""), "stops ")) + + logs, err := h.docker.RunWithOutput("logs", "--since", "24h", services.IdleContainer) + if err != nil { + r.warn(fmt.Sprintf("Could not read alios_idle logs: %v", err), "") + return + } + busy := 0 + for _, line := range strings.Split(logs, "\n") { + if i := strings.Index(line, idle.BusyWarning+" "); i >= 0 { + busy++ + r.warn(strings.TrimSpace(line[i+len(idle.BusyWarning):]), "") + } + } + if busy == 0 { + r.ok("No project busy for hours without traffic (last %s)", 24*time.Hour) + } +} diff --git a/internal/commands/pause.go b/internal/commands/pause.go index 51d7679..4ee31e6 100644 --- a/internal/commands/pause.go +++ b/internal/commands/pause.go @@ -21,6 +21,10 @@ func (h *Handler) handlePause() error { fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to stop shares: %v\n", err) } + // The waker goes first: stopping projects takes a while, and a request + // arriving in the meantime would start one again behind the pause. + stoppedIdle := h.services.StopIdle() + stoppedProjects, err := h.projects.StopAll() if err != nil { return fmt.Errorf("failed to stop project containers: %w", err) @@ -30,6 +34,7 @@ func (h *Handler) handlePause() error { if err != nil { return fmt.Errorf("failed to stop global services: %w", err) } + stoppedServices = append(stoppedServices, stoppedIdle...) if len(stoppedProjects) == 0 && len(stoppedServices) == 0 { fmt.Println(utils.Colorize("[INFO]", utils.ColorBlue) + " Nothing was running") diff --git a/internal/commands/share.go b/internal/commands/share.go index 4be0e23..33f009a 100644 --- a/internal/commands/share.go +++ b/internal/commands/share.go @@ -51,8 +51,8 @@ func (h *Handler) handleShare(args []string) error { if project.Status == "not initialized" { return fmt.Errorf("project not initialized. Run 'alios start' first") } - if project.Status != "running" { - return fmt.Errorf("project container is not running. Run 'alios start' first") + if err := h.wakeForCommand(); err != nil { + return err } mode := "quick tunnel" diff --git a/internal/config/config.go b/internal/config/config.go index 93cdabf..e30dc26 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -18,6 +18,10 @@ const ( // AliosBinary is the installation path for the alios binary AliosBinary = "/usr/local/bin/alios" + + // IdleImage is the alios_idle service's image, tagged with the CLI + // version so each CLI runs the service built from the same source. + IdleImage = "ghcr.io/aliasproject/alios-idle:" + Version ) // Config holds the application configuration @@ -43,6 +47,12 @@ type Config struct { // throwaway trycloudflare.com quick tunnel. ShareTunnelToken string ShareDomain string + + // IdleTimeout is how long a project may sit idle before alios_idle stops + // it (ALIOS_IDLE_TIMEOUT: a Go duration such as "30m", or "off"). Empty + // means the service's own default. Passed through to the service as-is; + // it validates the value. + IdleTimeout string } // ShareNamedMode reports whether alios share should use a named tunnel. @@ -184,6 +194,9 @@ func (c *Config) loadFromEnvironment() { // Named-tunnel sharing c.ShareTunnelToken = os.Getenv("ALIOS_SHARE_TUNNEL_TOKEN") c.ShareDomain = normalizeShareDomain(os.Getenv("ALIOS_SHARE_DOMAIN")) + + // Scale to zero + c.IdleTimeout = strings.TrimSpace(os.Getenv("ALIOS_IDLE_TIMEOUT")) } // normalizeShareDomain accepts the forms people paste - "*.acme-dev.com" (the diff --git a/internal/idle/engine.go b/internal/idle/engine.go new file mode 100644 index 0000000..cee2832 --- /dev/null +++ b/internal/idle/engine.go @@ -0,0 +1,267 @@ +package idle + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "time" +) + +// ProjectLabel marks a container as an alios project; IdleLabel holds its +// per-project setting ("off", or a timeout such as "2h"). Both are written by +// project.Manager.createContainer. +const ( + ProjectLabel = "alios.project.name" + IdleLabel = "alios.project.idle" +) + +// Container is the part of a container's state the service needs. +type Container struct { + ID string + Name string // without the leading slash + Project string // ProjectLabel value + Idle string // IdleLabel value + Running bool + StartedAt string // RFC 3339; from Inspect only + MainPID int // host PID of the main process; from Inspect only +} + +// StartedWithin reports whether the container's current run began less than +// d ago. +func (c *Container) StartedWithin(d time.Duration, now time.Time) bool { + at, err := time.Parse(time.RFC3339Nano, c.StartedAt) + return err == nil && now.Sub(at) < d +} + +// Engine is the Docker access the service needs. *SocketEngine implements it +// against the real daemon; tests use a fake. +type Engine interface { + ListProjects(ctx context.Context) ([]Container, error) + Inspect(ctx context.Context, name string) (*Container, error) + Sample(ctx context.Context, c *Container) (Sample, error) + Start(ctx context.Context, id string) error + Stop(ctx context.Context, id string, timeout time.Duration) error +} + +// ErrNotFound is returned by Inspect for a container that doesn't exist. +var ErrNotFound = fmt.Errorf("container not found") + +// SocketEngine talks to the Docker Engine API over a unix socket. +type SocketEngine struct { + http *http.Client +} + +// NewSocketEngine returns an Engine using the daemon socket at path. +func NewSocketEngine(path string) *SocketEngine { + return &SocketEngine{http: &http.Client{ + // Bounds every call, so a wedged container can't hang the watcher. + // Generous enough for a stop, which waits up to 10s for the app. + Timeout: 30 * time.Second, + Transport: &http.Transport{ + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", path) + }, + }, + }} +} + +func (e *SocketEngine) do(ctx context.Context, method, path string, out any) (int, error) { + req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, nil) + if err != nil { + return 0, err + } + resp, err := e.http.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + + if resp.StatusCode >= 400 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) + return resp.StatusCode, fmt.Errorf("%s %s: %d %s", method, path, resp.StatusCode, body) + } + if out != nil { + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { + return resp.StatusCode, fmt.Errorf("%s %s: decoding response: %w", method, path, err) + } + } + return resp.StatusCode, nil +} + +// ListProjects returns every alios project container, running or not. +func (e *SocketEngine) ListProjects(ctx context.Context) ([]Container, error) { + filters := url.QueryEscape(fmt.Sprintf(`{"label":[%q]}`, ProjectLabel)) + var list []struct { + ID string `json:"Id"` + Names []string + State string + Labels map[string]string + } + if _, err := e.do(ctx, http.MethodGet, "/containers/json?all=true&filters="+filters, &list); err != nil { + return nil, err + } + + out := make([]Container, 0, len(list)) + for _, c := range list { + name := "" + if len(c.Names) > 0 { + name = trimSlash(c.Names[0]) + } + out = append(out, Container{ + ID: c.ID, + Name: name, + Project: c.Labels[ProjectLabel], + Idle: c.Labels[IdleLabel], + Running: c.State == "running", + }) + } + return out, nil +} + +// Inspect returns one container by name or ID. +func (e *SocketEngine) Inspect(ctx context.Context, name string) (*Container, error) { + var c struct { + ID string `json:"Id"` + Name string + State struct { + Running bool + StartedAt string + Pid int + } + Config struct { + Labels map[string]string + } + } + status, err := e.do(ctx, http.MethodGet, "/containers/"+url.PathEscape(name)+"/json", &c) + if status == http.StatusNotFound { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return &Container{ + ID: c.ID, + Name: trimSlash(c.Name), + Project: c.Config.Labels[ProjectLabel], + Idle: c.Config.Labels[IdleLabel], + Running: c.State.Running, + StartedAt: c.State.StartedAt, + MainPID: c.State.Pid, + }, nil +} + +// Sample reads a running container's CPU and network counters and counts the +// processes exec'd into it. c must come from Inspect, for its MainPID. +func (e *SocketEngine) Sample(ctx context.Context, c *Container) (Sample, error) { + id := c.ID + var stats struct { + CPUStats struct { + CPUUsage struct { + TotalUsage uint64 `json:"total_usage"` + } `json:"cpu_usage"` + } `json:"cpu_stats"` + Networks map[string]struct { + RxBytes uint64 `json:"rx_bytes"` + TxBytes uint64 `json:"tx_bytes"` + } `json:"networks"` + } + // one-shot skips the extra second the daemon otherwise spends collecting + // a "previous" CPU reading; the tracker keeps its own. + if _, err := e.do(ctx, http.MethodGet, "/containers/"+id+"/stats?stream=false&one-shot=true", &stats); err != nil { + return Sample{}, err + } + + // Default ps arguments (-ef) on purpose: they work with whatever ps the + // daemon's host has, including Docker Desktop's VM. + var top struct { + Titles []string + Processes [][]string + } + if _, err := e.do(ctx, http.MethodGet, "/containers/"+id+"/top", &top); err != nil { + return Sample{}, err + } + execProcs, err := countExecProcs(top.Titles, top.Processes, c.MainPID) + if err != nil { + return Sample{}, err + } + + s := Sample{At: time.Now(), CPUNanos: stats.CPUStats.CPUUsage.TotalUsage, ExecProcs: execProcs} + for _, n := range stats.Networks { + s.NetBytes += n.RxBytes + n.TxBytes + } + return s, nil +} + +// Start starts a container. Starting one that's already running is fine. +func (e *SocketEngine) Start(ctx context.Context, id string) error { + _, err := e.do(ctx, http.MethodPost, "/containers/"+id+"/start", nil) + return err +} + +// Stop stops a container, killing it if it hasn't exited after timeout. +func (e *SocketEngine) Stop(ctx context.Context, id string, timeout time.Duration) error { + _, err := e.do(ctx, http.MethodPost, fmt.Sprintf("/containers/%s/stop?t=%d", id, int(timeout.Seconds())), nil) + return err +} + +// countExecProcs counts the processes in a `docker top` listing that don't +// descend from mainPID. Everything the container's own server starts (worker +// processes, a supervisor's queue workers) descends from it; `docker exec` +// sessions are started beside it by the runtime, so they don't. +func countExecProcs(titles []string, rows [][]string, mainPID int) (int, error) { + pidCol, ppidCol := -1, -1 + for i, t := range titles { + switch t { + case "PID": + pidCol = i + case "PPID": + ppidCol = i + } + } + if pidCol < 0 || ppidCol < 0 { + return 0, fmt.Errorf("docker top output has no PID/PPID columns: %v", titles) + } + + parent := make(map[int]int, len(rows)) + for _, row := range rows { + if len(row) <= pidCol || len(row) <= ppidCol { + continue + } + pid, err1 := strconv.Atoi(row[pidCol]) + ppid, err2 := strconv.Atoi(row[ppidCol]) + if err1 == nil && err2 == nil { + parent[pid] = ppid + } + } + + count := 0 + for pid := range parent { + p := pid + // Walk up while the parent is inside the container. Bounded by the + // listing's size, so a malformed cycle can't loop forever. + for i := 0; i <= len(parent) && p != mainPID; i++ { + pp, ok := parent[p] + if !ok { + break + } + p = pp + } + if p != mainPID { + count++ + } + } + return count, nil +} + +func trimSlash(name string) string { + if len(name) > 0 && name[0] == '/' { + return name[1:] + } + return name +} diff --git a/internal/idle/engine_test.go b/internal/idle/engine_test.go new file mode 100644 index 0000000..a412517 --- /dev/null +++ b/internal/idle/engine_test.go @@ -0,0 +1,24 @@ +package idle + +import "testing" + +func TestCountExecProcs(t *testing.T) { + titles := []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"} + row := func(pid, ppid string) []string { return []string{"1000", pid, ppid, "0", "", "?", "", "x"} } + + // 100 is the main process (its parent, the runtime shim 90, isn't in the + // container). 101/102 are its workers; 200 is an exec'd shell running + // composer (201); 300 is a health check. + rows := [][]string{row("100", "90"), row("101", "100"), row("102", "101"), row("200", "95"), row("201", "200"), row("300", "96")} + n, err := countExecProcs(titles, rows, 100) + if err != nil || n != 3 { + t.Fatalf("countExecProcs = %d, %v; want 3 (shell, composer, health check)", n, err) + } + + if n, _ := countExecProcs(titles, rows[:3], 100); n != 0 { + t.Fatalf("server and its workers alone counted %d exec'd processes", n) + } + if _, err := countExecProcs([]string{"PID", "CMD"}, rows, 100); err == nil { + t.Fatal("missing PPID column wasn't reported") + } +} diff --git a/internal/idle/fake_test.go b/internal/idle/fake_test.go new file mode 100644 index 0000000..2d89177 --- /dev/null +++ b/internal/idle/fake_test.go @@ -0,0 +1,97 @@ +package idle + +import ( + "context" + "io" + "log" + "sync" + "time" +) + +// fakeEngine is an in-memory Docker for the waker and watcher tests. +type fakeEngine struct { + mu sync.Mutex + containers map[string]*Container // by name + samples map[string][]Sample // by ID, consumed in order + starts int + stops []string + startErr error +} + +func newFakeEngine(cs ...Container) *fakeEngine { + f := &fakeEngine{containers: map[string]*Container{}, samples: map[string][]Sample{}} + for i := range cs { + c := cs[i] + f.containers[c.Name] = &c + } + return f +} + +func (f *fakeEngine) byID(id string) *Container { + for _, c := range f.containers { + if c.ID == id || c.Name == id { + return c + } + } + return nil +} + +func (f *fakeEngine) ListProjects(context.Context) ([]Container, error) { + f.mu.Lock() + defer f.mu.Unlock() + var out []Container + for _, c := range f.containers { + if c.Project != "" { + out = append(out, *c) + } + } + return out, nil +} + +func (f *fakeEngine) Inspect(_ context.Context, name string) (*Container, error) { + f.mu.Lock() + defer f.mu.Unlock() + c := f.byID(name) + if c == nil { + return nil, ErrNotFound + } + cp := *c + return &cp, nil +} + +func (f *fakeEngine) Sample(_ context.Context, c *Container) (Sample, error) { + f.mu.Lock() + defer f.mu.Unlock() + queue := f.samples[c.ID] + s := queue[0] + if len(queue) > 1 { + f.samples[c.ID] = queue[1:] + } + return s, nil +} + +func (f *fakeEngine) Start(_ context.Context, id string) error { + f.mu.Lock() + defer f.mu.Unlock() + f.starts++ + if f.startErr != nil { + return f.startErr + } + c := f.byID(id) + if !c.Running { + c.Running = true + c.StartedAt = time.Now().UTC().Format(time.RFC3339Nano) + } + return nil +} + +func (f *fakeEngine) Stop(_ context.Context, id string, _ time.Duration) error { + f.mu.Lock() + defer f.mu.Unlock() + c := f.byID(id) + c.Running = false + f.stops = append(f.stops, c.Project) + return nil +} + +var discard = log.New(io.Discard, "", 0) diff --git a/internal/idle/policy.go b/internal/idle/policy.go new file mode 100644 index 0000000..ae7e14a --- /dev/null +++ b/internal/idle/policy.go @@ -0,0 +1,149 @@ +// Package idle is the alios_idle service: it stops project containers that +// have gone quiet and starts them again when a request arrives for them. +// +// It runs as its own container (cmd/alios-idle) next to the other global +// services, and talks to the Docker Engine API over the mounted socket +// directly rather than through internal/docker.Client: that client shells out +// to the docker CLI, which the service's image doesn't ship. +package idle + +import ( + "slices" + "time" +) + +// Sample is one reading of a container's raw counters. CPU and network are +// cumulative since the container started. ExecProcs counts processes that +// don't descend from the container's main process: `docker exec` sessions +// (alios exec, alios shell) and health checks. +type Sample struct { + At time.Time + CPUNanos uint64 + NetBytes uint64 + ExecProcs int +} + +// Thresholds decide when a container counts as active between two samples. +type Thresholds struct { + // CPUFraction is the share of one core, averaged over the interval, + // above which the container is busy. Idle FrankenPHP containers sit near + // 0.001; a running job is well above 0.01. + CPUFraction float64 + // NetBytesPerMinute is the traffic (rx+tx) above which the container is + // being used. Any page view or open dev-server connection clears it; + // background ARP/DNS chatter doesn't. + NetBytesPerMinute uint64 +} + +// DefaultThresholds are tuned against idle alios_php_* containers, which use +// about 0.1% of a core and a few hundred bytes of traffic an hour. +var DefaultThresholds = Thresholds{ + CPUFraction: 0.01, + NetBytesPerMinute: 8 * 1024, +} + +// Activity is what Tracker.Observe concludes from the newest sample. +type Activity struct { + Active bool + // Reasons lists what made the container active ("cpu", "network", + // "exec", "new"), for logging. + Reasons []string + // IdleFor is how long the container has been quiet; zero when active. + IdleFor time.Duration + // BusyWithoutTrafficFor is how long the container has been using CPU + // with no network traffic at all - a job running on its own, or + // something stuck. An open but idle shell keeps a project awake without + // counting here. Zero when that isn't the case. + BusyWithoutTrafficFor time.Duration +} + +type instance struct { + startedAt string + last Sample + execBefore bool + lastActive time.Time + busySince time.Time +} + +// Tracker remembers each container's previous sample and decides whether it +// is idle. It holds no state worth persisting: after a restart every +// container simply starts a fresh idle timer. +type Tracker struct { + th Thresholds + instances map[string]*instance +} + +// NewTracker returns a Tracker using the given thresholds. +func NewTracker(th Thresholds) *Tracker { + return &Tracker{th: th, instances: make(map[string]*instance)} +} + +// Observe records a sample for container id. startedAt identifies the +// container's current run: when it changes the container was restarted, and +// its counters start over. +func (t *Tracker) Observe(id, startedAt string, s Sample) Activity { + inst, ok := t.instances[id] + if !ok || inst.startedAt != startedAt || s.CPUNanos < inst.last.CPUNanos || s.NetBytes < inst.last.NetBytes { + t.instances[id] = &instance{startedAt: startedAt, last: s, execBefore: s.ExecProcs > 0, lastActive: s.At} + return Activity{Active: true, Reasons: []string{"new"}} + } + + elapsed := s.At.Sub(inst.last.At) + if elapsed <= 0 { + return t.activity(inst, s.At, nil, false) + } + + exec := s.ExecProcs > 0 + + var reasons []string + cpu := float64(s.CPUNanos-inst.last.CPUNanos) / float64(elapsed.Nanoseconds()) + if cpu > t.th.CPUFraction { + reasons = append(reasons, "cpu") + } + netPerMin := float64(s.NetBytes-inst.last.NetBytes) / elapsed.Minutes() + traffic := netPerMin > float64(t.th.NetBytesPerMinute) + if traffic { + reasons = append(reasons, "network") + } + // An exec'd process counts only when seen twice in a row, so a health + // check that happens to be running at the moment of a sample doesn't + // reset the timer. Real work that short shows up as CPU anyway. An idle + // `alios shell` uses no CPU or container network, so this is the only + // signal that keeps a project with an open shell awake. + if exec && inst.execBefore { + reasons = append(reasons, "exec") + } + inst.execBefore = exec + inst.last = s + + return t.activity(inst, s.At, reasons, traffic) +} + +func (t *Tracker) activity(inst *instance, now time.Time, reasons []string, traffic bool) Activity { + if len(reasons) == 0 { + inst.busySince = time.Time{} + return Activity{IdleFor: now.Sub(inst.lastActive)} + } + + inst.lastActive = now + a := Activity{Active: true, Reasons: reasons} + if traffic || !slices.Contains(reasons, "cpu") { + inst.busySince = time.Time{} + } else { + if inst.busySince.IsZero() { + inst.busySince = now + } + a.BusyWithoutTrafficFor = now.Sub(inst.busySince) + } + return a +} + +// Forget drops containers that weren't in the latest listing, so a removed +// project doesn't linger in memory. +func (t *Tracker) Forget(keep map[string]bool) { + for id := range t.instances { + if !keep[id] { + delete(t.instances, id) + } + } +} diff --git a/internal/idle/policy_test.go b/internal/idle/policy_test.go new file mode 100644 index 0000000..e8491ac --- /dev/null +++ b/internal/idle/policy_test.go @@ -0,0 +1,140 @@ +package idle + +import ( + "testing" + "time" +) + +var t0 = time.Date(2026, 10, 13, 9, 0, 0, 0, time.UTC) + +// feed observes a sequence of samples 30s apart, starting from base, and +// returns the activity for the last one. +func feed(tr *Tracker, base Sample, steps ...func(*Sample)) Activity { + s := base + a := tr.Observe("c1", "run1", s) + for _, step := range steps { + s.At = s.At.Add(30 * time.Second) + step(&s) + a = tr.Observe("c1", "run1", s) + } + return a +} + +func quiet(s *Sample) { s.CPUNanos += 10_000_000; s.NetBytes += 100 } // 0.03% CPU, 200 B/min + +func busyCPU(s *Sample) { s.CPUNanos += 15_000_000_000 } // half a core + +func traffic(s *Sample) { s.NetBytes += 50_000 } + +func withExec(n int) func(*Sample) { + return func(s *Sample) { quiet(s); s.ExecProcs = n } +} + +func base() Sample { return Sample{At: t0, CPUNanos: 1e9, NetBytes: 1000} } + +func TestFirstSampleIsActive(t *testing.T) { + a := NewTracker(DefaultThresholds).Observe("c1", "run1", base()) + if !a.Active { + t.Fatal("a container seen for the first time must get a fresh idle timer, not count as idle") + } +} + +func TestQuietContainerAccumulatesIdleTime(t *testing.T) { + a := feed(NewTracker(DefaultThresholds), base(), quiet, quiet, quiet, quiet) + if a.Active { + t.Fatalf("background noise counted as activity: %v", a.Reasons) + } + if a.IdleFor != 2*time.Minute { + t.Fatalf("IdleFor = %v, want 2m (four quiet 30s intervals)", a.IdleFor) + } +} + +func TestEachSignalCountsAsActivity(t *testing.T) { + cases := map[string][]func(*Sample){ + "cpu": {quiet, busyCPU}, + "network": {quiet, traffic}, + "exec": {quiet, withExec(1), withExec(1)}, + } + for want, steps := range cases { + a := feed(NewTracker(DefaultThresholds), base(), steps...) + if !a.Active || len(a.Reasons) == 0 || a.Reasons[0] != want { + t.Errorf("%s: got active=%v reasons=%v", want, a.Active, a.Reasons) + } + } +} + +func TestActivityResetsIdleTimer(t *testing.T) { + a := feed(NewTracker(DefaultThresholds), base(), quiet, quiet, traffic, quiet) + if a.IdleFor != 30*time.Second { + t.Fatalf("IdleFor = %v, want 30s since the last request", a.IdleFor) + } +} + +func TestSingleExecBlipIsIgnored(t *testing.T) { + // A health check caught mid-run shows up as one exec'd process in one + // sample. It must not keep the container awake. + a := feed(NewTracker(DefaultThresholds), base(), quiet, withExec(1), withExec(0), quiet) + if a.Active { + t.Fatalf("one-sample exec blip counted as activity: %v", a.Reasons) + } +} + +func TestShellOpenFromTheStartKeepsItAwake(t *testing.T) { + // `alios shell` on a sleeping project starts the container and execs a + // shell before the watcher's first sample. An idle shell uses no CPU or + // container network; it must still count for as long as it's open. + b := base() + b.ExecProcs = 1 + steps := []func(*Sample){} + for i := 0; i < 120; i++ { // an hour + steps = append(steps, withExec(1)) + } + if a := feed(NewTracker(DefaultThresholds), b, steps...); !a.Active { + t.Fatalf("open shell not counted: idle for %v", a.IdleFor) + } +} + +func TestRestartStartsAFreshTimer(t *testing.T) { + tr := NewTracker(DefaultThresholds) + feed(tr, base(), quiet, quiet, quiet) + a := tr.Observe("c1", "run2", Sample{At: t0.Add(5 * time.Minute), CPUNanos: 5, NetBytes: 5}) + if !a.Active { + t.Fatal("a restarted container must not inherit the idle time of its previous run") + } +} + +func TestBusyWithoutTrafficIsReported(t *testing.T) { + a := feed(NewTracker(DefaultThresholds), base(), busyCPU, busyCPU, busyCPU) + if a.BusyWithoutTrafficFor != time.Minute { + t.Fatalf("BusyWithoutTrafficFor = %v, want 1m", a.BusyWithoutTrafficFor) + } + a = feed(NewTracker(DefaultThresholds), base(), busyCPU, func(s *Sample) { busyCPU(s); traffic(s) }) + if a.BusyWithoutTrafficFor != 0 { + t.Fatal("work driven by requests isn't 'busy without traffic'") + } +} + +func TestForgetDropsRemovedContainers(t *testing.T) { + tr := NewTracker(DefaultThresholds) + tr.Observe("c1", "run1", base()) + tr.Observe("c2", "run1", base()) + tr.Forget(map[string]bool{"c2": true}) + if _, ok := tr.instances["c1"]; ok { + t.Fatal("c1 wasn't forgotten") + } + if _, ok := tr.instances["c2"]; !ok { + t.Fatal("c2 was forgotten") + } +} + +func TestIdleShellIsNotBusyWithoutTraffic(t *testing.T) { + // An open `alios shell` keeps the project awake, but it isn't a stuck + // job: it must not trigger busy warnings. + steps := []func(*Sample){} + for i := 0; i < 10; i++ { + steps = append(steps, withExec(1)) + } + if a := feed(NewTracker(DefaultThresholds), base(), steps...); !a.Active || a.BusyWithoutTrafficFor != 0 { + t.Fatalf("active=%v busy=%v, want active and not busy", a.Active, a.BusyWithoutTrafficFor) + } +} diff --git a/internal/idle/waker.go b/internal/idle/waker.go new file mode 100644 index 0000000..b8c3c5e --- /dev/null +++ b/internal/idle/waker.go @@ -0,0 +1,198 @@ +package idle + +import ( + "context" + "errors" + "fmt" + "html" + "log" + "net" + "net/http" + "regexp" + "strings" + "sync" + "time" +) + +// ProjectHeader names the project a woken request is for. The vhost's +// alios_wake snippet sets it (see services.baseCaddyfile), so the waker never +// has to guess the project from a Host that might be a share's public name. +const ProjectHeader = "X-Alios-Project" + +var validProject = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]*$`) + +// Waker answers the requests Caddy couldn't deliver because the project's +// container is stopped: it starts the container, waits until it accepts +// connections, then redirects the browser to the same URL to try again. +type Waker struct { + Engine Engine + // Ready reports whether the project's server accepts connections yet. + // Defaults to dialing :80 on the shared network. + Ready func(ctx context.Context, container string) bool + WakeTimeout time.Duration + Log *log.Logger + + mu sync.Mutex + waits map[string]*wake +} + +// recentStart is how long after a container starts a failed request is still +// assumed to be one Caddy sent while it was down, rather than a running +// project failing. Requests for a page's assets arrive in a burst, and the +// later ones can reach the waker after the first one already woke it; a +// visit right after `alios start` or `alios exec` started it is the same. +const recentStart = 15 * time.Second + +// wake is one start in progress. Concurrent requests for the same project +// (a page and its assets) share it instead of each starting the container. +type wake struct { + done chan struct{} + err error +} + +var errNotReady = errors.New("didn't accept connections in time") + +func (w *Waker) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/healthz" && r.Header.Get(ProjectHeader) == "" { + rw.WriteHeader(http.StatusNoContent) + return + } + + project := r.Header.Get(ProjectHeader) + if !validProject.MatchString(project) { + page(rw, http.StatusBadRequest, "Unknown project", "This request didn't name a project.") + return + } + + ctx := r.Context() + c, err := w.Engine.Inspect(ctx, "alios_php_"+project) + if errors.Is(err, ErrNotFound) || (err == nil && c.Project != project) { + // Only ever start containers alios created for this project. + page(rw, http.StatusNotFound, "No project here", fmt.Sprintf("There's no container for %s. Run 'alios start' in the project.", project)) + return + } + if err != nil { + w.Log.Printf("inspecting %s: %v", project, err) + page(rw, http.StatusBadGateway, "Couldn't check the project", err.Error()) + return + } + + switch { + case w.inProgress(c.ID) != nil || !c.Running || !w.ready(ctx, c.Name): + if err := w.wakeOnce(c); err != nil { + w.Log.Printf("waking %s: %v", project, err) + page(rw, http.StatusGatewayTimeout, "Project didn't start", + fmt.Sprintf("%s: %v. Check 'alios logs'.", project, err)) + return + } + case !c.StartedWithin(recentStart, time.Now()): + // Caddy failed to reach a container that has been up and listening + // for a while, so starting it again won't help - and redirecting + // would loop. + page(rw, http.StatusBadGateway, "Project isn't responding", + fmt.Sprintf("%s is running but the request to it failed. Check 'alios logs'.", project)) + return + } + // Otherwise it's up because a wake just finished: retry as well. + + // 307 keeps the method and body, so a form POST that woke the project + // is resubmitted rather than turned into a GET. The relative Location + // keeps whatever scheme and host the browser used. + rw.Header().Set("Cache-Control", "no-store") + rw.Header().Set("Location", sameOriginPath(r.URL.RequestURI())) + rw.WriteHeader(http.StatusTemporaryRedirect) +} + +// sameOriginPath makes a request URI safe to redirect to. A path starting +// "//" (or "/\", which browsers treat the same) would be read as a +// protocol-relative URL, turning https:////evil.com into a redirect +// to evil.com. +func sameOriginPath(uri string) string { + return "/" + strings.TrimLeft(uri, "/\\") +} + +func (w *Waker) inProgress(id string) *wake { + w.mu.Lock() + defer w.mu.Unlock() + return w.waits[id] +} + +func (w *Waker) wakeOnce(c *Container) error { + w.mu.Lock() + if w.waits == nil { + w.waits = make(map[string]*wake) + } + if wk, ok := w.waits[c.ID]; ok { + w.mu.Unlock() + <-wk.done + return wk.err + } + wk := &wake{done: make(chan struct{})} + w.waits[c.ID] = wk + w.mu.Unlock() + + // Detached from the request: if the browser gives up, the container + // should still finish starting for the next attempt. + ctx, cancel := context.WithTimeout(context.Background(), w.WakeTimeout) + defer cancel() + start := time.Now() + wk.err = w.start(ctx, c) + if wk.err == nil { + w.Log.Printf("woke %s in %s", c.Project, time.Since(start).Round(time.Millisecond)) + } + + w.mu.Lock() + delete(w.waits, c.ID) + w.mu.Unlock() + close(wk.done) + return wk.err +} + +func (w *Waker) start(ctx context.Context, c *Container) error { + if err := w.Engine.Start(ctx, c.ID); err != nil { + return err + } + for i := 1; ; i++ { + if w.ready(ctx, c.Name) { + return nil + } + select { + case <-ctx.Done(): + return errNotReady + case <-time.After(100 * time.Millisecond): + } + // A container that was being stopped when the request came in + // (by the watcher, or `alios stop`) still counted as running, so + // Start was a no-op. Once the stop finishes, start it for real. + if i%10 == 0 { + if cur, err := w.Engine.Inspect(ctx, c.ID); err == nil && !cur.Running { + if err := w.Engine.Start(ctx, c.ID); err != nil { + return err + } + } + } + } +} + +func (w *Waker) ready(ctx context.Context, container string) bool { + if w.Ready != nil { + return w.Ready(ctx, container) + } + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", net.JoinHostPort(container, "80")) + if err != nil { + return false + } + conn.Close() + return true +} + +func page(rw http.ResponseWriter, status int, title, detail string) { + rw.Header().Set("Content-Type", "text/html; charset=utf-8") + rw.Header().Set("Cache-Control", "no-store") + rw.WriteHeader(status) + fmt.Fprintf(rw, `%[1]s + +

%[1]s

%[2]s

`, html.EscapeString(title), html.EscapeString(detail)) +} diff --git a/internal/idle/waker_test.go b/internal/idle/waker_test.go new file mode 100644 index 0000000..f010bbe --- /dev/null +++ b/internal/idle/waker_test.go @@ -0,0 +1,259 @@ +package idle + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// shop is a project container that, if running, has been up for an hour. +func shop(running bool) Container { + return Container{ID: "id-shop", Name: "alios_php_shop", Project: "shop", Running: running, + StartedAt: time.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano)} +} + +// readyWhenRunning makes the fake server accept connections once its +// container is running, like the real one shortly after start. +func readyWhenRunning(f *fakeEngine) func(context.Context, string) bool { + return func(_ context.Context, name string) bool { + f.mu.Lock() + defer f.mu.Unlock() + c := f.byID(name) + return c != nil && c.Running + } +} + +func newWaker(f *fakeEngine) *Waker { + return &Waker{Engine: f, Ready: readyWhenRunning(f), WakeTimeout: time.Second, Log: discard} +} + +func wakeRequest(method, target, project string) *http.Request { + r := httptest.NewRequest(method, target, nil) + if project != "" { + r.Header.Set(ProjectHeader, project) + } + return r +} + +func TestWakeStartsContainerAndRedirectsToSameURL(t *testing.T) { + f := newFakeEngine(shop(false)) + rw := httptest.NewRecorder() + newWaker(f).ServeHTTP(rw, wakeRequest(http.MethodPost, "/cart/add?id=7", "shop")) + + if rw.Code != http.StatusTemporaryRedirect { + t.Fatalf("status = %d, want 307 (keeps the POST)", rw.Code) + } + if loc := rw.Header().Get("Location"); loc != "/cart/add?id=7" { + t.Fatalf("Location = %q, want the original path and query", loc) + } + if f.starts != 1 || !f.containers["alios_php_shop"].Running { + t.Fatal("container wasn't started") + } +} + +func TestRunningButUnreachableDoesNotRedirectLoop(t *testing.T) { + // Caddy failed to reach a container that is up and listening (say the + // app's own server crashed mid-request). Redirecting would loop forever. + f := newFakeEngine(shop(true)) + rw := httptest.NewRecorder() + newWaker(f).ServeHTTP(rw, wakeRequest(http.MethodGet, "/", "shop")) + + if rw.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want 502", rw.Code) + } + if f.starts != 0 { + t.Fatal("started a container that was already running") + } +} + +func TestOnlyStartsContainersOfTheNamedProject(t *testing.T) { + // alios_php_shop exists but belongs to some other project label - never + // start a container alios didn't create for this project. + other := shop(false) + other.Project = "not-shop" + cases := map[string]*fakeEngine{ + "missing container": newFakeEngine(), + "label mismatch": newFakeEngine(other), + } + for name, f := range cases { + rw := httptest.NewRecorder() + newWaker(f).ServeHTTP(rw, wakeRequest(http.MethodGet, "/", "shop")) + if rw.Code != http.StatusNotFound || f.starts != 0 { + t.Errorf("%s: status=%d starts=%d, want 404 and no start", name, rw.Code, f.starts) + } + } +} + +func TestRejectsMissingOrInvalidProjectHeader(t *testing.T) { + for _, project := range []string{"", "../etc", "shop/../x", "-rm"} { + f := newFakeEngine(shop(false)) + rw := httptest.NewRecorder() + newWaker(f).ServeHTTP(rw, wakeRequest(http.MethodGet, "/", project)) + if rw.Code != http.StatusBadRequest || f.starts != 0 { + t.Errorf("project %q: status=%d starts=%d, want 400 and no start", project, rw.Code, f.starts) + } + } +} + +func TestConcurrentRequestsShareOneStart(t *testing.T) { + f := newFakeEngine(shop(false)) + w := newWaker(f) + var readyCalls atomic.Int32 + release := make(chan struct{}) + w.Ready = func(ctx context.Context, name string) bool { + // Hold the first wake open until every request has arrived. + if readyCalls.Add(1) == 1 { + <-release + } + return readyWhenRunning(f)(ctx, name) + } + + var wg sync.WaitGroup + codes := make([]int, 5) + for i := range codes { + wg.Add(1) + go func(i int) { + defer wg.Done() + rw := httptest.NewRecorder() + w.ServeHTTP(rw, wakeRequest(http.MethodGet, "/asset.css", "shop")) + codes[i] = rw.Code + }(i) + } + time.Sleep(50 * time.Millisecond) + close(release) + wg.Wait() + + for i, code := range codes { + if code != http.StatusTemporaryRedirect { + t.Errorf("request %d: status %d", i, code) + } + } + if f.starts != 1 { + t.Fatalf("starts = %d, want 1 shared start", f.starts) + } +} + +func TestStartFailureAndTimeoutReturnAnErrorPage(t *testing.T) { + f := newFakeEngine(shop(false)) + f.startErr = errors.New("port is already allocated") + rw := httptest.NewRecorder() + newWaker(f).ServeHTTP(rw, wakeRequest(http.MethodGet, "/", "shop")) + if rw.Code != http.StatusGatewayTimeout { + t.Fatalf("start failure: status = %d, want 504", rw.Code) + } + + f = newFakeEngine(shop(false)) + w := newWaker(f) + w.WakeTimeout = 200 * time.Millisecond + w.Ready = func(context.Context, string) bool { return false } + rw = httptest.NewRecorder() + w.ServeHTTP(rw, wakeRequest(http.MethodGet, "/", "shop")) + if rw.Code != http.StatusGatewayTimeout { + t.Fatalf("never ready: status = %d, want 504", rw.Code) + } +} + +func TestHealthz(t *testing.T) { + rw := httptest.NewRecorder() + newWaker(newFakeEngine()).ServeHTTP(rw, httptest.NewRequest(http.MethodGet, "/healthz", nil)) + if rw.Code != http.StatusNoContent { + t.Fatalf("status = %d", rw.Code) + } +} + +func TestRequestJustAfterAWakeIsRetriedNotFailed(t *testing.T) { + // A page's asset request that Caddy failed while the container was down + // reaches the waker after the page's own request already woke it. + f := newFakeEngine(shop(false)) + w := newWaker(f) + w.ServeHTTP(httptest.NewRecorder(), wakeRequest(http.MethodGet, "/", "shop")) + + rw := httptest.NewRecorder() + w.ServeHTTP(rw, wakeRequest(http.MethodGet, "/app.css", "shop")) + if rw.Code != http.StatusTemporaryRedirect { + t.Fatalf("status = %d, want 307 so the browser retries", rw.Code) + } + if f.starts != 1 { + t.Fatalf("starts = %d, want 1", f.starts) + } +} + +func TestRequestJustAfterAnotherStartIsRetried(t *testing.T) { + // Started a moment ago by `alios start` or `alios exec`, not by the + // waker: a request Caddy failed while it was down is still retried. + c := shop(true) + c.StartedAt = time.Now().Add(-2 * time.Second).UTC().Format(time.RFC3339Nano) + f := newFakeEngine(c) + rw := httptest.NewRecorder() + newWaker(f).ServeHTTP(rw, wakeRequest(http.MethodGet, "/", "shop")) + if rw.Code != http.StatusTemporaryRedirect { + t.Fatalf("status = %d, want 307", rw.Code) + } +} + +func TestRedirectNeverLeavesTheSite(t *testing.T) { + for target, want := range map[string]string{ + "//evil.com/login": "/evil.com/login", + "/\\evil.com": "/%5Cevil.com", // Go escapes the backslash; browsers keep it on-site + "///x?y=1": "/x?y=1", + "/": "/", + "/cart?next=//b.com": "/cart?next=//b.com", + } { + f := newFakeEngine(shop(false)) + r := wakeRequest(http.MethodGet, "/", "shop") + r.RequestURI = target + r.URL.Path, r.URL.RawQuery = target, "" + if i := strings.IndexByte(target, '?'); i >= 0 { + r.URL.Path, r.URL.RawQuery = target[:i], target[i+1:] + } + rw := httptest.NewRecorder() + newWaker(f).ServeHTTP(rw, r) + if loc := rw.Header().Get("Location"); loc != want { + t.Errorf("%q redirected to %q, want %q", target, loc, want) + } + } +} + +func TestWakeDuringAStopStartsItOnceTheStopFinishes(t *testing.T) { + // The watcher (or `alios stop`) is stopping the container when the + // request arrives: it still counts as running, so the first Start is a + // no-op. Once it has exited, the waker must start it again rather than + // wait for a port that will never open. + c := shop(true) + f := newFakeEngine(c) + w := newWaker(f) + w.WakeTimeout = 5 * time.Second + var ready atomic.Bool + w.Ready = func(context.Context, string) bool { return ready.Load() } + go func() { + time.Sleep(300 * time.Millisecond) + f.mu.Lock() + f.containers["alios_php_shop"].Running = false // the stop completes + f.mu.Unlock() + for { + f.mu.Lock() + up := f.containers["alios_php_shop"].Running + f.mu.Unlock() + if up { + ready.Store(true) + return + } + time.Sleep(20 * time.Millisecond) + } + }() + + rw := httptest.NewRecorder() + w.ServeHTTP(rw, wakeRequest(http.MethodGet, "/", "shop")) + if rw.Code != http.StatusTemporaryRedirect { + t.Fatalf("status = %d, want 307 once restarted", rw.Code) + } + if f.starts < 2 { + t.Fatalf("starts = %d, want a second start after the stop finished", f.starts) + } +} diff --git a/internal/idle/watcher.go b/internal/idle/watcher.go new file mode 100644 index 0000000..0a78bc8 --- /dev/null +++ b/internal/idle/watcher.go @@ -0,0 +1,151 @@ +package idle + +import ( + "context" + "log" + "strings" + "time" +) + +// BusyWarning starts the log line the watcher writes when a container has +// been busy for a long time with no traffic. `alios doctor` looks for it. +const BusyWarning = "busy-warning" + +// Watcher stops project containers once they've been idle for their timeout. +type Watcher struct { + Engine Engine + Tracker *Tracker + Interval time.Duration + // Timeout is the default idle time before a stop; zero disables stopping + // for projects without their own IdleLabel timeout. + Timeout time.Duration + // BusyWarnAfter is how long a container may stay busy without any + // traffic before the watcher logs a BusyWarning about it. + BusyWarnAfter time.Duration + Log *log.Logger + + warned map[string]bool +} + +// Run samples every Interval until ctx is cancelled. +func (w *Watcher) Run(ctx context.Context) { + ticker := time.NewTicker(w.Interval) + defer ticker.Stop() + for { + w.Tick(ctx) + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +// Tick samples every running project once and stops the ones that are idle. +func (w *Watcher) Tick(ctx context.Context) { + if w.warned == nil { + w.warned = make(map[string]bool) + } + + containers, err := w.Engine.ListProjects(ctx) + if err != nil { + w.Log.Printf("listing projects: %v", err) + return + } + + seen := make(map[string]bool, len(containers)) + for _, listed := range containers { + if !listed.Running { + continue + } + timeout, ok := w.timeoutFor(listed) + if !ok { + continue + } + + // Kept in the tracker even if this tick's reading fails, so a + // transient API error doesn't restart the project's idle timer. + seen[listed.ID] = true + + // The listing doesn't carry StartedAt or the main PID; Inspect does. + // StartedAt is how the tracker tells a restarted container from the + // same run. + c, err := w.Engine.Inspect(ctx, listed.ID) + if err != nil || !c.Running { + continue + } + s, err := w.Engine.Sample(ctx, c) + if err != nil { + w.Log.Printf("sampling %s: %v", c.Project, err) + continue + } + + a := w.Tracker.Observe(c.ID, c.StartedAt, s) + w.warnIfBusy(c, a) + + if a.Active || a.IdleFor < timeout { + continue + } + if err := w.Engine.Stop(ctx, c.ID, 10*time.Second); err != nil { + w.Log.Printf("stopping %s: %v", c.Project, err) + continue + } + w.Log.Printf("stopped %s after %s idle (wakes on the next request)", c.Project, a.IdleFor.Round(time.Second)) + } + + w.Tracker.Forget(seen) + for id := range w.warned { + if !seen[id] { + delete(w.warned, id) + } + } +} + +// timeoutFor returns the idle timeout for c, or false when c should never be +// stopped: the project opted out, or there's no default and no override. +func (w *Watcher) timeoutFor(c Container) (time.Duration, bool) { + setting := strings.TrimSpace(c.Idle) + switch setting { + case "": + return w.Timeout, w.Timeout > 0 + case "off", "never": + return 0, false + } + d, err := time.ParseDuration(setting) + if err != nil || d <= 0 { + w.Log.Printf("%s: ignoring invalid %s=%q, using the default", c.Project, IdleLabel, setting) + return w.Timeout, w.Timeout > 0 + } + return d, true +} + +func (w *Watcher) warnIfBusy(c *Container, a Activity) { + if w.BusyWarnAfter <= 0 || a.BusyWithoutTrafficFor < w.BusyWarnAfter { + if a.BusyWithoutTrafficFor == 0 { + delete(w.warned, c.ID) + } + return + } + if w.warned[c.ID] { + return + } + w.warned[c.ID] = true + w.Log.Printf("%s %s: busy for %s with no traffic (%s); check it's not stuck with 'alios logs' or 'docker top %s'", + BusyWarning, c.Project, a.BusyWithoutTrafficFor.Round(time.Minute), strings.Join(a.Reasons, ", "), c.Name) +} + +// DefaultTimeout is how long a project may sit idle before it's stopped when +// ALIOS_IDLE_TIMEOUT isn't set. +const DefaultTimeout = 30 * time.Minute + +// ParseTimeout reads a timeout setting: a Go duration, or "off"/"0" to +// disable. An empty string means the default. +func ParseTimeout(value string, def time.Duration) (time.Duration, error) { + switch strings.TrimSpace(value) { + case "": + return def, nil + case "off", "never", "0": + return 0, nil + } + return time.ParseDuration(strings.TrimSpace(value)) +} diff --git a/internal/idle/watcher_test.go b/internal/idle/watcher_test.go new file mode 100644 index 0000000..a6aab74 --- /dev/null +++ b/internal/idle/watcher_test.go @@ -0,0 +1,112 @@ +package idle + +import ( + "bytes" + "context" + "log" + "strings" + "testing" + "time" +) + +func project(name, idle string) Container { + return Container{ID: "id-" + name, Name: "alios_php_" + name, Project: name, Idle: idle, Running: true, StartedAt: "run1"} +} + +// quietSamples returns n samples 30s apart with background-noise deltas. +func quietSamples(n int) []Sample { + s := base() + out := []Sample{s} + for i := 1; i < n; i++ { + s.At = s.At.Add(30 * time.Second) + quiet(&s) + out = append(out, s) + } + return out +} + +func newWatcher(f *fakeEngine, timeout time.Duration) *Watcher { + return &Watcher{Engine: f, Tracker: NewTracker(DefaultThresholds), Timeout: timeout, Log: discard} +} + +func ticks(w *Watcher, n int) { + for i := 0; i < n; i++ { + w.Tick(context.Background()) + } +} + +func TestStopsAfterTimeoutOnly(t *testing.T) { + f := newFakeEngine(project("shop", "")) + f.samples["id-shop"] = quietSamples(10) + w := newWatcher(f, 2*time.Minute) + + ticks(w, 4) // 1m30s of quiet after the first sample + if len(f.stops) != 0 { + t.Fatalf("stopped after %d ticks, before the 2m timeout", 4) + } + ticks(w, 1) // 2m + if len(f.stops) != 1 || f.stops[0] != "shop" { + t.Fatalf("stops = %v, want shop stopped at 2m idle", f.stops) + } +} + +func TestPerProjectSettings(t *testing.T) { + f := newFakeEngine(project("off", "off"), project("short", "1m"), project("default", ""), project("bad", "soon")) + for _, id := range []string{"id-off", "id-short", "id-default", "id-bad"} { + f.samples[id] = quietSamples(10) + } + w := newWatcher(f, 0) // no default: only projects with their own timeout stop + + ticks(w, 6) + if strings.Join(f.stops, ",") != "short" { + t.Fatalf("stops = %v, want only the project with its own 1m timeout", f.stops) + } +} + +func TestStoppedContainersAreLeftAlone(t *testing.T) { + c := project("shop", "") + c.Running = false + f := newFakeEngine(c) + w := newWatcher(f, time.Minute) + ticks(w, 5) + if len(f.stops) != 0 { + t.Fatal("stopped a container that wasn't running") + } +} + +func TestBusyWarningIsLoggedOncePerStreak(t *testing.T) { + f := newFakeEngine(project("shop", "")) + s := base() + samples := []Sample{s} + for i := 0; i < 6; i++ { + s.At = s.At.Add(30 * time.Second) + busyCPU(&s) + samples = append(samples, s) + } + f.samples["id-shop"] = samples + + var buf bytes.Buffer + w := newWatcher(f, time.Hour) + w.Log = log.New(&buf, "", 0) + w.BusyWarnAfter = time.Minute + ticks(w, 7) + + if n := strings.Count(buf.String(), BusyWarning); n != 1 { + t.Fatalf("logged %d busy warnings, want 1:\n%s", n, buf.String()) + } + if len(f.stops) != 0 { + t.Fatal("stopped a busy container") + } +} + +func TestParseTimeout(t *testing.T) { + for in, want := range map[string]time.Duration{"": 30 * time.Minute, "off": 0, "0": 0, "45m": 45 * time.Minute} { + got, err := ParseTimeout(in, 30*time.Minute) + if err != nil || got != want { + t.Errorf("ParseTimeout(%q) = %v, %v; want %v", in, got, err, want) + } + } + if _, err := ParseTimeout("soon", time.Minute); err == nil { + t.Error("ParseTimeout accepted an invalid value") + } +} diff --git a/internal/project/idle.go b/internal/project/idle.go new file mode 100644 index 0000000..6bcd23b --- /dev/null +++ b/internal/project/idle.go @@ -0,0 +1,78 @@ +package project + +import ( + "fmt" + "time" + + "github.com/aliasproject/alios-cli/internal/idle" +) + +// SetIdle changes the current project's scale-to-zero setting and recreates +// the container to store it: "" uses the global ALIOS_IDLE_TIMEOUT, "off" +// keeps the project running, a duration ("2h") is its own idle timeout. +func (m *Manager) SetIdle(setting string) error { + if setting != "" && setting != "off" { + d, err := time.ParseDuration(setting) + if err != nil || d <= 0 { + return fmt.Errorf("invalid idle setting %q: use on, off, or a duration such as 45m or 2h", setting) + } + } + + project, err := m.GetCurrentProject() + if err != nil { + return err + } + if project.Status == "not initialized" { + return fmt.Errorf("project not initialized") + } + if project.Idle == setting { + return nil + } + + project.Idle = setting + return m.recreate(project) +} + +// Wake starts the current project's container if it's stopped - asleep after +// going idle, or stopped by hand - and waits until it's running. Commands +// that run inside the container call it, so they work on a sleeping project. +func (m *Manager) Wake() (woke bool, err error) { + project, err := m.GetCurrentProject() + if err != nil { + return false, err + } + if project.Status == "not initialized" { + return false, fmt.Errorf("project not initialized. Run 'alios start' first") + } + if project.Status == "running" { + return false, nil + } + + if err := m.docker.StartContainer(project.Container); err != nil { + return false, fmt.Errorf("failed to start project container: %w", err) + } + for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { + if m.docker.IsContainerRunning(project.Container) { + return true, nil + } + } + return false, fmt.Errorf("project container didn't start; check 'alios logs'") +} + +// DescribeIdle explains a project's idle setting for status output. +func DescribeIdle(setting, globalTimeout string) string { + switch setting { + case "off": + return "never stopped (alios idle off)" + case "": + timeout, err := idle.ParseTimeout(globalTimeout, idle.DefaultTimeout) + if err != nil { + return "stops when idle (invalid ALIOS_IDLE_TIMEOUT, using the default)" + } + if timeout == 0 { + return "never stopped (ALIOS_IDLE_TIMEOUT=off)" + } + return fmt.Sprintf("stops after %s idle", timeout) + } + return fmt.Sprintf("stops after %s idle (project setting)", setting) +} diff --git a/internal/project/manager.go b/internal/project/manager.go index f47f6a2..8e8aadf 100644 --- a/internal/project/manager.go +++ b/internal/project/manager.go @@ -11,6 +11,7 @@ import ( "github.com/aliasproject/alios-cli/internal/config" "github.com/aliasproject/alios-cli/internal/docker" + "github.com/aliasproject/alios-cli/internal/idle" "github.com/aliasproject/alios-cli/internal/utils" ) @@ -64,6 +65,11 @@ type Project struct { // keys as real env vars would only shadow the file with a stale copy // until the next restart. Env map[string]string + + // Idle is the project's scale-to-zero setting, from the + // alios.project.idle label (`alios idle`): "" for the global + // ALIOS_IDLE_TIMEOUT, "off" to never stop it, or its own timeout. + Idle string } // ImageChoice carries a project's first-init image and framework selection @@ -163,6 +169,7 @@ func (m *Manager) GetCurrentProject() (*Project, error) { BuildArgs: buildArgs, Framework: info.Labels["alios.project.framework"], Env: env, + Idle: info.Labels[idle.IdleLabel], }, nil } @@ -550,7 +557,7 @@ func (m *Manager) SetEnv(vars map[string]string) error { return nil } - return m.recreateWithEnv(project) + return m.recreate(project) } // UnsetEnv removes user env vars from the current project and recreates the @@ -575,15 +582,15 @@ func (m *Manager) UnsetEnv(keys []string) error { return nil } - return m.recreateWithEnv(project) + return m.recreate(project) } -// recreateWithEnv replaces the project's container with one carrying -// project.Env, preserving the running/stopped state it had before. The -// container has to be recreated even when stopped: its labels are the only -// place the env vars persist, so removing it and waiting for the next start -// would lose them. -func (m *Manager) recreateWithEnv(project *Project) error { +// recreate replaces the project's container with one carrying project's +// current settings (env vars, idle setting), preserving the running/stopped +// state it had before. The container has to be recreated even when stopped: +// its labels are the only place these settings persist, so removing it and +// waiting for the next start would lose them. +func (m *Manager) recreate(project *Project) error { wasRunning := project.Status == "running" if err := m.docker.RemoveContainer(project.Container, true); err != nil { @@ -1047,6 +1054,7 @@ func (m *Manager) createContainer(project *Project) error { "alios.project.build_args": serializeBuildArgs(project.BuildArgs), "alios.project.framework": project.Framework, envLabel: serializeEnv(project.Env), + idle.IdleLabel: project.Idle, }, DNS: dnsServers, } diff --git a/internal/services/idle.go b/internal/services/idle.go new file mode 100644 index 0000000..bfc2f36 --- /dev/null +++ b/internal/services/idle.go @@ -0,0 +1,103 @@ +package services + +import ( + "fmt" + + "github.com/aliasproject/alios-cli/internal/config" + "github.com/aliasproject/alios-cli/internal/docker" +) + +// IdleContainer is the alios_idle service, which stops idle projects and +// wakes them on the next request (cmd/alios-idle, internal/idle). +// +// It's run with `docker run` rather than in the compose group: it's +// optional, and compose aborts the whole `up` when one image can't be +// pulled, so an unpublished or unreachable alios-idle image would otherwise +// take every global service down with it. +const IdleContainer = "alios_idle" + +// idleTimeoutLabel records the ALIOS_IDLE_TIMEOUT the running service was +// started with, so status output can report the service's real setting +// rather than whatever the current shell happens to have. +const idleTimeoutLabel = "alios.idle.timeout" + +// startIdle makes sure alios_idle is running the image this CLI expects. +// +// The timeout is only changed when ALIOS_IDLE_TIMEOUT is set in this +// shell. Global services also start implicitly (`alios start` calls +// EnsureRunning), and a terminal without the variable mustn't silently +// reset a timeout chosen in another. +func (m *Manager) startIdle() error { + timeout := m.config.IdleTimeout + info, err := m.docker.InspectContainer(IdleContainer) + exists := err == nil + if exists && timeout == "" { + timeout = info.Labels[idleTimeoutLabel] + } + + if exists && info.Image == config.IdleImage && info.Labels[idleTimeoutLabel] == timeout { + if info.State == "running" { + return nil + } + return m.docker.StartContainer(IdleContainer) + } + // Get the new image before touching the old container: after a CLI + // update its tag is new, and if it can't be pulled (offline, not yet + // published) the old service must keep running rather than leave no + // waker at all. + if !m.docker.ImageExists(config.IdleImage) { + if err := m.docker.PullImage(config.IdleImage, nil); err != nil { + if exists { + if info.State != "running" { + if startErr := m.docker.StartContainer(IdleContainer); startErr != nil { + return fmt.Errorf("couldn't pull %s (%v), and the previous version wouldn't start either: %w", config.IdleImage, err, startErr) + } + } + return fmt.Errorf("couldn't pull %s, so the previous version keeps running: %w", config.IdleImage, err) + } + return fmt.Errorf("couldn't pull %s: %w", config.IdleImage, err) + } + } + + if exists { + if err := m.docker.RemoveContainer(IdleContainer, true); err != nil { + return fmt.Errorf("failed to replace %s: %w", IdleContainer, err) + } + } + + return m.docker.RunContainer(&docker.ContainerConfig{ + Name: IdleContainer, + Image: config.IdleImage, + Detached: true, + Restart: "unless-stopped", + Network: config.GetNetworkConfig().BridgeName, + // Docker Desktop maps this path to its VM's socket on macOS and + // Windows too. Rootless Docker isn't supported yet. + Volumes: []string{"/var/run/docker.sock:/var/run/docker.sock"}, + Environment: map[string]string{"ALIOS_IDLE_TIMEOUT": timeout}, + Labels: map[string]string{idleTimeoutLabel: timeout}, + }) +} + +// StopIdle stops alios_idle if it's running and returns its name, so a pause +// can stop it before the projects (otherwise a request arriving mid-pause +// wakes a project that was just stopped) and still resume it afterwards. +func (m *Manager) StopIdle() []string { + if !m.docker.IsContainerRunning(IdleContainer) { + return nil + } + if err := m.docker.StopContainer(IdleContainer, 10); err != nil { + return nil + } + return []string{IdleContainer} +} + +// IdleTimeoutSetting returns the ALIOS_IDLE_TIMEOUT alios_idle was started +// with ("" for its default), and whether the service is running. +func (m *Manager) IdleTimeoutSetting() (string, bool) { + info, err := m.docker.InspectContainer(IdleContainer) + if err != nil { + return "", false + } + return info.Labels[idleTimeoutLabel], info.State == "running" +} diff --git a/internal/services/manager.go b/internal/services/manager.go index 278f6f0..2b2d031 100644 --- a/internal/services/manager.go +++ b/internal/services/manager.go @@ -80,6 +80,40 @@ const baseCaddyfile = `{ } } +# Project vhosts end with "import alios_wake ". When the project's +# container is stopped, Caddy can't reach it and the request goes to +# alios_idle instead, which starts the container and redirects the browser +# back to the same URL. Scoped to upstream failures so the app's own error +# pages, and a share's basic-auth 401, pass through untouched. Defined before +# the import below, since Caddy needs a snippet declared before it's used. +# +# The failed first hop has already consumed the request body, so the waker +# is always asked with a bodiless GET; forwarding a POST would fail on the +# closed body. The browser resends the original method and body itself, +# because the waker answers with a 307. +(alios_wake) { + handle_errors 502 503 504 { + request_header -Content-Length + request_header -Content-Type + request_header -Transfer-Encoding + reverse_proxy ` + IdleContainer + `:8080 { + method GET + header_up X-Alios-Project {args[0]} + } + } +} + +# "alios stop" swaps a vhost's alios_wake import for this one: a project +# stopped by hand stays down until "alios start", rather than being started +# by the next visit (a polling tab would otherwise undo the stop at once). +(alios_stopped) { + handle_errors 502 503 504 { + header Content-Type "text/plain; charset=utf-8" + header Cache-Control no-store + respond "{args[0]} is stopped. Run 'alios start' in the project to start it again." 503 + } +} + import /etc/caddy/*.caddyfile https:// { @@ -101,7 +135,9 @@ http:// { } ` -// GlobalServices defines the core global services +// GlobalServices defines the core global services. alios_idle isn't one of +// them: it's optional (see idle.go), so a missing image never takes down +// DNS, Caddy and every project with it. var GlobalServices = []string{ "alios_dns", "alios-reverse-proxy", // matches the name production uses for the same role @@ -128,18 +164,8 @@ func (m *Manager) Start() error { return fmt.Errorf("failed to prepare CA for the reverse proxy: %w", err) } - // Write the base Caddyfile and the default page into the vhosts volume - // before the container ever starts. The published caddy image's own - // baked-in Caddyfile only serves a landing page and has no knowledge of - // per-project vhosts; mounting alios_vhosts at /etc/caddy replaces that - // entirely, so this file must exist in the volume (even empty of any - // project) or Caddy has nothing to run. Rewritten on every start so it - // can't drift from what this binary expects. - if err := m.docker.WriteFileToVolume("alios_vhosts", "default/index.html", defaultPage); err != nil { - return fmt.Errorf("failed to write default page: %w", err) - } - if err := m.docker.WriteFileToVolume("alios_vhosts", "Caddyfile", []byte(baseCaddyfile)); err != nil { - return fmt.Errorf("failed to write base Caddyfile: %w", err) + if err := m.WriteBaseConfig(); err != nil { + return err } // Generate compose configuration @@ -164,6 +190,27 @@ func (m *Manager) Start() error { fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to reload Caddy config: %v\n", err) } + if err := m.startIdle(); err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Scale to zero is unavailable, so idle projects won't be stopped or woken: %v\n", err) + } + + return nil +} + +// WriteBaseConfig writes the base Caddyfile and the default page into the +// vhosts volume. The published caddy image's own baked-in Caddyfile only +// serves a landing page and has no knowledge of per-project vhosts; mounting +// alios_vhosts at /etc/caddy replaces that entirely, so this file must exist +// in the volume (even empty of any project) or Caddy has nothing to run. +// Rewritten on every start, and before `cert repair` rewrites vhosts, so it +// can't drift from what those vhosts expect (the alios_wake snippet). +func (m *Manager) WriteBaseConfig() error { + if err := m.docker.WriteFileToVolume("alios_vhosts", "default/index.html", defaultPage); err != nil { + return fmt.Errorf("failed to write default page: %w", err) + } + if err := m.docker.WriteFileToVolume("alios_vhosts", "Caddyfile", []byte(baseCaddyfile)); err != nil { + return fmt.Errorf("failed to write base Caddyfile: %w", err) + } return nil } @@ -222,8 +269,10 @@ func (m *Manager) Status() ([]*Service, error) { services := make([]*Service, 0) - // Check core services - for _, containerName := range GlobalServices { + // Check core services, plus the optional alios_idle so a stopped or + // crashed one shows up in status rather than silently disabling scale + // to zero. + for _, containerName := range append(GlobalServices[:len(GlobalServices):len(GlobalServices)], IdleContainer) { displayName := strings.TrimPrefix(containerName, "alios_") if displayName == "alios-reverse-proxy" { displayName = "caddy" diff --git a/internal/share/manager.go b/internal/share/manager.go index 2377f7b..1bc4920 100644 --- a/internal/share/manager.go +++ b/internal/share/manager.go @@ -479,13 +479,11 @@ http://%s { header_up X-Alios-Share 1 } - # Scoped to upstream failures so basic_auth's 401 (and its - # WWW-Authenticate challenge) passes through untouched. - handle_errors 502 503 504 { - respond "Project unavailable" 503 - } + # Wakes the project if it's asleep. The snippet only handles upstream + # failures, so basic_auth's 401 and its challenge pass through. + import alios_wake %s } -`, mode, host, authLine, projectName) +`, mode, host, authLine, projectName, projectName) if err := m.docker.WriteFileToVolume(vhostVolume, projectName+vhostSuffix, []byte(vhost)); err != nil { return fmt.Errorf("failed to write share vhost: %w", err) diff --git a/internal/ssl/manager.go b/internal/ssl/manager.go index 91280ae..67d5c3d 100644 --- a/internal/ssl/manager.go +++ b/internal/ssl/manager.go @@ -115,7 +115,9 @@ func (m *Manager) SetupProjectSSL(projectName string) error { } // Create Caddy vhost configuration - if err := m.createCaddyVhost(projectName, domain); err != nil { + // Called by `alios start`, so the project wakes on visits again even if + // it was stopped with `alios stop`. + if err := m.createCaddyVhost(projectName, domain, false); err != nil { return fmt.Errorf("failed to create Caddy vhost: %w", err) } @@ -141,6 +143,13 @@ func (m *Manager) RepairVhosts(projectNames []string) (int, error) { return 0, fmt.Errorf("CA certificate not found. Run 'alios cert install' first") } + // Keep projects stopped with `alios stop` stopped: a repair only fixes + // configuration, it shouldn't make a visit start them again. + stopped, err := m.StoppedProjects() + if err != nil { + return 0, fmt.Errorf("failed to read which projects are stopped: %w", err) + } + var errs []string repaired := 0 @@ -160,7 +169,7 @@ func (m *Manager) RepairVhosts(projectNames []string) (int, error) { continue } - if err := m.createCaddyVhost(name, domain); err != nil { + if err := m.createCaddyVhost(name, domain, stopped[name]); err != nil { errs = append(errs, fmt.Sprintf("%s: failed to write vhost: %v", name, err)) continue } @@ -232,6 +241,14 @@ func (m *Manager) RemoveProjectVhost(projectName string) error { // updateVhostToHTTP updates a project's vhost configuration to use HTTP instead of HTTPS func (m *Manager) updateVhostToHTTP(projectName string) error { + // Keep an `alios stop`: removing the certificate shouldn't make a visit + // start the project again. + ending := wakeImport + if current, err := m.docker.ReadFileFromVolume("alios_vhosts", projectName+".caddyfile"); err == nil && + strings.Contains(current, stoppedImport+projectName) { + ending = stoppedImport + } + // Create HTTP-only vhost configuration - no tls directive, so Caddy serves // this site block in plaintext instead of attempting automatic HTTPS (which // can't work for .test domains anyway; see createCaddyVhost). @@ -242,11 +259,9 @@ func (m *Manager) updateVhostToHTTP(projectName string) error { header_up X-Forwarded-For {remote} header_up X-Forwarded-Proto {scheme} } - handle_errors { - respond "Project unavailable" 503 - } + `+ending+`%s } -`, projectName, projectName) +`, projectName, projectName, projectName) // Write HTTP vhost configuration to volume if err := m.docker.WriteFileToVolume("alios_vhosts", projectName+".caddyfile", []byte(httpVhostConfig)); err != nil { @@ -490,7 +505,12 @@ func (m *Manager) copyCAToTempFile(tmpPath string) error { // container by name on the shared Docker network natively, and reverse_proxy // handles WebSocket upgrade automatically, so neither needs the manual // resolver/upgrade-header wiring the old nginx vhost required. -func (m *Manager) createCaddyVhost(projectName, domain string) error { +func (m *Manager) createCaddyVhost(projectName, domain string, stopped bool) error { + ending := wakeImport + if stopped { + ending = stoppedImport + } + vhostConfig := fmt.Sprintf(`%s { tls /etc/caddy/ssl/%s.crt /etc/caddy/ssl/%s.key @@ -501,11 +521,9 @@ func (m *Manager) createCaddyVhost(projectName, domain string) error { header_up X-Forwarded-Proto {scheme} } - handle_errors { - respond "Project unavailable" 503 - } + `+ending+`%s } -`, domain, domain, domain, projectName) +`, domain, domain, domain, projectName, projectName) // Write directly to the alios_vhosts volume rather than docker exec-ing into // the Caddy container, so vhosts can be written/repaired even when Caddy isn't @@ -516,6 +534,82 @@ func (m *Manager) createCaddyVhost(projectName, domain string) error { return m.docker.WriteFileToVolume("alios_vhosts", projectName+".caddyfile", []byte(vhostConfig)) } +// Each project vhost ends with exactly one of these lines; see the +// alios_wake and alios_stopped snippets in services.baseCaddyfile. +const ( + wakeImport = "import alios_wake " + stoppedImport = "import alios_stopped " +) + +// SetProjectStopped switches a project's vhost between waking it on a visit +// (asleep) and answering that it's stopped (stopped with `alios stop`). The +// vhost is the record of which: like a share, it's routing state that lives +// where Caddy reads it, with no label or file of its own. A project without +// a vhost, or with one from before scale to zero, is left alone. +func (m *Manager) SetProjectStopped(projectName string, stopped bool) error { + file := projectName + ".caddyfile" + content, err := m.docker.ReadFileFromVolume("alios_vhosts", file) + if err == docker.ErrFileNotFound { + return nil + } + if err != nil { + return err + } + + updated, changed := swapVhostEnding(content, projectName, stopped) + if !changed { + return nil + } + if err := m.docker.WriteFileToVolume("alios_vhosts", file, []byte(updated)); err != nil { + return err + } + if m.docker.IsContainerRunning("alios-reverse-proxy") { + if err := m.reloadCaddy(); err != nil { + // Caddy keeps its old config, but the file it would load on + // its next start is the one it just rejected: put it back. + m.docker.WriteFileToVolume("alios_vhosts", file, []byte(content+"\n")) + return fmt.Errorf("Caddy rejected the change: %w", err) + } + } + return nil +} + +// swapVhostEnding switches a vhost's final import between alios_wake and +// alios_stopped. It matches the whole line, so a vhost that merely mentions +// another project whose name starts with this one's can't be changed. +func swapVhostEnding(content, projectName string, stopped bool) (string, bool) { + from, to := wakeImport+projectName, stoppedImport+projectName + if !stopped { + from, to = to, from + } + lines := strings.Split(strings.TrimRight(content, "\n"), "\n") + for i, line := range lines { + if strings.TrimSpace(line) == from { + lines[i] = strings.Replace(line, from, to, 1) + return strings.Join(lines, "\n") + "\n", true + } + } + return content, false +} + +// StoppedProjects returns the projects stopped with `alios stop`, read from +// every vhost with one throwaway container. +func (m *Manager) StoppedProjects() (map[string]bool, error) { + output, err := m.docker.RunWithOutput("run", "--rm", "-v", "alios_vhosts:/vhosts:ro", "alpine:latest", + "sh", "-c", "cd /vhosts && grep -l '"+strings.TrimSpace(stoppedImport)+"' *.caddyfile 2>/dev/null; true") + if err != nil { + return nil, err + } + stopped := make(map[string]bool) + for _, line := range strings.Split(output, "\n") { + line = strings.TrimSpace(line) + if strings.HasSuffix(line, ".caddyfile") && !strings.HasSuffix(line, ".share.caddyfile") { + stopped[strings.TrimSuffix(line, ".caddyfile")] = true + } + } + return stopped, nil +} + func (m *Manager) reloadCaddy() error { return m.docker.Run("exec", "alios-reverse-proxy", "caddy", "reload", "--config", "/etc/caddy/Caddyfile") } diff --git a/internal/ssl/vhost_test.go b/internal/ssl/vhost_test.go new file mode 100644 index 0000000..eb13e2e --- /dev/null +++ b/internal/ssl/vhost_test.go @@ -0,0 +1,34 @@ +package ssl + +import ( + "strings" + "testing" +) + +const shopVhost = "shop.test {\n reverse_proxy alios_php_shop:80\n\n import alios_wake shop\n}\n" + +func TestSwapVhostEnding(t *testing.T) { + stopped, changed := swapVhostEnding(shopVhost, "shop", true) + if !changed || !strings.Contains(stopped, " import alios_stopped shop\n") || strings.Contains(stopped, "alios_wake") { + t.Fatalf("stop: changed=%v\n%s", changed, stopped) + } + back, changed := swapVhostEnding(stopped, "shop", false) + if !changed || back != shopVhost { + t.Fatalf("start didn't restore the original vhost:\n%s", back) + } + if _, changed := swapVhostEnding(shopVhost, "shop", false); changed { + t.Fatal("waking an already-waking vhost changed it") + } +} + +func TestSwapVhostEndingMatchesWholeLine(t *testing.T) { + // "sho" is a prefix of "shop": its stop must not touch shop's vhost. + if out, changed := swapVhostEnding(shopVhost, "sho", true); changed { + t.Fatalf("prefix project changed another vhost:\n%s", out) + } + // A vhost from before scale to zero has neither import; leave it alone. + old := "shop.test {\n reverse_proxy alios_php_shop:80\n}\n" + if _, changed := swapVhostEnding(old, "shop", true); changed { + t.Fatal("pre-scale-to-zero vhost was changed") + } +} diff --git a/scripts/release.sh b/scripts/release.sh index ea57b95..f2e5793 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -83,6 +83,17 @@ build_binary "linux" "arm64" build_binary "windows" "amd64" echo -e "${GREEN}✓ Build complete!${NC}" + +# The alios_idle service image. The CLI runs the tag matching its own +# version (config.IdleImage), so it must be pushed before the release is +# published. Needs `docker buildx` and a ghcr.io login with write:packages. +echo -e "${YELLOW}Building and pushing ghcr.io/aliasproject/alios-idle:${VERSION}...${NC}" +docker buildx build \ + --platform linux/amd64,linux/arm64 \ + -f "$REPO_ROOT/Dockerfile.idle" \ + -t "ghcr.io/aliasproject/alios-idle:${VERSION}" \ + --push \ + "$REPO_ROOT" echo "" echo "Files in $BUILD_DIR:" ls -lh "$BUILD_DIR"