1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "slices"
10 "strings"
11 "time"
12 "unicode/utf8"
13
14 "github.com/bnema/zerowrap"
15
16 "bnema.dev/ermite/internal/domain"
17 "bnema.dev/ermite/internal/ports"
18)
19
20// maxVersionLen bounds RegisterRunner.version.
21const maxVersionLen = 64
22
23// --- registration ---
24
25// Register adds a runner and returns its token, shown once. The principal
26// needs runner:register on a token that is not restricted to repositories, or
27// to be root. A name in use is domain.ErrAlreadyExists unless Replace is set,
28// which removes the old runner (its token stops working at once).
29func (c *CI) Register(ctx context.Context, p domain.Principal, params ports.RegisterRunnerParams) (ports.RegisteredRunner, error) {
30 if err := canManageRunners(p); err != nil {
31 return ports.RegisteredRunner{}, err
32 }
33 if err := domain.ParseRunnerName(params.Name); err != nil {
34 return ports.RegisteredRunner{}, err
35 }
36 labels, err := domain.ParseRunnerLabels(params.Labels)
37 if err != nil {
38 return ports.RegisteredRunner{}, err
39 }
40 var v domain.Violations
41 if len(params.Version) > maxVersionLen || !utf8.ValidString(params.Version) {
42 v.Add("version", "is at most 64 characters")
43 }
44 switch params.Isolation {
45 case domain.CIIsolationVM, domain.CIIsolationContainerSysbox, domain.CIIsolationContainerPrivileged:
46 default:
47 v.Add("isolation", "is required")
48 }
49 if params.Arch != "x64" && params.Arch != "arm64" {
50 v.Add("arch", `must be "x64" or "arm64"`)
51 }
52 if params.OS != "linux" {
53 v.Add("os", `must be "linux"`)
54 }
55 if err := v.Err(); err != nil {
56 return ports.RegisteredRunner{}, err
57 }
58
59 token := newToken(domain.RunnerTokenPrefix)
60 r := domain.CIRunner{
61 ID: newRunnerID(), Name: params.Name, Labels: domain.RunnerLabels(labels, params.OS, params.Arch),
62 Isolation: params.Isolation, Version: params.Version, Arch: params.Arch, OS: params.OS,
63 RegisteredAt: c.now(), TokenHash: domain.HashTokenSecret(token),
64 }
65 removed, err := c.cfg.Store.CreateRunner(ctx, r, params.Replace)
66 if err != nil {
67 return ports.RegisteredRunner{}, err
68 }
69 log := zerowrap.FromCtx(ctx)
70 log.Info().Str("runner_id", r.ID).Str("runner", r.Name).Str("isolation", string(r.Isolation)).
71 Int("replaced", len(removed)).Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("runner registered")
72 c.forgetRunners(removed)
73 return ports.RegisteredRunner{Runner: r, Token: token}, nil
74}
75
76// forgetRunners drops what is kept in memory for removed runners and ends
77// their polls in progress.
78func (c *CI) forgetRunners(rs []domain.CIRunner) {
79 c.mu.Lock()
80 for _, r := range rs {
81 delete(c.polls, r.ID)
82 delete(c.seen, r.ID)
83 }
84 c.mu.Unlock()
85 c.wakeQueue()
86}
87
88// runnerFor authenticates a runner token.
89func (c *CI) runnerFor(ctx context.Context, secret string) (domain.CIRunner, error) {
90 if !domain.IsRunnerToken(secret) {
91 return domain.CIRunner{}, domain.ErrUnauthenticated
92 }
93 r, err := c.cfg.Store.FindRunnerByToken(ctx, domain.HashTokenSecret(secret))
94 if errors.Is(err, domain.ErrNotFound) {
95 return domain.CIRunner{}, domain.ErrUnauthenticated
96 }
97 return r, err
98}
99
100func (c *CI) markSeen(runnerID string) {
101 c.mu.Lock()
102 c.seen[runnerID] = c.now()
103 c.mu.Unlock()
104}
105
106// --- FetchJob ---
107
108var errNoJob = errors.New("no job")
109
110// FetchJob holds the call until a queued job matches the runner, or the poll
111// time passes. A job is given to exactly one runner: assignments are made one
112// at a time under a lock and recorded before the answer is sent.
113func (c *CI) FetchJob(ctx context.Context, secret string, params ports.FetchJobParams) (ports.FetchJobResult, error) {
114 runner, err := c.runnerFor(ctx, secret)
115 if err != nil {
116 return ports.FetchJobResult{}, err
117 }
118 offered, err := offeredLabels(runner, params.Labels)
119 if err != nil {
120 return ports.FetchJobResult{}, err
121 }
122 if params.PollID != "" {
123 if err := checkPollID(params.PollID); err != nil {
124 return ports.FetchJobResult{}, err
125 }
126 j, ok, err := c.repeatPoll(ctx, runner, params.PollID)
127 if err != nil {
128 return ports.FetchJobResult{}, err // the runner asks again with the same poll id
129 }
130 if ok {
131 return ports.FetchJobResult{Job: j}, nil
132 }
133 }
134 c.markSeen(runner.ID)
135 deadline := time.NewTimer(c.cfg.PollTimeout)
136 defer deadline.Stop()
137 for {
138 wake := c.pending.wait(queueKey) // before looking: a job made meanwhile wakes us
139 job, err := c.assignTo(ctx, runner, offered, params.PollID)
140 switch {
141 case err == nil:
142 c.markSeen(runner.ID)
143 return ports.FetchJobResult{Job: job}, nil
144 case !errors.Is(err, errNoJob):
145 return ports.FetchJobResult{}, err
146 }
147 select {
148 case <-wake:
149 case <-deadline.C:
150 c.markSeen(runner.ID)
151 return ports.FetchJobResult{}, nil
152 case <-ctx.Done():
153 return ports.FetchJobResult{}, ctx.Err()
154 case <-c.ctx.Done():
155 return ports.FetchJobResult{RetryAfter: time.Second}, nil
156 }
157 // A removed runner's poll ends with unauthenticated.
158 if _, err := c.cfg.Store.GetRunner(ctx, runner.ID); errors.Is(err, domain.ErrNotFound) {
159 return ports.FetchJobResult{}, domain.ErrUnauthenticated
160 }
161 }
162}
163
164func checkPollID(id string) error {
165 if len(id) > 64 {
166 return fmt.Errorf("%w: poll_id is at most 64 characters", domain.ErrInvalid)
167 }
168 for _, r := range id {
169 if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '_' && r != '-' {
170 return fmt.Errorf("%w: poll_id has letters, digits, '_' and '-' only", domain.ErrInvalid)
171 }
172 }
173 return nil
174}
175
176// offeredLabels are the labels of one poll: all those of the runner, or the
177// subset the call names.
178func offeredLabels(r domain.CIRunner, asked []string) ([]string, error) {
179 if len(asked) == 0 {
180 return r.Labels, nil
181 }
182 var out []string
183 for _, l := range asked {
184 l = strings.ToLower(l)
185 if !slices.Contains(r.Labels, l) {
186 return nil, fmt.Errorf("%w: label %q is not a label of the runner", domain.ErrInvalid, l)
187 }
188 out = append(out, l)
189 }
190 return out, nil
191}
192
193// repeatPoll answers a retried poll with the assignment the first call made,
194// as long as it has not been acknowledged or cancelled.
195func (c *CI) repeatPoll(ctx context.Context, runner domain.CIRunner, pollID string) (*ports.RunnerJob, bool, error) {
196 c.mu.Lock()
197 rec, ok := c.polls[runner.ID]
198 c.mu.Unlock()
199 if !ok || rec.pollID != pollID {
200 return nil, false, nil
201 }
202 var rid int64
203 var ra int32
204 var id string
205 if _, err := fmt.Sscanf(rec.ref, "%d/%d/%s", &rid, &ra, &id); err != nil {
206 return nil, false, nil
207 }
208 var out *ports.RunnerJob
209 err := c.withRun(ctx, rid, ra, func(rs *runState) error {
210 j := rs.find(id)
211 if j == nil || j.Phase != domain.CIPhaseAssigned || j.TokenHash != rec.hash || j.RunnerID != runner.ID {
212 return errNoJob
213 }
214 // The secrets are not kept with the poll: they are read again.
215 settings, err := c.settingsOf(ctx, rs, *j)
216 if err != nil {
217 return err
218 }
219 out = c.runnerJob(rs, *j, rec.token, rec.ghToken, settings)
220 return nil
221 })
222 switch {
223 case err == nil && out != nil:
224 return out, true, nil
225 case isSettingsError(err):
226 return nil, false, err // checked first: it may wrap ErrConflict or ErrNotFound
227 case err == nil, errors.Is(err, errNoJob), errors.Is(err, domain.ErrNotFound), errors.Is(err, domain.ErrConflict):
228 return nil, false, nil // nothing to repeat: the poll goes on as a new one
229 }
230 return nil, false, err // the settings could not be read: not a lost assignment
231}
232
233// runnerJob is the job as the runner gets it. settings are read when the job
234// is assigned and live in this value only: j is a copy, so the contexts it
235// carries (with the variables as they are now) are not stored, and the secrets
236// go nowhere but to the runner (never to the run record, the github context or
237// a log; RunnerJob prints without them).
238//
239// TODO(ci3-c2): the runner writes the "Set up job" log; it states there that
240// secrets were withheld when Trusted is false (the server adds no setup line).
241func (c *CI) runnerJob(rs *runState, j domain.CIJob, token, ghToken string, settings ports.JobSettings) *ports.RunnerJob {
242 if settings.Vars != nil {
243 j.ContextsJSON = withVars(j.ContextsJSON, settings.Vars)
244 }
245 return &ports.RunnerJob{
246 Job: j, Token: token, GithubToken: ghToken, Repo: rs.run.Repo, Sha: rs.run.Sha, Ref: rs.run.Ref,
247 WorkflowPath: rs.run.WorkflowPath, WorkflowYAML: rs.src.WorkflowYAML,
248 Environment: j.Environment, Vars: settings.Vars, Secrets: settings.Secrets, Trusted: rs.run.Trusted,
249 Permissions: domain.TokenPermissions(j.Permissions, rs.run.Trusted),
250 }
251}
252
253// assignTo gives the oldest queued job that matches the labels to the runner,
254// or errNoJob. The assignment lock makes the choice and the write one step.
255func (c *CI) assignTo(ctx context.Context, runner domain.CIRunner, offered []string, pollID string) (*ports.RunnerJob, error) {
256 c.assign.Lock()
257 defer c.assign.Unlock()
258 ready, err := c.cfg.Store.ListReadyJobs(ctx, 0)
259 if err != nil {
260 return nil, err
261 }
262 for _, cand := range ready {
263 if !domain.LabelsMatch(cand.Labels, offered) {
264 continue
265 }
266 var out *ports.RunnerJob
267 err := c.withRun(ctx, cand.RunID, cand.RunAttempt, func(rs *runState) error {
268 j := rs.find(cand.ID)
269 if j == nil || j.Phase != domain.CIPhaseReady || rs.run.CancelRequested {
270 return errNoJob
271 }
272 // Before anything changes: a failure here leaves the job ready.
273 settings, err := c.settingsOf(ctx, rs, *j)
274 if err != nil {
275 return err
276 }
277 token := newToken(domain.JobTokenPrefix)
278 ghToken := rs.issueRepoToken(j)
279 j.Phase, j.AssignedAt = domain.CIPhaseAssigned, c.now()
280 j.TokenHash, j.TokenValidUntil = domain.HashTokenSecret(token), time.Time{}
281 j.RunnerID, j.RunnerName, j.Isolation = runner.ID, runner.Name, runner.Isolation
282 rs.touch(j)
283 if err := rs.flush(ctx); err != nil {
284 return err
285 }
286 out = c.runnerJob(rs, *j, token, ghToken, settings)
287 if pollID != "" {
288 c.mu.Lock()
289 c.polls[runner.ID] = pollRecord{pollID: pollID, ref: jobRef(*j), token: token, ghToken: ghToken, hash: j.TokenHash}
290 c.mu.Unlock()
291 }
292 return nil
293 })
294 switch {
295 case err == nil:
296 log := zerowrap.FromCtx(ctx)
297 log.Info().Str("runner", runner.Name).Str("job_id", out.Job.ID).Int64("run_id", out.Job.RunID).Msg("job assigned")
298 return out, nil
299 case isSettingsError(err):
300 return nil, err // the job stays ready; the runner polls again
301 case errors.Is(err, errNoJob), errors.Is(err, domain.ErrNotFound), errors.Is(err, domain.ErrConflict):
302 continue // taken or gone meanwhile
303 default:
304 return nil, err
305 }
306 }
307 return nil, errNoJob
308}
309
310// --- the calls of a job token ---
311
312// jobFor authenticates a job token and checks that it is the one of jobID.
313func (c *CI) jobFor(ctx context.Context, secret, jobID string) (domain.CIJob, error) {
314 if !domain.IsJobToken(secret) {
315 return domain.CIJob{}, domain.ErrUnauthenticated
316 }
317 j, err := c.cfg.Store.FindJobByToken(ctx, domain.HashTokenSecret(secret), c.now())
318 if errors.Is(err, domain.ErrNotFound) {
319 return domain.CIJob{}, domain.ErrUnauthenticated
320 }
321 if err != nil {
322 return domain.CIJob{}, err
323 }
324 if j.ID != jobID {
325 return domain.CIJob{}, fmt.Errorf("%w: this token is the token of another job", domain.ErrForbidden)
326 }
327 return j, nil
328}
329
330func endedError(j domain.CIJob) error {
331 return &domain.JobEndedError{Conclusion: j.Conclusion, Message: j.Error}
332}
333
334// lockedJob runs fn with the lock of the run and the job read again.
335func (c *CI) lockedJob(ctx context.Context, j domain.CIJob, fn func(cur *domain.CIJob) error) error {
336 lock := c.runLock(j.RunID)
337 lock.Lock()
338 defer lock.Unlock()
339 cur, err := c.cfg.Store.GetJob(ctx, j.RunID, j.RunAttempt, j.ID)
340 if err != nil {
341 return err
342 }
343 if err := sameAssignment(j, cur); err != nil {
344 return err
345 }
346 return fn(&cur)
347}
348
349// sameAssignment checks, under the lock of the run, that the job a token was
350// found for is still given under that token: an assignment cancelled and given
351// again since has a new one, and the old runner is unauthenticated. A job that
352// has ended answers with its end instead (the callers do).
353func sameAssignment(was, cur domain.CIJob) error {
354 if !cur.Ended() && cur.TokenHash != was.TokenHash {
355 return domain.ErrUnauthenticated
356 }
357 return nil
358}
359
360// saveJob writes one job (its steps changed) with the annotations that change
361// with it, and publishes JobUpdated. The status of the run does not depend on
362// steps.
363func (c *CI) saveJob(ctx context.Context, j *domain.CIJob, anns ...ports.CIStepAnnotations) error {
364 v, err := c.cfg.Store.Apply(ctx, ports.CIWrite{Jobs: []domain.CIJob{*j}, Annotations: anns})
365 if err != nil {
366 return fmt.Errorf("write job %s: %w", j.ID, err)
367 }
368 j.Version = v
369 if repo, err := c.cfg.Meta.Get(ctx, j.Repo); err == nil {
370 lines, _ := c.cfg.Logs.Count(ctx, logRef(*j))
371 c.cfg.Bus.Publish(ctx, domain.JobUpdated{Job: *j, Lines: lines, At: c.now(), Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
372 }
373 c.jobs.notify(jobRef(*j))
374 return nil
375}
376
377func logRef(j domain.CIJob) ports.CILogRef {
378 return ports.CILogRef{RunID: j.RunID, JobID: j.ID, Attempt: j.Attempt}
379}
380
381// UpdateJob applies the steps and the annotations of the request whole or not
382// at all. The annotations of each step they name replace those stored, whether
383// the step is completed or not.
384func (c *CI) UpdateJob(ctx context.Context, secret, jobID string, steps []ports.StepUpdate, annotations []domain.CIAnnotation) error {
385 j, err := c.jobFor(ctx, secret, jobID)
386 if err != nil {
387 return err
388 }
389 if j.Ended() {
390 return endedError(j)
391 }
392 if err := checkStepUpdates(steps); err != nil {
393 return err
394 }
395 if err := domain.CheckAnnotations(annotations); err != nil {
396 return err
397 }
398 return c.lockedJob(ctx, j, func(cur *domain.CIJob) error {
399 if cur.Ended() {
400 return endedError(*cur)
401 }
402 next, changed, err := applySteps(cur.Steps, steps)
403 if err != nil {
404 return err
405 }
406 writes, err := c.annotationWrites(ctx, *cur, annotations)
407 if err != nil {
408 return err
409 }
410 if !changed && len(writes) == 0 {
411 return nil
412 }
413 cur.Steps = next
414 return c.saveJob(ctx, cur, writes...)
415 })
416}
417
418// checkStepUpdates validates the shape of the steps of a request.
419func checkStepUpdates(steps []ports.StepUpdate) error {
420 if len(steps) > domain.CIMaxSteps {
421 return fmt.Errorf("%w: at most %d steps", domain.ErrInvalid, domain.CIMaxSteps)
422 }
423 for _, s := range steps {
424 if s.Number < 1 || s.Number > domain.CIMaxSteps {
425 return fmt.Errorf("%w: step number %d is not between 1 and %d", domain.ErrInvalid, s.Number, domain.CIMaxSteps)
426 }
427 switch s.State {
428 case domain.CIStepPending:
429 if s.Conclusion != domain.CINoConclusion || s.Outcome != domain.CINoConclusion {
430 return fmt.Errorf("%w: step %d is not completed: it has no conclusion or outcome", domain.ErrInvalid, s.Number)
431 }
432 case domain.CIStepInProgress:
433 if s.Conclusion != domain.CINoConclusion || s.Outcome != domain.CINoConclusion || s.StartedAt.IsZero() {
434 return fmt.Errorf("%w: step %d is in progress: started_at is required, conclusion and outcome are not allowed", domain.ErrInvalid, s.Number)
435 }
436 case domain.CIStepCompleted:
437 switch s.Conclusion {
438 case domain.CISuccess, domain.CIFailure, domain.CICancelled, domain.CISkipped:
439 default:
440 return fmt.Errorf("%w: step %d is completed: its conclusion must be success, failure, cancelled or skipped", domain.ErrInvalid, s.Number)
441 }
442 switch s.Outcome {
443 case domain.CINoConclusion, domain.CISuccess, domain.CIFailure, domain.CICancelled, domain.CISkipped:
444 default:
445 return fmt.Errorf("%w: step %d is completed: its outcome must be success, failure, cancelled or skipped", domain.ErrInvalid, s.Number)
446 }
447 if s.StartedAt.IsZero() && s.Conclusion != domain.CISkipped {
448 return fmt.Errorf("%w: step %d: started_at is required", domain.ErrInvalid, s.Number)
449 }
450 if s.CompletedAt.IsZero() {
451 return fmt.Errorf("%w: step %d is completed: completed_at is required", domain.ErrInvalid, s.Number)
452 }
453 default:
454 return fmt.Errorf("%w: step %d has no state", domain.ErrInvalid, s.Number)
455 }
456 }
457 return nil
458}
459
460// applySteps returns the steps after the updates, and whether anything
461// changed. The input is not modified.
462func applySteps(have []domain.CIStep, ups []ports.StepUpdate) ([]domain.CIStep, bool, error) {
463 out := slices.Clone(have)
464 changed := false
465 for _, u := range ups {
466 name := truncateRunes(u.Name, domain.CIMaxStepName)
467 i := slices.IndexFunc(out, func(s domain.CIStep) bool { return s.Number == u.Number })
468 if i < 0 {
469 out = append(out, domain.CIStep{
470 Number: u.Number, Name: name, State: u.State, Conclusion: u.Conclusion, Outcome: u.Outcome,
471 StartedAt: u.StartedAt, CompletedAt: u.CompletedAt,
472 })
473 changed = true
474 continue
475 }
476 cur := out[i]
477 next := cur
478 next.Name, next.State, next.Conclusion, next.Outcome = name, u.State, u.Conclusion, u.Outcome
479 next.StartedAt, next.CompletedAt = u.StartedAt, u.CompletedAt
480 if cur.Name != "" && name == "" {
481 next.Name = cur.Name // an empty name never erases one
482 }
483 switch {
484 case cur.State == domain.CIStepCompleted:
485 same := next.State == cur.State && next.Conclusion == cur.Conclusion && effectiveOutcome(next) == effectiveOutcome(cur) && next.Name == cur.Name &&
486 next.StartedAt.Equal(cur.StartedAt) && next.CompletedAt.Equal(cur.CompletedAt)
487 if !same {
488 return nil, false, fmt.Errorf("%w: step %d is completed: it cannot change", domain.ErrPreconditionFailed, u.Number)
489 }
490 continue
491 case cur.State == domain.CIStepInProgress && next.State == domain.CIStepPending:
492 return nil, false, fmt.Errorf("%w: step %d cannot go from in progress back to pending", domain.ErrPreconditionFailed, u.Number)
493 }
494 if !stepsEqual(cur, next) {
495 out[i], changed = next, true
496 }
497 }
498 slices.SortFunc(out, func(a, b domain.CIStep) int { return int(a.Number) - int(b.Number) })
499 return out, changed, nil
500}
501
502// effectiveOutcome is the outcome of a step, read as its conclusion when the
503// runner did not report one.
504func effectiveOutcome(s domain.CIStep) domain.CIConclusion {
505 if s.Outcome == domain.CINoConclusion {
506 return s.Conclusion
507 }
508 return s.Outcome
509}
510
511func stepsEqual(a, b domain.CIStep) bool {
512 return a.Number == b.Number && a.Name == b.Name && a.State == b.State && a.Conclusion == b.Conclusion && a.Outcome == b.Outcome &&
513 a.StartedAt.Equal(b.StartedAt) && a.CompletedAt.Equal(b.CompletedAt) && a.LogStart == b.LogStart && a.HasLines == b.HasLines
514}
515
516// lastLineStep returns the highest step number that has lines, 0 for none.
517func lastLineStep(steps []domain.CIStep) int32 {
518 var last int32
519 for _, s := range steps {
520 if s.HasLines {
521 last = max(last, s.Number)
522 }
523 }
524 return last
525}
526
527// checkLines validates the shape of the lines of an AppendLog request.
528func checkLines(step int32, offset int64, lines []domain.CILogLine) error {
529 if step < 1 || step > domain.CIMaxSteps {
530 return fmt.Errorf("%w: step %d is not between 1 and %d", domain.ErrInvalid, step, domain.CIMaxSteps)
531 }
532 if offset < 0 {
533 return fmt.Errorf("%w: negative offset", domain.ErrInvalid)
534 }
535 if len(lines) > domain.CIMaxLogLines {
536 return fmt.Errorf("%w: at most %d lines per request", domain.ErrInvalid, domain.CIMaxLogLines)
537 }
538 total := 0
539 for i, l := range lines {
540 if strings.ContainsRune(l.Text, '\n') || !utf8.ValidString(l.Text) {
541 return fmt.Errorf("%w: line %d has a line feed or is not valid UTF-8", domain.ErrInvalid, i)
542 }
543 if l.Time.IsZero() {
544 return fmt.Errorf("%w: line %d has no time", domain.ErrInvalid, i)
545 }
546 if l.Continued && offset == 0 && i == 0 {
547 return fmt.Errorf("%w: the first line of a job cannot be continued", domain.ErrInvalid)
548 }
549 total += len(l.Text)
550 }
551 if total > domain.CIMaxLogChunkBytes {
552 return fmt.Errorf("%w: at most %d bytes of text per request", domain.ErrInvalid, domain.CIMaxLogChunkBytes)
553 }
554 return nil
555}
556
557// AppendLog appends lines of a step to the log of the job; see runner.proto
558// for the rules of offsets. The metadata store is written only when a step
559// gets its first line.
560func (c *CI) AppendLog(ctx context.Context, secret, jobID string, step int32, offset int64, lines []domain.CILogLine) (int64, error) {
561 j, err := c.jobFor(ctx, secret, jobID)
562 if err != nil {
563 return 0, err
564 }
565 if j.Ended() {
566 return 0, endedError(j)
567 }
568 if err := checkLines(step, offset, lines); err != nil {
569 return 0, err
570 }
571 var next int64
572 limitHit := false
573 err = c.lockedJob(ctx, j, func(cur *domain.CIJob) error {
574 if cur.Ended() {
575 return endedError(*cur)
576 }
577 ref := logRef(*cur)
578 count, err := c.cfg.Logs.Count(ctx, ref)
579 if err != nil {
580 return err
581 }
582 if offset > count {
583 return &ports.ErrCILogGap{Count: count}
584 }
585 skip := count - offset
586 if skip >= int64(len(lines)) {
587 next = count // everything is stored already
588 return nil
589 }
590 last := lastLineStep(cur.Steps)
591 if step < last {
592 return fmt.Errorf("%w: step %d is below step %d, which already has lines", domain.ErrPreconditionFailed, step, last)
593 }
594 if first := lines[skip]; first.Continued && count > 0 && step != last {
595 return fmt.Errorf("%w: a continued line must be in the step of the line before it", domain.ErrPreconditionFailed)
596 }
597 n, added, err := c.cfg.Logs.Append(ctx, ref, offset, lines, domain.CIMaxLogBytes)
598 if errors.Is(err, ports.ErrCILogLimit) {
599 limitHit = true
600 return nil
601 }
602 if err != nil {
603 return err
604 }
605 next = n
606 if added == 0 {
607 return nil
608 }
609 return c.startStepLines(ctx, cur, step, count, lines[skip].Time)
610 })
611 if err != nil {
612 return 0, err
613 }
614 if limitHit {
615 return 0, c.stopForLogLimit(ctx, j)
616 }
617 return next, nil
618}
619
620// startStepLines records where the lines of a step begin, creating the step
621// when UpdateJob did not announce it.
622func (c *CI) startStepLines(ctx context.Context, cur *domain.CIJob, step int32, firstLine int64, at time.Time) error {
623 i := slices.IndexFunc(cur.Steps, func(s domain.CIStep) bool { return s.Number == step })
624 switch {
625 case i < 0:
626 cur.Steps = append(cur.Steps, domain.CIStep{
627 Number: step, State: domain.CIStepInProgress, StartedAt: at, HasLines: true, LogStart: firstLine,
628 })
629 slices.SortFunc(cur.Steps, func(a, b domain.CIStep) int { return int(a.Number) - int(b.Number) })
630 case cur.Steps[i].HasLines:
631 return nil
632 default:
633 cur.Steps[i].HasLines, cur.Steps[i].LogStart = true, firstLine
634 }
635 return c.saveJob(ctx, cur)
636}
637
638// stopForLogLimit ends a job whose log reached its limit: a last line says
639// so, the job fails, and the call answers like any call after the end.
640func (c *CI) stopForLogLimit(ctx context.Context, j domain.CIJob) error {
641 var ended *domain.JobEndedError
642 err := c.withRun(ctx, j.RunID, j.RunAttempt, func(rs *runState) error {
643 cur := rs.find(j.ID)
644 if cur == nil {
645 return domain.ErrNotFound
646 }
647 if cur.Ended() {
648 ended = &domain.JobEndedError{Conclusion: cur.Conclusion, Message: cur.Error}
649 return nil
650 }
651 if err := sameAssignment(j, *cur); err != nil {
652 return err
653 }
654 _, _ = c.cfg.Logs.AppendForced(ctx, logRef(*cur), []domain.CILogLine{{Time: c.now(), Text: "##[error]" + domain.CILogLimitMessage}})
655 rs.end(cur, domain.CIFailure, domain.CILogLimitMessage)
656 ended = &domain.JobEndedError{Conclusion: domain.CIFailure, Message: domain.CILogLimitMessage}
657 if err := rs.advance(ctx); err != nil {
658 return err
659 }
660 return rs.flush(ctx)
661 })
662 if err != nil {
663 return err
664 }
665 if ended == nil {
666 return domain.ErrNotFound // a typed nil would be taken for an error
667 }
668 return ended
669}
670
671// Heartbeat tells the server that the runner is alive. The first one
672// acknowledges the assignment; the others only move the deadline.
673func (c *CI) Heartbeat(ctx context.Context, secret, jobID string) error {
674 j, err := c.jobFor(ctx, secret, jobID)
675 if err != nil {
676 return err
677 }
678 if j.Ended() {
679 return endedError(j)
680 }
681 // Everything is done under the lock of the run: the acknowledgement, and
682 // the note of the heartbeat, which must not be written once the job ended
683 // (end() forgets it under the same lock).
684 return c.withRun(ctx, j.RunID, j.RunAttempt, func(rs *runState) error {
685 cur := rs.find(j.ID)
686 switch {
687 case cur == nil:
688 return domain.ErrUnauthenticated
689 case cur.Ended():
690 return endedError(*cur)
691 case cur.TokenHash != j.TokenHash:
692 return domain.ErrUnauthenticated // the assignment was cancelled and given again
693 }
694 now := c.now()
695 if cur.Phase == domain.CIPhaseAssigned {
696 cur.Phase, cur.AckedAt, cur.StartedAt, cur.AssignCancels = domain.CIPhaseRunning, now, now, 0
697 rs.touch(cur)
698 if err := rs.flush(ctx); err != nil {
699 return err
700 }
701 c.forgetPoll(jobRef(*cur)) // the token it holds is the runner's now
702 }
703 c.mu.Lock()
704 c.heartbeats[jobRef(*cur)] = now
705 c.seen[cur.RunnerID] = now
706 c.mu.Unlock()
707 return nil
708 })
709}
710
711// forgetPoll drops the remembered assignment (and its plaintext token) of a
712// job: after the acknowledgement or the cancel of the assignment, a retried
713// poll has nothing to repeat.
714func (c *CI) forgetPoll(ref string) {
715 c.mu.Lock()
716 defer c.mu.Unlock()
717 for id, p := range c.polls {
718 if p.ref == ref {
719 delete(c.polls, id)
720 }
721 }
722}
723
724// WatchJob streams what the runner must react to: the cancel request (the
725// first message when one is already pending), keepalives, and the end.
726func (c *CI) WatchJob(ctx context.Context, secret, jobID string, ready func(), send func(ports.JobSignal) error) error {
727 j, err := c.jobFor(ctx, secret, jobID)
728 if err != nil {
729 return err
730 }
731 if j.Ended() {
732 return endedError(j)
733 }
734 ref := jobRef(j)
735 keepalive := time.NewTicker(c.cfg.Keepalive)
736 defer keepalive.Stop()
737 cancelSent := false
738 if ready != nil {
739 ready()
740 }
741 for {
742 wake := c.jobs.wait(ref)
743 cur, err := c.cfg.Store.GetJob(ctx, j.RunID, j.RunAttempt, j.ID)
744 if err != nil {
745 return err
746 }
747 if cur.TokenHash != j.TokenHash && !cur.Ended() {
748 return domain.ErrUnauthenticated // given again
749 }
750 if cur.Ended() {
751 return send(ports.JobSignal{Ended: &domain.JobEndedError{Conclusion: cur.Conclusion, Message: cur.Error}})
752 }
753 if cur.CancelReason != domain.CICancelNone && !cancelSent {
754 cancelSent = true
755 if err := send(ports.JobSignal{Cancel: &ports.JobCancel{
756 Reason: cur.CancelReason, Message: cur.CancelMessage, RequestedAt: cur.CancelRequestedAt,
757 }}); err != nil {
758 return err
759 }
760 }
761 select {
762 case <-wake:
763 case <-keepalive.C:
764 if err := send(ports.JobSignal{Keepalive: true}); err != nil {
765 return err
766 }
767 case <-ctx.Done():
768 return nil
769 case <-c.ctx.Done():
770 return nil
771 }
772 }
773}
774
775// CompleteJob ends a job, once. A later call returns the stored result.
776func (c *CI) CompleteJob(ctx context.Context, secret string, params ports.CompleteJobParams) (ports.CompleteJobResult, error) {
777 j, err := c.jobFor(ctx, secret, params.JobID)
778 if err != nil {
779 return ports.CompleteJobResult{}, err
780 }
781 if j.Ended() {
782 return ports.CompleteJobResult{Conclusion: j.Conclusion, Error: j.Error}, nil
783 }
784 switch params.Conclusion {
785 case domain.CISuccess, domain.CIFailure, domain.CICancelled, domain.CITimedOut:
786 default:
787 return ports.CompleteJobResult{}, fmt.Errorf("%w: a runner reports success, failure, cancelled or timed_out", domain.ErrInvalid)
788 }
789 if params.RunnerShutdown && params.Conclusion != domain.CICancelled {
790 return ports.CompleteJobResult{}, fmt.Errorf("%w: runner_shutdown goes with cancelled", domain.ErrInvalid)
791 }
792 if err := domain.CheckOutputs(params.Outputs); err != nil {
793 return ports.CompleteJobResult{}, err
794 }
795 if err := checkStepUpdates(params.Steps); err != nil {
796 return ports.CompleteJobResult{}, err
797 }
798 if err := domain.CheckAnnotations(params.Annotations); err != nil {
799 return ports.CompleteJobResult{}, err
800 }
801 var res ports.CompleteJobResult
802 err = c.withRun(ctx, j.RunID, j.RunAttempt, func(rs *runState) error {
803 cur := rs.find(j.ID)
804 if cur == nil {
805 return domain.ErrNotFound
806 }
807 if cur.Ended() { // ended by the server since
808 res = ports.CompleteJobResult{Conclusion: cur.Conclusion, Error: cur.Error}
809 return nil
810 }
811 if err := sameAssignment(j, *cur); err != nil {
812 return err
813 }
814 steps, _, err := applySteps(cur.Steps, params.Steps)
815 if err != nil {
816 return err
817 }
818 writes, err := c.annotationWrites(ctx, *cur, params.Annotations)
819 if err != nil {
820 return err
821 }
822 rs.annotations = append(rs.annotations, writes...)
823 cur.Steps = steps
824 cur.Outputs = params.Outputs
825 msg := ""
826 if params.RunnerShutdown {
827 msg = domain.CIShutdownMessage
828 }
829 rs.end(cur, params.Conclusion, msg)
830 if err := rs.advance(ctx); err != nil {
831 return err
832 }
833 res = ports.CompleteJobResult{Conclusion: cur.Conclusion, Error: cur.Error, Applied: true}
834 return rs.flush(ctx)
835 })
836 if err != nil {
837 return ports.CompleteJobResult{}, err
838 }
839 if res.Applied {
840 log := zerowrap.FromCtx(ctx)
841 log.Info().Str("job_id", j.ID).Int64("run_id", j.RunID).Str("conclusion", string(res.Conclusion)).Msg("job completed")
842 }
843 return res, nil
844}