// Package runner voert pipelinejobs uit, elk in een eigen Docker-container. package runner import ( "bytes" "context" "fmt" "io" "log/slog" "os" "os/exec" "path/filepath" "strings" "sync" "time" "gitlab.com/Timfa/bluegit/internal/access" "gitlab.com/Timfa/bluegit/internal/ci" "gitlab.com/Timfa/bluegit/internal/gitrepo" "gitlab.com/Timfa/bluegit/internal/store" "gitlab.com/Timfa/bluegit/internal/webhook" ) // Runner plant jobs en stuurt het resultaat door naar webhooks. type Runner struct { Store *store.Store GitBin string Docker string Storage string BaseURL string Network string Timeout time.Duration Log *slog.Logger OnEvent func(repoID int64, ev webhook.Event) slots chan struct{} mu sync.RWMutex } // SetStorage wijzigt het pad waarop jobs hun clone en artifacts zetten. func (r *Runner) SetStorage(path string) { r.mu.Lock() r.Storage = path r.mu.Unlock() } func (r *Runner) storage() string { r.mu.RLock() defer r.mu.RUnlock() return r.Storage } // Loop blijft jobs oppakken tot ctx afloopt. func (r *Runner) Loop(ctx context.Context, concurrency int) { if concurrency < 1 { concurrency = 1 } r.slots = make(chan struct{}, concurrency) tick := time.NewTicker(2 * time.Second) defer tick.Stop() for { select { case <-ctx.Done(): return case <-tick.C: r.Tick(ctx) } } } // Tick bekijkt alle open pipelines één keer. // Zonder opslagpad gebeurt er niets. func (r *Runner) Tick(ctx context.Context) { if r.storage() == "" { return } pipes, err := r.Store.ActivePipelines(ctx) if err != nil { r.Log.Error("pipelines", "err", err) return } for _, p := range pipes { r.schedule(ctx, p) } } func (r *Runner) schedule(ctx context.Context, p store.Pipeline) { r.settle(ctx, p.ID) jobs, err := r.Store.JobsByPipeline(ctx, p.ID) if err != nil { r.Log.Error("jobs", "err", err) return } specs := make([]ci.Job, len(jobs)) status := map[string]string{} for i, j := range jobs { specs[i] = ci.Job{Name: j.Name, Stage: j.Stage, Needs: j.Needs, Optional: j.Optional, NeedsSet: j.NeedsSet, AllowFailure: j.AllowFailure, When: j.When} status[j.Name] = j.Status } for _, j := range jobs { if j.Status != "queued" && j.Status != "manual" { continue } switch ci.Gate(specs, status, specs[indexOf(jobs, j.Name)]) { case "skip": _ = r.Store.SkipJob(ctx, j.ID, "skipped because an earlier job failed\n") status[j.Name] = "skipped" case "fail": _ = r.Store.FinishJob(ctx, j.ID, "failed", "a required job is not part of this pipeline\n") status[j.Name] = "failed" case "ready": if j.Status != "queued" { continue } if busy, _ := r.Store.ResourceBusy(ctx, j.RepoID, j.ResourceGroup, j.ID); busy { continue } ok, err := r.Store.MarkJobRunning(ctx, j.ID) if err != nil || !ok { continue } status[j.Name] = "running" job := j pipe := p go r.execute(ctx, pipe, job) } } } // settle slaat jobs over die door een harde mislukking niet meer hoeven. // Dat gebeurt meteen, ook als de pipelinestatus al op failed was gezet. func (r *Runner) settle(ctx context.Context, pipelineID int64) { for { jobs, err := r.Store.JobsByPipeline(ctx, pipelineID) if err != nil { if r.Log != nil { r.Log.Error("jobs", "err", err) } return } specs := make([]ci.Job, len(jobs)) status := map[string]string{} for i, j := range jobs { specs[i] = ci.Job{Name: j.Name, Stage: j.Stage, Needs: j.Needs, Optional: j.Optional, NeedsSet: j.NeedsSet, AllowFailure: j.AllowFailure, When: j.When} status[j.Name] = j.Status } moved := false for _, j := range jobs { if j.Status != "queued" && j.Status != "manual" { continue } switch ci.Gate(specs, status, specs[indexOf(jobs, j.Name)]) { case "skip": if err := r.Store.SkipJob(ctx, j.ID, "skipped because an earlier job failed\n"); err != nil && r.Log != nil { r.Log.Error("skip", "err", err) continue } status[j.Name] = "skipped" moved = true case "fail": if err := r.Store.FinishJob(ctx, j.ID, "failed", "a required job is not part of this pipeline\n"); err != nil && r.Log != nil { r.Log.Error("fail", "err", err) continue } status[j.Name] = "failed" moved = true } } if !moved { return } } } func indexOf(jobs []store.Job, name string) int { for i, j := range jobs { if j.Name == name { return i } } return 0 } func (r *Runner) execute(ctx context.Context, p store.Pipeline, job store.Job) { if r.slots != nil { r.slots <- struct{}{} defer func() { <-r.slots }() } before, _ := r.Store.PipelineByID(context.Background(), p.RepoID, p.ID) mask, err := r.runOne(ctx, p, job) status := "success" extra := "" if err != nil { status = "failed" extra = stamp(ci.Mask(err.Error(), mask)) } if ferr := r.Store.FinishJob(context.Background(), job.ID, status, extra); ferr != nil { r.Log.Error("job afronden", "err", ferr) } r.settle(context.Background(), p.ID) final, rerr := r.Store.RefreshPipelineStatus(context.Background(), p.ID) if rerr != nil { r.Log.Error("pipelinestatus", "err", rerr) return } if before.Status != final && (final == "success" || final == "failed") && r.OnEvent != nil { kind := webhook.EventPipelineSuccess word := "geslaagd" if final == "failed" { kind = webhook.EventPipelineFailure word = "mislukt" } repo, err := r.Store.RepoByID(context.Background(), p.RepoID) if err != nil { return } branch, _ := gitrepo.BranchOfRef(p.Ref) if branch == "" { branch = strings.TrimPrefix(p.Ref, "refs/heads/") } r.OnEvent(p.RepoID, webhook.Event{ Type: kind, Project: repo.FullPath(), Branch: branch, Commit: p.CommitSHA, Summary: fmt.Sprintf("pipeline #%d voor %s is %s", p.ID, repo.FullPath(), word), URL: strings.TrimRight(r.BaseURL, "/") + "/" + repo.FullPath() + "/-/pipelines/" + fmt.Sprint(p.ID), PipelineID: fmt.Sprint(p.ID), }) } } func (r *Runner) runOne(ctx context.Context, p store.Pipeline, job store.Job) ([]string, error) { limit := r.Timeout if job.Timeout > 0 { limit = job.Timeout } if limit > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, limit) defer cancel() } repo, err := r.Store.RepoByID(ctx, p.RepoID) if err != nil { return nil, err } sink := &logSink{store: r.Store, jobID: job.ID} sink.section("prepare", "Preparing the docker executor") work := filepath.Join(r.storage(), "work", fmt.Sprint(p.ID), job.Name) _ = os.RemoveAll(work) if err := os.MkdirAll(work, 0o755); err != nil { sink.closeSection() return nil, err } bare := gitrepo.Dir(r.storage(), repo.OwnerPath, repo.Name) if _, err := execOut(ctx, r.GitBin, "clone", "--local", bare, work); err != nil { sink.closeSection() return nil, fmt.Errorf("clone: %w", err) } if _, err := execOut(ctx, r.GitBin, "-C", work, "checkout", "--detach", p.CommitSHA); err != nil { sink.closeSection() return nil, fmt.Errorf("checkout %s: %w", p.CommitSHA, err) } if err := r.restoreCache(repo.ID, job, work); err != nil { sink.closeSection() return nil, err } if err := r.materialize(ctx, p, job, work); err != nil { sink.closeSection() return nil, err } scriptPath := filepath.Join(work, ".bluegit-job.sh") if err := os.WriteFile(scriptPath, []byte(shellScript(job)), 0o755); err != nil { sink.closeSection() return nil, err } token, err := r.Store.CreateJobToken(ctx, job.ID) if err != nil { sink.closeSection() return nil, err } env, mask, err := r.environment(ctx, repo, p, job, token) if err != nil { sink.closeSection() return nil, err } sink.secrets = mask if _, err := exec.LookPath(r.Docker); err != nil { sink.closeSection() return mask, fmt.Errorf("docker (%s) is not available; the job only runs in a container", r.Docker) } sink.closeSection() // -e NAAM zonder waarde laat Docker de variabele uit de omgeving van // deze client overnemen. Zo blijft een meerregelige sleutel heel en // staat de waarde niet in de proceslijst. args := []string{"run", "--rm", "--network", r.Network, "-v", work + ":/workspace", "-w", "/workspace"} cmdEnv := append([]string{}, os.Environ()...) for k, v := range env { args = append(args, "-e", k) cmdEnv = append(cmdEnv, k+"="+v) } args = append(args, "--entrypoint", "sh", job.Image, "/workspace/.bluegit-job.sh") cmd := exec.CommandContext(ctx, r.Docker, args...) cmd.Env = cmdEnv cmd.Stdout = sink cmd.Stderr = sink err = cmd.Run() sink.flush() if err != nil { return mask, fmt.Errorf("container ended with an error: %w", err) } if err := r.collect(ctx, job, work); err != nil { return mask, err } if err := r.saveCache(repo.ID, job, work); err != nil { return mask, err } return mask, nil } func shellScript(job store.Job) string { var b strings.Builder b.WriteString("#!/bin/sh\ncd /workspace\nrc=0\n") fmt.Fprintf(&b, "echo \"section_start:before:Preparing environment\"\n") if strings.TrimSpace(job.Before) != "" { b.WriteString("(\nset -e\n") b.WriteString(job.Before) if !strings.HasSuffix(job.Before, "\n") { b.WriteByte('\n') } b.WriteString(")\nbrc=$?\n") } else { b.WriteString("brc=0\n") } b.WriteString("echo \"section_end:before:Preparing environment\"\n") b.WriteString("echo \"section_start:script:Running script\"\n") b.WriteString("if [ \"$brc\" -eq 0 ]; then\n(\nset -e\n") b.WriteString(job.Script) if !strings.HasSuffix(job.Script, "\n") { b.WriteByte('\n') } b.WriteString(")\nrc=$?\nelse\nrc=$brc\nfi\n") b.WriteString("echo \"section_end:script:Running script\"\n") b.WriteString("echo \"section_start:after:After script\"\n") if strings.TrimSpace(job.After) != "" { b.WriteString("(\nset -e\n") b.WriteString(job.After) if !strings.HasSuffix(job.After, "\n") { b.WriteByte('\n') } b.WriteString(")\n") } b.WriteString("echo \"section_end:after:After script\"\nexit \"$rc\"\n") return b.String() } func (r *Runner) materialize(ctx context.Context, p store.Pipeline, job store.Job, work string) error { jobs, err := r.Store.JobsByPipeline(ctx, p.ID) if err != nil { return err } wanted := map[string]bool{} if job.NeedsSet { for _, n := range job.Needs { wanted[n] = true } } else { stageOrder := map[string]int{} n := 0 for _, j := range jobs { if _, ok := stageOrder[j.Stage]; !ok { stageOrder[j.Stage] = n n++ } } my := stageOrder[job.Stage] for _, j := range jobs { if stageOrder[j.Stage] < my { wanted[j.Name] = true } } } for _, j := range jobs { if !wanted[j.Name] || j.Status != "success" { continue } for _, rel := range j.ArtifactPaths { src, err := r.Store.ArtifactPath(ctx, p.ID, j.Name, rel) if err != nil { continue } dst := filepath.Join(work, filepath.FromSlash(rel)) if err := copyFile(src, dst); err != nil { return err } } } return nil } func (r *Runner) collect(ctx context.Context, job store.Job, work string) error { var expires *time.Time if job.ArtifactExpire > 0 { t := time.Now().Add(job.ArtifactExpire) expires = &t } for _, rel := range job.ArtifactPaths { src := filepath.Join(work, filepath.FromSlash(rel)) info, err := os.Stat(src) if err != nil || info.IsDir() { return fmt.Errorf("artifact %s ontbreekt", rel) } dst := filepath.Join(r.storage(), "artifacts", fmt.Sprint(job.ID), filepath.FromSlash(rel)) if err := copyFile(src, dst); err != nil { return err } if err := r.Store.AddArtifact(ctx, job.ID, rel, dst, info.Size(), expires); err != nil { return err } } return nil } func (r *Runner) environment(ctx context.Context, repo store.Repo, p store.Pipeline, job store.Job, token string) (map[string]string, []string, error) { name, _ := ci.SplitRef(p.Ref) patterns, err := r.Store.ProtectedPatterns(ctx, repo.ID) if err != nil { return nil, nil, err } refProtected := access.BranchProtected(patterns, name) env := map[string]string{} var mask []string if repo.OwnerKind == "group" { groupSecrets, err := r.Store.SecretValues(ctx, "group", repo.OwnerID, refProtected) if err != nil { return nil, nil, err } for k, v := range groupSecrets { env[k] = v mask = append(mask, v) } } repoSecrets, err := r.Store.SecretValues(ctx, "repo", repo.ID, refProtected) if err != nil { return nil, nil, err } for k, v := range repoSecrets { env[k] = v mask = append(mask, v) } for k, v := range job.Variables { env[k] = v } base := strings.TrimRight(r.BaseURL, "/") pre := ci.Variables(ci.Ref{ SHA: p.CommitSHA, FullRef: p.Ref, Title: p.CommitTitle, DefaultBranch: repo.DefaultBranch, Source: p.Source, ProjectPath: repo.FullPath(), ProjectURL: base + "/" + repo.FullPath(), APIURL: base + "/api/v1", PipelineID: p.ID, }) for k, v := range pre { env[k] = v } env["CI_JOB_ID"] = fmt.Sprint(job.ID) env["CI_JOB_NAME"] = job.Name env["CI_JOB_STAGE"] = job.Stage env["CI_JOB_URL"] = base + "/" + repo.FullPath() + "/-/pipelines/" + fmt.Sprint(p.ID) + "/jobs/" + fmt.Sprint(job.ID) env["CI_JOB_TOKEN"] = token mask = append(mask, token) return env, mask, nil } func (r *Runner) restoreCache(repoID int64, job store.Job, work string) error { if len(job.CachePaths) == 0 { return nil } root := r.cacheDir(repoID, job.CacheKey) for _, rel := range job.CachePaths { src := filepath.Join(root, filepath.FromSlash(rel)) if _, err := os.Stat(src); err != nil { continue } if err := copyFile(src, filepath.Join(work, filepath.FromSlash(rel))); err != nil { return err } } return nil } func (r *Runner) saveCache(repoID int64, job store.Job, work string) error { if len(job.CachePaths) == 0 { return nil } root := r.cacheDir(repoID, job.CacheKey) for _, rel := range job.CachePaths { src := filepath.Join(work, filepath.FromSlash(rel)) info, err := os.Stat(src) if err != nil || info.IsDir() { continue } if err := copyFile(src, filepath.Join(root, filepath.FromSlash(rel))); err != nil { return err } } return nil } func (r *Runner) cacheDir(repoID int64, key string) string { if key == "" { key = "default" } var b strings.Builder for _, r := range key { if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '.' || r == '_' || r == '-' { b.WriteRune(r) } } safe := b.String() if safe == "" { safe = "default" } return filepath.Join(r.storage(), "cache", fmt.Sprint(repoID), safe) } func stamp(line string) string { return time.Now().UTC().Format(time.RFC3339) + "\t" + line + "\n" } type logSink struct { mu sync.Mutex store *store.Store jobID int64 secrets []string partial string current string opened time.Time } func (l *logSink) Write(p []byte) (int, error) { l.mu.Lock() defer l.mu.Unlock() l.partial += string(p) for { i := strings.IndexByte(l.partial, '\n') if i < 0 { break } l.emit(strings.TrimRight(l.partial[:i], "\r")) l.partial = l.partial[i+1:] } return len(p), nil } func (l *logSink) flush() { l.mu.Lock() defer l.mu.Unlock() if strings.TrimSpace(l.partial) != "" { l.emit(l.partial) } l.partial = "" } func (l *logSink) emit(line string) { line = ci.Mask(line, l.secrets) if strings.HasPrefix(line, "section_start:") || strings.HasPrefix(line, "section_end:") { if l.current != "" && strings.HasPrefix(line, "section_end:") { dur := int(time.Since(l.opened).Seconds()) line = line + "\t" + fmt.Sprintf("%02d:%02d", dur/60, dur%60) l.current = "" } if strings.HasPrefix(line, "section_start:") { l.current = line l.opened = time.Now() } } _ = l.store.AppendJobLog(context.Background(), l.jobID, stamp(line)) } func (l *logSink) section(name, title string) { l.emit("section_start:" + name + ":" + title) } func (l *logSink) closeSection() { if l.current == "" { return } name := "prepare" if parts := strings.SplitN(strings.TrimPrefix(l.current, "section_start:"), ":", 2); len(parts) > 0 && parts[0] != "" { name = parts[0] } l.emit("section_end:" + name + ":done") } func copyFile(src, dst string) error { if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { return err } in, err := os.Open(src) if err != nil { return err } defer in.Close() out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) if err != nil { return err } defer out.Close() _, err = io.Copy(out, in) return err } func execOut(ctx context.Context, bin string, args ...string) (string, error) { if bin == "" { bin = "git" } cmd := exec.CommandContext(ctx, bin, args...) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if err := cmd.Run(); err != nil { msg := strings.TrimSpace(stderr.String()) if msg == "" { msg = err.Error() } return "", fmt.Errorf("%s", msg) } return stdout.String(), nil }