internal/ci/sched.go
189 lines · 6087 bytes
1package ci
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "log/slog"
9 "os"
10 "time"
11
12 "gitbay.org/gitbay/internal/config"
13 "gitbay.org/gitbay/internal/gitutil"
14 "gitbay.org/gitbay/internal/store"
15)
16
17// isoNow is the timestamp format schedules are compared in.
18func isoNow(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05Z") }
19
20// NextRun returns the next firing time for a cron expression as a stored
21// timestamp. The caller has already validated the expression.
22func NextRun(expr string, after time.Time) string {
23 c, err := ParseCron(expr)
24 if err != nil {
25 return isoNow(after.Add(24 * time.Hour)) // unreachable after Parse validation
26 }
27 n := c.Next(after)
28 if n.IsZero() {
29 return isoNow(after.AddDate(1, 0, 0))
30 }
31 return isoNow(n)
32}
33
34// Scheduler fires scheduled builds. repoDir maps a repo to its bare path.
35// Security is the instance's code scanning job; with no image it never
36// queues.
37type Scheduler struct {
38 St *store.Store
39 RepoDir func(owner, name string) string
40 SiteURL string
41 Security config.Security
42}
43
44// Run ticks until the context ends. GITBAY_SCHED_TICK overrides the
45// interval for tests.
46func (s *Scheduler) Run(ctx context.Context) {
47 tick := time.Minute
48 if v := os.Getenv("GITBAY_SCHED_TICK"); v != "" {
49 if d, err := time.ParseDuration(v); err == nil {
50 tick = d
51 }
52 }
53 t := time.NewTicker(tick)
54 defer t.Stop()
55 for {
56 select {
57 case <-ctx.Done():
58 return
59 case <-t.C:
60 s.RunDue(time.Now())
61 }
62 }
63}
64
65// RunDue queues every due scheduled build and advances its next_run, and
66// fails any build a runner claimed and never reported. Split from the
67// ticker for tests.
68func (s *Scheduler) RunDue(now time.Time) {
69 s.reapStale()
70 s.runSecurityDue(now)
71 due, err := s.St.DueSchedules(isoNow(now))
72 if err != nil {
73 slog.Error("scheduler: listing due builds", "err", err)
74 return
75 }
76 for _, e := range due {
77 repo, err := s.St.RepoByID(e.RepoID)
78 if err != nil {
79 s.St.RemoveSchedule(e.RepoID, e.Job) // repo gone
80 continue
81 }
82 // Always advance first so a broken repo cannot wedge the loop.
83 s.St.SetScheduleNext(e.RepoID, e.Job, NextRun(e.Cron, now))
84 dir := s.RepoDir(repo.OwnerName, repo.Name)
85 sha, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch)
86 if err != nil {
87 continue // empty repo
88 }
89 raw, err := gitutil.ReadBlob(dir, sha, ConfigPath, 1<<16)
90 if err != nil {
91 s.St.RemoveSchedule(e.RepoID, e.Job) // config removed
92 continue
93 }
94 jobs, err := Parse(raw)
95 if err != nil {
96 continue
97 }
98 var job *Job
99 for i := range jobs {
100 if jobs[i].Name == e.Job && jobs[i].Schedule != "" {
101 job = &jobs[i]
102 break
103 }
104 }
105 if job == nil {
106 s.St.RemoveSchedule(e.RepoID, e.Job)
107 continue
108 }
109 // The push path skips a job whose build for the commit is still
110 // pending or running; so does a tick. Without this a repository
111 // no runner serves gained one row per tick forever (#206). A
112 // finished build does not suppress the tick: a schedule re-runs
113 // an unchanged commit on purpose.
114 if built, err := s.St.BuildsForCommit(repo.ID, sha); err == nil {
115 if b, ok := built[job.Name]; ok && (b.Status == "pending" || b.Status == "running") {
116 continue
117 }
118 }
119 steps, _ := json.Marshal(job.Steps)
120 n, err := s.St.CreateBuild(repo.ID, job.Name, sha, repo.DefaultBranch, string(steps), job.Image, "", true)
121 if err != nil {
122 slog.Error("scheduler: queueing build", "repo", repo.Path(), "job", job.Name, "err", err)
123 continue
124 }
125 url := fmt.Sprintf("%s/%s/builds/%d", s.SiteURL, repo.Path(), n)
126 s.St.SetCommitStatus(repo.ID, sha, "ci/"+job.Name, "pending", "scheduled", url, 0)
127 }
128}
129
130// runSecurityDue queues the code scan for every repository whose next scan
131// is due, and advances it.
132func (s *Scheduler) runSecurityDue(now time.Time) {
133 if s.Security.Image == "" {
134 return
135 }
136 due, err := s.St.DueSecurityScans(isoNow(now))
137 if err != nil {
138 slog.Error("scheduler: listing due security scans", "err", err)
139 return
140 }
141 for _, repo := range due {
142 s.St.SetSecurityNext(repo.ID, NextRun(s.Security.Schedule, now))
143 if _, err := QueueSecurityScan(s.St, s.Security, s.RepoDir(repo.OwnerName, repo.Name), repo); err != nil {
144 slog.Warn("scheduler: queueing security scan", "repo", repo.Path(), "err", err)
145 }
146 }
147}
148
149// ErrScanPending is QueueSecurityScan finding the last scan of the
150// default branch's tip still pending or running.
151var ErrScanPending = errors.New("a scan of this commit is already pending or running")
152
153// QueueSecurityScan queues the code scan of the default branch's tip. It
154// sets no commit status: the scan reports through its issue, and a status
155// would put it in front of merge gates that never asked for it.
156func QueueSecurityScan(st *store.Store, sec config.Security, dir string, repo store.Repo) (int64, error) {
157 sha, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch)
158 if err != nil {
159 return 0, fmt.Errorf("%s has no commits on %s", repo.Path(), repo.DefaultBranch)
160 }
161 if built, err := st.BuildsForCommit(repo.ID, sha); err == nil {
162 if b, ok := built[SecurityJob]; ok && (b.Status == "pending" || b.Status == "running") {
163 return 0, ErrScanPending
164 }
165 }
166 steps, _ := json.Marshal(sec.Steps)
167 return st.CreateBuild(repo.ID, SecurityJob, sha, repo.DefaultBranch, string(steps), sec.Image, "", true)
168}
169
170// reapStale resolves builds running past the deadline, so a runner that
171// died mid-build leaves neither a build running nor a commit pending
172// forever. It runs on the tick rather than on the next runner claim, so it
173// does not need a runner to be alive.
174func (s *Scheduler) reapStale() {
175 stale, err := s.St.ReapStaleBuilds()
176 if err != nil {
177 slog.Error("scheduler: reaping stale builds", "err", err)
178 return
179 }
180 for _, b := range stale {
181 repo, err := s.St.RepoByID(b.RepoID)
182 if err != nil {
183 continue
184 }
185 url := fmt.Sprintf("%s/%s/builds/%d", s.SiteURL, repo.Path(), b.Number)
186 s.St.SetCommitStatus(repo.ID, b.SHA, "ci/"+b.Job, "failure", "build abandoned", url, 0)
187 slog.Warn("build abandoned", "repo", repo.Path(), "build", b.Number, "job", b.Job)
188 }
189}