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