internal/store/builds.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/store/builds.go

550 lines · 18984 bytes

35 symbols in this file
  1package store
  2
  3import (
  4	"database/sql"
  5	"errors"
  6	"os"
  7	"strconv"
  8	"strings"
  9	"time"
 10)
 11
 12// Build is one CI job execution for one commit.
 13type Build struct {
 14	ID         int64
 15	RepoID     int64
 16	Number     int64
 17	Job        string
 18	SHA        string
 19	Ref        string
 20	Steps      string // JSON array of shell commands
 21	Image      string // container image for the steps; "" means the runner default
 22	Tree       string // the commit's tree; "" when not deduplicated by tree
 23	Status     string // pending|running|success|failure
 24	CreatedAt  string
 25	StartedAt  string
 26	FinishedAt string
 27	// LogClosedAt is when the runner's log stream ended; "" while it is
 28	// open or was never opened. Set on a running build only.
 29	LogClosedAt string
 30	// Trusted is false for a merge request head fetched from another
 31	// repository: its steps run without the target's secrets.
 32	Trusted bool
 33	// FailedStep is the 1-based step a failed build stopped at, 0 when it
 34	// stopped before its first step or did not fail. FailedReason is the
 35	// runner's one line: "exit 1", "build timed out after 45m0s".
 36	FailedStep   int
 37	FailedReason string
 38}
 39
 40// MaxBuildLog caps a build's stored log; appends past it are dropped.
 41const MaxBuildLog = 2 << 20
 42
 43// truncNotice is appended once when a log first hits the cap. A log that
 44// simply stops is indistinguishable from a build that died mid-step, which
 45// is the reading that sent people hunting for a nonexistent test failure.
 46var truncNotice = []byte("\n[log truncated: reached the " +
 47	strconv.Itoa(MaxBuildLog>>20) + " MiB cap; earlier output is above]\n")
 48
 49// CreateBuild allocates the per-repo build number in the same transaction
 50// as the insert, like issue and MR numbers.
 51func (s *Store) CreateBuild(repoID int64, job, sha, ref, stepsJSON, image, tree string, trusted bool) (int64, error) {
 52	tx, err := s.DB.Begin()
 53	if err != nil {
 54		return 0, err
 55	}
 56	defer tx.Rollback()
 57	if _, err := tx.Exec("UPDATE repos SET build_counter = build_counter + 1 WHERE id = ?", repoID); err != nil {
 58		return 0, err
 59	}
 60	var n int64
 61	if err := tx.QueryRow("SELECT build_counter FROM repos WHERE id = ?", repoID).Scan(&n); err != nil {
 62		return 0, err
 63	}
 64	// A runner names a build by id in runner log and runner done, so an id
 65	// is never handed out twice, including after a repository's deletion
 66	// takes the newest builds with it (#306). builds is not AUTOINCREMENT
 67	// because rebuilding it would copy every stored log; the high-water
 68	// mark lives in settings instead.
 69	var id int64
 70	if err := tx.QueryRow(`SELECT MAX(
 71			COALESCE((SELECT MAX(id) FROM builds), 0),
 72			COALESCE((SELECT CAST(value AS INTEGER) FROM settings WHERE key = 'build_id_seq'), 0)) + 1`).
 73		Scan(&id); err != nil {
 74		return 0, err
 75	}
 76	if _, err := tx.Exec(
 77		"INSERT INTO builds (id, repo_id, number, job, sha, ref, steps, image, tree, trusted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
 78		id, repoID, n, job, sha, ref, stepsJSON, image, tree, trusted); err != nil {
 79		return 0, err
 80	}
 81	if _, err := tx.Exec(`INSERT INTO settings (key, value) VALUES ('build_id_seq', ?)
 82		ON CONFLICT (key) DO UPDATE SET value = excluded.value`, strconv.FormatInt(id, 10)); err != nil {
 83		return 0, err
 84	}
 85	return n, tx.Commit()
 86}
 87
 88const buildSelect = `
 89	SELECT id, repo_id, number, job, sha, ref, steps, image, tree, status, created_at, started_at, finished_at, log_closed_at, trusted,
 90	       failed_step, failed_reason
 91	FROM builds`
 92
 93func scanBuild(row interface{ Scan(...any) error }) (Build, error) {
 94	var b Build
 95	var trusted int
 96	err := row.Scan(&b.ID, &b.RepoID, &b.Number, &b.Job, &b.SHA, &b.Ref, &b.Steps, &b.Image, &b.Tree,
 97		&b.Status, &b.CreatedAt, &b.StartedAt, &b.FinishedAt, &b.LogClosedAt, &trusted,
 98		&b.FailedStep, &b.FailedReason)
 99	b.Trusted = trusted != 0
100	return b, err
101}
102
103// ClaimBuild atomically hands the oldest pending build to a runner and
104// marks it running. A non-empty repoIDs restricts the claim to those
105// repositories. Untrusted builds — merge request heads from another
106// repository — are skipped unless untrusted is set: they run a stranger's
107// code, which only a runner that isolates should take.
108func (s *Store) ClaimBuild(repoIDs []int64, untrusted bool) (Build, bool, error) {
109	return s.ClaimBuildFor(repoIDs, untrusted, nil)
110}
111
112// ClaimBuildFor is ClaimBuild where jobs narrows some repositories to the
113// jobs named for them (RunnerJobFilters).
114func (s *Store) ClaimBuildFor(repoIDs []int64, untrusted bool, jobs map[int64][]string) (Build, bool, error) {
115	tx, err := s.DB.Begin()
116	if err != nil {
117		return Build{}, false, err
118	}
119	defer tx.Rollback()
120	query := "SELECT id FROM builds WHERE status = 'pending'"
121	args := []any{}
122	if !untrusted {
123		query += " AND trusted = 1"
124	}
125	if len(repoIDs) > 0 {
126		var whole []int64
127		var narrowed []string
128		for _, id := range repoIDs {
129			names, ok := jobs[id]
130			if !ok {
131				whole = append(whole, id)
132				continue
133			}
134			narrowed = append(narrowed, "(repo_id = ? AND job IN ("+marks(len(names))+"))")
135			args = append(args, id)
136			for _, n := range names {
137				args = append(args, n)
138			}
139		}
140		var alts []string
141		if len(whole) > 0 {
142			alts = append(alts, "repo_id IN ("+marks(len(whole))+")")
143			// The narrowed repos' args were appended first; put these in
144			// front to match the clause order.
145			front := make([]any, len(whole))
146			for i, id := range whole {
147				front[i] = id
148			}
149			args = append(front, args...)
150		}
151		alts = append(alts, narrowed...)
152		query += " AND (" + strings.Join(alts, " OR ") + ")"
153	}
154	query += " ORDER BY id LIMIT 1"
155	var id int64
156	err = tx.QueryRow(query, args...).Scan(&id)
157	if errors.Is(err, sql.ErrNoRows) {
158		return Build{}, false, nil
159	}
160	if err != nil {
161		return Build{}, false, err
162	}
163	if _, err := tx.Exec(
164		"UPDATE builds SET status = 'running', started_at = strftime('%Y-%m-%dT%H:%M:%SZ','now') WHERE id = ?", id); err != nil {
165		return Build{}, false, err
166	}
167	b, err := scanBuild(tx.QueryRow(buildSelect+" WHERE id = ?", id))
168	if err != nil {
169		return Build{}, false, err
170	}
171	return b, true, tx.Commit()
172}
173
174// StaleBuildDeadline is how long a claimed build may stay running before the
175// server gives up on it. Comfortably longer than the runner's own -timeout
176// (45m by default), so this only fires when the runner never reported at all —
177// it was killed, restarted, or lost the network mid-build.
178const StaleBuildDeadline = 90 * time.Minute
179
180// staleBuildDeadline is StaleBuildDeadline unless GITBAY_STALE_BUILD_DEADLINE
181// shortens it, which tests do.
182func staleBuildDeadline() time.Duration {
183	if v := os.Getenv("GITBAY_STALE_BUILD_DEADLINE"); v != "" {
184		if d, err := time.ParseDuration(v); err == nil && d > 0 {
185			return d
186		}
187	}
188	return StaleBuildDeadline
189}
190
191// StaleLogGrace is how long a running build may go on after its log
192// stream ended before it is treated as abandoned. The runner reports the
193// outcome right after closing the stream, retrying for about thirty
194// seconds if the server is unreachable; two minutes outlasts that.
195const StaleLogGrace = 2 * time.Minute
196
197// MarkBuildLogClosed records that the runner's log stream for a build
198// ended, on a build still running. A build that finishes normally is
199// reported moments later and the mark is moot; one that is not has lost
200// its runner, and ReapStaleBuilds fails it after StaleLogGrace rather
201// than at the deadline (#179).
202func (s *Store) MarkBuildLogClosed(id int64) error {
203	_, err := s.DB.Exec(`
204		UPDATE builds SET log_closed_at = strftime('%Y-%m-%dT%H:%M:%SZ','now')
205		WHERE id = ? AND status = 'running' AND log_closed_at = ''`, id)
206	return err
207}
208
209// ReapStaleBuilds fails every running build whose runner is gone and
210// returns them, so the caller can resolve their commit statuses: one whose
211// log stream ended more than StaleLogGrace ago with no outcome reported,
212// or one running past the deadline with no stream ever seen. A runner that
213// dies between claiming a build and reporting it otherwise leaves the row
214// claimed forever, and the commit pending forever with it.
215func (s *Store) ReapStaleBuilds() ([]Build, error) {
216	const layout = "2006-01-02T15:04:05Z"
217	now := time.Now().UTC()
218	cutoff := now.Add(-staleBuildDeadline()).Format(layout)
219	logCutoff := now.Add(-StaleLogGrace).Format(layout)
220	rows, err := s.DB.Query(buildSelect+
221		" WHERE status = 'running' AND ((started_at != '' AND started_at < ?)"+
222		" OR (log_closed_at != '' AND log_closed_at < ?))", cutoff, logCutoff)
223	if err != nil {
224		return nil, err
225	}
226	defer rows.Close()
227	var stale []Build
228	for rows.Next() {
229		b, err := scanBuild(rows)
230		if err != nil {
231			return nil, err
232		}
233		stale = append(stale, b)
234	}
235	if err := rows.Err(); err != nil {
236		return nil, err
237	}
238	for _, b := range stale {
239		if err := s.AppendBuildLog(b.ID, []byte(
240			"\nbuild abandoned: the runner never reported an outcome\n")); err != nil {
241			return nil, err
242		}
243		if err := s.FinishBuild(b.ID, "failure"); err != nil {
244			return nil, err
245		}
246		if _, err := s.DB.Exec(`UPDATE builds SET reaped_at = finished_at WHERE id = ?`, b.ID); err != nil {
247			return nil, err
248		}
249	}
250	return stale, nil
251}
252
253// QueueStats is the state of the build queue: what waits now, and over
254// the last day how long a build waited to be claimed and how many were
255// ended by the reaper rather than by a runner's report (#184).
256type QueueStats struct {
257	Pending       int64 `json:"pending"`
258	Claimed24h    int64 `json:"claimed_24h"`
259	ClaimWaitAvgS int64 `json:"claim_wait_avg_s"`
260	ClaimWaitMaxS int64 `json:"claim_wait_max_s"`
261	Reaped24h     int64 `json:"reaped_24h"`
262}
263
264func (s *Store) QueueStats() (QueueStats, error) {
265	var q QueueStats
266	since := time.Now().UTC().Add(-24 * time.Hour).Format("2006-01-02T15:04:05Z")
267	err := s.DB.QueryRow(`SELECT
268		(SELECT COUNT(*) FROM builds WHERE status = 'pending'),
269		COUNT(*),
270		CAST(COALESCE(AVG(strftime('%s', started_at) - strftime('%s', created_at)), 0) AS INTEGER),
271		CAST(COALESCE(MAX(strftime('%s', started_at) - strftime('%s', created_at)), 0) AS INTEGER),
272		(SELECT COUNT(*) FROM builds WHERE reaped_at >= ?)
273		FROM builds WHERE started_at >= ?`, since, since).
274		Scan(&q.Pending, &q.Claimed24h, &q.ClaimWaitAvgS, &q.ClaimWaitMaxS, &q.Reaped24h)
275	return q, err
276}
277
278// AppendBuildLog adds a chunk to the build's log, dropping bytes past the cap.
279func (s *Store) AppendBuildLog(id int64, chunk []byte) error {
280	res, err := s.DB.Exec(`
281		UPDATE builds SET log = log || ?
282		WHERE id = ? AND length(log) < ?`, chunk, id, MaxBuildLog)
283	if err != nil {
284		return err
285	}
286	if n, _ := res.RowsAffected(); n > 0 {
287		s.wakeBuild(id)
288		return nil
289	}
290	// Over the cap. The bounds match exactly once: appending the notice puts
291	// the log past the upper bound, so later chunks fall through silently.
292	_, err = s.DB.Exec(`
293		UPDATE builds SET log = log || ?
294		WHERE id = ? AND length(log) >= ? AND length(log) < ?`,
295		truncNotice, id, MaxBuildLog, MaxBuildLog+len(truncNotice))
296	if err == nil {
297		s.wakeBuild(id)
298	}
299	return err
300}
301
302// FinishBuild records the outcome of a running build.
303func (s *Store) FinishBuild(id int64, status string) error {
304	res, err := s.DB.Exec(`
305		UPDATE builds SET status = ?, finished_at = strftime('%Y-%m-%dT%H:%M:%SZ','now')
306		WHERE id = ? AND status = 'running'`, status, id)
307	if err != nil {
308		return err
309	}
310	if n, _ := res.RowsAffected(); n == 0 {
311		return ErrNotFound
312	}
313	s.wakeBuild(id)
314	return nil
315}
316
317// SetBuildFailure records where a running build failed. The runner
318// reports it with the outcome; it is written first, so a reader woken
319// by the finish sees both.
320func (s *Store) SetBuildFailure(id int64, step int, reason string) error {
321	res, err := s.DB.Exec(`UPDATE builds SET failed_step = ?, failed_reason = ?
322		WHERE id = ? AND status = 'running'`, step, reason, id)
323	if err != nil {
324		return err
325	}
326	if n, _ := res.RowsAffected(); n == 0 {
327		return ErrNotFound
328	}
329	return nil
330}
331
332func (s *Store) BuildByID(id int64) (Build, error) {
333	b, err := scanBuild(s.DB.QueryRow(buildSelect+" WHERE id = ?", id))
334	if errors.Is(err, sql.ErrNoRows) {
335		return b, ErrNotFound
336	}
337	return b, err
338}
339
340func (s *Store) BuildByNumber(repoID, number int64) (Build, error) {
341	b, err := scanBuild(s.DB.QueryRow(buildSelect+" WHERE repo_id = ? AND number = ?", repoID, number))
342	if errors.Is(err, sql.ErrNoRows) {
343		return b, ErrNotFound
344	}
345	return b, err
346}
347
348// BuildFilter narrows ListBuilds to builds matching every non-empty field.
349// Before is the keyset cursor: only builds numbered below it, which with
350// the newest-first order is the page after the one that ended there.
351type BuildFilter struct {
352	Ref    string
353	Status string
354	Job    string
355	Before int64
356}
357
358func (s *Store) ListBuilds(repoID int64, f BuildFilter, limit int) ([]Build, error) {
359	q := buildSelect + " WHERE repo_id = ?"
360	args := []any{repoID}
361	if f.Ref != "" {
362		q += " AND ref = ?"
363		args = append(args, f.Ref)
364	}
365	if f.Status != "" {
366		q += " AND status = ?"
367		args = append(args, f.Status)
368	}
369	if f.Job != "" {
370		q += " AND job = ?"
371		args = append(args, f.Job)
372	}
373	if f.Before > 0 {
374		q += " AND number < ?"
375		args = append(args, f.Before)
376	}
377	q += " ORDER BY number DESC LIMIT ?"
378	args = append(args, limit)
379	return queryAll(s.DB, scanBuild, q, args...)
380}
381
382// BuildLog returns the stored log bytes.
383func (s *Store) BuildLog(id int64) ([]byte, error) {
384	var log []byte
385	err := s.DB.QueryRow("SELECT log FROM builds WHERE id = ?", id).Scan(&log)
386	if errors.Is(err, sql.ErrNoRows) {
387		return nil, ErrNotFound
388	}
389	return log, err
390}
391
392// BuildLogWait returns a channel closed by the next append to, finish of
393// or cancel of the build. Take it before reading, so a change between the
394// read and the wait still wakes the reader. Only this process's writes
395// wake it.
396func (s *Store) BuildLogWait(id int64) <-chan struct{} {
397	s.logMu.Lock()
398	defer s.logMu.Unlock()
399	if s.logWait == nil {
400		s.logWait = map[int64]chan struct{}{}
401	}
402	ch, ok := s.logWait[id]
403	if !ok {
404		ch = make(chan struct{})
405		s.logWait[id] = ch
406	}
407	return ch
408}
409
410func (s *Store) wakeBuild(id int64) {
411	s.logMu.Lock()
412	defer s.logMu.Unlock()
413	if ch, ok := s.logWait[id]; ok {
414		close(ch)
415		delete(s.logWait, id)
416	}
417}
418
419// BuildLogFrom returns the build's status and its log past offset bytes,
420// read together so a terminal status comes with every byte before it.
421// The cast matters: || stores the log as text, and substr on text counts
422// characters.
423func (s *Store) BuildLogFrom(id, offset int64) (string, []byte, error) {
424	var status string
425	var chunk []byte
426	err := s.DB.QueryRow(`SELECT status, substr(CAST(log AS BLOB), ?) FROM builds WHERE id = ?`,
427		offset+1, id).Scan(&status, &chunk)
428	if errors.Is(err, sql.ErrNoRows) {
429		return "", nil, ErrNotFound
430	}
431	return status, chunk, err
432}
433
434// LatestBuild returns the newest build for a repo, optionally narrowed to
435// one job. It is what a status badge reports.
436func (s *Store) LatestBuild(repoID int64, job string) (Build, error) {
437	q := buildSelect + " WHERE repo_id = ?"
438	args := []any{repoID}
439	if job != "" {
440		q += " AND job = ?"
441		args = append(args, job)
442	}
443	q += " ORDER BY number DESC LIMIT 1"
444	b, err := scanBuild(s.DB.QueryRow(q, args...))
445	if errors.Is(err, sql.ErrNoRows) {
446		return b, ErrNotFound
447	}
448	return b, err
449}
450
451// BuildsForCommit returns the newest build per job for one commit. A merge
452// request's checks are ci/<job> statuses; this is where their timing comes
453// from, in one query rather than one per check.
454func (s *Store) BuildsForCommit(repoID int64, sha string) (map[string]Build, error) {
455	return s.newestPerJob(" WHERE repo_id = ? AND sha = ? ORDER BY number ASC", repoID, sha)
456}
457
458// BuildsForCommitOnRef returns the newest build per job for one commit
459// made for one ref. A job sees GITBAY_REF, so a build for another ref
460// says nothing about what the job does on this one.
461func (s *Store) BuildsForCommitOnRef(repoID int64, sha, ref string) (map[string]Build, error) {
462	return s.newestPerJob(" WHERE repo_id = ? AND sha = ? AND ref = ? ORDER BY number ASC", repoID, sha, ref)
463}
464
465func (s *Store) newestPerJob(where string, args ...any) (map[string]Build, error) {
466	rows, err := s.DB.Query(buildSelect+where, args...)
467	if err != nil {
468		return nil, err
469	}
470	defer rows.Close()
471	out := map[string]Build{}
472	for rows.Next() {
473		b, err := scanBuild(rows)
474		if err != nil {
475			return nil, err
476		}
477		out[b.Job] = b // ascending: the last row for a job wins
478	}
479	return out, rows.Err()
480}
481
482// Elapsed reports how long a build ran. Zero until it has both a start and
483// a finish, which is every state but success and failure.
484func (b Build) Elapsed() time.Duration {
485	const layout = "2006-01-02T15:04:05Z"
486	start, err := time.Parse(layout, b.StartedAt)
487	if err != nil {
488		return 0
489	}
490	end, err := time.Parse(layout, b.FinishedAt)
491	if err != nil {
492		return 0
493	}
494	if d := end.Sub(start); d > 0 {
495		return d.Round(time.Second)
496	}
497	return 0
498}
499
500// CancelBuild withdraws a queued or running build. A running one is
501// ended by the runner, which learns of the cancellation when its log
502// session is closed, and whose later report lands on a row that already
503// says cancelled.
504func (s *Store) CancelBuild(id int64) error {
505	res, err := s.DB.Exec(`UPDATE builds SET status = 'cancelled',
506		finished_at = strftime('%Y-%m-%dT%H:%M:%SZ','now') WHERE id = ? AND status IN ('pending', 'running')`, id)
507	if err != nil {
508		return err
509	}
510	if n, _ := res.RowsAffected(); n == 0 {
511		return ErrNotFound
512	}
513	s.wakeBuild(id)
514	return nil
515}
516
517// SuccessBuildForTree finds a passed build of the job for a tree rather
518// than a commit: a rebase that changes nothing in the tree has already
519// been built (#177). Only a build for the same ref counts, since a job
520// sees GITBAY_REF and may do something else on another one. Only a
521// trusted build on the image the job names
522// counts: a fork's result, or one from an image the job has left, does
523// not stand for the repository's own (#258). A job naming no image
524// matches builds that named none, whichever default the runner used;
525// the CI wiki page says so. An empty tree never matches.
526func (s *Store) SuccessBuildForTree(repoID int64, tree, ref, job, image string) (Build, bool, error) {
527	if tree == "" {
528		return Build{}, false, nil
529	}
530	b, err := scanBuild(s.DB.QueryRow(buildSelect+
531		" WHERE repo_id = ? AND tree = ? AND ref = ? AND job = ? AND image = ? AND trusted = 1 AND status = 'success'"+
532		" ORDER BY number DESC LIMIT 1", repoID, tree, ref, job, image))
533	if errors.Is(err, sql.ErrNoRows) {
534		return Build{}, false, nil
535	}
536	return b, err == nil, err
537}
538
539// SuccessBuildFor finds a passed trusted build of the commit for the job,
540// on any ref: what a cancelled duplicate can point back at.
541func (s *Store) SuccessBuildFor(repoID int64, sha, job string) (Build, bool, error) {
542	b, err := scanBuild(s.DB.QueryRow(buildSelect+
543		" WHERE repo_id = ? AND sha = ? AND job = ? AND trusted = 1 AND status = 'success' ORDER BY number DESC LIMIT 1", repoID, sha, job))
544	if errors.Is(err, sql.ErrNoRows) {
545		return Build{}, false, nil
546	}
547	return b, err == nil, err
548}
549
550func marks(n int) string { return strings.TrimSuffix(strings.Repeat("?,", n), ",") }