internal/control/build.go

e9566eed86ebcd185c4b85f63d667b5e671fe787
gitbay/internal/control/build.go history · blame · raw

911 lines · 34425 bytes

  1package control
  2
  3import (
  4	"encoding/json"
  5	"errors"
  6	"fmt"
  7	"io"
  8	"log/slog"
  9	"regexp"
 10	"slices"
 11	"strconv"
 12	"strings"
 13	"time"
 14
 15	"gitbay.org/gitbay/internal/ci"
 16	"gitbay.org/gitbay/internal/gitutil"
 17	"gitbay.org/gitbay/internal/policy"
 18	"gitbay.org/gitbay/internal/protocol"
 19	"gitbay.org/gitbay/internal/store"
 20)
 21
 22func init() {
 23	register(Command{Path: []string{"build", "list"},
 24		Summary: "list recent builds",
 25		Usage:   "build list <owner/name> [--ref <branch>] [--status <state>] [--job <name>] [--limit <n>] [--cursor <c>]", ReadOnly: true, Run: runBuildList})
 26	register(Command{Path: []string{"build", "show"},
 27		Summary: "show one build",
 28		Usage:   "build show <owner/name> <n>", ReadOnly: true, Run: runBuildShow})
 29	register(Command{Path: []string{"build", "log"},
 30		Summary: "print a build's log",
 31		Usage:   "build log <owner/name> <n>", ReadOnly: true, Run: runBuildLog})
 32
 33	register(Command{Path: []string{"build", "jobs"},
 34		Summary: "list the jobs a trigger can name",
 35		Usage:   "build jobs <owner/name>", ReadOnly: true, Run: runBuildJobs})
 36
 37	register(Command{Path: []string{"build", "cancel"},
 38		Summary: "withdraw a queued build before a runner claims it",
 39		Usage:   "build cancel <owner/name> <n>", Run: runBuildCancel})
 40	register(Command{Path: []string{"build", "trigger"},
 41		Summary: "queue a job now (scheduled or not)",
 42		Usage:   "build trigger <owner/name> <job>", Run: runBuildTrigger})
 43	// Secrets: set over stdin, listed by name only, injected into the
 44	// repo's builds as environment variables. Same discipline as mirror
 45	// tokens — the value never appears in argv, logs, or output.
 46	register(Command{Path: []string{"repo", "secret", "set"},
 47		Summary:    "set a build secret",
 48		Usage:      "repo secret set <owner/name> <NAME> (value on stdin)",
 49		ReadsStdin: true, Run: runSecretSet})
 50	register(Command{Path: []string{"repo", "secret", "remove"},
 51		Summary: "remove a build secret",
 52		Usage:   "repo secret remove <owner/name> <NAME>", Run: runSecretRemove})
 53	register(Command{Path: []string{"repo", "secret", "list"},
 54		Summary: "list build secret names",
 55		Usage:   "repo secret list <owner/name>", ReadOnly: true, Run: runSecretList})
 56
 57	// Runner commands: the claim/report loop for gitbay-runner. A runner
 58	// executes arbitrary repo code, so handing out jobs is the instance
 59	// operator's call: a key added with --scope runner, which the
 60	// dispatcher confines to these three commands and read-only git, or
 61	// an admin key, which a runner host should not hold (#92).
 62	register(Command{Path: []string{"runner", "next"},
 63		Summary: "claim the oldest pending build this key may run (runner protocol)",
 64		Usage:   "runner next [--untrusted] [<owner/name>...]", Run: runRunnerNext})
 65	register(Command{Path: []string{"runner", "log"},
 66		Summary: "append a build's log from stdin",
 67		Usage:   "runner log <build-id>", ReadsStdin: true, Run: runRunnerLog})
 68	register(Command{Path: []string{"runner", "done"},
 69		Summary: "finish a build",
 70		Usage:   "runner done <build-id> success|failure", Run: runRunnerDone})
 71}
 72
 73type BuildOut struct {
 74	Number     int64  `json:"number"`
 75	Job        string `json:"job"`
 76	Status     string `json:"status"`
 77	SHA        string `json:"sha"`
 78	Ref        string `json:"ref"`
 79	CreatedAt  string `json:"created_at"`
 80	FinishedAt string `json:"finished_at,omitempty"`
 81	// Subject is the first line of the commit's message, so a build
 82	// names what it ran on rather than only its sha (#241). It is empty
 83	// when the commit is no longer in the repository.
 84	Subject string `json:"subject,omitempty"`
 85}
 86
 87func buildToOut(b store.Build) BuildOut {
 88	return BuildOut{Number: b.Number, Job: b.Job, Status: b.Status, SHA: b.SHA,
 89		Ref: b.Ref, CreatedAt: b.CreatedAt, FinishedAt: b.FinishedAt}
 90}
 91
 92func buildRef(c *Ctx, args []string) (store.Repo, store.Build, int) {
 93	if len(args) != 2 {
 94		return store.Repo{}, store.Build{}, c.usageWith("expected <owner/name> <number>")
 95	}
 96	repo, code := resolveRepo(c, args[0], policy.CanRead)
 97	if code >= 0 {
 98		return repo, store.Build{}, code
 99	}
100	n, err := strconv.ParseInt(args[1], 10, 64)
101	if err != nil {
102		return repo, store.Build{}, c.fail(protocol.ExitUsage, "bad build number %q", args[1])
103	}
104	b, err := c.Store.BuildByNumber(repo.ID, n)
105	if err != nil {
106		return repo, b, c.fail(protocol.ExitNotFound, "no build %d on %s", n, repo.Path())
107	}
108	return repo, b, -1
109}
110
111// buildStatuses is the vocabulary --status accepts, and what a bad value
112// is told to pick from.
113var buildStatuses = []string{"pending", "running", "success", "failure", "cancelled"}
114
115// buildPage is how many builds one page of build list returns when no
116// --limit is given. The cap has always been there; what it is now
117// reachable past, with --cursor (#244).
118const buildPage = 50
119
120func runBuildList(c *Ctx, args []string) int {
121	args, p, code := parsePageFlags(c, args, "build", true)
122	if code >= 0 {
123		return code
124	}
125	f, err := parseFlags(args, flagSpec{Values: []string{"--ref", "--status", "--job"}, MaxPos: 1, Usage: c.Cmd.Usage})
126	if err != nil {
127		return c.fail(protocol.ExitUsage, "%v", err)
128	}
129	path := f.pos(0)
130	if path == "" {
131		return c.usage()
132	}
133	status := f.Value("--status")
134	if f.Has("--status") && !slices.Contains(buildStatuses, status) {
135		return c.fail(protocol.ExitUsage, "--status must be one of %s", strings.Join(buildStatuses, ", "))
136	}
137	repo, code := resolveRepo(c, path, policy.CanRead)
138	if code >= 0 {
139		return code
140	}
141	limit := p.queryLimit()
142	if limit == 0 {
143		limit = buildPage
144	}
145	filter := store.BuildFilter{Ref: f.Value("--ref"), Status: status, Job: f.Value("--job"), Before: p.keyInt()}
146	builds, err := c.Store.ListBuilds(repo.ID, filter, limit)
147	if err != nil {
148		return c.fail(protocol.ExitFailure, "%v", err)
149	}
150	builds, next := trimPage(p, builds, "build", func(b store.Build) string {
151		return strconv.FormatInt(b.Number, 10)
152	})
153	var ds []BuildOut
154	for _, b := range builds {
155		ds = append(ds, buildToOut(b))
156	}
157	subjects := buildSubjects(c, repo, ds)
158	for i := range ds {
159		ds[i].Subject = subjects[ds[i].SHA]
160	}
161	return c.emitPage(p, ds, next, func(w io.Writer) {
162		for _, d := range ds {
163			fmt.Fprintf(w, "%d\t%s\t%s\t%.10s\t%s\t%s\n", d.Number, d.Job, d.Status, d.SHA, d.Ref, d.Subject)
164		}
165	})
166}
167
168// buildSubjects reads the commit subject of each distinct sha on a page
169// of builds. Several jobs of one push share a commit, so the set is
170// usually far smaller than the page.
171func buildSubjects(c *Ctx, repo store.Repo, ds []BuildOut) map[string]string {
172	seen := map[string]bool{}
173	var shas []string
174	for _, d := range ds {
175		if d.SHA != "" && !seen[d.SHA] {
176			seen[d.SHA] = true
177			shas = append(shas, d.SHA)
178		}
179	}
180	return gitutil.Subjects(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name), shas)
181}
182
183func runBuildShow(c *Ctx, args []string) int {
184	_, b, code := buildRef(c, args)
185	if code >= 0 {
186		return code
187	}
188	d := buildToOut(b)
189	return c.emit(d, func(w io.Writer) {
190		fmt.Fprintf(w, "build %d\t%s\t%s\n%.10s on %s\nqueued %s", d.Number, d.Job, d.Status, d.SHA, d.Ref, d.CreatedAt)
191		if d.FinishedAt != "" {
192			fmt.Fprintf(w, ", finished %s", d.FinishedAt)
193		}
194		fmt.Fprintln(w)
195	})
196}
197
198func runBuildLog(c *Ctx, args []string) int {
199	_, b, code := buildRef(c, args)
200	if code >= 0 {
201		return code
202	}
203	log, err := c.Store.BuildLog(b.ID)
204	if err != nil {
205		return c.fail(protocol.ExitFailure, "%v", err)
206	}
207	c.Stdout.Write(log)
208	return protocol.ExitOK
209}
210
211type JobOut struct {
212	Name     string `json:"name"`
213	Schedule string `json:"schedule,omitempty"`
214	Tags     string `json:"tags,omitempty"`
215}
216
217// repoJobs reads the CI config on the default branch — the same file the
218// scheduler reads — and returns its jobs with the sha they came from.
219func repoJobs(c *Ctx, repo store.Repo) ([]ci.Job, string, int) {
220	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
221	sha, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch)
222	if err != nil {
223		return nil, "", c.fail(protocol.ExitFailure, "resolving %s: %v", repo.DefaultBranch, err)
224	}
225	raw, err := gitutil.ReadBlob(dir, sha, ci.ConfigPath, 1<<16)
226	if err != nil {
227		return nil, "", c.fail(protocol.ExitNotFound, "%s has no %s on %s", repo.Path(), ci.ConfigPath, repo.DefaultBranch)
228	}
229	jobs, err := ci.Parse(raw)
230	if err != nil {
231		return nil, "", c.failErr(err)
232	}
233	return jobs, sha, -1
234}
235
236// runBuildJobs answers "what can I trigger?". Without it only a surface
237// that can read the repository's git could offer the choice.
238func runBuildJobs(c *Ctx, args []string) int {
239	if len(args) != 1 {
240		return c.usage()
241	}
242	repo, code := resolveRepo(c, args[0], policy.CanRead)
243	if code >= 0 {
244		return code
245	}
246	jobs, _, code := repoJobs(c, repo)
247	if code >= 0 {
248		return code
249	}
250	out := make([]JobOut, 0, len(jobs))
251	for _, j := range jobs {
252		out = append(out, JobOut{Name: j.Name, Schedule: j.Schedule, Tags: j.Tags})
253	}
254	return c.emit(out, func(w io.Writer) {
255		for _, j := range out {
256			switch {
257			case j.Schedule != "":
258				fmt.Fprintf(w, "%s\tschedule %s\n", j.Name, j.Schedule)
259			case j.Tags != "":
260				fmt.Fprintf(w, "%s\ttags %s\n", j.Name, j.Tags)
261			default:
262				fmt.Fprintf(w, "%s\ton push\n", j.Name)
263			}
264		}
265	})
266}
267
268func runBuildTrigger(c *Ctx, args []string) int {
269	if len(args) != 2 {
270		return c.usage()
271	}
272	repo, code := resolveRepo(c, args[0], policy.CanWrite)
273	if code >= 0 {
274		return code
275	}
276	jobs, sha, code := repoJobs(c, repo)
277	if code >= 0 {
278		return code
279	}
280	for _, j := range jobs {
281		if j.Name != args[1] {
282			continue
283		}
284		steps, _ := json.Marshal(j.Steps)
285		tree, _ := gitutil.ResolveTree(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name), sha)
286		n, err := c.Store.CreateBuild(repo.ID, j.Name, sha, repo.DefaultBranch, string(steps), j.Image, tree, true)
287		if err != nil {
288			return c.fail(protocol.ExitFailure, "%v", err)
289		}
290		url := fmt.Sprintf("%s/%s/builds/%d", c.Cfg.Server.SiteURL, repo.Path(), n)
291		c.Store.SetCommitStatus(repo.ID, sha, "ci/"+j.Name, "pending", "triggered", url, c.User.ID)
292		return c.emit(map[string]any{"build": n, "job": j.Name, "sha": sha}, func(w io.Writer) {
293			fmt.Fprintf(w, "queued build %d (%s @ %.10s)\n", n, j.Name, sha)
294		})
295	}
296	return c.fail(protocol.ExitNotFound, "no job %q in %s", args[1], ci.ConfigPath)
297}
298
299// secretName is env-var shaped: the value lands in the build environment.
300var secretName = regexp.MustCompile(`^[A-Z_][A-Z0-9_]{0,63}$`)
301
302func runSecretSet(c *Ctx, args []string) int {
303	if len(args) != 2 {
304		return c.usage()
305	}
306	if !secretName.MatchString(args[1]) {
307		return c.fail(protocol.ExitUsage, "secret names are env-var shaped: uppercase letters, digits, _")
308	}
309	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
310	if code >= 0 {
311		return code
312	}
313	raw, err := io.ReadAll(io.LimitReader(c.Stdin, 64<<10))
314	if err != nil {
315		return c.fail(protocol.ExitFailure, "reading secret: %v", err)
316	}
317	value := strings.TrimRight(string(raw), "\n")
318	if value == "" {
319		return c.fail(protocol.ExitUsage, "no value on stdin (pipe it: printf %%s TOKEN | ...)")
320	}
321	if err := c.Store.SetBuildSecret(repo.ID, args[1], value); err != nil {
322		return c.fail(protocol.ExitFailure, "%v", err)
323	}
324	return c.emit(map[string]string{"secret": args[1]}, func(w io.Writer) {
325		fmt.Fprintf(w, "secret %s set on %s\n", args[1], repo.Path())
326	})
327}
328
329func runSecretRemove(c *Ctx, args []string) int {
330	if len(args) != 2 {
331		return c.usage()
332	}
333	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
334	if code >= 0 {
335		return code
336	}
337	if err := c.Store.RemoveBuildSecret(repo.ID, args[1]); err != nil {
338		if errors.Is(err, store.ErrNotFound) {
339			return c.fail(protocol.ExitNotFound, "no secret %s on %s", args[1], repo.Path())
340		}
341		return c.fail(protocol.ExitFailure, "%v", err)
342	}
343	return c.emit(map[string]string{"removed": args[1]}, func(w io.Writer) {
344		fmt.Fprintf(w, "removed %s\n", args[1])
345	})
346}
347
348func runSecretList(c *Ctx, args []string) int {
349	if len(args) != 1 {
350		return c.usage()
351	}
352	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
353	if code >= 0 {
354		return code
355	}
356	names, err := c.Store.ListBuildSecretNames(repo.ID)
357	if err != nil {
358		return c.fail(protocol.ExitFailure, "%v", err)
359	}
360	return c.emit(names, func(w io.Writer) {
361		for _, n := range names {
362			fmt.Fprintln(w, n)
363		}
364	})
365}
366
367// runnerSession resolves the key behind a runner-protocol session:
368// Source is the key's fingerprint. A build is claimed by a key, so a
369// session without one is told so plainly rather than half-running. An
370// admin key is accepted so an operator can rotate at their own pace; a
371// runner host should hold a key added with --scope runner.
372func runnerSession(c *Ctx) (store.SSHKey, int) {
373	if c.Scope != "runner" && !c.User.IsAdmin {
374		return store.SSHKey{}, c.fail(protocol.ExitDenied, "runner commands need a key added with --scope runner")
375	}
376	key, err := c.Store.SSHKeyByFingerprint(c.Source)
377	if err != nil {
378		return store.SSHKey{}, c.fail(protocol.ExitDenied, "runner commands need an SSH key session")
379	}
380	return key, -1
381}
382
383// runnerAdmin reports whether a session claims builds instance-wide. The
384// bypass is the key, not the account: a scope-runner key is confined to
385// its attachments whoever owns it, including an instance admin.
386func runnerAdmin(c *Ctx) bool {
387	return c.User.IsAdmin && c.Scope != "runner"
388}
389
390// runnerMayBuild reports whether a runner session may act on a
391// repository's builds: an admin key may on any, a runner key on the
392// repositories it is attached to (#184).
393func runnerMayBuild(c *Ctx, key store.SSHKey, repoID int64) (bool, error) {
394	if runnerAdmin(c) {
395		return true, nil
396	}
397	return c.Store.RunnerAttached(key.ID, repoID)
398}
399
400// maxOrphanSkip bounds how many claimed builds runRunnerNext will find
401// unreachable and cancel in one call before giving up. Only fast-forward
402// merges are allowed here, so any branch whose target advances gets
403// rebased and force-pushed, and a stack of branches can do that repeatedly
404// in one sitting — the issue this guards saw five in an afternoon. The cap
405// is well above that, so a real backlog is never cut short, while a
406// repository whose queue is orphaned end to end still returns rather than
407// walking it forever.
408const maxOrphanSkip = 50
409
410func runRunnerNext(c *Ctx, args []string) int {
411	key, code := runnerSession(c)
412	if code >= 0 {
413		return code
414	}
415	f, err := parseFlags(args, flagSpec{Bools: []string{"--untrusted"}, MaxPos: -1,
416		Usage: "runner next [--untrusted] [<owner/name>...]"})
417	if err != nil {
418		return c.fail(protocol.ExitUsage, "%v", err)
419	}
420	// The candidate set. An admin key claims from any repository, narrowed
421	// by the names given. A runner key claims from the repositories it is
422	// attached to; a name outside them is refused, not ignored, so a
423	// misconfigured runner says so instead of idling.
424	var repoIDs []int64
425	for _, arg := range f.Pos {
426		repo, code := resolveRepo(c, arg, policy.CanRead)
427		if code >= 0 {
428			return code
429		}
430		ok, err := runnerMayBuild(c, key, repo.ID)
431		if err != nil {
432			return c.fail(protocol.ExitFailure, "%v", err)
433		}
434		if !ok {
435			return c.fail(protocol.ExitDenied, "this key is not attached to %s; a repository admin attaches it with repo runner add", repo.Path())
436		}
437		repoIDs = append(repoIDs, repo.ID)
438	}
439	if !runnerAdmin(c) && len(repoIDs) == 0 {
440		repoIDs, err = c.Store.RunnerRepoIDs(key.ID)
441		if err != nil {
442			return c.fail(protocol.ExitFailure, "%v", err)
443		}
444		if len(repoIDs) == 0 {
445			// Nothing attached: nothing to claim. Still a heartbeat, so
446			// admin runners shows the key polling.
447			c.Store.TouchRunner(key.ID, c.User.ID, "", 0)
448			return c.emit(map[string]any{}, func(w io.Writer) { fmt.Fprintln(w, "no pending builds") })
449		}
450	}
451	untrusted := f.Has("--untrusted")
452	var b store.Build
453	var repo store.Repo
454	var ok bool
455	for attempt := 0; attempt < maxOrphanSkip; attempt++ {
456		b, ok, err = c.Store.ClaimBuild(repoIDs, untrusted)
457		if err != nil {
458			return c.fail(protocol.ExitFailure, "%v", err)
459		}
460		if !ok {
461			break
462		}
463		repo, err = c.Store.RepoByID(b.RepoID)
464		if err != nil {
465			return c.fail(protocol.ExitFailure, "%v", err)
466		}
467		// Only fast-forward merges are allowed here, so a target that
468		// advances gets rebased and force-pushed, orphaning whatever was
469		// queued for the old head: the runner would clone the repo and
470		// fail at checkout with a git internal error that reads exactly
471		// like a real failure. Catch it here instead. A check that itself
472		// fails is not evidence of anything — the build runs for real and
473		// is left to fail on its own terms, never cancelled on a guess.
474		reachable, err := gitutil.Reachable(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name), b.SHA)
475		if err != nil || reachable {
476			break
477		}
478		if code := cancelOrphanedBuild(c, repo, b); code >= 0 {
479			return code
480		}
481		// Cancelled, not claimed: if the cap is hit right here, the runner
482		// heartbeat below must not record this build as the one handed out.
483		b, ok = store.Build{}, false
484	}
485	// The poll itself is the runner's heartbeat: admin runners reads it.
486	c.Store.TouchRunner(key.ID, c.User.ID, strings.Join(f.Pos, ","), b.ID)
487	if !ok {
488		return c.emit(map[string]any{}, func(w io.Writer) { fmt.Fprintln(w, "no pending builds") })
489	}
490	var steps []string
491	json.Unmarshal([]byte(b.Steps), &steps)
492	// Secrets ride the claim: this channel is admin-only and the values
493	// land in the build's environment, nowhere else.
494	var secrets map[string]string
495	if b.Trusted {
496		secrets, err = c.Store.BuildSecrets(b.RepoID)
497		if err != nil {
498			return c.fail(protocol.ExitFailure, "%v", err)
499		}
500	}
501	d := struct {
502		ID      int64             `json:"id"`
503		Repo    string            `json:"repo"`
504		Number  int64             `json:"number"`
505		Job     string            `json:"job"`
506		SHA     string            `json:"sha"`
507		Ref     string            `json:"ref"`
508		Steps   []string          `json:"steps"`
509		Image   string            `json:"image,omitempty"`
510		Secrets map[string]string `json:"secrets,omitempty"`
511	}{b.ID, repo.Path(), b.Number, b.Job, b.SHA, b.Ref, steps, b.Image, secrets}
512	return c.emit(d, func(w io.Writer) {
513		fmt.Fprintf(w, "build %d: %s %s @ %.10s\n", d.ID, d.Repo, d.Job, d.SHA)
514	})
515}
516
517func runRunnerLog(c *Ctx, args []string) int {
518	key, code := runnerSession(c)
519	if code >= 0 {
520		return code
521	}
522	if len(args) != 1 {
523		return c.usage()
524	}
525	id, err := strconv.ParseInt(args[0], 10, 64)
526	if err != nil {
527		return c.fail(protocol.ExitUsage, "bad build id %q", args[0])
528	}
529	if b, err := c.Store.BuildByID(id); err != nil {
530		return c.fail(protocol.ExitNotFound, "no build %d", id)
531	} else if ok, err := runnerMayBuild(c, key, b.RepoID); err != nil {
532		return c.fail(protocol.ExitFailure, "%v", err)
533	} else if !ok {
534		return c.fail(protocol.ExitDenied, "this key is not attached to the build's repository; a repository admin attaches it with repo runner add")
535	}
536	// Stream stdin into the log in chunks so long builds appear live. An
537	// append that fails drops its chunk and the loop keeps draining: ending
538	// the session here breaks the runner's pipe, and a broken pipe is how a
539	// transient SQLITE_BUSY used to fail the build the log belonged to.
540	//
541	// The session is also how a running build is cancelled: while it is
542	// open the build's row is watched, and when the row stops saying
543	// running the session ends with ExitNotFound, which the runner reads as
544	// "stop this build". Any other end of the session is a lost stream.
545	type chunk struct {
546		data []byte
547		err  error
548	}
549	chunks := make(chan chunk, 4)
550	go func() {
551		buf := make([]byte, 64<<10)
552		for {
553			n, rerr := c.Stdin.Read(buf)
554			if n > 0 {
555				chunks <- chunk{data: append([]byte(nil), buf[:n]...)}
556			}
557			if rerr != nil {
558				chunks <- chunk{err: rerr}
559				return
560			}
561		}
562	}()
563	watch := time.NewTicker(2 * time.Second)
564	defer watch.Stop()
565	dropped := 0
566	for {
567		select {
568		case ch := <-chunks:
569			if len(ch.data) > 0 {
570				if err := c.Store.AppendBuildLog(id, ch.data); err != nil {
571					dropped++
572					slog.Warn("appending build log", "build", id, "err", err)
573				}
574			}
575			if ch.err != nil {
576				if dropped > 0 {
577					slog.Warn("build log incomplete", "build", id, "dropped_chunks", dropped)
578				}
579				// The stream ending is the last thing the server hears
580				// from a runner that is about to die; note the time so
581				// the scheduler can fail the build if no outcome follows.
582				if err := c.Store.MarkBuildLogClosed(id); err != nil {
583					slog.Warn("marking build log closed", "build", id, "err", err)
584				}
585				return c.emit(map[string]string{"log": "ok"}, func(w io.Writer) {})
586			}
587		case <-watch.C:
588			if b, err := c.Store.BuildByID(id); err == nil && b.Status != "running" {
589				return c.fail(protocol.ExitNotFound, "build %d is %s; stop", id, b.Status)
590			}
591		}
592	}
593}
594
595func runRunnerDone(c *Ctx, args []string) int {
596	key, code := runnerSession(c)
597	if code >= 0 {
598		return code
599	}
600	if len(args) != 2 || (args[1] != "success" && args[1] != "failure") {
601		return c.usage()
602	}
603	id, err := strconv.ParseInt(args[0], 10, 64)
604	if err != nil {
605		return c.fail(protocol.ExitUsage, "bad build id %q", args[0])
606	}
607	b, err := c.Store.BuildByID(id)
608	if err != nil {
609		return c.fail(protocol.ExitNotFound, "no build %d", id)
610	}
611	if ok, err := runnerMayBuild(c, key, b.RepoID); err != nil {
612		return c.fail(protocol.ExitFailure, "%v", err)
613	} else if !ok {
614		return c.fail(protocol.ExitDenied, "this key is not attached to the build's repository; a repository admin attaches it with repo runner add")
615	}
616	// Cancelled underneath the runner: its report is late, not wrong.
617	// The row, the status and the log were settled by the cancel.
618	if b.Status == "cancelled" {
619		c.Store.RunnerDone(key.ID)
620		return c.emit(map[string]any{"build": b.Number, "status": "cancelled"}, func(w io.Writer) {
621			fmt.Fprintf(w, "build %d was cancelled\n", b.Number)
622		})
623	}
624	if err := c.Store.FinishBuild(id, args[1]); err != nil {
625		return c.fail(protocol.ExitFailure, "finishing build %d: %v", id, err)
626	}
627	c.Store.RunnerDone(key.ID)
628	repo, err := c.Store.RepoByID(b.RepoID)
629	if err != nil {
630		return c.fail(protocol.ExitFailure, "%v", err)
631	}
632	url := fmt.Sprintf("%s/%s/builds/%d", c.Cfg.Server.SiteURL, repo.Path(), b.Number)
633	desc := "build " + args[1]
634	if err := c.Store.SetCommitStatus(repo.ID, b.SHA, "ci/"+b.Job, args[1], desc, url, c.User.ID); err != nil {
635		return c.fail(protocol.ExitFailure, "%v", err)
636	}
637	c.Store.RecordEvent(repo.ID, c.User.ID, "build."+args[1],
638		fmt.Sprintf(`{"number":%d,"job":%q,"sha":%q}`, b.Number, b.Job, b.SHA))
639	// A red build mails the repo's notify targets with the log tail — a
640	// failed scheduled job must not wait to be noticed.
641	if args[1] == "failure" {
642		if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
643			tail := ""
644			if log, err := c.Store.BuildLog(id); err == nil && len(log) > 0 {
645				if len(log) > 2000 {
646					log = log[len(log)-2000:]
647				}
648				tail = string(log)
649			}
650			notify(c, targets, notice{repo: repo, kind: "build",
651				subject: fmt.Sprintf("[%s] build %d failed: %s on %s", repo.Path(), b.Number, b.Job, b.Ref),
652				action:  fmt.Sprintf("build %d failed: %s on %s", b.Number, b.Job, b.Ref),
653				body:    fmt.Sprintf("job %s failed at %.10s.\n\n…%s\n\n%s\n", b.Job, b.SHA, tail, url),
654				path:    fmt.Sprintf("%s/builds/%d", repo.Path(), b.Number)})
655		}
656	}
657	return c.emit(map[string]any{"build": b.Number, "status": args[1]}, func(w io.Writer) {
658		fmt.Fprintf(w, "build %d %s\n", b.Number, args[1])
659	})
660}
661
662// QueueBranchBuilds reads .gitbay/ci.yml at sha and creates one pending
663// build per push job, with a pending commit status the runner resolves.
664// A broken config surfaces as a failed "ci/config" status, not silence.
665//
666// Both paths that move a branch call this: post-receive for a push, and
667// the merge path for a merge, which updates the ref directly and so never
668// reaches a hook. old is the branch's sha before this update, the diff
669// base a job's path filters run against; a new branch has no prior
670// commit and sends old as empty or all zeros. queueJobs falls back to
671// the merge base with the default branch in that case, so a filter
672// still applies to a branch's first push — the shape most changes have,
673// since branch-then-MR is the normal workflow here.
674func QueueBranchBuilds(
675	st *store.Store, root, siteURL string,
676	repo store.Repo, userID int64, branch, old, sha string, now time.Time,
677) {
678	queueJobs(st, root, siteURL, repo, userID, branch, old, sha, now, true, branch == repo.DefaultBranch, true)
679}
680
681// QueueMRBuilds queues the push jobs for a merge request head fetched
682// from another repository, which the target holds at
683// refs/merge-requests/<n>/head, so a fork's merge request has ci/<job>
684// statuses for require-checks to gate on (#98). The head is untrusted:
685// its build runs without the target's secrets. A same-repository head is
686// the branch push's job and is not queued here; a failed one is rebuilt
687// when it lands, not when it is proposed.
688func QueueMRBuilds(
689	st *store.Store, root, siteURL string,
690	repo store.Repo, userID, n int64, sha string,
691) {
692	// No old sha, and unlike QueueBranchBuilds, no merge-base fallback
693	// either: this deliberately keeps failing open and running every
694	// job. require_checks refuses a merge when an MR head has no
695	// statuses at all (mr.go), so filtering a head down to zero jobs
696	// would make it unmergeable rather than just unfiltered (#172).
697	queueJobs(st, root, siteURL, repo, userID, mrHeadRef(n), "", sha, time.Now(), false, false, false)
698}
699
700// skipReason names why a job's path filters excluded this push, mirroring
701// the order ci.Selected checks them in: an unmatched paths list rules a
702// job out before paths-ignore is even considered.
703func skipReason(j ci.Job, changed []string) string {
704	if len(j.Paths) > 0 {
705		hit := false
706		for _, f := range changed {
707			for _, p := range j.Paths {
708				if ci.Match(p, f) {
709					hit = true
710				}
711			}
712		}
713		if !hit {
714			return "no changed file matches paths"
715		}
716	}
717	return "every changed file matched paths-ignore"
718}
719
720func queueJobs(
721	st *store.Store, root, siteURL string,
722	repo store.Repo, userID int64, ref, old, sha string, now time.Time,
723	trusted, syncSchedules, deriveMergeBase bool,
724) {
725	dir := RepoDir(root, repo.OwnerName, repo.Name)
726	raw, err := gitutil.ReadBlob(dir, sha, ci.ConfigPath, 1<<16)
727	if err != nil {
728		return // no CI config at this commit
729	}
730	jobs, err := ci.Parse(raw)
731	if err != nil {
732		st.SetCommitStatus(repo.ID, sha, "ci/config", "failure", err.Error(), "", userID)
733		return
734	}
735	// A build is a fact about a commit, not a ref: a job has no branch
736	// filter, so a commit that already passed a job on another branch has
737	// nothing left to prove when a fast-forward lands it here, and one
738	// still queued or running there will say soon enough. A failed,
739	// abandoned or cancelled build does not count; that commit runs again.
740	built, err := st.BuildsForCommit(repo.ID, sha)
741	if err != nil {
742		built = nil
743	}
744	// A job's result is a property of the tree, not the commit: a rebase
745	// onto a base that touched nothing the branch did gives every commit
746	// a new sha and the same tree, and re-running the suite over it
747	// proves nothing it did not already prove (#177). A success recorded
748	// against the tree stands for the new commit.
749	tree, _ := gitutil.ResolveTree(dir, sha)
750	// The changed-file list a job's path filters run against, computed
751	// once and only if some job actually declares one. When the diff
752	// base does not exist or the diff itself fails, filtered stays
753	// false and every job runs: a filter that cannot be evaluated must
754	// not silently skip CI.
755	//
756	// A branch's first push has no old sha, but a diff base still
757	// exists: the merge base with the default branch. Without deriving
758	// one, every job runs on every new branch, and since branch-then-MR
759	// is the normal workflow, that is the push path filters matter most
760	// for. The merge base of the default branch's tip with itself is
761	// the tip, carrying no diff — that covers the default branch's own
762	// first push on a fresh repository, and must fail open rather than
763	// read as "nothing changed".
764	filtered := false
765	var changed []string
766	for _, j := range jobs {
767		if len(j.Paths) == 0 && len(j.PathsIgnore) == 0 {
768			continue
769		}
770		diffOld := old
771		// A force-push rewrote the branch, so the old tip is not an
772		// ancestor of the new one and old..new is not "what this push
773		// changed" — it is the difference between two histories. After a
774		// rebase that is whatever the new base added, typically nothing
775		// the branch itself touched, so every path filter concludes its
776		// job is unnecessary and the branch reads as green without its
777		// suite having run (#176). The merge base is the honest base:
778		// the filter is deciding about the branch's relationship to its
779		// target, which is what the merge base expresses.
780		if ci.HasDiffBase(diffOld) && deriveMergeBase {
781			if ok, err := gitutil.IsAncestor(dir, diffOld, sha); err != nil || !ok {
782				diffOld = ""
783			}
784		}
785		if !ci.HasDiffBase(diffOld) && deriveMergeBase {
786			if base, err := gitutil.MergeBase(dir, "refs/heads/"+repo.DefaultBranch, sha); err == nil && base != sha {
787				diffOld = base
788			}
789		}
790		if ci.HasDiffBase(diffOld) {
791			if files, err := gitutil.DiffFiles(dir, diffOld, sha); err == nil {
792				changed, filtered = files, true
793			}
794		}
795		break
796	}
797	var schedules []store.Schedule
798	for _, j := range jobs {
799		// Tag jobs run on matching tag pushes only.
800		if j.Tags != "" {
801			continue
802		}
803		if b, ok := built[j.Name]; ok && (b.Status == "success" || b.Status == "pending" || b.Status == "running") {
804			continue
805		}
806		if prev, ok, _ := st.SuccessBuildForTree(repo.ID, tree, j.Name); ok && prev.SHA != sha {
807			url := fmt.Sprintf("%s/%s/builds/%d", siteURL, repo.Path(), prev.Number)
808			st.SetCommitStatus(repo.ID, sha, "ci/"+j.Name, "success",
809				fmt.Sprintf("passed in build %d as %.10s, same tree", prev.Number, prev.SHA), url, userID)
810			continue
811		}
812		// Scheduled jobs run on their cron, not on push; a default-branch
813		// push (re)registers them.
814		if j.Schedule != "" {
815			if syncSchedules {
816				schedules = append(schedules, store.Schedule{
817					RepoID: repo.ID, Job: j.Name, Cron: j.Schedule,
818					NextRun: ci.NextRun(j.Schedule, now),
819				})
820			}
821			continue
822		}
823		// A filter that excludes this push is not silence: it satisfies
824		// require_checks with a skipped status instead of leaving the
825		// commit with none at all, which the gate refuses outright (#172).
826		if filtered && !ci.Selected(j, changed) {
827			st.SetCommitStatus(repo.ID, sha, "ci/"+j.Name, "skipped", skipReason(j, changed), "", userID)
828			continue
829		}
830		steps, _ := json.Marshal(j.Steps)
831		n, err := st.CreateBuild(repo.ID, j.Name, sha, ref, string(steps), j.Image, tree, trusted)
832		if err != nil {
833			slog.Error("queueing build", "repo", repo.Path(), "job", j.Name, "err", err)
834			continue
835		}
836		url := fmt.Sprintf("%s/%s/builds/%d", siteURL, repo.Path(), n)
837		st.SetCommitStatus(repo.ID, sha, "ci/"+j.Name, "pending", "queued", url, userID)
838	}
839	if syncSchedules {
840		if err := st.SyncSchedules(repo.ID, schedules); err != nil {
841			slog.Error("syncing schedules", "repo", repo.Path(), "err", err)
842		}
843	}
844}
845
846// resolveCancelledCommitStatus sets the commit status for a build that was
847// just cancelled: if the commit already passed this job on another ref,
848// that result stands again; otherwise the context reports the
849// cancellation as an error, so the queued status left behind is never
850// pending forever.
851func resolveCancelledCommitStatus(c *Ctx, repo store.Repo, b store.Build) {
852	if prev, ok, err := c.Store.SuccessBuildFor(repo.ID, b.SHA, b.Job); err == nil && ok {
853		url := fmt.Sprintf("%s/%s/builds/%d", c.Cfg.Server.SiteURL, repo.Path(), prev.Number)
854		c.Store.SetCommitStatus(repo.ID, b.SHA, "ci/"+b.Job, "success",
855			fmt.Sprintf("passed in build %d on %s", prev.Number, prev.Ref), url, c.User.ID)
856		return
857	}
858	url := fmt.Sprintf("%s/%s/builds/%d", c.Cfg.Server.SiteURL, repo.Path(), b.Number)
859	c.Store.SetCommitStatus(repo.ID, b.SHA, "ci/"+b.Job, "error", "cancelled", url, c.User.ID)
860}
861
862// cancelOrphanedBuild withdraws a build runRunnerNext claimed and then
863// found unreachable. It leaves the same shape behind as a build cancel a
864// person runs by hand: CancelBuild's status, a log line saying why, and
865// the commit status resolved rather than left pending. Returns -1 to mean
866// "handled, keep going"; anything else is the exit code to return.
867func cancelOrphanedBuild(c *Ctx, repo store.Repo, b store.Build) int {
868	if err := c.Store.CancelBuild(b.ID); err != nil {
869		return c.fail(protocol.ExitFailure, "%v", err)
870	}
871	c.Store.AppendBuildLog(b.ID, []byte(fmt.Sprintf(
872		"cancelled: %.10s is not reachable from any ref; the sha was likely orphaned by a force-push\n", b.SHA)))
873	resolveCancelledCommitStatus(c, repo, b)
874	c.Store.RecordEvent(repo.ID, c.User.ID, "build.cancelled", fmt.Sprintf(`{"number":%d,"job":%q,"sha":%q}`, b.Number, b.Job, b.SHA))
875	return -1
876}
877
878func runBuildCancel(c *Ctx, args []string) int {
879	repo, b, code := buildRef(c, args)
880	if code >= 0 {
881		return code
882	}
883	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
884	if err != nil {
885		return c.fail(protocol.ExitFailure, "%v", err)
886	}
887	if !policy.CanWrite(c.User, repo, grant) {
888		return c.fail(protocol.ExitDenied, "cancelling a build needs write access to %s; ask its owner", repo.Path())
889	}
890	if b.Status != "pending" && b.Status != "running" {
891		return c.fail(protocol.ExitUsage, "build %d is %s; only a queued or running build can be cancelled", b.Number, b.Status)
892	}
893	if err := c.Store.CancelBuild(b.ID); err != nil {
894		return c.fail(protocol.ExitFailure, "%v", err)
895	}
896	if b.Status == "running" {
897		c.Store.AppendBuildLog(b.ID, []byte(fmt.Sprintf("\ncancelled by %s while running; the runner stops at its next check\n", c.User.Username)))
898	} else {
899		c.Store.AppendBuildLog(b.ID, []byte(fmt.Sprintf("cancelled by %s before a runner claimed it\n", c.User.Username)))
900	}
901	// The queued status replaced whatever the commit had for this job.
902	resolveCancelledCommitStatus(c, repo, b)
903	c.Store.RecordEvent(repo.ID, c.User.ID, "build.cancelled", fmt.Sprintf(`{"number":%d,"job":%q,"sha":%q}`, b.Number, b.Job, b.SHA))
904	return c.emit(map[string]any{"number": b.Number, "job": b.Job, "status": "cancelled", "was": b.Status}, func(w io.Writer) {
905		if b.Status == "running" {
906			fmt.Fprintf(w, "cancelled %s build %d (%s); the runner stops at its next check\n", repo.Path(), b.Number, b.Job)
907			return
908		}
909		fmt.Fprintf(w, "cancelled %s build %d (%s)\n", repo.Path(), b.Number, b.Job)
910	})
911}