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 }
250}
251
252// assignTo gives the oldest queued job that matches the labels to the runner,
253// or errNoJob. The assignment lock makes the choice and the write one step.
254func (c *CI) assignTo(ctx context.Context, runner domain.CIRunner, offered []string, pollID string) (*ports.RunnerJob, error) {
255 c.assign.Lock()
256 defer c.assign.Unlock()
257 ready, err := c.cfg.Store.ListReadyJobs(ctx, 0)
258 if err != nil {
259 return nil, err
260 }
261 for _, cand := range ready {
262 if !domain.LabelsMatch(cand.Labels, offered) {
263 continue
264 }
265 var out *ports.RunnerJob
266 err := c.withRun(ctx, cand.RunID, cand.RunAttempt, func(rs *runState) error {
267 j := rs.find(cand.ID)
268 if j == nil || j.Phase != domain.CIPhaseReady || rs.run.CancelRequested {
269 return errNoJob
270 }
271 // Before anything changes: a failure here leaves the job ready.
272 settings, err := c.settingsOf(ctx, rs, *j)
273 if err != nil {
274 return err
275 }
276 token := newToken(domain.JobTokenPrefix)
277 ghToken := rs.issueRepoToken(j)
278 j.Phase, j.AssignedAt = domain.CIPhaseAssigned, c.now()
279 j.TokenHash, j.TokenValidUntil = domain.HashTokenSecret(token), time.Time{}
280 j.RunnerID, j.RunnerName, j.Isolation = runner.ID, runner.Name, runner.Isolation
281 rs.touch(j)
282 if err := rs.flush(ctx); err != nil {
283 return err
284 }
285 out = c.runnerJob(rs, *j, token, ghToken, settings)
286 if pollID != "" {
287 c.mu.Lock()
288 c.polls[runner.ID] = pollRecord{pollID: pollID, ref: jobRef(*j), token: token, ghToken: ghToken, hash: j.TokenHash}
289 c.mu.Unlock()
290 }
291 return nil
292 })
293 switch {
294 case err == nil:
295 log := zerowrap.FromCtx(ctx)
296 log.Info().Str("runner", runner.Name).Str("job_id", out.Job.ID).Int64("run_id", out.Job.RunID).Msg("job assigned")
297 return out, nil
298 case isSettingsError(err):
299 return nil, err // the job stays ready; the runner polls again
300 case errors.Is(err, errNoJob), errors.Is(err, domain.ErrNotFound), errors.Is(err, domain.ErrConflict):
301 continue // taken or gone meanwhile
302 default:
303 return nil, err
304 }
305 }
306 return nil, errNoJob
307}
308
309// --- the calls of a job token ---
310
311// jobFor authenticates a job token and checks that it is the one of jobID.
312func (c *CI) jobFor(ctx context.Context, secret, jobID string) (domain.CIJob, error) {
313 if !domain.IsJobToken(secret) {
314 return domain.CIJob{}, domain.ErrUnauthenticated
315 }
316 j, err := c.cfg.Store.FindJobByToken(ctx, domain.HashTokenSecret(secret), c.now())
317 if errors.Is(err, domain.ErrNotFound) {
318 return domain.CIJob{}, domain.ErrUnauthenticated
319 }
320 if err != nil {
321 return domain.CIJob{}, err
322 }
323 if j.ID != jobID {
324 return domain.CIJob{}, fmt.Errorf("%w: this token is the token of another job", domain.ErrForbidden)
325 }
326 return j, nil
327}
328
329func endedError(j domain.CIJob) error {
330 return &domain.JobEndedError{Conclusion: j.Conclusion, Message: j.Error}
331}
332
333// lockedJob runs fn with the lock of the run and the job read again.
334func (c *CI) lockedJob(ctx context.Context, j domain.CIJob, fn func(cur *domain.CIJob) error) error {
335 lock := c.runLock(j.RunID)
336 lock.Lock()
337 defer lock.Unlock()
338 cur, err := c.cfg.Store.GetJob(ctx, j.RunID, j.RunAttempt, j.ID)
339 if err != nil {
340 return err
341 }
342 if err := sameAssignment(j, cur); err != nil {
343 return err
344 }
345 return fn(&cur)
346}
347
348// sameAssignment checks, under the lock of the run, that the job a token was
349// found for is still given under that token: an assignment cancelled and given
350// again since has a new one, and the old runner is unauthenticated. A job that
351// has ended answers with its end instead (the callers do).
352func sameAssignment(was, cur domain.CIJob) error {
353 if !cur.Ended() && cur.TokenHash != was.TokenHash {
354 return domain.ErrUnauthenticated
355 }
356 return nil
357}
358
359// saveJob writes one job (its steps changed) with the annotations that change
360// with it, and publishes JobUpdated. The status of the run does not depend on
361// steps.
362func (c *CI) saveJob(ctx context.Context, j *domain.CIJob, anns ...ports.CIStepAnnotations) error {
363 v, err := c.cfg.Store.Apply(ctx, ports.CIWrite{Jobs: []domain.CIJob{*j}, Annotations: anns})
364 if err != nil {
365 return fmt.Errorf("write job %s: %w", j.ID, err)
366 }
367 j.Version = v
368 if repo, err := c.cfg.Meta.Get(ctx, j.Repo); err == nil {
369 lines, _ := c.cfg.Logs.Count(ctx, logRef(*j))
370 c.cfg.Bus.Publish(ctx, domain.JobUpdated{Job: *j, Lines: lines, At: c.now(), Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
371 }
372 c.jobs.notify(jobRef(*j))
373 return nil
374}
375
376func logRef(j domain.CIJob) ports.CILogRef {
377 return ports.CILogRef{RunID: j.RunID, JobID: j.ID, Attempt: j.Attempt}
378}
379
380// UpdateJob applies the steps and the annotations of the request whole or not
381// at all. The annotations of each step they name replace those stored, whether
382// the step is completed or not.
383func (c *CI) UpdateJob(ctx context.Context, secret, jobID string, steps []ports.StepUpdate, annotations []domain.CIAnnotation) error {
384 j, err := c.jobFor(ctx, secret, jobID)
385 if err != nil {
386 return err
387 }
388 if j.Ended() {
389 return endedError(j)
390 }
391 if err := checkStepUpdates(steps); err != nil {
392 return err
393 }
394 if err := domain.CheckAnnotations(annotations); err != nil {
395 return err
396 }
397 return c.lockedJob(ctx, j, func(cur *domain.CIJob) error {
398 if cur.Ended() {
399 return endedError(*cur)
400 }
401 next, changed, err := applySteps(cur.Steps, steps)
402 if err != nil {
403 return err
404 }
405 writes, err := c.annotationWrites(ctx, *cur, annotations)
406 if err != nil {
407 return err
408 }
409 if !changed && len(writes) == 0 {
410 return nil
411 }
412 cur.Steps = next
413 return c.saveJob(ctx, cur, writes...)
414 })
415}
416
417// checkStepUpdates validates the shape of the steps of a request.
418func checkStepUpdates(steps []ports.StepUpdate) error {
419 if len(steps) > domain.CIMaxSteps {
420 return fmt.Errorf("%w: at most %d steps", domain.ErrInvalid, domain.CIMaxSteps)
421 }
422 for _, s := range steps {
423 if s.Number < 1 || s.Number > domain.CIMaxSteps {
424 return fmt.Errorf("%w: step number %d is not between 1 and %d", domain.ErrInvalid, s.Number, domain.CIMaxSteps)
425 }
426 switch s.State {
427 case domain.CIStepPending:
428 if s.Conclusion != domain.CINoConclusion || s.Outcome != domain.CINoConclusion {
429 return fmt.Errorf("%w: step %d is not completed: it has no conclusion or outcome", domain.ErrInvalid, s.Number)
430 }
431 case domain.CIStepInProgress:
432 if s.Conclusion != domain.CINoConclusion || s.Outcome != domain.CINoConclusion || s.StartedAt.IsZero() {
433 return fmt.Errorf("%w: step %d is in progress: started_at is required, conclusion and outcome are not allowed", domain.ErrInvalid, s.Number)
434 }
435 case domain.CIStepCompleted:
436 switch s.Conclusion {
437 case domain.CISuccess, domain.CIFailure, domain.CICancelled, domain.CISkipped:
438 default:
439 return fmt.Errorf("%w: step %d is completed: its conclusion must be success, failure, cancelled or skipped", domain.ErrInvalid, s.Number)
440 }
441 switch s.Outcome {
442 case domain.CINoConclusion, domain.CISuccess, domain.CIFailure, domain.CICancelled, domain.CISkipped:
443 default:
444 return fmt.Errorf("%w: step %d is completed: its outcome must be success, failure, cancelled or skipped", domain.ErrInvalid, s.Number)
445 }
446 if s.StartedAt.IsZero() && s.Conclusion != domain.CISkipped {
447 return fmt.Errorf("%w: step %d: started_at is required", domain.ErrInvalid, s.Number)
448 }
449 if s.CompletedAt.IsZero() {
450 return fmt.Errorf("%w: step %d is completed: completed_at is required", domain.ErrInvalid, s.Number)
451 }
452 default:
453 return fmt.Errorf("%w: step %d has no state", domain.ErrInvalid, s.Number)
454 }
455 }
456 return nil
457}
458
459// applySteps returns the steps after the updates, and whether anything
460// changed. The input is not modified.
461func applySteps(have []domain.CIStep, ups []ports.StepUpdate) ([]domain.CIStep, bool, error) {
462 out := slices.Clone(have)
463 changed := false
464 for _, u := range ups {
465 name := truncateRunes(u.Name, domain.CIMaxStepName)
466 i := slices.IndexFunc(out, func(s domain.CIStep) bool { return s.Number == u.Number })
467 if i < 0 {
468 out = append(out, domain.CIStep{
469 Number: u.Number, Name: name, State: u.State, Conclusion: u.Conclusion, Outcome: u.Outcome,
470 StartedAt: u.StartedAt, CompletedAt: u.CompletedAt,
471 })
472 changed = true
473 continue
474 }
475 cur := out[i]
476 next := cur
477 next.Name, next.State, next.Conclusion, next.Outcome = name, u.State, u.Conclusion, u.Outcome
478 next.StartedAt, next.CompletedAt = u.StartedAt, u.CompletedAt
479 if cur.Name != "" && name == "" {
480 next.Name = cur.Name // an empty name never erases one
481 }
482 switch {
483 case cur.State == domain.CIStepCompleted:
484 same := next.State == cur.State && next.Conclusion == cur.Conclusion && effectiveOutcome(next) == effectiveOutcome(cur) && next.Name == cur.Name &&
485 next.StartedAt.Equal(cur.StartedAt) && next.CompletedAt.Equal(cur.CompletedAt)
486 if !same {
487 return nil, false, fmt.Errorf("%w: step %d is completed: it cannot change", domain.ErrPreconditionFailed, u.Number)
488 }
489 continue
490 case cur.State == domain.CIStepInProgress && next.State == domain.CIStepPending:
491 return nil, false, fmt.Errorf("%w: step %d cannot go from in progress back to pending", domain.ErrPreconditionFailed, u.Number)
492 }
493 if !stepsEqual(cur, next) {
494 out[i], changed = next, true
495 }
496 }
497 slices.SortFunc(out, func(a, b domain.CIStep) int { return int(a.Number) - int(b.Number) })
498 return out, changed, nil
499}
500
501// effectiveOutcome is the outcome of a step, read as its conclusion when the
502// runner did not report one.
503func effectiveOutcome(s domain.CIStep) domain.CIConclusion {
504 if s.Outcome == domain.CINoConclusion {
505 return s.Conclusion
506 }
507 return s.Outcome
508}
509
510func stepsEqual(a, b domain.CIStep) bool {
511 return a.Number == b.Number && a.Name == b.Name && a.State == b.State && a.Conclusion == b.Conclusion && a.Outcome == b.Outcome &&
512 a.StartedAt.Equal(b.StartedAt) && a.CompletedAt.Equal(b.CompletedAt) && a.LogStart == b.LogStart && a.HasLines == b.HasLines
513}
514
515// lastLineStep returns the highest step number that has lines, 0 for none.
516func lastLineStep(steps []domain.CIStep) int32 {
517 var last int32
518 for _, s := range steps {
519 if s.HasLines {
520 last = max(last, s.Number)
521 }
522 }
523 return last
524}
525
526// checkLines validates the shape of the lines of an AppendLog request.
527func checkLines(step int32, offset int64, lines []domain.CILogLine) error {
528 if step < 1 || step > domain.CIMaxSteps {
529 return fmt.Errorf("%w: step %d is not between 1 and %d", domain.ErrInvalid, step, domain.CIMaxSteps)
530 }
531 if offset < 0 {
532 return fmt.Errorf("%w: negative offset", domain.ErrInvalid)
533 }
534 if len(lines) > domain.CIMaxLogLines {
535 return fmt.Errorf("%w: at most %d lines per request", domain.ErrInvalid, domain.CIMaxLogLines)
536 }
537 total := 0
538 for i, l := range lines {
539 if strings.ContainsRune(l.Text, '\n') || !utf8.ValidString(l.Text) {
540 return fmt.Errorf("%w: line %d has a line feed or is not valid UTF-8", domain.ErrInvalid, i)
541 }
542 if l.Time.IsZero() {
543 return fmt.Errorf("%w: line %d has no time", domain.ErrInvalid, i)
544 }
545 if l.Continued && offset == 0 && i == 0 {
546 return fmt.Errorf("%w: the first line of a job cannot be continued", domain.ErrInvalid)
547 }
548 total += len(l.Text)
549 }
550 if total > domain.CIMaxLogChunkBytes {
551 return fmt.Errorf("%w: at most %d bytes of text per request", domain.ErrInvalid, domain.CIMaxLogChunkBytes)
552 }
553 return nil
554}
555
556// AppendLog appends lines of a step to the log of the job; see runner.proto
557// for the rules of offsets. The metadata store is written only when a step
558// gets its first line.
559func (c *CI) AppendLog(ctx context.Context, secret, jobID string, step int32, offset int64, lines []domain.CILogLine) (int64, error) {
560 j, err := c.jobFor(ctx, secret, jobID)
561 if err != nil {
562 return 0, err
563 }
564 if j.Ended() {
565 return 0, endedError(j)
566 }
567 if err := checkLines(step, offset, lines); err != nil {
568 return 0, err
569 }
570 var next int64
571 limitHit := false
572 err = c.lockedJob(ctx, j, func(cur *domain.CIJob) error {
573 if cur.Ended() {
574 return endedError(*cur)
575 }
576 ref := logRef(*cur)
577 count, err := c.cfg.Logs.Count(ctx, ref)
578 if err != nil {
579 return err
580 }
581 if offset > count {
582 return &ports.ErrCILogGap{Count: count}
583 }
584 skip := count - offset
585 if skip >= int64(len(lines)) {
586 next = count // everything is stored already
587 return nil
588 }
589 last := lastLineStep(cur.Steps)
590 if step < last {
591 return fmt.Errorf("%w: step %d is below step %d, which already has lines", domain.ErrPreconditionFailed, step, last)
592 }
593 if first := lines[skip]; first.Continued && count > 0 && step != last {
594 return fmt.Errorf("%w: a continued line must be in the step of the line before it", domain.ErrPreconditionFailed)
595 }
596 n, added, err := c.cfg.Logs.Append(ctx, ref, offset, lines, domain.CIMaxLogBytes)
597 if errors.Is(err, ports.ErrCILogLimit) {
598 limitHit = true
599 return nil
600 }
601 if err != nil {
602 return err
603 }
604 next = n
605 if added == 0 {
606 return nil
607 }
608 return c.startStepLines(ctx, cur, step, count, lines[skip].Time)
609 })
610 if err != nil {
611 return 0, err
612 }
613 if limitHit {
614 return 0, c.stopForLogLimit(ctx, j)
615 }
616 return next, nil
617}
618
619// startStepLines records where the lines of a step begin, creating the step
620// when UpdateJob did not announce it.
621func (c *CI) startStepLines(ctx context.Context, cur *domain.CIJob, step int32, firstLine int64, at time.Time) error {
622 i := slices.IndexFunc(cur.Steps, func(s domain.CIStep) bool { return s.Number == step })
623 switch {
624 case i < 0:
625 cur.Steps = append(cur.Steps, domain.CIStep{
626 Number: step, State: domain.CIStepInProgress, StartedAt: at, HasLines: true, LogStart: firstLine,
627 })
628 slices.SortFunc(cur.Steps, func(a, b domain.CIStep) int { return int(a.Number) - int(b.Number) })
629 case cur.Steps[i].HasLines:
630 return nil
631 default:
632 cur.Steps[i].HasLines, cur.Steps[i].LogStart = true, firstLine
633 }
634 return c.saveJob(ctx, cur)
635}
636
637// stopForLogLimit ends a job whose log reached its limit: a last line says
638// so, the job fails, and the call answers like any call after the end.
639func (c *CI) stopForLogLimit(ctx context.Context, j domain.CIJob) error {
640 var ended *domain.JobEndedError
641 err := c.withRun(ctx, j.RunID, j.RunAttempt, func(rs *runState) error {
642 cur := rs.find(j.ID)
643 if cur == nil {
644 return domain.ErrNotFound
645 }
646 if cur.Ended() {
647 ended = &domain.JobEndedError{Conclusion: cur.Conclusion, Message: cur.Error}
648 return nil
649 }
650 if err := sameAssignment(j, *cur); err != nil {
651 return err
652 }
653 _, _ = c.cfg.Logs.AppendForced(ctx, logRef(*cur), []domain.CILogLine{{Time: c.now(), Text: "##[error]" + domain.CILogLimitMessage}})
654 rs.end(cur, domain.CIFailure, domain.CILogLimitMessage)
655 ended = &domain.JobEndedError{Conclusion: domain.CIFailure, Message: domain.CILogLimitMessage}
656 if err := rs.advance(ctx); err != nil {
657 return err
658 }
659 return rs.flush(ctx)
660 })
661 if err != nil {
662 return err
663 }
664 if ended == nil {
665 return domain.ErrNotFound // a typed nil would be taken for an error
666 }
667 return ended
668}
669
670// Heartbeat tells the server that the runner is alive. The first one
671// acknowledges the assignment; the others only move the deadline.
672func (c *CI) Heartbeat(ctx context.Context, secret, jobID string) error {
673 j, err := c.jobFor(ctx, secret, jobID)
674 if err != nil {
675 return err
676 }
677 if j.Ended() {
678 return endedError(j)
679 }
680 // Everything is done under the lock of the run: the acknowledgement, and
681 // the note of the heartbeat, which must not be written once the job ended
682 // (end() forgets it under the same lock).
683 return c.withRun(ctx, j.RunID, j.RunAttempt, func(rs *runState) error {
684 cur := rs.find(j.ID)
685 switch {
686 case cur == nil:
687 return domain.ErrUnauthenticated
688 case cur.Ended():
689 return endedError(*cur)
690 case cur.TokenHash != j.TokenHash:
691 return domain.ErrUnauthenticated // the assignment was cancelled and given again
692 }
693 now := c.now()
694 if cur.Phase == domain.CIPhaseAssigned {
695 cur.Phase, cur.AckedAt, cur.StartedAt, cur.AssignCancels = domain.CIPhaseRunning, now, now, 0
696 rs.touch(cur)
697 if err := rs.flush(ctx); err != nil {
698 return err
699 }
700 c.forgetPoll(jobRef(*cur)) // the token it holds is the runner's now
701 }
702 c.mu.Lock()
703 c.heartbeats[jobRef(*cur)] = now
704 c.seen[cur.RunnerID] = now
705 c.mu.Unlock()
706 return nil
707 })
708}
709
710// forgetPoll drops the remembered assignment (and its plaintext token) of a
711// job: after the acknowledgement or the cancel of the assignment, a retried
712// poll has nothing to repeat.
713func (c *CI) forgetPoll(ref string) {
714 c.mu.Lock()
715 defer c.mu.Unlock()
716 for id, p := range c.polls {
717 if p.ref == ref {
718 delete(c.polls, id)
719 }
720 }
721}
722
723// WatchJob streams what the runner must react to: the cancel request (the
724// first message when one is already pending), keepalives, and the end.
725func (c *CI) WatchJob(ctx context.Context, secret, jobID string, ready func(), send func(ports.JobSignal) error) error {
726 j, err := c.jobFor(ctx, secret, jobID)
727 if err != nil {
728 return err
729 }
730 if j.Ended() {
731 return endedError(j)
732 }
733 ref := jobRef(j)
734 keepalive := time.NewTicker(c.cfg.Keepalive)
735 defer keepalive.Stop()
736 cancelSent := false
737 if ready != nil {
738 ready()
739 }
740 for {
741 wake := c.jobs.wait(ref)
742 cur, err := c.cfg.Store.GetJob(ctx, j.RunID, j.RunAttempt, j.ID)
743 if err != nil {
744 return err
745 }
746 if cur.TokenHash != j.TokenHash && !cur.Ended() {
747 return domain.ErrUnauthenticated // given again
748 }
749 if cur.Ended() {
750 return send(ports.JobSignal{Ended: &domain.JobEndedError{Conclusion: cur.Conclusion, Message: cur.Error}})
751 }
752 if cur.CancelReason != domain.CICancelNone && !cancelSent {
753 cancelSent = true
754 if err := send(ports.JobSignal{Cancel: &ports.JobCancel{
755 Reason: cur.CancelReason, Message: cur.CancelMessage, RequestedAt: cur.CancelRequestedAt,
756 }}); err != nil {
757 return err
758 }
759 }
760 select {
761 case <-wake:
762 case <-keepalive.C:
763 if err := send(ports.JobSignal{Keepalive: true}); err != nil {
764 return err
765 }
766 case <-ctx.Done():
767 return nil
768 case <-c.ctx.Done():
769 return nil
770 }
771 }
772}
773
774// CompleteJob ends a job, once. A later call returns the stored result.
775func (c *CI) CompleteJob(ctx context.Context, secret string, params ports.CompleteJobParams) (ports.CompleteJobResult, error) {
776 j, err := c.jobFor(ctx, secret, params.JobID)
777 if err != nil {
778 return ports.CompleteJobResult{}, err
779 }
780 if j.Ended() {
781 return ports.CompleteJobResult{Conclusion: j.Conclusion, Error: j.Error}, nil
782 }
783 switch params.Conclusion {
784 case domain.CISuccess, domain.CIFailure, domain.CICancelled, domain.CITimedOut:
785 default:
786 return ports.CompleteJobResult{}, fmt.Errorf("%w: a runner reports success, failure, cancelled or timed_out", domain.ErrInvalid)
787 }
788 if params.RunnerShutdown && params.Conclusion != domain.CICancelled {
789 return ports.CompleteJobResult{}, fmt.Errorf("%w: runner_shutdown goes with cancelled", domain.ErrInvalid)
790 }
791 if err := domain.CheckOutputs(params.Outputs); err != nil {
792 return ports.CompleteJobResult{}, err
793 }
794 if err := checkStepUpdates(params.Steps); err != nil {
795 return ports.CompleteJobResult{}, err
796 }
797 if err := domain.CheckAnnotations(params.Annotations); err != nil {
798 return ports.CompleteJobResult{}, err
799 }
800 var res ports.CompleteJobResult
801 err = c.withRun(ctx, j.RunID, j.RunAttempt, func(rs *runState) error {
802 cur := rs.find(j.ID)
803 if cur == nil {
804 return domain.ErrNotFound
805 }
806 if cur.Ended() { // ended by the server since
807 res = ports.CompleteJobResult{Conclusion: cur.Conclusion, Error: cur.Error}
808 return nil
809 }
810 if err := sameAssignment(j, *cur); err != nil {
811 return err
812 }
813 steps, _, err := applySteps(cur.Steps, params.Steps)
814 if err != nil {
815 return err
816 }
817 writes, err := c.annotationWrites(ctx, *cur, params.Annotations)
818 if err != nil {
819 return err
820 }
821 rs.annotations = append(rs.annotations, writes...)
822 cur.Steps = steps
823 cur.Outputs = params.Outputs
824 msg := ""
825 if params.RunnerShutdown {
826 msg = domain.CIShutdownMessage
827 }
828 rs.end(cur, params.Conclusion, msg)
829 if err := rs.advance(ctx); err != nil {
830 return err
831 }
832 res = ports.CompleteJobResult{Conclusion: cur.Conclusion, Error: cur.Error, Applied: true}
833 return rs.flush(ctx)
834 })
835 if err != nil {
836 return ports.CompleteJobResult{}, err
837 }
838 if res.Applied {
839 log := zerowrap.FromCtx(ctx)
840 log.Info().Str("job_id", j.ID).Int64("run_id", j.RunID).Str("conclusion", string(res.Conclusion)).Msg("job completed")
841 }
842 return res, nil
843}