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