cmd/gitbay-runner/main.go
502 lines · 17346 bytes
1// gitbay-runner executes CI builds queued by a gitbay server. It polls over
2// SSH — the same authenticated channel everything else uses — claims one
3// build at a time, clones the repo, runs each step with `sh -c`, streams the
4// combined output back, and reports success or failure.
5//
6// The account behind the runner's key must be an instance admin: a runner
7// executes arbitrary repo code, so handing out jobs is the operator's call.
8// v1 runs steps directly on the host under this process's user; run it as a
9// dedicated unprivileged user.
10package main
11
12import (
13 "encoding/json"
14 "flag"
15 "fmt"
16 "io"
17 "log"
18 "os"
19 "os/exec"
20 "os/signal"
21 "path/filepath"
22 "strings"
23 "sync"
24 "syscall"
25 "time"
26
27 "gitbay.org/gitbay/internal/buildinfo"
28 "gitbay.org/gitbay/internal/toolpath"
29)
30
31type job struct {
32 ID int64 `json:"id"`
33 Repo string `json:"repo"`
34 Number int64 `json:"number"`
35 Job string `json:"job"`
36 SHA string `json:"sha"`
37 Ref string `json:"ref"`
38 Steps []string `json:"steps"`
39 Image string `json:"image"`
40 Secrets map[string]string `json:"secrets"`
41}
42
43type runner struct {
44 remote string // ssh destination, e.g. git@gitbay.org
45 sshOpts []string
46 cloneBase string // e.g. ssh://git@gitbay.org
47 workdir string
48 timeout time.Duration
49 // image is the container image for a job that names none, and
50 // isolation selects how steps run: "podman" or "none".
51 image string
52 isolation string
53 // memory and cpus cap one build's container; empty means no cap.
54 memory string
55 cpus string
56 // stepFn is step, replaceable by tests.
57 stepFn func() (bool, error)
58 // repos limits which repositories this runner claims builds for. Empty
59 // means any, which is what a runner on the server itself wants; a runner
60 // somewhere that should not execute every repository's steps names them.
61 repos []string
62}
63
64func main() {
65 var (
66 remote = flag.String("remote", "git@gitbay.org", "ssh destination of the gitbay server")
67 sshOpts = flag.String("ssh-opts", "", "extra ssh options, space-separated (also used for git clone)")
68 cloneBase = flag.String("clone-base", "", "clone URL prefix (default ssh://<remote>)")
69 workdir = flag.String("workdir", defaultWorkdir(), "build workspace root")
70 poll = flag.Duration("poll", 5*time.Second, "idle poll interval")
71 timeout = flag.Duration("timeout", 30*time.Minute, "per-build time limit")
72 repos = flag.String("repos", "", "only claim builds for these repositories, comma-separated owner/name (default: any)")
73 once = flag.Bool("once", false, "process at most one build, then exit")
74 jobs = flag.Int("jobs", 1, "builds to run at once")
75 image = flag.String("image", "", "default container image for jobs that name none")
76 isolation = flag.String("isolation", "podman", "how steps run: podman, or none for no container")
77 memory = flag.String("memory", "", "memory limit per build container, e.g. 4g (podman only; default unlimited)")
78 cpus = flag.String("cpus", "", "CPU limit per build container, e.g. 2 (podman only; default unlimited)")
79 version = flag.Bool("version", false, "print the commit this binary was built from, then exit")
80 )
81 flag.Parse()
82 if *version {
83 fmt.Println(buildinfo.String())
84 return
85 }
86 // The runner links internal/store, so it goes stale on changes that never
87 // touch cmd/gitbay-runner. Say which commit is running.
88 log.Printf("gitbay-runner %s", buildinfo.String())
89 r := &runner{
90 remote: *remote,
91 cloneBase: *cloneBase,
92 workdir: *workdir,
93 timeout: *timeout,
94 image: *image,
95 isolation: *isolation,
96 memory: *memory,
97 cpus: *cpus,
98 }
99 if err := r.checkIsolation(); err != nil {
100 // Refusing to start is the point. A runner that quietly fell back
101 // to running repository code on the host would drop isolation
102 // with nothing to surface it, which is worse than a stopped
103 // runner: the operator sees a failed unit either way, but only
104 // one of them is honest about why (#144).
105 log.Fatalf("isolation: %v", err)
106 }
107 if *sshOpts != "" {
108 r.sshOpts = strings.Fields(*sshOpts)
109 }
110 for _, name := range strings.Split(*repos, ",") {
111 if name = strings.TrimSpace(name); name != "" {
112 r.repos = append(r.repos, name)
113 }
114 }
115 if r.cloneBase == "" {
116 r.cloneBase = "ssh://" + *remote
117 }
118 // 0o700, not 0o755: a build's checkout and its secrets-bearing
119 // environment are this user's business alone, and the default sits
120 // beside other users' data on a shared host.
121 if err := os.MkdirAll(r.workdir, 0o700); err != nil {
122 log.Fatal(err)
123 }
124 if err := checkWorkdir(r.workdir); err != nil {
125 log.Fatal(err)
126 }
127 n := *jobs
128 if n < 1 {
129 log.Fatal("-jobs must be at least 1")
130 }
131 if *once {
132 // "at most one build" is one build, whatever -jobs says.
133 n = 1
134 }
135 // `runner next` claims inside one transaction, so several workers
136 // claiming at once is already safe; the runner just never used that.
137 // Each build works in its own build-<id> directory, so they do not
138 // meet on disk either.
139 // A stop signal drains: no build is claimed after it, and each build
140 // already in flight runs to completion and is reported. The old
141 // behaviour was to die mid-build, which left the build "running" on
142 // the server with nothing executing (#179). The unit's
143 // TimeoutStopSec bounds the drain; a second signal ends it now.
144 stop := make(chan struct{})
145 go func() {
146 sigs := make(chan os.Signal, 2)
147 signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
148 <-sigs
149 log.Printf("draining: finishing builds in flight, claiming no more")
150 close(stop)
151 <-sigs
152 log.Printf("second signal: exiting without draining")
153 os.Exit(1)
154 }()
155 r.serve(n, *once, *poll, stop)
156}
157
158// serve runs n workers until stop closes. A worker checks stop only
159// between builds, so closing it never interrupts one.
160func (r *runner) serve(n int, once bool, poll time.Duration, stop <-chan struct{}) {
161 if r.stepFn == nil {
162 r.stepFn = r.step
163 }
164 var wg sync.WaitGroup
165 for i := 0; i < n; i++ {
166 wg.Add(1)
167 go func(i int) {
168 defer wg.Done()
169 if n > 1 {
170 time.Sleep(time.Duration(i) * poll / time.Duration(n))
171 }
172 for {
173 select {
174 case <-stop:
175 return
176 default:
177 }
178 ran, err := r.stepFn()
179 if err != nil {
180 log.Printf("runner: %v", err)
181 }
182 if once {
183 return
184 }
185 if !ran {
186 select {
187 case <-stop:
188 return
189 case <-time.After(poll):
190 }
191 }
192 }
193 }(i)
194 }
195 wg.Wait()
196}
197
198// step claims and executes at most one build. ran reports whether there was
199// one, so the caller knows when to idle.
200func (r *runner) step() (bool, error) {
201 out, err := r.ssh(nil, append([]string{"runner", "next"}, append(r.repos, "--json")...)...)
202 if err != nil {
203 return false, fmt.Errorf("claiming build: %w (%s)", err, out)
204 }
205 var env struct {
206 Data job `json:"data"`
207 }
208 if err := json.Unmarshal([]byte(out), &env); err != nil {
209 return false, fmt.Errorf("parsing job: %w", err)
210 }
211 if env.Data.ID == 0 {
212 return false, nil
213 }
214 j := env.Data
215 log.Printf("build %d: %s %s @ %.10s", j.ID, j.Repo, j.Job, j.SHA)
216 status := "failure"
217 if r.run(j) {
218 status = "success"
219 }
220 if err := r.reportDone(j.ID, status); err != nil {
221 return true, err
222 }
223 log.Printf("build %d: %s", j.ID, status)
224 return true, nil
225}
226
227// logSink forwards a build's output to the server and swallows any error
228// doing so. os/exec surfaces a write failure on a step's stdout through
229// cmd.Wait(), so a sink that can fail is a sink that can fail the build it
230// was only recording — a restart or a dropped session used to turn a green
231// suite red, with the explaining line written to the same dead pipe. Losing
232// log lines is the acceptable failure here; losing the build is not.
233type logSink struct {
234 mu sync.Mutex
235 w io.Writer // nil once a write has failed
236}
237
238func (s *logSink) Write(p []byte) (int, error) {
239 s.mu.Lock()
240 defer s.mu.Unlock()
241 if s.w != nil {
242 if _, err := s.w.Write(p); err != nil {
243 s.w = nil
244 }
245 }
246 return len(p), nil
247}
248
249// broken reports whether the stream was lost, so a build can say its log is
250// incomplete rather than appear to have simply stopped.
251func (s *logSink) broken() bool {
252 s.mu.Lock()
253 defer s.mu.Unlock()
254 return s.w == nil
255}
256
257// run clones, checks out, and executes the steps, streaming output to the
258// server. Returns whether every step succeeded.
259func (r *runner) run(j job) bool {
260 dir := filepath.Join(r.workdir, fmt.Sprintf("build-%d", j.ID))
261 defer os.RemoveAll(dir)
262
263 // A build's HOME. Not the workspace, which is removed after every
264 // build: the Go module cache, the sonar scanner and every other tool
265 // cache live under HOME, so a per-build one re-downloads the world
266 // each time. Not the runner's own home either, where its SSH key and
267 // credential dotfiles are. A directory beside the workspaces is
268 // neither.
269 //
270 // One per repository: shared across repositories, a step could poison
271 // the module cache or plant a .gitconfig that another repository's
272 // build would honour, and the container mounts the home read-write
273 // (#184).
274 buildHome, err := buildHomeFor(r.workdir, j.Repo)
275 if err != nil {
276 log.Printf("build %d: build home: %v", j.ID, err)
277 return false
278 }
279
280 // One long-lived `runner log` session receives the whole stream.
281 logCmd := exec.Command(toolpath.Look("ssh"), append(r.sshOpts, r.remote, "runner", "log", fmt.Sprint(j.ID))...)
282 pipe, err := logCmd.StdinPipe()
283 if err != nil {
284 log.Printf("build %d: log pipe: %v", j.ID, err)
285 return false
286 }
287 sink := &logSink{w: pipe}
288 logCmd.Stdout, logCmd.Stderr = io.Discard, io.Discard
289 if err := logCmd.Start(); err != nil {
290 log.Printf("build %d: log stream: %v", j.ID, err)
291 return false
292 }
293 // The server ends the log session with exit 3 when the build is
294 // cancelled; any other end is a lost stream, which the sink absorbs.
295 cancelled := make(chan struct{})
296 logExited := make(chan struct{})
297 go func() {
298 defer close(logExited)
299 err := logCmd.Wait()
300 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 3 {
301 close(cancelled)
302 return
303 }
304 if err != nil {
305 log.Printf("build %d: log session ended: %v", j.ID, err)
306 }
307 }()
308 // runStep starts cmd and waits for it, the cancel signal, or the
309 // deadline. Every phase goes through it, so a cancel during the clone
310 // lands as fast as one during a step.
311 runStep := func(cmd *exec.Cmd, deadline time.Time) (bool, string) {
312 select {
313 case <-cancelled:
314 return false, "cancelled"
315 default:
316 }
317 ownProcessGroup(cmd)
318 if err := cmd.Start(); err != nil {
319 return false, fmt.Sprintf("start: %v", err)
320 }
321 done := make(chan error, 1)
322 go func() { done <- cmd.Wait() }()
323 // After a kill, Wait returns once every holder of the log pipe is
324 // gone; the group kill makes that prompt, and the cap makes sure a
325 // straggler cannot hold the build open.
326 reap := func() {
327 killTree(cmd)
328 select {
329 case <-done:
330 case <-time.After(10 * time.Second):
331 }
332 }
333 select {
334 case err := <-done:
335 if err != nil {
336 return false, fmt.Sprintf("step failed: %v", err)
337 }
338 return true, ""
339 case <-cancelled:
340 reap()
341 return false, "cancelled"
342 case <-time.After(time.Until(deadline)):
343 reap()
344 return false, fmt.Sprintf("build timed out after %s", r.timeout)
345 }
346 }
347 defer func() {
348 select {
349 case <-cancelled:
350 log.Printf("build %d: cancelled", j.ID)
351 default:
352 if sink.broken() {
353 log.Printf("build %d: log stream lost; stored log is incomplete", j.ID)
354 }
355 }
356 pipe.Close()
357 <-logExited
358 }()
359
360 gitSSH := strings.TrimSpace("ssh " + strings.Join(r.sshOpts, " "))
361 cloneURL := r.cloneBase + "/" + j.Repo + ".git"
362 deadline := time.Now().Add(r.timeout)
363 fmt.Fprintf(sink, "$ git clone %s (%.10s)\n", cloneURL, j.SHA)
364 // A merge request head lives under refs/merge-requests/, which a
365 // clone does not fetch; ask for the ref before checking out.
366 steps := [][]string{{"clone", "-q", cloneURL, dir}}
367 if strings.HasPrefix(j.Ref, "refs/") {
368 steps = append(steps, []string{"-C", dir, "fetch", "-q", "origin", j.Ref})
369 }
370 steps = append(steps, []string{"-C", dir, "checkout", "-q", j.SHA})
371 for _, args := range steps {
372 cmd := exec.Command(toolpath.Look("git"), args...)
373 cmd.Env = append(os.Environ(), "GIT_SSH_COMMAND="+gitSSH, "GIT_TERMINAL_PROMPT=0")
374 cmd.Stdout, cmd.Stderr = sink, sink
375 if ok, why := runStep(cmd, deadline); !ok {
376 fmt.Fprintf(sink, "git %s: %s\n", args[0], why)
377 return false
378 }
379 }
380
381 env := stepEnv(j, buildHome)
382 return r.runSteps(j, dir, env, sink, deadline, runStep)
383}
384
385// stepEnv builds the environment a build step runs with. It is
386// constructed, not inherited: os.Environ() would hand repository content
387// the runner's entire environment, including anything an operator set on
388// the service (#144).
389//
390// HOME is the repository's build home, not the runner's own: tools read
391// credentials out of dotfiles — .netrc, .npmrc, .gitconfig — and a build
392// has no business finding the runner's. It is not the workspace either,
393// because the workspace is deleted after every build and every tool
394// cache lives under HOME.
395//
396// PATH is the one thing carried over: without it a step cannot find the
397// tools the host was provisioned with.
398// buildHomeFor is the build home for one repository: <workdir>/home/<owner>/<name>,
399// created on first use. The repository path comes from the server, but a
400// home must still never resolve outside the home root.
401func buildHomeFor(workdir, repo string) (string, error) {
402 root := filepath.Join(workdir, "home")
403 dir := filepath.Join(root, filepath.FromSlash(repo))
404 if rel, err := filepath.Rel(root, dir); err != nil || rel == "." || strings.HasPrefix(rel, "..") {
405 return "", fmt.Errorf("repository path %q escapes the build home root", repo)
406 }
407 if err := os.MkdirAll(dir, 0o700); err != nil {
408 return "", err
409 }
410 return dir, nil
411}
412
413func stepEnv(j job, home string) []string {
414 path := os.Getenv("PATH")
415 if path == "" {
416 path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
417 }
418 env := []string{
419 "PATH=" + path,
420 "HOME=" + home,
421 "LANG=C.UTF-8",
422 "CI=true",
423 "GITBAY_REPO=" + j.Repo,
424 "GITBAY_SHA=" + j.SHA,
425 "GITBAY_REF=" + j.Ref,
426 "GITBAY_JOB=" + j.Job,
427 }
428 // The server sends secrets only for a trusted build — a merge request
429 // head from a fork arrives with none — so this loop is empty exactly
430 // when it should be.
431 for name, value := range j.Secrets {
432 env = append(env, name+"="+value)
433 }
434 return env
435}
436
437// ssh runs one control command against the server and returns stdout.// ssh runs one control command against the server and returns stdout.
438func (r *runner) ssh(stdin io.Reader, args ...string) (string, error) {
439 cmd := exec.Command(toolpath.Look("ssh"), append(append(r.sshOpts, r.remote), args...)...)
440 if stdin != nil {
441 cmd.Stdin = stdin
442 }
443 var out, errOut strings.Builder
444 cmd.Stdout, cmd.Stderr = &out, &errOut
445 if err := cmd.Run(); err != nil {
446 return out.String() + errOut.String(), err
447 }
448 return out.String(), nil
449}
450
451// defaultWorkdir picks a build workspace that another local user cannot
452// have created first.
453//
454// The default used to be <tmp>/gitbay-runner: a fixed name inside a
455// world-writable directory, created with MkdirAll, which succeeds against
456// an existing directory whoever owns it. On a shared host another user
457// could have made it — or symlinked it — before the runner started, and
458// this is the process that clones repositories and exports build secrets
459// into step environments (go:S5445, #153).
460//
461// The user's cache directory is not world-writable and is per-user by
462// construction. Falling back to tmp keeps a runner working where HOME is
463// unset, and checkWorkdir refuses the unsafe cases there.
464func defaultWorkdir() string {
465 if cache, err := os.UserCacheDir(); err == nil && cache != "" {
466 return filepath.Join(cache, "gitbay-runner")
467 }
468 return filepath.Join(os.TempDir(), "gitbay-runner")
469}
470
471// checkWorkdir makes sure the workspace is a directory this user owns
472// privately. MkdirAll is happy with one that already exists, so being
473// able to create it proves nothing about who made it.
474//
475// A directory we own that is merely too permissive is tightened rather
476// than refused: every runner before this one created its workspace 0755,
477// so refusing would take the runner down on upgrade to fix a permission
478// we are entitled to change. What cannot be repaired — a symlink, or
479// something owned by someone else — is refused, because those are what an
480// attacker leaves behind and neither is ours to correct.
481func checkWorkdir(dir string) error {
482 fi, err := os.Lstat(dir)
483 if err != nil {
484 return err
485 }
486 if fi.Mode()&os.ModeSymlink != 0 {
487 return fmt.Errorf("workdir %s is a symlink; point -workdir at a real directory", dir)
488 }
489 if !fi.IsDir() {
490 return fmt.Errorf("workdir %s is not a directory", dir)
491 }
492 if st, ok := fi.Sys().(*syscall.Stat_t); ok && int(st.Uid) != os.Getuid() {
493 return fmt.Errorf("workdir %s is owned by uid %d, not this process's %d", dir, st.Uid, os.Getuid())
494 }
495 if perm := fi.Mode().Perm(); perm&0o077 != 0 {
496 log.Printf("workdir %s was mode %04o; tightening to 0700 (builds and their secrets are this user's alone)", dir, perm)
497 if err := os.Chmod(dir, 0o700); err != nil {
498 return fmt.Errorf("tightening workdir %s: %w", dir, err)
499 }
500 }
501 return nil
502}