diff --git a/.quality/baseline.json b/.quality/baseline.json index 76f32e7..5b70ba4 100644 --- a/.quality/baseline.json +++ b/.quality/baseline.json @@ -1,6 +1,6 @@ { - "measuredOn": "main 08061db, 2026-11-21, with the commands in .quality/README.md; the full mutation run went one file at a time with .quality/mutant-tests.sh and 2 workers", - "coverage": { "lines": 89.19, "metric": "statement coverage of cmd/ and internal/ without tests, as go tool cover -func totals it" }, + "measuredOn": "main 08061db, 2026-11-21, with the commands in .quality/README.md; the full mutation run went one file at a time with .quality/mutant-tests.sh and 2 workers; coverage remeasured 2026-11-26 for the runner pools change", + "coverage": { "lines": 90.92, "metric": "statement coverage of cmd/ and internal/ without tests, as go tool cover -func totals it" }, "functionsMeasured": 59, "functionsOverCrap10": 10, "functionsOverCrap10List": [ diff --git a/CHANGELOG.md b/CHANGELOG.md index c2bb66c..eccb0c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ the major version is 0, a minor release may change configuration (each such chan ## [Unreleased] ### Added +- `RUNNER_POOLS`: one controller serves several runner images. It takes a JSON list of pools, each with a `label`, `image`, `prefix`, `max_runners`, `scopes` and an optional `region` (falling back to `RUNNER_REGION`). Each cycle reads every scope once, whichever pools list it, gives each queued job to the pool whose label it asks for, and plans each pool on its own, so a full pool never holds up another. The App's one webhook wakes the controller for a job of any pool, so a second image no longer needs a second controller that only polls and scans the same repositories again. Labels and prefixes must differ across pools. The single-pool variables (`RUNNER_IMAGE`, `RUNNER_SCOPES`, `RUNNER_LABEL`, `RUNNER_SERVICE_PREFIX`, `MAX_RUNNERS`) still configure one pool unchanged; setting them together with `RUNNER_POOLS` is refused. `MAX_CREATE_PER_CYCLE` applies per pool. docs/deploy.md describes moving from two controllers to one; the second-controller setup is no longer documented. - The `sqlite3` command-line shell in every image variant, for tests and scripts that drive a SQLite database from the shell. - `libssl-dev` in every image variant, so Rust crates that link OpenSSL (`openssl-sys`) build on the pool; the build checks that `pkg-config` finds it. - The GitHub CLI (`gh` 2.102.0, pinned by version and sha256) in every image variant, so a job can open or comment on issues without a GitHub-hosted runner. Nothing is logged in: a job passes `GH_TOKEN`. @@ -17,6 +18,8 @@ the major version is 0, a minor release may change configuration (each such chan - Jobs queued in a run that GitHub reports as `pending` (for example while it waits on a concurrency group) are served; the controller listed only `queued` and `in_progress` runs and left such jobs waiting forever. ### Changed +- The webhook matches a job's labels without case, as GitHub and the job scan already do; a label written `Railway` in `runs-on` now wakes the controller too. +- A label of `self-hosted`, `linux` or `x64` is refused at start: every runner has those, so they cannot pick out a pool. - A queued-job webhook starts a cycle after a 3 s debounce instead of a fixed 20 s; cycles still start at least 20 s apart (measured from the previous cycle's start). - CI rebuilds the runner images only when `image/` changes and the controller image only when its Go code or Dockerfile changes, with a per-target layer cache; a version tag still publishes all three. diff --git a/README.md b/README.md index 72d728c..69e3adf 100644 --- a/README.md +++ b/README.md @@ -134,13 +134,15 @@ limits. [docs/deploy.md](docs/deploy.md) has the full guide, rollout and rollbac | --- | --- | --- | | `GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_WEBHOOK_SECRET` | the App (the PEM may keep `\n` escaped) | required | | `RUNNER_RAILWAY_TOKEN`, `RUNNER_RAILWAY_PROJECT_ID`, `RUNNER_RAILWAY_ENVIRONMENT_ID` | a project token, project and environment of the **runner** project (not `RAILWAY_*`: Railway injects those for the controller's own project, and the controller refuses to manage the project it runs in) | required | -| `RUNNER_IMAGE` | the runner image, pinned to a version or digest | required | -| `RUNNER_SCOPES` | comma list of `org:` and `repo:/` that may get runners | required | -| `RUNNER_LABEL` | the `runs-on` label of this controller's runners | `railway` | -| `RUNNER_SERVICE_PREFIX` | Railway service-name prefix of this controller's runners; a second controller in the same runner project needs its own (a letter, a letter or digit, a dash, e.g. `rp-`) | `rr-` | -| `RUNNER_REGION` | Railway region id for this controller's runners, e.g. `us-east4-eqdc4a`; the API's `regions` query lists them. Unset leaves placement to Railway (the workspace's preferred region) | unset | +| `RUNNER_POOLS` | several runner images on one controller: a JSON list of pools, see [Several pools](#several-pools). Set it instead of the five single-pool variables below | unset | +| `RUNNER_IMAGE` | the runner image, pinned to a version or digest (single pool) | required without `RUNNER_POOLS` | +| `RUNNER_SCOPES` | comma list of `org:` and `repo:/` that may get runners (single pool) | required without `RUNNER_POOLS` | +| `RUNNER_LABEL` | the `runs-on` label of the runners (single pool) | `railway` | +| `RUNNER_SERVICE_PREFIX` | Railway service-name prefix of the runners: a letter, a letter or digit, a dash, e.g. `rp-` (single pool) | `rr-` | +| `MAX_RUNNERS` | services at a time (single pool) | `8` | +| `RUNNER_REGION` | Railway region id for the runners, e.g. `us-east4-eqdc4a`, for every pool without a `region` of its own; the API's `regions` query lists them. Unset leaves placement to Railway (the workspace's preferred region) | unset | | `RUNNER_GROUP_ID` | the dedicated runner group of org runners; required for an `org:` scope, and the Default group (1) is refused | none | -| `MAX_RUNNERS` / `MAX_CREATE_PER_CYCLE` | services in all / created in one cycle | `8` / `4` | +| `MAX_CREATE_PER_CYCLE` | services one pool creates in one cycle | `4` | | `POLL_SECONDS` | polling period (a queued-job webhook wakes a cycle sooner: after a 3 s debounce, and at least 20 s after the previous cycle started) | `120` | | `STARTUP_GRACE_SECONDS` | how long a registered runner may stay offline before its service is removed | `300` | | `IDLE_TTL_SECONDS` | how long a surplus idle runner is kept | `120` | @@ -149,6 +151,33 @@ limits. [docs/deploy.md](docs/deploy.md) has the full guide, rollout and rollbac | `ALERT_FAILED_CYCLES` | after this many failed cycles in a row: one alert (naming scopes unreadable that long), `/healthz` 503, and one "recovered" alert when a cycle succeeds again. A scope GitHub answers 404 for this many cycles in a row raises one alert of its own | `3` | | `PORT` | HTTP port | `8080` | +### Several pools + +One controller can serve several runner images, each a pool with its own label, image, service-name +prefix, maximum and scopes. Each cycle reads every scope once, whichever pools list it, and gives each +queued job to the pool whose label it asks for. Each pool is then planned on its own, so a pool at its +maximum never holds up another. The App's one webhook wakes the controller for a job of any pool. + +``` +RUNNER_POOLS=[ + {"label":"railway","image":"ghcr.io/farzai/github-runner-railway:","prefix":"rr-","max_runners":4,"scopes":["repo:acme/app","repo:acme/api"]}, + {"label":"railway-pg","image":"ghcr.io/farzai/github-runner-railway:pg-","prefix":"rp-","max_runners":2,"scopes":["repo:acme/app"]} +] +``` + +* Every field is required except `region`, which falls back to `RUNNER_REGION`. An unknown field is + refused, so a typo stops the controller at start. +* Labels must differ (compared without case, as GitHub does) and cannot be `self-hosted`, `linux` or + `x64`. A job that asks for two pool labels fits no runner and is left alone. +* Prefixes must differ. The prefix rule (a letter, a letter or digit, a dash) means one prefix is never + the start of another, so no pool lists or removes another pool's services. +* `RUNNER_POOLS` together with `RUNNER_IMAGE`, `RUNNER_LABEL`, `RUNNER_SERVICE_PREFIX`, `MAX_RUNNERS` or + `RUNNER_SCOPES` is refused. Without `RUNNER_POOLS`, those five variables are one pool, as before. +* `MAX_CREATE_PER_CYCLE` applies to each pool, so N pools can create up to N times that many services in + one cycle. +* Before you take a pool out, drain it: move its workflows to another label and wait until its services + are gone. The controller no longer lists the services of a prefix it does not have. + ## The runner images | Image | Contents | @@ -159,10 +188,8 @@ limits. [docs/deploy.md](docs/deploy.md) has the full guide, rollout and rollbac | `ghcr.io/farzai/github-runner-railway:php-` | the base image plus PHP 8.3, 8.4 and 8.5 (ondrej/php PPA) and Composer, and `use-php ` to pick one; for PHP projects, since `setup-php` cannot run without sudo | | `ghcr.io/farzai/github-runner-railway:redis-` | the base image plus a pinned `redis-server` and `ci-redis` | -To serve both, run a **second controller** with `RUNNER_LABEL=railway-pg`, `RUNNER_SERVICE_PREFIX=rp-` -and the `pg-` image, in the same runner project. Each controller lists and removes only its own -services and only takes jobs that ask for its label. A GitHub App has one webhook URL, so the second -controller works on polling alone (set `POLL_SECONDS=60`). +To serve more than one image, give each its own pool in `RUNNER_POOLS` (see [Several pools](#several-pools)): +one controller, one webhook, each pool with its own label and prefix. The published `pg-` image has PostgreSQL 18 and no extensions. Build your own with another major and PGDG extensions (all pinned, from the signed PGDG repository) and push it to your registry: @@ -244,8 +271,8 @@ For workflows you cannot change yet (`sudo apt-get install`, `playwright install `ldconfig` in a step), the `sudo-` image gives the runner user passwordless sudo. Each job is its own container, so root stays inside that job's container and is gone when it ends, but the job can now change anything in it, and the container still shares the runner project's private -network with concurrent jobs. Use it for private repositories only, in its own pool (a controller -with its own label and `RUNNER_SERVICE_PREFIX`), and prefer a derived image where you can. The +network with concurrent jobs. Use it for private repositories only, in its own pool (its own label and +prefix in `RUNNER_POOLS`), and prefer a derived image where you can. The default images stay sudo-free. ## Limits @@ -261,7 +288,7 @@ default images stay sudo-free. about 1,000 processes and threads). `nproc` shows the host's cores, not the quota; Node's `os.availableParallelism()` reads the quota. Pass explicit `-j`/worker counts to be safe. * **Railway API:** 1,000 requests an hour per token. A job costs about four calls and a cycle one, so - roughly 230 jobs an hour at the default poll; two controllers sharing one token share that budget. + roughly 230 jobs an hour at the default poll; every pool, and every controller sharing the token, shares that budget. * **GitHub API:** 5,000 requests an hour per installation, shared by every scope of that installation (one access token per installation). Run and job lists are read with `If-None-Match`, and an unchanged list (`304`) does not count against the limit. Prefer `repo:` scopes for large organizations: diff --git a/cmd/controller/main.go b/cmd/controller/main.go index 85d9f17..a90e995 100644 --- a/cmd/controller/main.go +++ b/cmd/controller/main.go @@ -26,12 +26,12 @@ func main() { log.Error("startup", "err", err.Error()) os.Exit(1) } - gh, err := ghapp.New(ghapp.Config{AppID: cfg.AppID, PrivateKey: cfg.PrivateKey, Label: cfg.Label, RunnerGroupID: cfg.RunnerGroupID}) + gh, err := ghapp.New(ghapp.Config{AppID: cfg.AppID, PrivateKey: cfg.PrivateKey, Labels: cfg.Labels(), RunnerGroupID: cfg.RunnerGroupID}) if err != nil { log.Error("startup", "err", err.Error()) os.Exit(1) } - rw := railway.New(railway.Config{Token: cfg.RailwayToken, ProjectID: cfg.RailwayProject, EnvironmentID: cfg.RailwayEnv, Image: cfg.Image, Prefix: cfg.ServicePrefix, Region: cfg.Region}) + rw := railway.New(railway.Config{Token: cfg.RailwayToken, ProjectID: cfg.RailwayProject, EnvironmentID: cfg.RailwayEnv, Prefixes: cfg.Prefixes()}) alert := func(msg string) { log.Error("ALERT", "alert", msg) // not "msg": slog writes the message under that key if cfg.AlertURL == "" { @@ -43,13 +43,13 @@ func main() { } } c := controller.New(controller.Config{ - Scopes: cfg.Scopes, Prefix: cfg.ServicePrefix, MaxRunners: cfg.MaxRunners, MaxCreatePerCycle: cfg.MaxCreatePerCycle, + Pools: cfg.Pools, MaxCreatePerCycle: cfg.MaxCreatePerCycle, StartupGrace: cfg.StartupGrace, IdleTTL: cfg.IdleTTL, MaxAge: cfg.MaxAge, AlertAfter: cfg.AlertAfter, Interval: cfg.Interval, FailAlertAfter: cfg.FailAlertAfter, Alert: alert, Log: log, }, gh, rw) mux := http.NewServeMux() - mux.Handle("/webhook", webhook.Handler(cfg.WebhookSecret, cfg.Label, func(e webhook.Event) { + mux.Handle("/webhook", webhook.Handler(cfg.WebhookSecret, cfg.Labels(), func(e webhook.Event) { log.Info("workflow_job", "action", e.Action, "repo", e.Repo) c.OnEvent(e) })) diff --git a/docs/deploy.md b/docs/deploy.md index fbdb1ec..4cfd528 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -7,15 +7,16 @@ specific to one deployment. The README's quick start is the short version. | Railway project | Holds | Token | | --- | --- | --- | -| **Controller project** | one controller service per pool | used only to deploy the controller | -| **Runner project** | nothing but the one-job runner services the controllers create and delete | a project token, given to the controller as `RUNNER_RAILWAY_TOKEN` | +| **Controller project** | the controller service, which serves every pool | used only to deploy the controller | +| **Runner project** | nothing but the one-job runner services the controller creates and deletes | a project token, given to the controller as `RUNNER_RAILWAY_TOKEN` | Keep them apart: services in one Railway environment share a private network, and a job must not reach the controller (it holds the App key and the Railway token). Keep nothing else in the runner project. -Serve **private repositories only** (see SECURITY.md). A pool is one controller with one label and one -runner image; most setups need one pool, and the optional Postgres pool is a second controller. +Serve **private repositories only** (see SECURITY.md). A pool is one label and one runner image, and +one controller serves every pool. Most setups need one pool; the optional Postgres pool is a second +entry in `RUNNER_POOLS`. ## Before the controller can start @@ -54,29 +55,58 @@ healthcheck path `/healthz`, restart on failure. Never put these values in a repository or a log. The controller exits at start when one is missing, naming the variable only. Then set the App's webhook URL to `https:///webhook`. -`RUNNER_SCOPES` is the real guard of what the pool serves: the controller only makes runners for the -scopes it lists, and a `repo:` scope's runners can only be used by that repository. +`RUNNER_SCOPES` (or each pool's `scopes`) is the real guard of what a pool serves: the controller only +makes runners for the scopes it lists, and a `repo:` scope's runners can only be used by that +repository. ## The Postgres pool (optional) -For jobs that need PostgreSQL or Playwright's browsers, a second controller service in the same -controller project: +For jobs that need PostgreSQL or Playwright's browsers, add a second pool to the same controller. +Replace `RUNNER_IMAGE`, `RUNNER_SCOPES`, `RUNNER_LABEL`, `RUNNER_SERVICE_PREFIX` and `MAX_RUNNERS` with +one `RUNNER_POOLS` variable that holds both pools (the controller refuses a mix of the two): -| Variable | Value | +``` +RUNNER_POOLS=[ + {"label":"railway","image":"ghcr.io/farzai/github-runner-railway:","prefix":"rr-","max_runners":4,"scopes":["repo:/"]}, + {"label":"railway-pg","image":"ghcr.io/farzai/github-runner-railway:pg-","prefix":"rp-","max_runners":2,"scopes":["repo:/"]} +] +``` + +| Field | Value | | --- | --- | -| `RUNNER_LABEL` | e.g. `railway-pg` | -| `RUNNER_SERVICE_PREFIX` | e.g. `rp-` (the first controller keeps `rr-`; each lists and removes only its own services) | -| `RUNNER_REGION` | optional, e.g. `us-east4-eqdc4a`: the region this controller's runners are created in; unset uses the workspace's preferred region | -| `RUNNER_IMAGE` | `ghcr.io/farzai/github-runner-railway:pg-` | -| `RUNNER_SCOPES` | only the repositories that need it | -| `POLL_SECONDS` | `60`: the App's one webhook URL goes to the first controller, so this one polls | -| everything else | as the first controller (same App, same runner project and token) | +| `label` | the `runs-on` label of the pool's jobs; each pool its own, e.g. `railway-pg` | +| `image` | the pool's runner image, pinned to a version or digest | +| `prefix` | the pool's service-name prefix, each pool its own, e.g. `rp-` (the controller lists and removes a pool's services by it) | +| `max_runners` | the pool's own maximum; a full pool never holds up another | +| `scopes` | only the repositories that need it; a repository in two pools is still read once a cycle | +| `region` | optional, e.g. `us-east4-eqdc4a`; unset takes `RUNNER_REGION` | + +The App's one webhook wakes the controller for a job of any pool, so no pool works on polling alone. +Every other variable is shared (same App, same runner project and token). The README's "Several pools" +section has the rules. A job there runs `ci-postgres start ` and reads `CI_POSTGRES_URL` (README). The Playwright browsers of the version pinned in `image/Dockerfile` are baked in under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`, so `playwright install` of that version downloads nothing; a job on another Playwright version downloads its own browsers into the same directory. +## Moving from two controllers to one + +An older setup ran the Postgres pool as a controller of its own, with its own `RUNNER_LABEL`, +`RUNNER_SERVICE_PREFIX` and `RUNNER_IMAGE`, working on polling alone. To fold it into the main one: + +1. Stop the Postgres controller (remove its deployment). Two controllers must never manage the same + prefix at once. +2. Set `RUNNER_POOLS` on the main controller with both pools, each with the label, image, prefix, + maximum, scopes and region it had (a controller's `RUNNER_REGION` becomes its pool's `region`), + remove the five single-pool variables, and redeploy. Keeping the prefixes means the controller adopts + the runner services already running. +3. Delete the Postgres controller's service once the main one shows both pools in its `controller up` log + line and jobs of both labels get runners. + +To go back, redeploy the previous controller image with its single-pool variables and start the Postgres +controller again. + ## Rollout and rollback 1. Deploy with `MAX_RUNNERS=1` and one private pilot repository in `RUNNER_SCOPES`. @@ -88,12 +118,13 @@ a job on another Playwright version downloads its own browsers into the same dir 4. Add repositories to `RUNNER_SCOPES` one at a time and raise `MAX_RUNNERS` to your parallel jobs. 5. **Rollback:** set the jobs' `runs-on` back to a hosted runner, stop the controller (remove its deployment or delete the service; `MAX_RUNNERS` cannot be 0), and delete any `*` services - left in the runner project. + of each pool left in the runner project. ## Upgrades Pin both images to a release (`:vX.Y.Z`, `:pg-vX.Y.Z`) or a digest. To upgrade, change -`RUNNER_IMAGE` and the controller's image to the new version and redeploy the controller; runners +`RUNNER_IMAGE` (or each pool's `image`) and the controller's image to the new version and redeploy the +controller; runners already running finish on the old image. Read CHANGELOG.md for anything that needs a new variable. ## Which image tag is current @@ -118,11 +149,11 @@ else you need running. Runners can run in a project next to services that stay up, such as a shared CI database or a cache, and reach them over the private network (`.railway.internal`). The controller lists, counts -and deletes only services whose names are exactly `<6 hex>-<6 hex>`, the names +and deletes only services whose names are exactly `<6 hex>-<6 hex>`, the names it makes; any other service, including one that starts with the prefix (`rr-postgres`), is never touched (tested in `internal/railway`). Still: -* Pick a prefix no other service in the project uses, and give each controller its own. +* Pick prefixes no other service in the project uses, one per pool. * Everything a job runs can reach those services, and any concurrent job can too: use this only for private repositories of one trust level, and give the shared services their own credentials. * A shared database is state that outlives jobs: tests must clean up after themselves or use their @@ -132,19 +163,20 @@ touched (tested in `internal/railway`). Still: ## Sizing -* **`MAX_RUNNERS`**: the most jobs you want running at once: for one repository, its widest matrix +* **`MAX_RUNNERS`** (a pool's `max_runners`): the most jobs you want running at once: for one repository, its widest matrix times the workflows that can run together; for several, the sum at your busiest hour. Each runner is a container with its own CPU and memory, so this is also your spend cap. Watch `queued` in - `/healthz` and the `cycle` log line: jobs that wait while `services` equals `MAX_RUNNERS` mean the + `/healthz` and the `cycle` log line: jobs that wait while `services` equals `MAX_RUNNERS` (the sum of the pools' maximums) mean the cap is too low. -* **`MAX_CREATE_PER_CYCLE`**: how many runners one cycle may start, about the size of a burst (one - push's matrix). Higher starts a burst faster but spends more Railway calls at once. +* **`MAX_CREATE_PER_CYCLE`**: how many runners one pool may start in one cycle, about the size of a + burst (one push's matrix). Higher starts a burst faster but spends more Railway calls at once; N + pools can start up to N times that many in one cycle. * **Railway API**: per token, by plan: 100 requests an hour (Free), 1,000 (Hobby), 10,000 (Pro), plus 10 (Hobby) or 50 (Pro) a second (Railway docs, public API, read 2026-10-17). The limit actually applied is in the `X-RateLimit-Limit` header of every answer; a Pro workspace was observed at 1,000 an hour for project tokens on 2026-10-17, so plan for the header, not the table. A job costs about four - calls (create, configure, deploy, delete) and every cycle one list call; controllers that share a - token share its budget. At 1,000 an hour and the default poll that is roughly 230 jobs an hour. + calls (create, configure, deploy, delete) and every cycle one list call, whatever the number of + pools; controllers that share a token share its budget. At 1,000 an hour and the default poll that is roughly 230 jobs an hour. * **GitHub API**: 5,000 requests an hour per installation (more above 20 repositories), shared by every scope of that installation. A cycle reads, per repository, four run lists (`queued`, `pending`, `in_progress`, and the 20 newest runs unfiltered, since GitHub's status filter can leave diff --git a/internal/config/config.go b/internal/config/config.go index d31dabc..0f4b6f0 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( + "encoding/json" "fmt" "regexp" "strconv" @@ -17,12 +18,9 @@ type Config struct { AppID, PrivateKey, WebhookSecret string RailwayToken string RailwayProject, RailwayEnv string - Image, Label string - ServicePrefix string // Railway service names of this controller's runners - Region string // Railway region of the runners; empty leaves it to Railway - Scopes []reconcile.Scope + Pools []reconcile.Pool RunnerGroupID int - MaxRunners, MaxCreatePerCycle int + MaxCreatePerCycle int // per pool, per cycle Interval, StartupGrace, IdleTTL time.Duration MaxAge, AlertAfter time.Duration FailAlertAfter int // failed cycles in a row before an alert and a 503 @@ -32,11 +30,29 @@ type Config struct { // String is the config without its secrets. func (c Config) String() string { - keys := make([]string, 0, len(c.Scopes)) - for _, s := range c.Scopes { - keys = append(keys, s.Key()) + pools := make([]string, 0, len(c.Pools)) + for _, p := range c.Pools { + keys := make([]string, 0, len(p.Scopes)) + for _, s := range p.Scopes { + keys = append(keys, s.Key()) + } + pools = append(pools, fmt.Sprintf("[label=%s prefix=%s region=%s image=%s max=%d scopes=%s]", p.Label, p.Prefix, p.Region, p.Image, p.MaxRunners, strings.Join(keys, ","))) + } + return fmt.Sprintf("pools=%s interval=%s", strings.Join(pools, " "), c.Interval) +} + +// Labels is every pool's label, in pool order. +func (c Config) Labels() []string { return c.each(func(p reconcile.Pool) string { return p.Label }) } + +// Prefixes is every pool's service-name prefix, in pool order. +func (c Config) Prefixes() []string { return c.each(func(p reconcile.Pool) string { return p.Prefix }) } + +func (c Config) each(field func(reconcile.Pool) string) []string { + out := make([]string, len(c.Pools)) + for i, p := range c.Pools { + out[i] = field(p) } - return fmt.Sprintf("scopes=%s label=%s prefix=%s region=%s image=%s max=%d interval=%s", strings.Join(keys, ","), c.Label, c.ServicePrefix, c.Region, c.Image, c.MaxRunners, c.Interval) + return out } // Load reads and checks the environment through get. @@ -55,7 +71,6 @@ func Load(get func(string) string) (Config, error) { }{ {"GITHUB_APP_ID", &c.AppID}, {"GITHUB_APP_PRIVATE_KEY", &c.PrivateKey}, {"GITHUB_WEBHOOK_SECRET", &c.WebhookSecret}, {"RUNNER_RAILWAY_TOKEN", &c.RailwayToken}, {"RUNNER_RAILWAY_PROJECT_ID", &c.RailwayProject}, {"RUNNER_RAILWAY_ENVIRONMENT_ID", &c.RailwayEnv}, - {"RUNNER_IMAGE", &c.Image}, } { if err := need(f.name, f.into); err != nil { return Config{}, err @@ -67,43 +82,17 @@ func Load(get func(string) string) (Config, error) { if own := strings.TrimSpace(get("RAILWAY_PROJECT_ID")); own != "" && own == c.RailwayProject { return Config{}, fmt.Errorf("config: RUNNER_RAILWAY_PROJECT_ID is the project the controller runs in; the runners belong in their own project") } - var raw string - if err := need("RUNNER_SCOPES", &raw); err != nil { - return Config{}, err - } - for _, part := range strings.Split(raw, ",") { - s, err := parseScope(strings.TrimSpace(part)) - if err != nil { - return Config{}, err - } - c.Scopes = append(c.Scopes, s) - } - str := func(name, def string) string { - if v := strings.TrimSpace(get(name)); v != "" { - return v - } - return def - } var err error num := func(name string, def int) int { - v := strings.TrimSpace(get(name)) - if v == "" { - return def - } - n, perr := strconv.Atoi(v) - if perr != nil || n < 0 { - err = fmt.Errorf("config: %s is not a non-negative number", name) - return def + n, nerr := number(get, name, def) + if nerr != nil { + err = nerr } return n } - c.Label = str("RUNNER_LABEL", "railway") - c.ServicePrefix = str("RUNNER_SERVICE_PREFIX", "rr-") - c.Region = str("RUNNER_REGION", "") - c.Port = str("PORT", "8080") + c.Port = text(get, "PORT", "8080") c.AlertURL = strings.TrimSpace(get("ALERT_WEBHOOK_URL")) c.RunnerGroupID = num("RUNNER_GROUP_ID", 0) - c.MaxRunners = num("MAX_RUNNERS", 8) c.MaxCreatePerCycle = num("MAX_CREATE_PER_CYCLE", 4) c.Interval = time.Duration(num("POLL_SECONDS", 120)) * time.Second c.StartupGrace = time.Duration(num("STARTUP_GRACE_SECONDS", 300)) * time.Second @@ -114,35 +103,227 @@ func Load(get func(string) string) (Config, error) { if err != nil { return Config{}, err } - for _, sc := range c.Scopes { - if sc.Kind == "org" && (c.RunnerGroupID == 0 || c.RunnerGroupID == 1) { - return Config{}, fmt.Errorf("config: RUNNER_GROUP_ID must name a dedicated runner group (not the Default group, 1) for an org scope") - } - } - // One letter, one letter or digit, a dash: never a prefix of another valid prefix, so two - // controllers sharing the runner project cannot list or reap each other's services. - if !servicePrefix.MatchString(c.ServicePrefix) { - return Config{}, fmt.Errorf("config: RUNNER_SERVICE_PREFIX must be two lowercase letters or digits (the first a letter) and a dash, e.g. rp-") + if c.Pools, err = loadPools(get); err != nil { + return Config{}, err } - // A Railway region id, e.g. us-east4-eqdc4a. Railway itself refuses an unknown one when the - // first runner is created; this only catches what cannot be a region id at all. - if c.Region != "" && !region.MatchString(c.Region) { - return Config{}, fmt.Errorf("config: RUNNER_REGION must be a Railway region id of lowercase letters, digits and dashes, e.g. us-east4-eqdc4a") + for _, p := range c.Pools { + for _, sc := range p.Scopes { + if sc.Kind == "org" && (c.RunnerGroupID == 0 || c.RunnerGroupID == 1) { + return Config{}, fmt.Errorf("config: RUNNER_GROUP_ID must name a dedicated runner group (not the Default group, 1) for an org scope") + } + } } if c.FailAlertAfter < 1 { return Config{}, fmt.Errorf("config: ALERT_FAILED_CYCLES must be at least 1") } - if c.MaxRunners < 1 || c.MaxCreatePerCycle < 1 || c.Interval < 10*time.Second { - return Config{}, fmt.Errorf("config: MAX_RUNNERS and MAX_CREATE_PER_CYCLE must be at least 1 and POLL_SECONDS at least 10") + if c.MaxCreatePerCycle < 1 || c.Interval < 10*time.Second { + return Config{}, fmt.Errorf("config: MAX_CREATE_PER_CYCLE must be at least 1 and POLL_SECONDS at least 10") } return c, nil } +// text reads a variable, def when it is unset or blank. +func text(get func(string) string, name, def string) string { + if v := strings.TrimSpace(get(name)); v != "" { + return v + } + return def +} + +// number reads a non-negative whole number, def when the variable is unset. +func number(get func(string) string, name string, def int) (int, error) { + v := strings.TrimSpace(get(name)) + if v == "" { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + return def, fmt.Errorf("config: %s is not a non-negative number", name) + } + return n, nil +} + +// singlePoolVars are the variables of a one-pool setup, which RUNNER_POOLS replaces. +var singlePoolVars = []string{"RUNNER_IMAGE", "RUNNER_LABEL", "RUNNER_SERVICE_PREFIX", "MAX_RUNNERS", "RUNNER_SCOPES"} + +// poolNames is how errors name each field of a pool: the single-pool variable, or the field of +// RUNNER_POOLS it came from. +type poolNames struct{ label, image, prefix, region, max, scopes string } + +func singleNames() poolNames { + return poolNames{"RUNNER_LABEL", "RUNNER_IMAGE", "RUNNER_SERVICE_PREFIX", "RUNNER_REGION", "MAX_RUNNERS", "RUNNER_SCOPES"} +} + +func pooledNames(i int) poolNames { + f := func(field string) string { return fmt.Sprintf("RUNNER_POOLS[%d].%s", i, field) } + return poolNames{f("label"), f("image"), f("prefix"), f("region"), f("max_runners"), f("scopes")} +} + +// loadPools reads RUNNER_POOLS, or the single-pool variables as one pool when it is unset. A +// pool with no region of its own takes RUNNER_REGION. +func loadPools(get func(string) string) ([]reconcile.Pool, error) { + region := strings.TrimSpace(get("RUNNER_REGION")) + if err := checkRegion(region, "RUNNER_REGION"); err != nil { + return nil, err + } + raw := strings.TrimSpace(get("RUNNER_POOLS")) + if raw == "" { + p, err := singlePool(get, region) + if err != nil { + return nil, err + } + return []reconcile.Pool{p}, nil + } + for _, name := range singlePoolVars { + if strings.TrimSpace(get(name)) != "" { + return nil, fmt.Errorf("config: %s cannot be set together with RUNNER_POOLS; put it in the pool instead", name) + } + } + return parsePools(raw, region) +} + +// singlePool is the one pool of the single-pool variables, with today's defaults. +func singlePool(get func(string) string, region string) (reconcile.Pool, error) { + p := reconcile.Pool{Image: text(get, "RUNNER_IMAGE", ""), Label: text(get, "RUNNER_LABEL", "railway"), Prefix: text(get, "RUNNER_SERVICE_PREFIX", "rr-"), Region: region} + if p.Image == "" { + return p, fmt.Errorf("config: RUNNER_IMAGE is not set") + } + raw := text(get, "RUNNER_SCOPES", "") + if raw == "" { + return p, fmt.Errorf("config: RUNNER_SCOPES is not set") + } + var err error + if p.Scopes, err = parseScopes(strings.Split(raw, ","), "RUNNER_SCOPES"); err != nil { + return p, err + } + if p.MaxRunners, err = number(get, "MAX_RUNNERS", 8); err != nil { + return p, err + } + return p, checkPool(p, singleNames()) +} + +// poolJSON is one entry of RUNNER_POOLS. +type poolJSON struct { + Label string `json:"label"` + Image string `json:"image"` + Prefix string `json:"prefix"` + Region string `json:"region"` + MaxRunners int `json:"max_runners"` + Scopes []string `json:"scopes"` +} + +// parsePools reads RUNNER_POOLS strictly: one JSON array, no unknown field, every pool checked +// on its own and against the others. +func parsePools(raw, region string) ([]reconcile.Pool, error) { + dec := json.NewDecoder(strings.NewReader(raw)) + dec.DisallowUnknownFields() + var in []poolJSON + if err := dec.Decode(&in); err != nil || dec.More() { + return nil, fmt.Errorf("config: RUNNER_POOLS is not a JSON array of pools (label, image, prefix, max_runners, scopes, and optional region)") + } + if len(in) == 0 { + return nil, fmt.Errorf("config: RUNNER_POOLS has no pool") + } + pools := make([]reconcile.Pool, 0, len(in)) + for i, pj := range in { + names := pooledNames(i) + p, err := pj.pool(region, names) + if err == nil { + err = checkApart(p, pools, names) + } + if err != nil { + return nil, err + } + pools = append(pools, p) + } + return pools, nil +} + +// pool is the entry as a checked pool; with no region of its own it takes region. +func (pj poolJSON) pool(region string, names poolNames) (reconcile.Pool, error) { + p := reconcile.Pool{Label: strings.TrimSpace(pj.Label), Image: strings.TrimSpace(pj.Image), Prefix: strings.TrimSpace(pj.Prefix), + Region: strings.TrimSpace(pj.Region), MaxRunners: pj.MaxRunners} + if p.Region == "" { + p.Region = region + } + for _, f := range []struct{ v, name string }{{p.Label, names.label}, {p.Image, names.image}, {p.Prefix, names.prefix}} { + if f.v == "" { + return p, fmt.Errorf("config: %s is not set", f.name) + } + } + if len(pj.Scopes) == 0 { + return p, fmt.Errorf("config: %s is empty", names.scopes) + } + var err error + if p.Scopes, err = parseScopes(pj.Scopes, names.scopes); err != nil { + return p, err + } + return p, checkPool(p, names) +} + +// checkPool checks what a pool must be on its own. +func checkPool(p reconcile.Pool, names poolNames) error { + if p.Label == "" || reserved[strings.ToLower(p.Label)] { + return fmt.Errorf("config: %s must be a label of your own, not self-hosted, linux or x64 (every runner has those)", names.label) + } + // One letter, one letter or digit, a dash: never a prefix of another valid prefix, so two pools + // (or two controllers) sharing the runner project cannot list or reap each other's services. + if !servicePrefix.MatchString(p.Prefix) { + return fmt.Errorf("config: %s must be two lowercase letters or digits (the first a letter) and a dash, e.g. rp-", names.prefix) + } + if err := checkRegion(p.Region, names.region); err != nil { + return err + } + if p.MaxRunners < 1 { + return fmt.Errorf("config: %s must be at least 1", names.max) + } + return nil +} + +// checkApart refuses a pool that shares a prefix or a label with an earlier one: a prefix would +// let one pool reap the other's services, and a label would leave a job two pools to go to. +func checkApart(p reconcile.Pool, earlier []reconcile.Pool, names poolNames) error { + for _, e := range earlier { + if e.Prefix == p.Prefix { + return fmt.Errorf("config: %s %s is another pool's prefix; each pool needs its own", names.prefix, p.Prefix) + } + if strings.EqualFold(e.Label, p.Label) { + return fmt.Errorf("config: %s %s is another pool's label (labels compare without case); each pool needs its own", names.label, p.Label) + } + } + return nil +} + +// reserved is the labels every runner has, which cannot tell one pool from another. +var reserved = map[string]bool{"self-hosted": true, "linux": true, "x64": true} + +// checkRegion accepts a Railway region id, e.g. us-east4-eqdc4a, or nothing. Railway itself +// refuses an unknown one when the first runner is created; this only catches what cannot be a +// region id at all. +func checkRegion(r, name string) error { + if r != "" && !region.MatchString(r) { + return fmt.Errorf("config: %s must be a Railway region id of lowercase letters, digits and dashes, e.g. us-east4-eqdc4a", name) + } + return nil +} + var servicePrefix = regexp.MustCompile(`^[a-z][a-z0-9]-$`) var region = regexp.MustCompile(`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`) -func parseScope(s string) (reconcile.Scope, error) { +func parseScopes(entries []string, name string) ([]reconcile.Scope, error) { + out := make([]reconcile.Scope, 0, len(entries)) + for _, e := range entries { + s, err := parseScope(strings.TrimSpace(e), name) + if err != nil { + return nil, err + } + out = append(out, s) + } + return out, nil +} + +func parseScope(s, name string) (reconcile.Scope, error) { kind, rest, ok := strings.Cut(s, ":") switch { case ok && kind == "org" && rest != "" && !strings.Contains(rest, "/"): @@ -153,5 +334,5 @@ func parseScope(s string) (reconcile.Scope, error) { return reconcile.Scope{Kind: "repo", Owner: owner, Repo: repo}, nil } } - return reconcile.Scope{}, fmt.Errorf("config: RUNNER_SCOPES entry %q is not org: or repo:/", s) + return reconcile.Scope{}, fmt.Errorf("config: %s entry %q is not org: or repo:/", name, s) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 3d86d27..69181a4 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -22,10 +22,10 @@ func TestLoadParsesScopesAndDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if len(c.Scopes) != 2 || c.Scopes[0].Key() != "org:acme" || c.Scopes[1].Key() != "repo:acme/app" { - t.Errorf("scopes %+v", c.Scopes) + if len(c.Pools) != 1 || len(c.Pools[0].Scopes) != 2 || c.Pools[0].Scopes[0].Key() != "org:acme" || c.Pools[0].Scopes[1].Key() != "repo:acme/app" { + t.Errorf("pools %+v", c.Pools) } - if c.Label != "railway" || c.MaxRunners != 8 || c.Interval != 2*time.Minute || c.MaxAge != 6*time.Hour+10*time.Minute || c.Port != "8080" { + if c.Pools[0].Label != "railway" || c.Pools[0].MaxRunners != 8 || c.Interval != 2*time.Minute || c.MaxAge != 6*time.Hour+10*time.Minute || c.Port != "8080" { t.Errorf("defaults %+v", c) } } @@ -125,13 +125,13 @@ func TestTheControllerRefusesToManageTheProjectItRunsIn(t *testing.T) { // it is a safe Railway service name and one prefix can never start another ("rr-" vs "rr-pg-"). func TestTheServicePrefixDefaultsToRrAndIsValidated(t *testing.T) { c, err := Load(env(base())) - if err != nil || c.ServicePrefix != "rr-" { - t.Fatalf("default prefix %q err %v, want rr-", c.ServicePrefix, err) + if err != nil || c.Pools[0].Prefix != "rr-" { + t.Fatalf("default prefix %q err %v, want rr-", c.Pools[0].Prefix, err) } m := base() m["RUNNER_SERVICE_PREFIX"] = "rp-" - if c, err := Load(env(m)); err != nil || c.ServicePrefix != "rp-" { - t.Fatalf("prefix %q err %v, want rp-", c.ServicePrefix, err) + if c, err := Load(env(m)); err != nil || c.Pools[0].Prefix != "rp-" { + t.Fatalf("prefix %q err %v, want rp-", c.Pools[0].Prefix, err) } for _, bad := range []string{"rp", "RP-", "rr-pg-", "r-p-", "toolong-", "-", "r p-"} { m["RUNNER_SERVICE_PREFIX"] = bad @@ -145,13 +145,13 @@ func TestTheServicePrefixDefaultsToRrAndIsValidated(t *testing.T) { // placement (the workspace's preferred region), so an existing controller is unchanged. func TestTheRunnerRegionIsOptionalAndValidated(t *testing.T) { c, err := Load(env(base())) - if err != nil || c.Region != "" { - t.Fatalf("default region %q err %v, want empty", c.Region, err) + if err != nil || c.Pools[0].Region != "" { + t.Fatalf("default region %q err %v, want empty", c.Pools[0].Region, err) } m := base() m["RUNNER_REGION"] = " us-east4-eqdc4a " - if c, err := Load(env(m)); err != nil || c.Region != "us-east4-eqdc4a" { - t.Fatalf("region %q err %v, want us-east4-eqdc4a", c.Region, err) + if c, err := Load(env(m)); err != nil || c.Pools[0].Region != "us-east4-eqdc4a" { + t.Fatalf("region %q err %v, want us-east4-eqdc4a", c.Pools[0].Region, err) } if !strings.Contains(c.String(), "region=") { t.Errorf("String() %q should name the region so a startup log shows where runners go", c.String()) diff --git a/internal/config/pools_test.go b/internal/config/pools_test.go new file mode 100644 index 0000000..c76ba40 --- /dev/null +++ b/internal/config/pools_test.go @@ -0,0 +1,178 @@ +package config + +import ( + "reflect" + "strings" + "testing" + + "github.com/farzai/github-runner-railway/internal/reconcile" +) + +// pooled is base() with the pools in RUNNER_POOLS instead of the single-pool variables. +func pooled(pools string) map[string]string { + m := base() + for _, k := range []string{"RUNNER_IMAGE", "RUNNER_SCOPES"} { + delete(m, k) + } + m["RUNNER_POOLS"] = pools + return m +} + +const twoPools = `[ + {"label":"railway","image":"ghcr.io/acme/runner:1","prefix":"rr-","max_runners":4,"scopes":["org:acme","repo:acme/app"]}, + {"label":"railway-pg","image":"ghcr.io/acme/runner:pg-1","prefix":"rp-","region":"europe-west4","max_runners":2,"scopes":["repo:acme/app"]} +]` + +// The variables of a single-pool setup keep working: they are one pool, with today's defaults. +func TestTheSinglePoolVariablesLoadAsOnePool(t *testing.T) { + m := base() + m["RUNNER_REGION"] = "us-east4-eqdc4a" + c, err := Load(env(m)) + if err != nil { + t.Fatal(err) + } + want := []reconcile.Pool{{Label: "railway", Image: "ghcr.io/acme/github-runner-railway:1", Prefix: "rr-", Region: "us-east4-eqdc4a", MaxRunners: 8, + Scopes: []reconcile.Scope{{Kind: "org", Owner: "acme"}, {Kind: "repo", Owner: "acme", Repo: "app"}}}} + if !reflect.DeepEqual(c.Pools, want) { + t.Errorf("pools %+v, want %+v", c.Pools, want) + } + m["RUNNER_LABEL"], m["RUNNER_SERVICE_PREFIX"], m["MAX_RUNNERS"] = "railway-pg", "rp-", "3" + if c, err = Load(env(m)); err != nil || c.Pools[0].Label != "railway-pg" || c.Pools[0].Prefix != "rp-" || c.Pools[0].MaxRunners != 3 { + t.Errorf("err %v pools %+v", err, c.Pools) + } +} + +func TestRunnerPoolsLoadsEveryPoolAndARegionFallsBackToRunnerRegion(t *testing.T) { + m := pooled(twoPools) + m["RUNNER_REGION"] = "us-east4-eqdc4a" + c, err := Load(env(m)) + if err != nil { + t.Fatal(err) + } + if len(c.Pools) != 2 { + t.Fatalf("pools %+v", c.Pools) + } + a, b := c.Pools[0], c.Pools[1] + if a.Label != "railway" || a.Image != "ghcr.io/acme/runner:1" || a.Prefix != "rr-" || a.MaxRunners != 4 || len(a.Scopes) != 2 || a.Region != "us-east4-eqdc4a" { + t.Errorf("first pool %+v", a) + } + if b.Label != "railway-pg" || b.Prefix != "rp-" || b.MaxRunners != 2 || b.Region != "europe-west4" || len(b.Scopes) != 1 || b.Scopes[0].Key() != "repo:acme/app" { + t.Errorf("second pool %+v", b) + } + if got := c.Labels(); !reflect.DeepEqual(got, []string{"railway", "railway-pg"}) { + t.Errorf("labels %v", got) + } + if got := c.Prefixes(); !reflect.DeepEqual(got, []string{"rr-", "rp-"}) { + t.Errorf("prefixes %v", got) + } + for _, s := range []string{"label=railway-pg", "prefix=rp-", "image=ghcr.io/acme/runner:pg-1", "region=europe-west4", "max=2", "scopes=repo:acme/app"} { + if !strings.Contains(c.String(), s) { + t.Errorf("String() %q lacks %q", c.String(), s) + } + } +} + +func TestRunnerPoolsIsRefusedWhenMalformedNamingTheVariable(t *testing.T) { + ok := `{"label":"railway","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}` + for name, pools := range map[string]string{ + "not JSON": `[{`, + "not a list": ok, + "empty list": `[]`, + "trailing data": `[` + ok + `] []`, + "unknown field": `[{"label":"railway","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"],"maxrunners":2}]`, + "no label": `[{"image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "no image": `[{"label":"railway","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "no prefix": `[{"label":"railway","image":"i","max_runners":1,"scopes":["repo:acme/app"]}]`, + "no max": `[{"label":"railway","image":"i","prefix":"rr-","scopes":["repo:acme/app"]}]`, + "negative max": `[{"label":"railway","image":"i","prefix":"rr-","max_runners":-1,"scopes":["repo:acme/app"]}]`, + "no scopes": `[{"label":"railway","image":"i","prefix":"rr-","max_runners":1,"scopes":[]}]`, + "bad scope": `[{"label":"railway","image":"i","prefix":"rr-","max_runners":1,"scopes":["acme"]}]`, + "bad prefix": `[{"label":"railway","image":"i","prefix":"rr-pg-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "bad region": `[{"label":"railway","image":"i","prefix":"rr-","region":"US East","max_runners":1,"scopes":["repo:acme/app"]}]`, + "same prefix": `[` + ok + `,{"label":"railway-pg","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "same label": `[` + ok + `,{"label":"Railway","image":"i","prefix":"rp-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "reserved label": `[{"label":"linux","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "reserved label 2": `[{"label":"Self-Hosted","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "reserved label 3": `[{"label":"X64","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "blank label": `[{"label":" ","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]`, + "org with no group": `[{"label":"railway","image":"i","prefix":"rr-","max_runners":1,"scopes":["org:other"]}]`, + } { + m := pooled(pools) + if name == "org with no group" { + delete(m, "RUNNER_GROUP_ID") + } + _, err := Load(env(m)) + if err == nil { + t.Errorf("%s: accepted", name) + continue + } + if want := "RUNNER_POOLS"; name != "org with no group" && !strings.Contains(err.Error(), want) { + t.Errorf("%s: err %q does not name %s", name, err, want) + } + } +} + +// Two answers to the same question are refused rather than one silently winning. +func TestRunnerPoolsCannotBeMixedWithTheSinglePoolVariables(t *testing.T) { + for _, k := range []string{"RUNNER_IMAGE", "RUNNER_LABEL", "RUNNER_SERVICE_PREFIX", "MAX_RUNNERS", "RUNNER_SCOPES"} { + m := pooled(twoPools) + m[k] = "x" + if _, err := Load(env(m)); err == nil || !strings.Contains(err.Error(), k) || !strings.Contains(err.Error(), "RUNNER_POOLS") { + t.Errorf("%s with RUNNER_POOLS: err %v", k, err) + } + } + m := pooled(twoPools) + m["RUNNER_REGION"] = "us-east4-eqdc4a" // the default region of every pool, not a single-pool variable + if _, err := Load(env(m)); err != nil { + t.Errorf("RUNNER_REGION with RUNNER_POOLS: %v", err) + } + m["RUNNER_REGION"] = "US East" + if _, err := Load(env(m)); err == nil || !strings.Contains(err.Error(), "RUNNER_REGION") { + t.Errorf("a bad RUNNER_REGION with RUNNER_POOLS: err %v", err) + } +} + +func TestWithoutRunnerPoolsTheImageAndScopesAreStillRequired(t *testing.T) { + for _, k := range []string{"RUNNER_IMAGE", "RUNNER_SCOPES"} { + m := base() + delete(m, k) + if _, err := Load(env(m)); err == nil || !strings.Contains(err.Error(), k) { + t.Errorf("without %s: err %v", k, err) + } + } +} + +func TestCreatesPerCycleAndThePollPeriodHaveAFloor(t *testing.T) { + for k, v := range map[string]string{"MAX_CREATE_PER_CYCLE": "0", "POLL_SECONDS": "9"} { + m := base() + m[k] = v + if _, err := Load(env(m)); err == nil || !strings.Contains(err.Error(), k) { + t.Errorf("%s=%s: err %v", k, v, err) + } + } + m := base() + m["POLL_SECONDS"] = "10" + if _, err := Load(env(m)); err != nil { + t.Errorf("POLL_SECONDS=10: %v", err) + } +} + +// Each lower bound is exact: the bound itself is accepted, one below it refused. +func TestEachNumberIsAcceptedFromItsLowerBound(t *testing.T) { + m := base() + m["ALERT_FAILED_CYCLES"], m["STARTUP_GRACE_SECONDS"], m["MAX_RUNNERS"], m["MAX_CREATE_PER_CYCLE"] = "1", "0", "1", "1" + if c, err := Load(env(m)); err != nil || c.FailAlertAfter != 1 || c.StartupGrace != 0 || c.Pools[0].MaxRunners != 1 || c.MaxCreatePerCycle != 1 { + t.Errorf("err %v config %+v", err, c) + } + for _, v := range []string{"-1", "abc", "1.5"} { + m := base() + m["STARTUP_GRACE_SECONDS"] = v + if _, err := Load(env(m)); err == nil || !strings.Contains(err.Error(), "STARTUP_GRACE_SECONDS") { + t.Errorf("STARTUP_GRACE_SECONDS=%s: err %v", v, err) + } + } + one := `[{"label":"railway","image":"i","prefix":"rr-","max_runners":1,"scopes":["repo:acme/app"]}]` + if c, err := Load(env(pooled(one))); err != nil || c.Pools[0].MaxRunners != 1 { + t.Errorf("max_runners 1: err %v", err) + } +} diff --git a/internal/controller/controller.go b/internal/controller/controller.go index 10b092b..d9acc6f 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -26,23 +26,21 @@ import ( type GH interface { QueuedJobs(ctx context.Context, s reconcile.Scope) ([]ghapp.Job, error) Runners(ctx context.Context, s reconcile.Scope) ([]reconcile.Runner, error) - JITConfig(ctx context.Context, s reconcile.Scope, name string) (string, int64, error) + JITConfig(ctx context.Context, s reconcile.Scope, name, label string) (string, int64, error) DeleteRunner(ctx context.Context, s reconcile.Scope, id int64) error } // RW is the Railway side. type RW interface { List(ctx context.Context) ([]reconcile.Service, error) - Create(ctx context.Context, name string, vars map[string]string) (string, error) + Create(ctx context.Context, pool reconcile.Pool, name string, vars map[string]string) (string, error) Delete(ctx context.Context, id string) error } // Config is the controller's knobs. type Config struct { - Scopes []reconcile.Scope - Prefix string - MaxRunners int - MaxCreatePerCycle int + Pools []reconcile.Pool // each planned on its own; a scope in two pools is read once + MaxCreatePerCycle int // per pool StartupGrace time.Duration IdleTTL time.Duration MaxAge time.Duration @@ -58,6 +56,7 @@ type Config struct { // Controller applies plans. type Controller struct { cfg Config + scopes []reconcile.Scope // every pool's scopes, each once gh GH rw RW now func() time.Time @@ -115,10 +114,25 @@ func New(cfg Config, gh GH, rw RW) *Controller { if cfg.FailAlertAfter <= 0 { cfg.FailAlertAfter = 3 } - return &Controller{cfg: cfg, gh: gh, rw: rw, now: time.Now, wake: make(chan struct{}, 1), alerted: map[int64]string{}, + return &Controller{cfg: cfg, scopes: distinctScopes(cfg.Pools), gh: gh, rw: rw, now: time.Now, wake: make(chan struct{}, 1), alerted: map[int64]string{}, scopeFails: map[string]int{}, missing: map[string]int{}, goneAlerted: map[string]bool{}, lowWarn: map[string]time.Time{}} } +// distinctScopes is every pool's scopes, each once, in the order they first appear. +func distinctScopes(pools []reconcile.Pool) []reconcile.Scope { + var out []reconcile.Scope + seen := map[string]bool{} + for _, p := range pools { + for _, s := range p.Scopes { + if !seen[s.Key()] { + seen[s.Key()] = true + out = append(out, s) + } + } + } + return out +} + // OnEvent is the webhook handler. Only a queued job can need a new runner; the rest wait for // the next poll, since every wake-up costs a scan of GitHub. func (c *Controller) OnEvent(e webhook.Event) { @@ -223,65 +237,124 @@ func (c *Controller) Cycle(ctx context.Context) (err error) { }() rd := c.readScopes(ctx) gap = unlistedGap{jobs: c.warnUnlisted(rd.jobs), readFailed: rd.unlistedReadFailed} - errs, queued, runners, jobsOf, readable := rd.errs, rd.queued, rd.runners, rd.jobs, rd.readable + errs := rd.errs all, err := c.rw.List(ctx) if err != nil { errs = append(errs, err) c.record(now, errs, 0, 0, gap) return errors.Join(errs...) } + services := c.lookable(all, rd.readable) + var sum poolOutcome + for _, p := range c.cfg.Pools { + o := c.cyclePool(ctx, now, p, rd, services) + errs = append(errs, o.errs...) + sum.created, sum.reaped, sum.services, sum.queued = sum.created+o.created, sum.reaped+o.reaped, sum.services+o.services, sum.queued+o.queued + } + created, reaped = sum.created, sum.reaped + c.forgetAlerted(rd.jobs) + c.warnLowLimits() + c.record(now, errs, sum.services, sum.queued, gap) + return errors.Join(errs...) +} + +// lookable drops the services of a configured scope that could not be read this cycle: a guess about +// them could kill a busy runner. A service of a scope no pool has any more stays, to be reaped in time. +func (c *Controller) lookable(all []reconcile.Service, readable []reconcile.Scope) []reconcile.Service { ok := map[string]bool{} for _, s := range readable { ok[s.Hash()] = true } - var services []reconcile.Service + known := map[string]bool{} + for _, s := range c.scopes { + known[s.Hash()] = true + } + var out []reconcile.Service for _, sv := range all { - known := false - for _, s := range c.cfg.Scopes { - known = known || s.Hash() == sv.ScopeHash + if !known[sv.ScopeHash] || ok[sv.ScopeHash] { + out = append(out, sv) } - if !known || ok[sv.ScopeHash] { // a service of an unreadable scope is not looked at - services = append(services, sv) + } + return out +} + +// poolOutcome is what one pool's part of a cycle did. +type poolOutcome struct { + created, reaped int + services int // the pool's services once its plan is applied + queued int // the pool's queued jobs in its readable scopes + errs []error +} + +// cyclePool plans and applies one pool: only its own services (by prefix), only the jobs that ask +// for its label, in the scopes of its that could be read. Another pool's services are never its +// supply, never count toward its maximum and are never reaped by it. +func (c *Controller) cyclePool(ctx context.Context, now time.Time, p reconcile.Pool, rd scopeReads, services []reconcile.Service) poolOutcome { + var o poolOutcome + var mine []reconcile.Service + for _, sv := range services { + if strings.HasPrefix(sv.Name, p.Prefix) { + mine = append(mine, sv) } } + readable, jobs, queued := poolJobs(p, rd) + for _, n := range queued { + o.queued += n + } plan := reconcile.Make(reconcile.Input{ - Now: now, Queued: queued, Services: services, Runners: runners, - Params: reconcile.Params{MaxRunners: c.cfg.MaxRunners, MaxCreatePerCycle: c.cfg.MaxCreatePerCycle, StartupGrace: c.cfg.StartupGrace, + Now: now, Queued: queued, Services: mine, Runners: rd.runners, + Params: reconcile.Params{MaxRunners: p.MaxRunners, MaxCreatePerCycle: c.cfg.MaxCreatePerCycle, StartupGrace: c.cfg.StartupGrace, IdleTTL: c.cfg.IdleTTL, MaxAge: c.cfg.MaxAge, Scopes: readable}, }) for _, r := range plan.Reap { deleted, err := c.reap(ctx, r) if err != nil { - errs = append(errs, err) + o.errs = append(o.errs, err) continue } if deleted { - reaped++ + o.reaped++ } } createdBy := map[string]int{} for _, cr := range plan.Create { - if err := c.create(ctx, scopeByKey(readable, cr.Scope)); err != nil { - errs = append(errs, err) + if err := c.create(ctx, p, scopeByKey(readable, cr.Scope)); err != nil { + o.errs = append(o.errs, err) continue } createdBy[cr.Scope]++ - created++ + o.created++ } - c.alertLate(now, jobsOf, services, runners, createdBy) - c.warnLowLimits() - total := 0 - for _, n := range queued { - total += n + c.alertLate(now, p, jobs, mine, rd.runners, createdBy) + o.services = len(mine) + len(plan.Create) - len(plan.Reap) + return o +} + +// poolJobs are the pool's scopes that could be read this cycle, and in each the jobs that ask for +// the pool's label and how many there are. +func poolJobs(p reconcile.Pool, rd scopeReads) ([]reconcile.Scope, map[string][]ghapp.Job, map[string]int) { + var readable []reconcile.Scope + jobs, queued := map[string][]ghapp.Job{}, map[string]int{} + for _, s := range p.Scopes { + all, ok := rd.jobs[s.Key()] + if !ok { + continue + } + readable = append(readable, s) + var js []ghapp.Job + for _, j := range all { + if j.Label == p.Label { + js = append(js, j) + } + } + jobs[s.Key()], queued[s.Key()] = js, len(js) } - c.record(now, errs, len(services)+len(plan.Create)-len(plan.Reap), total, gap) - return errors.Join(errs...) + return readable, jobs, queued } // scopeReads is what reading every scope in a cycle found. type scopeReads struct { readable []reconcile.Scope - queued map[string]int runners map[string][]reconcile.Runner jobs map[string][]ghapp.Job errs []error // the errors that fail the cycle @@ -319,8 +392,8 @@ func (c *Controller) warnUnlistedRead(e *ghapp.UnlistedReadError) int { // readScopes reads every scope, records how each went, and raises or clears the missing-scope alerts. func (c *Controller) readScopes(ctx context.Context) scopeReads { - rd := scopeReads{queued: map[string]int{}, runners: map[string][]reconcile.Runner{}, jobs: map[string][]ghapp.Job{}} - for _, s := range c.cfg.Scopes { + rd := scopeReads{runners: map[string][]reconcile.Runner{}, jobs: map[string][]ghapp.Job{}} + for _, s := range c.scopes { jobs, rs, err := c.readScope(ctx, s) var ue *ghapp.UnlistedReadError if errors.As(err, &ue) { @@ -334,7 +407,7 @@ func (c *Controller) readScopes(ctx context.Context) scopeReads { continue } rd.readable = append(rd.readable, s) - rd.queued[s.Key()], rd.runners[s.Key()], rd.jobs[s.Key()] = len(jobs), rs, jobs + rd.runners[s.Key()], rd.jobs[s.Key()] = rs, jobs } if fail := c.noneReadable(); fail != nil { rd.errs = append(rd.errs, fail) @@ -350,7 +423,7 @@ func (c *Controller) readScopes(ctx context.Context) scopeReads { // another reason, those errors already fail the cycle and the 404 scopes are not blamed for it. func (c *Controller) noneReadable() error { var gone []string - for _, s := range c.cfg.Scopes { + for _, s := range c.scopes { if c.missing[s.Key()] == 0 { return nil } @@ -371,7 +444,7 @@ func (c *Controller) alertMissing(readable []reconcile.Scope) { c.pending = append(c.pending, "controller: scope "+s.Key()+" is readable again") } } - for _, s := range c.cfg.Scopes { + for _, s := range c.scopes { if n := c.missing[s.Key()]; n >= c.cfg.FailAlertAfter && !c.goneAlerted[s.Key()] { c.goneAlerted[s.Key()] = true c.pending = append(c.pending, fmt.Sprintf("controller: scope %s not found on GitHub for %d cycles in a row; "+ @@ -454,7 +527,7 @@ func (c *Controller) record(now time.Time, errs []error, services, queued int, g // unreadableScopes counts the scopes the last cycle could not read (a 404 included), and names the // ones that failed for FailAlertAfter cycles or more for another reason, for the operator's alert. func (c *Controller) unreadableScopes() (unreadable int, stuck []string) { - for _, s := range c.cfg.Scopes { + for _, s := range c.scopes { n := c.scopeFails[s.Key()] if n > 0 || c.missing[s.Key()] > 0 { unreadable++ @@ -477,7 +550,7 @@ func truncate(s string, n int) string { // and the service was kept. func (c *Controller) reap(ctx context.Context, r reconcile.Reap) (deleted bool, err error) { if r.RunnerID != 0 { - sc := scopeByKey(c.cfg.Scopes, r.Scope) + sc := scopeByKey(c.scopes, r.Scope) if err := c.gh.DeleteRunner(ctx, sc, r.RunnerID); err != nil { if errors.Is(err, ghapp.ErrBusy) && !r.Force { c.cfg.Log.Info("runner turned busy; kept", "service", r.Service.Name) @@ -495,30 +568,30 @@ func (c *Controller) reap(ctx context.Context, r reconcile.Reap) (deleted bool, return true, nil } -func (c *Controller) create(ctx context.Context, s reconcile.Scope) error { +func (c *Controller) create(ctx context.Context, p reconcile.Pool, s reconcile.Scope) error { var b [3]byte _, _ = rand.Read(b[:]) - name := c.cfg.Prefix + s.Hash() + "-" + hex.EncodeToString(b[:]) - jit, runnerID, err := c.gh.JITConfig(ctx, s, name) + name := p.Prefix + s.Hash() + "-" + hex.EncodeToString(b[:]) + jit, runnerID, err := c.gh.JITConfig(ctx, s, name, p.Label) if err != nil { return fmt.Errorf("jit config %s: %w", s.Key(), err) } - if _, err := c.rw.Create(ctx, name, map[string]string{"ACTIONS_RUNNER_INPUT_JITCONFIG": jit}); err != nil { + if _, err := c.rw.Create(ctx, p, name, map[string]string{"ACTIONS_RUNNER_INPUT_JITCONFIG": jit}); err != nil { if derr := c.gh.DeleteRunner(ctx, s, runnerID); derr != nil { c.cfg.Log.Error("could not remove the runner of a failed service", "runner", name) } return fmt.Errorf("create service %s: %w", name, err) } - c.cfg.Log.Info("created", "service", name, "scope", s.Key()) + c.cfg.Log.Info("created", "service", name, "scope", s.Key(), "pool", p.Label) return nil } -// alertLate raises one alert per job that has waited past AlertAfter with no runner coming -// for its scope (a service created this cycle or still starting counts as coming). -func (c *Controller) alertLate(now time.Time, jobs map[string][]ghapp.Job, services []reconcile.Service, runners map[string][]reconcile.Runner, created map[string]int) { - live := map[int64]bool{} +// alertLate raises one alert per job of the pool that has waited past AlertAfter with no runner +// of the pool coming for its scope (a service of the pool created this cycle or still starting +// counts as coming). +func (c *Controller) alertLate(now time.Time, p reconcile.Pool, jobs map[string][]ghapp.Job, services []reconcile.Service, runners map[string][]reconcile.Runner, created map[string]int) { for key, js := range jobs { - sc := scopeByKey(c.cfg.Scopes, key) + sc := scopeByKey(c.scopes, key) coming := created[key] for _, sv := range services { if sv.ScopeHash != sc.Hash() || sv.Exited { @@ -533,12 +606,22 @@ func (c *Controller) alertLate(now time.Time, jobs map[string][]ghapp.Job, servi } } for _, j := range js { - live[j.ID] = true if _, done := c.alerted[j.ID]; coming > 0 || done || j.CreatedAt.IsZero() || now.Sub(j.CreatedAt) < c.cfg.AlertAfter { continue } c.alerted[j.ID] = key - c.pending = append(c.pending, fmt.Sprintf("job %d in %s has been queued %s with no runner coming", j.ID, j.Repo, now.Sub(j.CreatedAt).Round(time.Second))) + c.pending = append(c.pending, fmt.Sprintf("job %d in %s has been queued %s with no %s runner coming", j.ID, j.Repo, now.Sub(j.CreatedAt).Round(time.Second), p.Label)) + } + } +} + +// forgetAlerted drops the mark of every alerted job no longer queued in a scope read this cycle, +// once over every pool's jobs, so one pool never clears a mark of another's in a shared scope. +func (c *Controller) forgetAlerted(jobs map[string][]ghapp.Job) { + live := map[int64]bool{} + for _, js := range jobs { + for _, j := range js { + live[j.ID] = true } } for id, key := range c.alerted { diff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.go index cf9fc42..84793c5 100644 --- a/internal/controller/controller_test.go +++ b/internal/controller/controller_test.go @@ -2,6 +2,9 @@ package controller import ( "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" "errors" "strings" "sync" @@ -17,8 +20,16 @@ var ( org = reconcile.Scope{Kind: "org", Owner: "acme"} repo = reconcile.Scope{Kind: "repo", Owner: "acme", Repo: "app"} now = time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC) + + errTest = errors.New("github 502") ) +func webhookSig(secret, body string) string { + m := hmac.New(sha256.New, []byte(secret)) + m.Write([]byte(body)) + return "sha256=" + hex.EncodeToString(m.Sum(nil)) +} + type fakeGH struct { mu sync.Mutex jobs map[string][]ghapp.Job @@ -28,24 +39,51 @@ type fakeGH struct { busy map[int64]bool deleted []int64 jit []string + labels map[string]string // runner name -> the label its JIT config registered nextID int64 hold func() // when set, QueuedJobs calls it first: a test holds a cycle open with it + + reads, runnerReads map[string]int // scope key -> QueuedJobs / Runners calls } +// QueuedJobs answers the scope's jobs; a job a test wrote with no label is the default pool's +// (railway), the label every single-pool test serves. func (f *fakeGH) QueuedJobs(_ context.Context, s reconcile.Scope) ([]ghapp.Job, error) { if f.hold != nil { f.hold() } - return f.jobs[s.Key()], f.jobsErr[s.Key()] + f.mu.Lock() + defer f.mu.Unlock() + if f.reads == nil { + f.reads = map[string]int{} + } + f.reads[s.Key()]++ + jobs := append([]ghapp.Job(nil), f.jobs[s.Key()]...) + for i := range jobs { + if jobs[i].Label == "" { + jobs[i].Label = "railway" + } + } + return jobs, f.jobsErr[s.Key()] } func (f *fakeGH) Runners(_ context.Context, s reconcile.Scope) ([]reconcile.Runner, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.runnerReads == nil { + f.runnerReads = map[string]int{} + } + f.runnerReads[s.Key()]++ return f.runners[s.Key()], f.runsErr[s.Key()] } -func (f *fakeGH) JITConfig(_ context.Context, s reconcile.Scope, name string) (string, int64, error) { +func (f *fakeGH) JITConfig(_ context.Context, s reconcile.Scope, name, label string) (string, int64, error) { f.mu.Lock() defer f.mu.Unlock() f.nextID++ f.jit = append(f.jit, s.Key()+" "+name) + if f.labels == nil { + f.labels = map[string]string{} + } + f.labels[name] = label return "JIT-" + name, 1000 + f.nextID, nil } func (f *fakeGH) DeleteRunner(_ context.Context, _ reconcile.Scope, id int64) error { @@ -60,31 +98,38 @@ type fakeRW struct { services []reconcile.Service created []string vars map[string]map[string]string + images map[string]string // service name -> image + regions map[string]string // service name -> region deleted []string createErr error + deleteErr error } func (f *fakeRW) List(context.Context) ([]reconcile.Service, error) { return f.services, nil } -func (f *fakeRW) Create(_ context.Context, name string, vars map[string]string) (string, error) { +func (f *fakeRW) Create(_ context.Context, p reconcile.Pool, name string, vars map[string]string) (string, error) { if f.createErr != nil { return "", f.createErr } f.created = append(f.created, name) if f.vars == nil { - f.vars = map[string]map[string]string{} + f.vars, f.images, f.regions = map[string]map[string]string{}, map[string]string{}, map[string]string{} } - f.vars[name] = vars + f.vars[name], f.images[name], f.regions[name] = vars, p.Image, p.Region return "id-" + name, nil } func (f *fakeRW) Delete(_ context.Context, id string) error { + if f.deleteErr != nil { + return f.deleteErr + } f.deleted = append(f.deleted, id) return nil } func newC(gh *fakeGH, rw *fakeRW) *Controller { c := New(Config{ - Scopes: []reconcile.Scope{org, repo}, Prefix: "rr-", MaxRunners: 10, MaxCreatePerCycle: 5, - StartupGrace: 3 * time.Minute, IdleTTL: 2 * time.Minute, MaxAge: 6 * time.Hour, AlertAfter: 5 * time.Minute, + Pools: []reconcile.Pool{{Label: "railway", Image: "img", Prefix: "rr-", MaxRunners: 10, Scopes: []reconcile.Scope{org, repo}}}, + MaxCreatePerCycle: 5, + StartupGrace: 3 * time.Minute, IdleTTL: 2 * time.Minute, MaxAge: 6 * time.Hour, AlertAfter: 5 * time.Minute, }, gh, rw) c.now = func() time.Time { return now } return c diff --git a/internal/controller/health_test.go b/internal/controller/health_test.go index d0b7035..595bea4 100644 --- a/internal/controller/health_test.go +++ b/internal/controller/health_test.go @@ -18,8 +18,9 @@ import ( func alerting(gh *fakeGH, rw *fakeRW) (*Controller, *[]string) { var alerts []string c := New(Config{ - Scopes: []reconcile.Scope{org, repo}, Prefix: "rr-", MaxRunners: 10, MaxCreatePerCycle: 5, - StartupGrace: 3 * time.Minute, IdleTTL: 2 * time.Minute, MaxAge: 6 * time.Hour, AlertAfter: 5 * time.Minute, + Pools: []reconcile.Pool{{Label: "railway", Image: "img", Prefix: "rr-", MaxRunners: 10, Scopes: []reconcile.Scope{org, repo}}}, + MaxCreatePerCycle: 5, + StartupGrace: 3 * time.Minute, IdleTTL: 2 * time.Minute, MaxAge: 6 * time.Hour, AlertAfter: 5 * time.Minute, Interval: time.Minute, FailAlertAfter: 3, Alert: func(m string) { alerts = append(alerts, m) }, }, gh, rw) c.now = func() time.Time { return now } diff --git a/internal/controller/notfound_test.go b/internal/controller/notfound_test.go index 04b204b..194d3db 100644 --- a/internal/controller/notfound_test.go +++ b/internal/controller/notfound_test.go @@ -185,11 +185,11 @@ func TestAMissingScopeIsAlertedOnceAndClearedWhenItReadsAgain(t *testing.T) { func TestASingleScopePoolThatIsNotFoundFailsAndAnEmptyPoolDoesNot(t *testing.T) { gh := &fakeGH{jobsErr: map[string]error{repo.Key(): notFound("acme/app")}} c, _ := alerting(gh, &fakeRW{}) - c.cfg.Scopes = []reconcile.Scope{repo} + c.scopes = []reconcile.Scope{repo} if err := c.Cycle(context.Background()); err == nil || !strings.Contains(err.Error(), repo.Key()) { t.Fatalf("cycle: %v, want a failure naming %s", err, repo.Key()) } - c.cfg.Scopes = nil + c.scopes = nil if err := c.Cycle(context.Background()); err != nil { t.Fatalf("cycle with no scopes: %v, want success", err) } diff --git a/internal/controller/pools_test.go b/internal/controller/pools_test.go new file mode 100644 index 0000000..37d95bb --- /dev/null +++ b/internal/controller/pools_test.go @@ -0,0 +1,256 @@ +package controller + +import ( + "bytes" + "context" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/farzai/github-runner-railway/internal/ghapp" + "github.com/farzai/github-runner-railway/internal/reconcile" + "github.com/farzai/github-runner-railway/internal/webhook" +) + +// Two pools on one controller: the base image under rr- and the Postgres image under rp-. +// "other" is a repository only the pg pool serves. +var other = reconcile.Scope{Kind: "repo", Owner: "acme", Repo: "db"} + +func basePool() reconcile.Pool { + return reconcile.Pool{Label: "railway", Image: "ghcr.io/acme/runner:1", Prefix: "rr-", MaxRunners: 4, Scopes: []reconcile.Scope{repo}} +} + +func pgPool() reconcile.Pool { + return reconcile.Pool{Label: "railway-pg", Image: "ghcr.io/acme/runner:pg-1", Prefix: "rp-", Region: "europe-west4", MaxRunners: 4, Scopes: []reconcile.Scope{repo, other}} +} + +func newPooled(gh *fakeGH, rw *fakeRW, pools ...reconcile.Pool) *Controller { + c := New(Config{ + Pools: pools, MaxCreatePerCycle: 5, + StartupGrace: 3 * time.Minute, IdleTTL: 2 * time.Minute, MaxAge: 6 * time.Hour, AlertAfter: 5 * time.Minute, + }, gh, rw) + c.now = func() time.Time { return now } + return c +} + +func job(id int64, label string, at time.Time) ghapp.Job { + return ghapp.Job{ID: id, Repo: "acme/app", Label: label, CreatedAt: at} +} + +func TestOneCycleServesEveryPoolFromItsOwnImageAndPrefixWithOneScanPerScope(t *testing.T) { + gh := &fakeGH{jobs: map[string][]ghapp.Job{repo.Key(): {job(1, "railway", now), job(2, "railway-pg", now)}}} + rw := &fakeRW{} + if err := newPooled(gh, rw, basePool(), pgPool()).Cycle(context.Background()); err != nil { + t.Fatal(err) + } + if len(rw.created) != 2 { + t.Fatalf("created %v, want one service per pool", rw.created) + } + byPrefix := map[string]string{} + for _, name := range rw.created { + byPrefix[name[:3]] = rw.images[name] + if !strings.HasPrefix(name[3:], repo.Hash()+"-") { + t.Errorf("name %q does not carry the scope hash after its prefix", name) + } + } + if byPrefix["rr-"] != "ghcr.io/acme/runner:1" || byPrefix["rp-"] != "ghcr.io/acme/runner:pg-1" { + t.Errorf("images by prefix %v: each pool's service must come from its own image", byPrefix) + } + for _, name := range rw.created { + want := map[string]string{"rr-": "railway", "rp-": "railway-pg"}[name[:3]] + if gh.labels[name] != want { + t.Errorf("runner %s registered with label %q, want %q", name, gh.labels[name], want) + } + wantRegion := map[string]string{"rr-": "", "rp-": "europe-west4"}[name[:3]] + if rw.regions[name] != wantRegion { + t.Errorf("service %s in region %q, want %q", name, rw.regions[name], wantRegion) + } + } + // repo is in both pools and read once; other is read once too + if gh.reads[repo.Key()] != 1 || gh.reads[other.Key()] != 1 || gh.runnerReads[repo.Key()] != 1 || gh.runnerReads[other.Key()] != 1 { + t.Errorf("job reads %v, runner reads %v: want one of each per scope per cycle", gh.reads, gh.runnerReads) + } +} + +func TestAPoolAtItsMaximumDoesNotBlockTheOtherPool(t *testing.T) { + base := basePool() + base.MaxRunners = 1 + busy := reconcile.Service{ID: "s1", Name: "rr-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-10 * time.Minute)} + gh := &fakeGH{ + jobs: map[string][]ghapp.Job{repo.Key(): {job(1, "railway", now), job(2, "railway-pg", now)}}, + runners: map[string][]reconcile.Runner{repo.Key(): {{ID: 9, Name: busy.Name, Busy: true}}}, + } + rw := &fakeRW{services: []reconcile.Service{busy}} + if err := newPooled(gh, rw, base, pgPool()).Cycle(context.Background()); err != nil { + t.Fatal(err) + } + if len(rw.created) != 1 || !strings.HasPrefix(rw.created[0], "rp-") { + t.Fatalf("created %v: the full base pool makes nothing, the pg pool still gets its runner", rw.created) + } +} + +func TestAPoolNeverReapsOrCountsAnotherPoolsServices(t *testing.T) { + // a busy pg runner in a scope only the pg pool serves + pgBusy := reconcile.Service{ID: "p1", Name: "rp-" + other.Hash() + "-aaaaaa", ScopeHash: other.Hash(), CreatedAt: now.Add(-10 * time.Minute)} + base := basePool() + base.MaxRunners = 1 + gh := &fakeGH{ + jobs: map[string][]ghapp.Job{repo.Key(): {job(1, "railway", now)}}, + runners: map[string][]reconcile.Runner{other.Key(): {{ID: 9, Name: pgBusy.Name, Busy: true}}}, + } + rw := &fakeRW{services: []reconcile.Service{pgBusy}} + if err := newPooled(gh, rw, base, pgPool()).Cycle(context.Background()); err != nil { + t.Fatal(err) + } + if len(rw.deleted) != 0 { + t.Errorf("deleted %v: the base pool must not reap a pg service", rw.deleted) + } + if len(rw.created) != 1 || !strings.HasPrefix(rw.created[0], "rr-") { + t.Errorf("created %v: the pg service must not count toward the base pool's maximum", rw.created) + } +} + +func TestAnIdleRunnerOfOnePoolIsNoSupplyForTheOtherPool(t *testing.T) { + idle := reconcile.Service{ID: "r1", Name: "rr-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-time.Minute)} + gh := &fakeGH{ + jobs: map[string][]ghapp.Job{repo.Key(): {job(2, "railway-pg", now)}}, + runners: map[string][]reconcile.Runner{repo.Key(): {{ID: 9, Name: idle.Name}}}, + } + rw := &fakeRW{services: []reconcile.Service{idle}} + if err := newPooled(gh, rw, basePool(), pgPool()).Cycle(context.Background()); err != nil { + t.Fatal(err) + } + if len(rw.created) != 1 || !strings.HasPrefix(rw.created[0], "rp-") { + t.Errorf("created %v: a base runner cannot take a pg job", rw.created) + } +} + +func TestAnExitedServiceIsReapedOncePerCycle(t *testing.T) { + gone := reconcile.Service{ID: "p1", Name: "rp-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-10 * time.Minute), Exited: true} + rw := &fakeRW{services: []reconcile.Service{gone}} + if err := newPooled(&fakeGH{}, rw, basePool(), pgPool()).Cycle(context.Background()); err != nil { + t.Fatal(err) + } + if len(rw.deleted) != 1 || rw.deleted[0] != "p1" { + t.Errorf("deleted %v, want p1 once", rw.deleted) + } +} + +func TestAnUnreadableSharedScopeCountsOnceAndNoPoolTouchesItsServices(t *testing.T) { + rr := reconcile.Service{ID: "r1", Name: "rr-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-time.Hour), Exited: true} + rp := reconcile.Service{ID: "p1", Name: "rp-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-time.Hour), Exited: true} + gh := &fakeGH{jobsErr: map[string]error{repo.Key(): errTest}} + rw := &fakeRW{services: []reconcile.Service{rr, rp}} + c := newPooled(gh, rw, basePool(), pgPool()) + _ = c.Cycle(context.Background()) + if len(rw.deleted) != 0 { + t.Errorf("deleted %v: services of an unreadable scope are left alone", rw.deleted) + } + if got := c.Status().UnreadableScopes; got != 1 { + t.Errorf("unreadable scopes %d, want 1: a scope in two pools is one scope", got) + } +} + +func TestALateJobIsAlertedOnceWhenTwoPoolsShareItsScope(t *testing.T) { + gh := &fakeGH{jobs: map[string][]ghapp.Job{repo.Key(): {job(1, "railway", now.Add(-10*time.Minute))}}} + rw := &fakeRW{createErr: errTest} // no runner can come + var alerts []string + c := newPooled(gh, rw, basePool(), pgPool()) + c.cfg.Alert = func(m string) { alerts = append(alerts, m) } + for i := 0; i < 2; i++ { + _ = c.Cycle(context.Background()) + } + late := 0 + for _, a := range alerts { + if strings.HasPrefix(a, "job 1 ") { + late++ + if !strings.Contains(a, "railway") { + t.Errorf("alert %q should name the pool label", a) + } + } + } + if late != 1 { + t.Errorf("alerts %v: want the late job alerted once", alerts) + } +} + +func TestAnotherPoolsNewRunnerDoesNotHideALateJob(t *testing.T) { + base := basePool() + base.MaxRunners = 1 + busy := reconcile.Service{ID: "s1", Name: "rr-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-10 * time.Minute)} + gh := &fakeGH{ + jobs: map[string][]ghapp.Job{repo.Key(): {job(1, "railway", now.Add(-10*time.Minute)), job(2, "railway-pg", now)}}, + runners: map[string][]reconcile.Runner{repo.Key(): {{ID: 9, Name: busy.Name, Busy: true}}}, + } + rw := &fakeRW{services: []reconcile.Service{busy}} + var alerts []string + c := newPooled(gh, rw, base, pgPool()) + c.cfg.Alert = func(m string) { alerts = append(alerts, m) } + _ = c.Cycle(context.Background()) + if len(rw.created) != 1 || len(alerts) != 1 || !strings.HasPrefix(alerts[0], "job 1 ") { + t.Errorf("created %v alerts %v: the pg runner made this cycle is no runner for the base job", rw.created, alerts) + } +} + +func TestQueuedOnHealthIsTheSumAcrossPools(t *testing.T) { + gh := &fakeGH{jobs: map[string][]ghapp.Job{ + repo.Key(): {job(1, "railway", now), job(2, "railway-pg", now)}, + other.Key(): {{ID: 3, Repo: "acme/db", Label: "railway-pg", CreatedAt: now}}, + }} + c := newPooled(gh, &fakeRW{}, basePool(), pgPool()) + _ = c.Cycle(context.Background()) + if st := c.Status(); st.Queued != 3 || st.Services != 3 { + t.Errorf("status %+v, want 3 queued and 3 services", st) + } +} + +func TestAQueuedWebhookForEitherPoolsLabelStartsACycle(t *testing.T) { + for _, label := range []string{"railway", "Railway-PG"} { + c := newPooled(&fakeGH{}, &fakeRW{}, basePool(), pgPool()) + h := webhook.Handler("s", []string{"railway", "railway-pg"}, c.OnEvent) + body := `{"action":"queued","workflow_job":{"id":7,"labels":["self-hosted","` + label + `"]},"repository":{"full_name":"acme/app","owner":{"login":"acme"}}}` + r := httptest.NewRequest(http.MethodPost, "/webhook", strings.NewReader(body)) + r.Header.Set("X-GitHub-Event", "workflow_job") + r.Header.Set("X-Hub-Signature-256", webhookSig("s", body)) + h.ServeHTTP(httptest.NewRecorder(), r) + select { + case <-c.wake: + default: + t.Errorf("label %s: a queued job did not wake the loop", label) + } + } +} + +func TestAFailedReapFailsTheCycleAndIsNotCounted(t *testing.T) { + gone := reconcile.Service{ID: "p1", Name: "rp-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-10 * time.Minute), Exited: true} + rw := &fakeRW{services: []reconcile.Service{gone}, deleteErr: errTest} + c := newPooled(&fakeGH{}, rw, basePool(), pgPool()) + if err := c.Cycle(context.Background()); err == nil { + t.Fatal("a reap Railway refused must fail the cycle") + } + if st := c.Status(); st.Services != 0 || st.LastError == "" { + t.Errorf("status %+v", st) + } +} + +func TestTheCycleLineCountsWhatEveryPoolCreatedAndReaped(t *testing.T) { + gh := &fakeGH{jobs: map[string][]ghapp.Job{repo.Key(): {job(1, "railway", now), job(2, "railway-pg", now)}}} + rw := &fakeRW{services: []reconcile.Service{ + {ID: "r1", Name: "rr-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-time.Hour), Exited: true}, + {ID: "p1", Name: "rp-" + repo.Hash() + "-aaaaaa", ScopeHash: repo.Hash(), CreatedAt: now.Add(-time.Hour), Exited: true}, + }} + var buf bytes.Buffer + c := newPooled(gh, rw, basePool(), pgPool()) + c.cfg.Log = slog.New(slog.NewTextHandler(&buf, nil)) + if err := c.Cycle(context.Background()); err != nil { + t.Fatal(err) + } + for _, want := range []string{"created=2", "reaped=2", "pool=railway-pg"} { + if !strings.Contains(buf.String(), want) { + t.Errorf("log %q lacks %s", buf.String(), want) + } + } +} diff --git a/internal/controller/wake_test.go b/internal/controller/wake_test.go index 173eeb4..333e6bc 100644 --- a/internal/controller/wake_test.go +++ b/internal/controller/wake_test.go @@ -49,7 +49,7 @@ func (g *countingGH) QueuedJobs(ctx context.Context, s reconcile.Scope) ([]ghapp func TestABurstOfNudgesInsideTheDebounceIsOneCycle(t *testing.T) { // a job is queued, so the nudged cycle finds work and no retry follows gh := &countingGH{fakeGH: fakeGH{jobs: map[string][]ghapp.Job{repo.Key(): {{ID: 1, Repo: "acme/app", CreatedAt: now}}}}} - c := New(Config{Scopes: []reconcile.Scope{repo}, Prefix: "rr-", MaxRunners: 1, MaxCreatePerCycle: 1, + c := New(Config{Pools: []reconcile.Pool{{Label: "railway", Image: "img", Prefix: "rr-", MaxRunners: 1, Scopes: []reconcile.Scope{repo}}}, MaxCreatePerCycle: 1, StartupGrace: time.Minute, IdleTTL: time.Minute, MaxAge: time.Hour, Interval: time.Hour, MinGap: time.Millisecond, Debounce: 150 * time.Millisecond}, gh, &fakeRW{}) ctx, cancel := context.WithCancel(context.Background()) @@ -77,7 +77,7 @@ type laggingGH struct { func (g *laggingGH) QueuedJobs(_ context.Context, s reconcile.Scope) ([]ghapp.Job, error) { if g.reads.Add(1) >= g.listFrom { - return []ghapp.Job{{ID: 1, Repo: "acme/app", CreatedAt: now}}, nil + return []ghapp.Job{{ID: 1, Repo: "acme/app", Label: "railway", CreatedAt: now}}, nil } return nil, nil } @@ -87,7 +87,7 @@ func (g *laggingGH) QueuedJobs(_ context.Context, s reconcile.Scope) ([]ghapp.Jo func TestAWebhookCycleThatFindsNothingChecksOnceMoreAfterTheGap(t *testing.T) { gh := &laggingGH{listFrom: 3} // read 1: start-up cycle, read 2: the webhook cycle, read 3: the retry rw := &fakeRW{} - c := New(Config{Scopes: []reconcile.Scope{repo}, Prefix: "rr-", MaxRunners: 1, MaxCreatePerCycle: 1, + c := New(Config{Pools: []reconcile.Pool{{Label: "railway", Image: "img", Prefix: "rr-", MaxRunners: 1, Scopes: []reconcile.Scope{repo}}}, MaxCreatePerCycle: 1, StartupGrace: time.Minute, IdleTTL: time.Minute, MaxAge: time.Hour, Interval: time.Hour, MinGap: 200 * time.Millisecond, Debounce: 20 * time.Millisecond}, gh, rw) ctx, cancel := context.WithCancel(context.Background()) diff --git a/internal/ghapp/ghapp.go b/internal/ghapp/ghapp.go index 78de1d8..ccae8ba 100644 --- a/internal/ghapp/ghapp.go +++ b/internal/ghapp/ghapp.go @@ -38,12 +38,12 @@ var ErrBusy = errors.New("ghapp: runner is busy") // (deleted, renamed, or the App no longer holds it). var ErrNotFound = errors.New("ghapp: not found") -// Config is the App and the label this fleet serves. +// Config is the App and the labels this fleet serves, one per pool. type Config struct { AppID string PrivateKey string // PEM; a Railway variable may hold it with the newlines escaped BaseURL string // default https://api.github.com - Label string + Labels []string RunnerGroupID int // the org runner group the runners join (repo scope always uses the default group, 1) HTTP *http.Client } @@ -82,6 +82,9 @@ func New(cfg Config) (*Client, error) { if cfg.AppID == "" { return nil, errors.New("ghapp: no app id") } + if len(cfg.Labels) == 0 { + return nil, errors.New("ghapp: no runner label") + } pemText := strings.ReplaceAll(strings.TrimSpace(cfg.PrivateKey), `\n`, "\n") block, _ := pem.Decode([]byte(pemText)) if block == nil { @@ -344,9 +347,9 @@ func (c *Client) each(ctx context.Context, first, bearer string, page func() any return nil } -// JITConfig registers a one-job runner called name in the scope and returns its encoded -// JIT config and the runner's id. -func (c *Client) JITConfig(ctx context.Context, s reconcile.Scope, name string) (string, int64, error) { +// JITConfig registers a one-job runner called name, with its pool's label, in the scope and +// returns its encoded JIT config and the runner's id. +func (c *Client) JITConfig(ctx context.Context, s reconcile.Scope, name, label string) (string, int64, error) { tok, err := c.installToken(ctx, s) if err != nil { return "", 0, err @@ -355,7 +358,7 @@ func (c *Client) JITConfig(ctx context.Context, s reconcile.Scope, name string) if s.Kind == "org" && c.cfg.RunnerGroupID > 0 { group = c.cfg.RunnerGroupID } - body := map[string]any{"name": name, "runner_group_id": group, "labels": []string{"self-hosted", "linux", "x64", c.cfg.Label}, "work_folder": "_work"} + body := map[string]any{"name": name, "runner_group_id": group, "labels": []string{"self-hosted", "linux", "x64", label}, "work_folder": "_work"} var out struct { Runner struct { ID int64 `json:"id"` @@ -414,6 +417,7 @@ func (c *Client) DeleteRunner(ctx context.Context, s reconcile.Scope, id int64) type Job struct { ID int64 Repo string + Label string // the pool label it asks for, spelled as configured CreatedAt time.Time Unlisted bool // found only through the unfiltered runs list: GitHub's status filter left its run out } @@ -599,31 +603,48 @@ func (c *Client) runJobs(ctx context.Context, repo string, run int64, tok string err := c.each(ctx, fmt.Sprintf("%s/repos/%s/actions/runs/%d/jobs?filter=latest&per_page=100", c.cfg.BaseURL, repo, run), tok, func() any { jobs.Jobs = nil; return &jobs }, func() { for _, j := range jobs.Jobs { - if j.Status != "queued" || seen[j.ID] || !c.canTake(j.Labels) { + label, ok := c.canTake(j.Labels) + if j.Status != "queued" || seen[j.ID] || !ok { continue } seen[j.ID] = true - out = append(out, Job{ID: j.ID, Repo: repo, CreatedAt: j.CreatedAt}) + out = append(out, Job{ID: j.ID, Repo: repo, Label: label, CreatedAt: j.CreatedAt}) } }) return out, err } -// canTake: a runner of ours has self-hosted, linux, x64 (GitHub adds the last two) and our -// label, so it can take a job only if every label the job asks for is one of those and ours is -// among them. Labels compare without case. -func (c *Client) canTake(jobLabels []string) bool { - ours := false +// canTake answers which pool's runner can take a job. A runner of ours has self-hosted, linux, +// x64 (GitHub adds the last two) and its pool's label, so it can take a job only if every label +// the job asks for is one of those and its pool's label is among them; a job that asks for two +// pool labels fits no runner. Labels compare without case; the answer is the configured spelling. +func (c *Client) canTake(jobLabels []string) (string, bool) { + label := "" for _, l := range jobLabels { - switch strings.ToLower(l) { - case strings.ToLower(c.cfg.Label): - ours = true - case "self-hosted", "linux", "x64": + switch { + case baseLabels[strings.ToLower(l)] || strings.EqualFold(l, label): + case label == "": + if label = c.poolLabel(l); label == "" { + return "", false + } default: - return false + return "", false + } + } + return label, label != "" +} + +// baseLabels is the labels every runner of ours has, whatever its pool. +var baseLabels = map[string]bool{"self-hosted": true, "linux": true, "x64": true} + +// poolLabel is the configured label l names, or "" when it names none. +func (c *Client) poolLabel(l string) string { + for _, p := range c.cfg.Labels { + if strings.EqualFold(l, p) { + return p } } - return ours + return "" } // RateLimit is what GitHub last reported for one installation. diff --git a/internal/ghapp/ghapp_test.go b/internal/ghapp/ghapp_test.go index 5f74c04..01c3e24 100644 --- a/internal/ghapp/ghapp_test.go +++ b/internal/ghapp/ghapp_test.go @@ -58,7 +58,7 @@ func newGH(t *testing.T, f *fake) *Client { } })) t.Cleanup(ts.Close) - c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Label: "railway", RunnerGroupID: 7}) + c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Labels: []string{"railway", "railway-pg"}, RunnerGroupID: 7}) if err != nil { t.Fatal(err) } @@ -70,7 +70,7 @@ var repo = reconcile.Scope{Kind: "repo", Owner: "acme", Repo: "app"} func TestAppJWTIsSignedWithTheKeyAndShortLived(t *testing.T) { pemKey, key := testKey(t) - c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: "http://x", Label: "l"}) + c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: "http://x", Labels: []string{"l"}}) if err != nil { t.Fatal(err) } @@ -99,20 +99,20 @@ func TestAppJWTIsSignedWithTheKeyAndShortLived(t *testing.T) { } func TestANewClientRefusesAMissingOrBrokenKey(t *testing.T) { - if _, err := New(Config{AppID: "1", PrivateKey: "", Label: "l"}); err == nil { + if _, err := New(Config{AppID: "1", PrivateKey: "", Labels: []string{"l"}}); err == nil { t.Error("empty key") } - if _, err := New(Config{AppID: "", PrivateKey: "x", Label: "l"}); err == nil { + if _, err := New(Config{AppID: "", PrivateKey: "x", Labels: []string{"l"}}); err == nil { t.Error("no app id") } - if _, err := New(Config{AppID: "1", PrivateKey: "not a pem", Label: "l"}); err == nil { + if _, err := New(Config{AppID: "1", PrivateKey: "not a pem", Labels: []string{"l"}}); err == nil { t.Error("garbage key") } } func TestAPEMWithEscapedNewlinesIsAccepted(t *testing.T) { pemKey, _ := testKey(t) - if _, err := New(Config{AppID: "1", PrivateKey: strings.ReplaceAll(pemKey, "\n", `\n`), Label: "l"}); err != nil { + if _, err := New(Config{AppID: "1", PrivateKey: strings.ReplaceAll(pemKey, "\n", `\n`), Labels: []string{"l"}}); err != nil { t.Errorf("a key pasted into a Railway variable keeps its newlines escaped: %v", err) } } @@ -122,7 +122,7 @@ func TestJITConfigForAnOrgUsesTheGroupAndLabelsAndTheInstallationToken(t *testin io.WriteString(w, `{"runner":{"id":9},"encoded_jit_config":"ENC"}`) }} c := newGH(t, f) - enc, id, err := c.JITConfig(context.Background(), org, "rr-abc-1") + enc, id, err := c.JITConfig(context.Background(), org, "rr-abc-1", "railway") if err != nil || enc != "ENC" || id != 9 { t.Fatalf("enc %q id %d err %v", enc, id, err) } @@ -144,7 +144,7 @@ func TestJITConfigForAnOrgUsesTheGroupAndLabelsAndTheInstallationToken(t *testin func TestJITConfigForARepoUsesTheRepoEndpointAndTheDefaultGroup(t *testing.T) { f := &fake{h: func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, `{"encoded_jit_config":"E2"}`) }} c := newGH(t, f) - if _, _, err := c.JITConfig(context.Background(), repo, "rr-x"); err != nil { + if _, _, err := c.JITConfig(context.Background(), repo, "rr-x", "railway-pg"); err != nil { t.Fatal(err) } last := len(f.reqs) - 1 @@ -394,10 +394,70 @@ func TestRedirectsAreNeverFollowedSoNoCredentialTravelsWithOne(t *testing.T) { func TestACallerSuppliedClientIsNotChanged(t *testing.T) { pemKey, _ := testKey(t) shared := &http.Client{} - if _, err := New(Config{AppID: "1", PrivateKey: pemKey, Label: "l", HTTP: shared}); err != nil { + if _, err := New(Config{AppID: "1", PrivateKey: pemKey, Labels: []string{"l"}, HTTP: shared}); err != nil { t.Fatal(err) } if shared.CheckRedirect != nil { t.Error("New changed the client it was given (it could be http.DefaultClient)") } } + +func TestJITConfigRegistersTheLabelOfThePoolItServes(t *testing.T) { + f := &fake{h: func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, `{"encoded_jit_config":"E3"}`) }} + c := newGH(t, f) + if _, _, err := c.JITConfig(context.Background(), repo, "rp-x", "railway-pg"); err != nil { + t.Fatal(err) + } + if last := f.bodies[len(f.bodies)-1]; !strings.Contains(last, `"labels":["self-hosted","linux","x64","railway-pg"]`) { + t.Errorf("body %s: the runner carries its pool's label", last) + } +} + +func TestNewNeedsAtLeastOneLabel(t *testing.T) { + pemKey, _ := testKey(t) + if _, err := New(Config{AppID: "1", PrivateKey: pemKey}); err == nil { + t.Error("a client with no label accepted: it could take no job") + } +} + +// Each job goes to the one pool whose label it asks for, in that pool's own spelling; a job that +// asks for two pool labels fits no runner (each runner has one), so no pool takes it. +func TestQueuedJobsCarryThePoolLabelEachJobAsksFor(t *testing.T) { + f := &fake{h: func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/actions/runs") && r.URL.Query().Get("status") == "queued": + io.WriteString(w, `{"workflow_runs":[{"id":11}]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs"): + io.WriteString(w, `{"workflow_runs":[]}`) + case strings.HasSuffix(r.URL.Path, "/runs/11/jobs"): + io.WriteString(w, `{"jobs":[`+ + `{"id":1,"status":"queued","labels":["self-hosted","Railway"]},`+ + `{"id":2,"status":"queued","labels":["self-hosted","linux","x64","railway-pg"]},`+ + `{"id":3,"status":"queued","labels":["railway","railway-pg"]},`+ + `{"id":4,"status":"queued","labels":["railway","railway"]},`+ + `{"id":5,"status":"queued","labels":["self-hosted","linux"]},`+ + `{"id":6,"status":"queued","labels":["railway","gpu"]}]}`) + default: + t.Errorf("unexpected %s", r.URL.RequestURI()) + w.WriteHeader(404) + } + }} + c := newGH(t, f) + jobs, err := c.QueuedJobs(context.Background(), repo) + if err != nil { + t.Fatal(err) + } + got := map[int64]string{} + for _, j := range jobs { + got[j.ID] = j.Label + } + want := map[int64]string{1: "railway", 2: "railway-pg", 4: "railway"} + if len(got) != len(want) { + t.Fatalf("jobs %v, want %v", got, want) + } + for id, l := range want { + if got[id] != l { + t.Errorf("job %d label %q, want %q", id, got[id], l) + } + } +} diff --git a/internal/ghapp/notfound_test.go b/internal/ghapp/notfound_test.go index d8d56ad..a484979 100644 --- a/internal/ghapp/notfound_test.go +++ b/internal/ghapp/notfound_test.go @@ -34,7 +34,7 @@ func TestARepoWhoseInstallationLookupAnswers404IsErrNotFound(t *testing.T) { w.WriteHeader(http.StatusNotFound) })) t.Cleanup(ts.Close) - c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Label: "railway"}) + c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Labels: []string{"railway", "railway-pg"}}) if err != nil { t.Fatal(err) } @@ -97,7 +97,7 @@ func TestAnOrgWhoseInstallationLookupAnswers404IsErrNotFound(t *testing.T) { w.WriteHeader(http.StatusNotFound) })) t.Cleanup(ts.Close) - c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Label: "railway"}) + c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Labels: []string{"railway", "railway-pg"}}) if err != nil { t.Fatal(err) } @@ -121,7 +121,7 @@ func TestAnInstallationWhoseTokenRequestAnswers404IsErrNotFoundAndForgotten(t *t } })) t.Cleanup(ts.Close) - c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Label: "railway"}) + c, err := New(Config{AppID: "123", PrivateKey: pemKey, BaseURL: ts.URL, Labels: []string{"railway", "railway-pg"}}) if err != nil { t.Fatal(err) } diff --git a/internal/railway/railway.go b/internal/railway/railway.go index 260c279..00e84c0 100644 --- a/internal/railway/railway.go +++ b/internal/railway/railway.go @@ -22,15 +22,13 @@ import ( // Backboard sits behind Cloudflare, which refuses a bot user agent with error 1010. const browserUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36" -// Config is the project and the image the runner services use. +// Config is the project the runner services live in and the name prefixes of the pools. type Config struct { URL string // default https://backboard.railway.com/graphql/v2 Token string ProjectID string EnvironmentID string - Image string - Prefix string // service names start with it, e.g. "rr-" - Region string // Railway region of each runner, e.g. "us-east4-eqdc4a"; empty leaves it to Railway + Prefixes []string // one per pool; service names start with one, e.g. "rr-" HTTP *http.Client } @@ -106,7 +104,8 @@ const listQuery = `query($p:String!){project(id:$p){services{edges{node{id name // part, six lowercase hex digits each (controller.create). var runnerName = regexp.MustCompile(`^[0-9a-f]{6}-[0-9a-f]{6}$`) -// List is our runner services (by name prefix) with whether their container has ended. +// List is every pool's runner services (by name prefix), from one listing, with whether their +// container has ended. func (c *Client) List(ctx context.Context) ([]reconcile.Service, error) { var d struct { Project struct { @@ -139,8 +138,8 @@ func (c *Client) List(ctx context.Context) ([]reconcile.Service, error) { n := e.Node // only the exact names the controller makes: a shared service that merely starts with the // prefix (rr-postgres) must never be listed, counted or deleted - rest, ok := strings.CutPrefix(n.Name, c.cfg.Prefix) - if !ok || !runnerName.MatchString(rest) { + rest, ok := c.runnerRest(n.Name) + if !ok { continue } s := reconcile.Service{ID: n.ID, Name: n.Name, CreatedAt: n.CreatedAt, ScopeHash: rest[:6]} @@ -157,16 +156,27 @@ func (c *Client) List(ctx context.Context) ([]reconcile.Service, error) { return out, nil } -// Create makes a runner service from the image with vars, never restarted, and deploys it -// once. A service that cannot be configured is deleted, not left half-made. -func (c *Client) Create(ctx context.Context, name string, vars map[string]string) (string, error) { +// runnerRest is what follows a pool's prefix in name, when name is exactly a runner service name +// of one of the pools. +func (c *Client) runnerRest(name string) (string, bool) { + for _, p := range c.cfg.Prefixes { + if rest, ok := strings.CutPrefix(name, p); ok && runnerName.MatchString(rest) { + return rest, true + } + } + return "", false +} + +// Create makes a runner service of the pool (its image, in its region) with vars, never restarted, +// and deploys it once. A service that cannot be configured is deleted, not left half-made. +func (c *Client) Create(ctx context.Context, pool reconcile.Pool, name string, vars map[string]string) (string, error) { var created struct { ServiceCreate struct { ID string `json:"id"` } `json:"serviceCreate"` } in := map[string]any{"projectId": c.cfg.ProjectID, "environmentId": c.cfg.EnvironmentID, "name": name, - "source": map[string]any{"image": c.cfg.Image}, "variables": vars} + "source": map[string]any{"image": pool.Image}, "variables": vars} if err := c.do(ctx, `mutation($i:ServiceCreateInput!){serviceCreate(input:$i){id name}}`, map[string]any{"i": in}, &created); err != nil { return "", err } @@ -178,9 +188,9 @@ func (c *Client) Create(ctx context.Context, name string, vars map[string]string // One replica. With a region, it is placed there through multiRegionConfig, the shape Railway // records on the deployment; without one, Railway uses the workspace's preferred region. instance := map[string]any{"restartPolicyType": "NEVER", "numReplicas": 1} - if c.cfg.Region != "" { + if pool.Region != "" { delete(instance, "numReplicas") - instance["multiRegionConfig"] = map[string]any{c.cfg.Region: map[string]any{"numReplicas": 1}} + instance["multiRegionConfig"] = map[string]any{pool.Region: map[string]any{"numReplicas": 1}} } if err := c.do(ctx, `mutation($s:String!,$e:String!,$i:ServiceInstanceUpdateInput!){serviceInstanceUpdate(serviceId:$s,environmentId:$e,input:$i)}`, map[string]any{"s": id, "e": c.cfg.EnvironmentID, "i": instance}, nil); err != nil { diff --git a/internal/railway/railway_test.go b/internal/railway/railway_test.go index fcd5a36..db77f3c 100644 --- a/internal/railway/railway_test.go +++ b/internal/railway/railway_test.go @@ -10,6 +10,8 @@ import ( "strings" "testing" "time" + + "github.com/farzai/github-runner-railway/internal/reconcile" ) type call struct { @@ -19,9 +21,11 @@ type call struct { func server(t *testing.T, reply func(c call) string) (*Client, *[]call, *http.Header) { t.Helper() - return serverWith(t, Config{Token: "tok-secret", ProjectID: "P", EnvironmentID: "E", Image: "ghcr.io/acme/runner:1", Prefix: "rr-"}, reply) + return serverWith(t, Config{Token: "tok-secret", ProjectID: "P", EnvironmentID: "E", Prefixes: []string{"rr-", "rp-"}}, reply) } +var pool = reconcile.Pool{Label: "railway", Image: "ghcr.io/acme/runner:1", Prefix: "rr-"} + func serverWith(t *testing.T, cfg Config, reply func(c call) string) (*Client, *[]call, *http.Header) { t.Helper() var calls []call @@ -62,6 +66,26 @@ func TestListReturnsOnlyOurServicesWithTheirState(t *testing.T) { } } +// One controller serves several pools in one runner project: one listing returns every pool's +// services, each matched by the exact name rule of its own prefix. +func TestListReturnsTheServicesOfEveryConfiguredPrefix(t *testing.T) { + c, calls, _ := server(t, func(call) string { + return `{"data":{"project":{"services":{"edges":[ + {"node":{"id":"1","name":"rr-abc123-0000a1","createdAt":"2026-10-17T11:00:00Z","serviceInstances":{"edges":[]}}}, + {"node":{"id":"2","name":"rp-abc123-0000a2","createdAt":"2026-10-17T11:01:00Z","serviceInstances":{"edges":[]}}}, + {"node":{"id":"3","name":"rq-abc123-0000a3","createdAt":"2026-10-17T11:01:00Z","serviceInstances":{"edges":[]}}}, + {"node":{"id":"4","name":"rp-postgres","createdAt":"2026-10-17T11:01:00Z","serviceInstances":{"edges":[]}}} + ]}}}}` + }) + got, err := c.List(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[0].ID != "1" || got[1].ID != "2" || got[1].ScopeHash != "abc123" || len(*calls) != 1 { + t.Errorf("services %+v after %d calls, want 1 and 2 from one listing", got, len(*calls)) + } +} + func TestCreateMakesTheServiceWithItsConfigThenDeploysOnce(t *testing.T) { c, calls, _ := server(t, func(c call) string { switch { @@ -71,7 +95,7 @@ func TestCreateMakesTheServiceWithItsConfigThenDeploysOnce(t *testing.T) { return `{"data":{"ok":true}}` } }) - id, err := c.Create(context.Background(), "rr-abc123-q", map[string]string{"ACTIONS_RUNNER_INPUT_JITCONFIG": "JIT"}) + id, err := c.Create(context.Background(), pool, "rr-abc123-q", map[string]string{"ACTIONS_RUNNER_INPUT_JITCONFIG": "JIT"}) if err != nil || id != "svc-9" { t.Fatalf("id %q err %v", id, err) } @@ -103,7 +127,7 @@ func TestCreateWithoutARegionLeavesPlacementToRailway(t *testing.T) { } return `{"data":{"ok":true}}` }) - if _, err := c.Create(context.Background(), "n", nil); err != nil { + if _, err := c.Create(context.Background(), pool, "n", nil); err != nil { t.Fatal(err) } cfg := (*calls)[1].Vars["i"].(map[string]any) @@ -118,13 +142,15 @@ func TestCreateWithoutARegionLeavesPlacementToRailway(t *testing.T) { // With a region, the one replica is placed there through multiRegionConfig, the shape Railway // itself records on a deployment ({"": {"numReplicas": 1}}). func TestCreatePlacesTheReplicaInTheConfiguredRegion(t *testing.T) { - c, calls, _ := serverWith(t, Config{Token: "t", ProjectID: "P", EnvironmentID: "E", Image: "i", Prefix: "rr-", Region: "us-east4-eqdc4a"}, func(c call) string { + c, calls, _ := server(t, func(c call) string { if strings.Contains(c.Query, "serviceCreate") { return `{"data":{"serviceCreate":{"id":"svc-9","name":"n"}}}` } return `{"data":{"ok":true}}` }) - if _, err := c.Create(context.Background(), "n", nil); err != nil { + p := pool + p.Region = "us-east4-eqdc4a" + if _, err := c.Create(context.Background(), p, "n", nil); err != nil { t.Fatal(err) } cfg := (*calls)[1].Vars["i"].(map[string]any) @@ -153,7 +179,7 @@ func TestADeployAfterAFailedConfigureIsNotMadeAndTheServiceIsRemoved(t *testing. } return `{"data":{"serviceDelete":true}}` }) - if _, err := c.Create(context.Background(), "n", nil); err == nil { + if _, err := c.Create(context.Background(), pool, "n", nil); err == nil { t.Fatal("want an error") } last := (*calls)[len(*calls)-1].Query @@ -186,7 +212,7 @@ func TestARedirectIsNotFollowedAndTheTokenGoesNowhereElse(t *testing.T) { defer other.Close() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, other.URL, http.StatusFound) })) defer ts.Close() - c := New(Config{URL: ts.URL, Token: "tok-secret", ProjectID: "P", EnvironmentID: "E", Prefix: "rr-"}) + c := New(Config{URL: ts.URL, Token: "tok-secret", ProjectID: "P", EnvironmentID: "E", Prefixes: []string{"rr-"}}) if _, err := c.List(context.Background()); err == nil || hits != 0 { t.Errorf("err %v hits %d: the Project-Access-Token must not follow a redirect", err, hits) } @@ -207,7 +233,7 @@ func TestOnlyExactRunnerNamesAreListedSoSharedServicesAreNeverTouched(t *testing names := []string{ "rr-abc123-0a1b2c", // ours "rr-postgres", "rr-redis", "rr-", "rr", "RR-abc123-0a1b2c", "xrr-abc123-0a1b2c", "rrx-abc123-0a1b2c", - "rr-abc123-0a1b2c-extra", "rr-abc12-0a1b2c", "rr-abc123-0a1b2", "rr-ABC123-0a1b2c", "rp-abc123-0a1b2c", + "rr-abc123-0a1b2c-extra", "rr-abc12-0a1b2c", "rr-abc123-0a1b2", "rr-ABC123-0a1b2c", "rq-abc123-0a1b2c", "rp-postgres", "postgres", "redis", "controller", } var edges []string diff --git a/internal/reconcile/reconcile.go b/internal/reconcile/reconcile.go index 920ed92..907ce46 100644 --- a/internal/reconcile/reconcile.go +++ b/internal/reconcile/reconcile.go @@ -32,6 +32,18 @@ func (s Scope) Hash() string { return hex.EncodeToString(h[:])[:6] } +// Pool is one kind of runner the controller keeps: the jobs that ask for Label run on services +// made from Image, named with Prefix, at most MaxRunners at a time, registered in Scopes. Make plans +// one pool at a time. +type Pool struct { + Label string + Image string + Prefix string // e.g. "rr-"; no two pools share one, and none starts another + Region string // Railway region of its runners; empty leaves it to Railway + MaxRunners int + Scopes []Scope +} + // Service is one runner service on Railway. type Service struct { ID string diff --git a/internal/webhook/webhook.go b/internal/webhook/webhook.go index a3fdd1d..537e652 100644 --- a/internal/webhook/webhook.go +++ b/internal/webhook/webhook.go @@ -40,9 +40,10 @@ type payload struct { } // Handler verifies the signature (HMAC SHA-256 with the shared secret) and calls handle for -// a workflow_job event that carries the label. Every other verified event is acknowledged -// and dropped. With no secret nothing can be verified, so everything is refused. -func Handler(secret, label string, handle func(Event)) http.Handler { +// a workflow_job event that carries one of the pool labels (compared without case, as GitHub +// compares runner labels). Every other verified event is acknowledged and dropped. With no +// secret nothing can be verified, so everything is refused. +func Handler(secret string, labels []string, handle func(Event)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) @@ -66,13 +67,7 @@ func Handler(secret, label string, handle func(Event)) http.Handler { http.Error(w, "bad payload", http.StatusBadRequest) return } - has := false - for _, l := range p.WorkflowJob.Labels { - if l == label { - has = true - } - } - if !has { + if !carriesAny(p.WorkflowJob.Labels, labels) { w.WriteHeader(http.StatusOK) return } @@ -81,6 +76,17 @@ func Handler(secret, label string, handle func(Event)) http.Handler { }) } +func carriesAny(jobLabels, labels []string) bool { + for _, j := range jobLabels { + for _, l := range labels { + if strings.EqualFold(j, l) { + return true + } + } + } + return false +} + func verified(secret, header string, body []byte) bool { if secret == "" || !strings.HasPrefix(header, "sha256=") { return false diff --git a/internal/webhook/webhook_test.go b/internal/webhook/webhook_test.go index 12c5794..4d0c487 100644 --- a/internal/webhook/webhook_test.go +++ b/internal/webhook/webhook_test.go @@ -32,7 +32,7 @@ const queued = `{"action":"queued","workflow_job":{"id":7,"labels":["self-hosted func TestAValidQueuedJobWithOurLabelNudgesTheController(t *testing.T) { var got []Event - h := Handler("s3cret", "railway", func(e Event) { got = append(got, e) }) + h := Handler("s3cret", []string{"railway"}, func(e Event) { got = append(got, e) }) if w := post(h, "s3cret", "workflow_job", queued, nil); w.Code != http.StatusAccepted { t.Fatalf("status %d", w.Code) } @@ -43,7 +43,7 @@ func TestAValidQueuedJobWithOurLabelNudgesTheController(t *testing.T) { func TestABadOrMissingSignatureIsRefusedAndNothingIsHandled(t *testing.T) { called := false - h := Handler("s3cret", "railway", func(Event) { called = true }) + h := Handler("s3cret", []string{"railway"}, func(Event) { called = true }) if w := post(h, "wrong", "workflow_job", queued, nil); w.Code != http.StatusUnauthorized { t.Errorf("wrong secret: status %d", w.Code) } @@ -59,14 +59,14 @@ func TestABadOrMissingSignatureIsRefusedAndNothingIsHandled(t *testing.T) { } func TestAnEmptySecretRefusesEverything(t *testing.T) { - h := Handler("", "railway", func(Event) { t.Error("handled") }) + h := Handler("", []string{"railway"}, func(Event) { t.Error("handled") }) if w := post(h, "", "workflow_job", queued, nil); w.Code != http.StatusUnauthorized { t.Errorf("status %d: with no secret configured nothing can be verified", w.Code) } } func TestOtherEventsAndOtherLabelsAreAcknowledgedAndIgnored(t *testing.T) { - h := Handler("s", "railway", func(Event) { t.Error("handled") }) + h := Handler("s", []string{"railway"}, func(Event) { t.Error("handled") }) if w := post(h, "s", "ping", `{}`, nil); w.Code != http.StatusOK { t.Errorf("ping: %d", w.Code) } @@ -77,9 +77,22 @@ func TestOtherEventsAndOtherLabelsAreAcknowledgedAndIgnored(t *testing.T) { } func TestAHugeBodyIsRefused(t *testing.T) { - h := Handler("s", "railway", func(Event) {}) + h := Handler("s", []string{"railway"}, func(Event) {}) big := strings.Repeat("a", 2<<20) if w := post(h, "s", "workflow_job", big, nil); w.Code != http.StatusRequestEntityTooLarge && w.Code != http.StatusUnauthorized { t.Errorf("status %d", w.Code) } } + +// One App has one webhook URL, so the one controller hears every pool's jobs: an event carrying any +// pool label nudges it, compared without case as GitHub compares runner labels. +func TestAQueuedJobWithAnyPoolLabelNudgesTheController(t *testing.T) { + for _, l := range []string{"railway", "railway-pg", "Railway-PG"} { + n := 0 + h := Handler("s", []string{"railway", "railway-pg"}, func(Event) { n++ }) + body := strings.Replace(queued, `"railway"`, `"`+l+`"`, 1) + if w := post(h, "s", "workflow_job", body, nil); w.Code != http.StatusAccepted || n != 1 { + t.Errorf("label %s: status %d, handled %d times", l, w.Code, n) + } + } +}