package runner
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"craftdesign.group/quarry/internal/ci"
"craftdesign.group/quarry/internal/cibridge"
"craftdesign.group/quarry/internal/outbound"
)
// Main is the runner's command line, shared by the standalone
// quarry-runner program and `quarry runner`. prog names the command in
// usage and errors; version is printed by --version and at startup.
func Main(args []string, prog, version string) error {
if cmd, ok := setupCommand(args); ok {
return runSetup(cmd, args[1:], version)
}
fs := flag.NewFlagSet(prog, flag.ContinueOnError)
maxTasks := fs.Int("max-tasks", 2, "tasks run at once")
work := fs.String("work", "", "workspace directory (default: the user cache dir)")
tasks := fs.String("tasks", "", "task types to poll for, comma separated (default: <repo>.job for workflow jobs, and the task names in ci/runner.json on trunk)")
pool := fs.String("pool", "", "drain only this runner pool, the quarry_pool: of the pipelines meant for it: the same as --tasks <repo>-NAME.job, and never <repo>.job")
mode := fs.String("checkout", "archive", `how a task gets its check-in: "archive" downloads the tree from the forge (needs nothing installed); "zit" clones it (needs zit, gives a real repository)`)
zitBin := fs.String("zit", "zit", `the zit binary, with --checkout zit`)
user := fs.String("user", "", "account to fetch a PRIVATE repository as when the forge gives no per-task read-only login (an older forge); its sync token goes in QUARRY_RUNNER_PASSWORD")
branch := fs.String("branch", "", "run only check-ins on this branch, as the forge says, and never a landing's merge: for a runner holding a deploy secret")
jobUsers := fs.String("job-users", "", "run every task as one of these users (comma separated), a pool this runner may become through sudo and each with a group of its own; required to receive CI secrets (RFC 0019)")
drainFor := fs.Duration("drain", DefaultDrainBudget, "on the first SIGTERM or SIGINT, how long running jobs may finish before they are ended and their tasks handed back; keep it under the service's TimeoutStopSec (systemd's default is 90s); a second signal ends at once")
tokenFile := fs.String("token-file", "", "read the worker token from this file instead of QUARRY_RUNNER_TOKEN; the file must be private to its owner (mode 0600)")
passwordFile := fs.String("password-file", "", "read the --user account's sync token from this file instead of QUARRY_RUNNER_PASSWORD; the file must be private to its owner (mode 0600)")
showVersion := fs.Bool("version", false, "print the version and exit")
fs.Usage = func() {
fmt.Fprintf(fs.Output(), `usage: QUARRY_RUNNER_TOKEN=<worker token> %s [flags] https://<forge>/r/<repo>
Runs this repository's CI tasks on this machine. Each task fetches the
check-in under test, reads ci/runner.json AT that check-in, and runs the
command it names for the task's type:
{"tasks": {"test": ["go", "test", "./..."],
"lint": {"argv": ["ruff", "check", "."], "fail_on_output": true,
"env": {"PYTHONPATH": "src"}, "dir": "app"}}}
It runs whatever the check-in's manifest says. Point it only at a
repository whose writers you trust with this machine.
Mint the token in the repository's Settings → Worker tokens.
`, prog)
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
return err
}
if *showVersion {
fmt.Println(prog, version)
return nil
}
if fs.NArg() != 1 {
fs.Usage()
return errors.New("name the repository's URL")
}
repoURL := strings.TrimSuffix(fs.Arg(0), "/")
u, err := url.Parse(repoURL)
if err != nil || u.Scheme == "" || u.Host == "" {
return fmt.Errorf("%q is not a repository URL like https://forge.example/r/name", repoURL)
}
// The runner sends its token and fetches a private tree back: https,
// or http only to the forge on this same machine (#225).
if _, err := outbound.CheckOperator(repoURL); err != nil {
return fmt.Errorf("%q: %v", repoURL, err)
}
segs := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(segs) < 2 || segs[0] != "r" {
return fmt.Errorf("%q is not a repository URL like https://forge.example/r/name", repoURL)
}
repo := segs[len(segs)-1] // /r/<owner>/<repo> and /r/<repo> both name <repo>
token, password, err := runnerSecrets(*tokenFile, *passwordFile)
if err != nil {
return err
}
if token == "" {
return errors.New("set QUARRY_RUNNER_TOKEN to a worker token from the repository's Settings → Worker tokens")
}
var checkout Checkout
switch *mode {
case "archive":
checkout = ArchiveCheckout{URL: repoURL, User: *user, Password: password}
case "zit":
checkout = ZitCheckout{Zit: *zitBin, URL: repoURL, User: *user, Password: password}
default:
return fmt.Errorf(`--checkout is "archive" or "zit", not %q`, *mode)
}
dir := *work
if dir == "" {
cache, err := os.UserCacheDir()
if err != nil {
return err
}
dir = filepath.Join(cache, "quarry-runner", repo)
}
// The first signal starts the drain (no new task, running jobs get
// --drain to finish); the second ends everything at once. Until the
// runner exists, the first signal stops the start-up work below.
sigs := make(chan os.Signal, 2)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(sigs)
ctx, kill := context.WithCancel(context.Background())
defer kill()
first := make(chan struct{})
go func() {
<-sigs
close(first)
<-sigs
kill()
}()
early, stopEarly := context.WithCancel(ctx)
defer stopEarly()
go func() {
select {
case <-first:
stopEarly()
case <-early.Done():
}
}()
names, err := poolTasks(repo, *pool, splitList(*tasks))
if err != nil {
return err
}
bridge := u.Scheme + "://" + u.Host + "/r/" + url.PathEscape(repo) + "/ci/bridge"
if len(names) == 0 {
if names, err = startupTasks(early, nil, log.Printf, bridge, token, repo, checkout, filepath.Join(dir, "trunk")); err != nil {
return err
}
}
self, err := os.Executable()
if err != nil {
return err
}
forge := ForgeBranch{API: u.Scheme + "://" + u.Host + "/api/v1/r/" + url.PathEscape(repo)}
r, err := New(Config{
Bridge: bridge,
Token: token,
Tasks: names,
MaxTasks: *maxTasks,
WorkDir: dir,
Checkout: checkout,
Version: version,
Branch: *branch,
JobUsers: splitList(*jobUsers),
DrainBudget: *drainFor,
Self: self,
BranchOf: forge.BranchOf,
Changed: forge.Changed,
Touched: forge.Touched,
})
if err != nil {
return err
}
go func() {
<-first
r.Drain()
}()
if err := r.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
return err
}
return nil
}
func splitList(s string) []string {
var out []string
for _, p := range strings.Split(s, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
// isRunnerCredential is whether an environment variable carries a
// credential of the runner's own: the worker token, the sync token, zit's
// password, or any other QUARRY_RUNNER_ setting. A task started without
// job users inherits the runner's environment, so each is read once and
// then removed, and never handed on (runnerEnviron): the repository's
// code never sees the worker token or the sync token.
func isRunnerCredential(name string) bool {
return name == "ZIT_PASSWORD" || strings.HasPrefix(name, "QUARRY_RUNNER_")
}
// runnerEnviron is the runner's environment less its own credentials,
// for a process that is not the runner's: a task, or zit.
func runnerEnviron() []string {
env := os.Environ()
out := make([]string, 0, len(env))
for _, kv := range env {
if name, _, _ := strings.Cut(kv, "="); !isRunnerCredential(name) {
out = append(out, kv)
}
}
return out
}
// runnerSecrets reads the worker token and the sync token, each from its
// file when one is named and otherwise from the environment, then clears
// every runner credential from the environment.
func runnerSecrets(tokenFile, passwordFile string) (token, password string, err error) {
defer func() {
for _, kv := range os.Environ() {
if name, _, _ := strings.Cut(kv, "="); isRunnerCredential(name) {
os.Unsetenv(name)
}
}
}()
token = strings.TrimSpace(os.Getenv("QUARRY_RUNNER_TOKEN"))
if tokenFile != "" {
if token, err = readTokenFile(tokenFile); err != nil {
return "", "", err
}
}
password = os.Getenv("QUARRY_RUNNER_PASSWORD")
if password == "" {
password = os.Getenv("ZIT_PASSWORD") // the name `quarry runner` first shipped with
}
if passwordFile != "" {
if password, err = readTokenFile(passwordFile); err != nil {
return "", "", err
}
}
return token, password, nil
}
// poolTasks is the task types a --pool runner polls: its pool's job
// type alone. With no pool, tasks stand as given. A pool and --tasks
// together would say two things at once, and are refused.
func poolTasks(repo, pool string, tasks []string) ([]string, error) {
if pool == "" {
return tasks, nil
}
if !ci.ValidPool(pool) {
return nil, fmt.Errorf("--pool %q: a pool is named in lowercase letters and digits, joined by single dashes, at most %d characters", pool, ci.PoolMax)
}
task, err := ci.PoolTaskType(ci.GroupFor(repo), pool)
if err != nil {
return nil, fmt.Errorf("--pool %s: %v", pool, err)
}
if len(tasks) > 0 {
return nil, fmt.Errorf("--pool %s is --tasks %s: give one of them", pool, task)
}
return []string{task}, nil
}
// startupTasks is the task types a runner given none polls: the ones
// trunk's ci/runner.json names, then the repository's workflow jobs
// (RFC 0019), which need no manifest. The forge says which, to the worker
// token alone; a forge older than that route leaves the runner reading
// trunk itself with its own checkout. A forge that answers with a fault
// stops the runner rather than start it on a guess.
func startupTasks(ctx context.Context, client *http.Client, logf func(string, ...any), bridge, token, repo string, checkout Checkout, base string) ([]string, error) {
names, err := fetchTrunkTasks(ctx, client, bridge, token)
switch {
case err == nil:
case errors.Is(err, errNoRoute) || errors.Is(err, errUnrecorded):
if errors.Is(err, errUnrecorded) {
logf("the forge has no record of this worker token (minted before it kept one): reading trunk's task names with the runner's own checkout; mint a new token in Settings → Runners")
}
if err := checkout.Checkout(ctx, base, "trunk"); err != nil {
return nil, fmt.Errorf("reading the task names from trunk: %w", err)
}
names = nil
if raw, err := os.ReadFile(filepath.Join(base, ManifestPath)); err == nil {
m, err := ParseManifest(raw)
if err != nil {
return nil, err
}
names = m.Names()
}
default:
return nil, fmt.Errorf("reading the task names from the forge: %w", withoutURL(err))
}
return append(names, ci.GroupFor(repo)+".job"), nil
}
// errUnrecorded is the forge answering 401 to a worker token: it has no
// record of it, as for one minted before it kept any.
var errUnrecorded = errors.New("the forge has no record of this worker token")
// fetchTrunkTasks asks the forge's bridge for the task types trunk's
// manifest names. errNoRoute is a forge without the route.
func fetchTrunkTasks(ctx context.Context, client *http.Client, bridge, token string) ([]string, error) {
if client == nil {
client = &http.Client{Timeout: 30 * time.Second}
}
req, err := http.NewRequestWithContext(ctx, "POST", strings.TrimSuffix(bridge, "/")+"/v1/trunk/tasks", strings.NewReader(`{}`))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusNotFound:
return nil, errNoRoute
case resp.StatusCode == http.StatusUnauthorized:
return nil, errUnrecorded
case resp.StatusCode != http.StatusOK:
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return nil, &statusError{Code: resp.StatusCode, Path: "/v1/trunk/tasks", Msg: strings.TrimSpace(string(msg)), Reason: resp.Header.Get(cibridge.ReasonHeader)}
}
var out struct {
Tasks []string `json:"tasks"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out); err != nil {
return nil, fmt.Errorf("the forge's task names could not be read: %v", err)
}
return out.Tasks, nil
}