cmd/gitbay-runner/main.go
301 lines · 9489 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 "path/filepath"
21 "strings"
22 "sync"
23 "time"
24
25 "gitbay.org/gitbay/internal/buildinfo"
26)
27
28type job struct {
29 ID int64 `json:"id"`
30 Repo string `json:"repo"`
31 Number int64 `json:"number"`
32 Job string `json:"job"`
33 SHA string `json:"sha"`
34 Ref string `json:"ref"`
35 Steps []string `json:"steps"`
36 Secrets map[string]string `json:"secrets"`
37}
38
39type runner struct {
40 remote string // ssh destination, e.g. git@gitbay.org
41 sshOpts []string
42 cloneBase string // e.g. ssh://git@gitbay.org
43 workdir string
44 timeout time.Duration
45 // repos limits which repositories this runner claims builds for. Empty
46 // means any, which is what a runner on the server itself wants; a runner
47 // somewhere that should not execute every repository's steps names them.
48 repos []string
49}
50
51func main() {
52 var (
53 remote = flag.String("remote", "git@gitbay.org", "ssh destination of the gitbay server")
54 sshOpts = flag.String("ssh-opts", "", "extra ssh options, space-separated (also used for git clone)")
55 cloneBase = flag.String("clone-base", "", "clone URL prefix (default ssh://<remote>)")
56 workdir = flag.String("workdir", filepath.Join(os.TempDir(), "gitbay-runner"), "build workspace root")
57 poll = flag.Duration("poll", 5*time.Second, "idle poll interval")
58 timeout = flag.Duration("timeout", 30*time.Minute, "per-build time limit")
59 repos = flag.String("repos", "", "only claim builds for these repositories, comma-separated owner/name (default: any)")
60 once = flag.Bool("once", false, "process at most one build, then exit")
61 version = flag.Bool("version", false, "print the commit this binary was built from, then exit")
62 )
63 flag.Parse()
64 if *version {
65 fmt.Println(buildinfo.String())
66 return
67 }
68 // The runner links internal/store, so it goes stale on changes that never
69 // touch cmd/gitbay-runner. Say which commit is running.
70 log.Printf("gitbay-runner %s", buildinfo.String())
71 r := &runner{
72 remote: *remote,
73 cloneBase: *cloneBase,
74 workdir: *workdir,
75 timeout: *timeout,
76 }
77 if *sshOpts != "" {
78 r.sshOpts = strings.Fields(*sshOpts)
79 }
80 for _, name := range strings.Split(*repos, ",") {
81 if name = strings.TrimSpace(name); name != "" {
82 r.repos = append(r.repos, name)
83 }
84 }
85 if r.cloneBase == "" {
86 r.cloneBase = "ssh://" + *remote
87 }
88 if err := os.MkdirAll(r.workdir, 0o755); err != nil {
89 log.Fatal(err)
90 }
91 for {
92 ran, err := r.step()
93 if err != nil {
94 log.Printf("runner: %v", err)
95 }
96 if *once {
97 return
98 }
99 if !ran {
100 time.Sleep(*poll)
101 }
102 }
103}
104
105// step claims and executes at most one build. ran reports whether there was
106// one, so the caller knows when to idle.
107func (r *runner) step() (bool, error) {
108 out, err := r.ssh(nil, append([]string{"runner", "next"}, append(r.repos, "--json")...)...)
109 if err != nil {
110 return false, fmt.Errorf("claiming build: %w (%s)", err, out)
111 }
112 var env struct {
113 Data job `json:"data"`
114 }
115 if err := json.Unmarshal([]byte(out), &env); err != nil {
116 return false, fmt.Errorf("parsing job: %w", err)
117 }
118 if env.Data.ID == 0 {
119 return false, nil
120 }
121 j := env.Data
122 log.Printf("build %d: %s %s @ %.10s", j.ID, j.Repo, j.Job, j.SHA)
123 status := "failure"
124 if r.run(j) {
125 status = "success"
126 }
127 if out, err := r.ssh(nil, "runner", "done", fmt.Sprint(j.ID), status); err != nil {
128 return true, fmt.Errorf("reporting build %d: %w (%s)", j.ID, err, out)
129 }
130 log.Printf("build %d: %s", j.ID, status)
131 return true, nil
132}
133
134// logSink forwards a build's output to the server and swallows any error
135// doing so. os/exec surfaces a write failure on a step's stdout through
136// cmd.Wait(), so a sink that can fail is a sink that can fail the build it
137// was only recording — a restart or a dropped session used to turn a green
138// suite red, with the explaining line written to the same dead pipe. Losing
139// log lines is the acceptable failure here; losing the build is not.
140type logSink struct {
141 mu sync.Mutex
142 w io.Writer // nil once a write has failed
143}
144
145func (s *logSink) Write(p []byte) (int, error) {
146 s.mu.Lock()
147 defer s.mu.Unlock()
148 if s.w != nil {
149 if _, err := s.w.Write(p); err != nil {
150 s.w = nil
151 }
152 }
153 return len(p), nil
154}
155
156// broken reports whether the stream was lost, so a build can say its log is
157// incomplete rather than appear to have simply stopped.
158func (s *logSink) broken() bool {
159 s.mu.Lock()
160 defer s.mu.Unlock()
161 return s.w == nil
162}
163
164// run clones, checks out, and executes the steps, streaming output to the
165// server. Returns whether every step succeeded.
166func (r *runner) run(j job) bool {
167 dir := filepath.Join(r.workdir, fmt.Sprintf("build-%d", j.ID))
168 defer os.RemoveAll(dir)
169
170 // One long-lived `runner log` session receives the whole stream.
171 logCmd := exec.Command("ssh", append(r.sshOpts, r.remote, "runner", "log", fmt.Sprint(j.ID))...)
172 pipe, err := logCmd.StdinPipe()
173 if err != nil {
174 log.Printf("build %d: log pipe: %v", j.ID, err)
175 return false
176 }
177 sink := &logSink{w: pipe}
178 logCmd.Stdout, logCmd.Stderr = io.Discard, io.Discard
179 if err := logCmd.Start(); err != nil {
180 log.Printf("build %d: log stream: %v", j.ID, err)
181 return false
182 }
183 // The server ends the log session with exit 3 when the build is
184 // cancelled; any other end is a lost stream, which the sink absorbs.
185 cancelled := make(chan struct{})
186 logExited := make(chan struct{})
187 go func() {
188 defer close(logExited)
189 err := logCmd.Wait()
190 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 3 {
191 close(cancelled)
192 return
193 }
194 if err != nil {
195 log.Printf("build %d: log session ended: %v", j.ID, err)
196 }
197 }()
198 // runStep starts cmd and waits for it, the cancel signal, or the
199 // deadline. Every phase goes through it, so a cancel during the clone
200 // lands as fast as one during a step.
201 runStep := func(cmd *exec.Cmd, deadline time.Time) (bool, string) {
202 select {
203 case <-cancelled:
204 return false, "cancelled"
205 default:
206 }
207 ownProcessGroup(cmd)
208 if err := cmd.Start(); err != nil {
209 return false, fmt.Sprintf("start: %v", err)
210 }
211 done := make(chan error, 1)
212 go func() { done <- cmd.Wait() }()
213 // After a kill, Wait returns once every holder of the log pipe is
214 // gone; the group kill makes that prompt, and the cap makes sure a
215 // straggler cannot hold the build open.
216 reap := func() {
217 killTree(cmd)
218 select {
219 case <-done:
220 case <-time.After(10 * time.Second):
221 }
222 }
223 select {
224 case err := <-done:
225 if err != nil {
226 return false, fmt.Sprintf("step failed: %v", err)
227 }
228 return true, ""
229 case <-cancelled:
230 reap()
231 return false, "cancelled"
232 case <-time.After(time.Until(deadline)):
233 reap()
234 return false, fmt.Sprintf("build timed out after %s", r.timeout)
235 }
236 }
237 defer func() {
238 select {
239 case <-cancelled:
240 log.Printf("build %d: cancelled", j.ID)
241 default:
242 if sink.broken() {
243 log.Printf("build %d: log stream lost; stored log is incomplete", j.ID)
244 }
245 }
246 pipe.Close()
247 <-logExited
248 }()
249
250 gitSSH := strings.TrimSpace("ssh " + strings.Join(r.sshOpts, " "))
251 cloneURL := r.cloneBase + "/" + j.Repo + ".git"
252 deadline := time.Now().Add(r.timeout)
253 fmt.Fprintf(sink, "$ git clone %s (%.10s)\n", cloneURL, j.SHA)
254 // A merge request head lives under refs/merge-requests/, which a
255 // clone does not fetch; ask for the ref before checking out.
256 steps := [][]string{{"clone", "-q", cloneURL, dir}}
257 if strings.HasPrefix(j.Ref, "refs/") {
258 steps = append(steps, []string{"-C", dir, "fetch", "-q", "origin", j.Ref})
259 }
260 steps = append(steps, []string{"-C", dir, "checkout", "-q", j.SHA})
261 for _, args := range steps {
262 cmd := exec.Command("git", args...)
263 cmd.Env = append(os.Environ(), "GIT_SSH_COMMAND="+gitSSH, "GIT_TERMINAL_PROMPT=0")
264 cmd.Stdout, cmd.Stderr = sink, sink
265 if ok, why := runStep(cmd, deadline); !ok {
266 fmt.Fprintf(sink, "git %s: %s\n", args[0], why)
267 return false
268 }
269 }
270
271 for _, step := range j.Steps {
272 fmt.Fprintf(sink, "$ %s\n", step)
273 cmd := exec.Command("sh", "-c", step)
274 cmd.Dir = dir
275 cmd.Env = append(os.Environ(),
276 "GITBAY_REPO="+j.Repo, "GITBAY_SHA="+j.SHA, "GITBAY_REF="+j.Ref, "GITBAY_JOB="+j.Job, "CI=true")
277 for name, value := range j.Secrets {
278 cmd.Env = append(cmd.Env, name+"="+value)
279 }
280 cmd.Stdout, cmd.Stderr = sink, sink
281 if ok, why := runStep(cmd, deadline); !ok {
282 fmt.Fprintf(sink, "%s\n", why)
283 return false
284 }
285 }
286 return true
287}
288
289// ssh runs one control command against the server and returns stdout.
290func (r *runner) ssh(stdin io.Reader, args ...string) (string, error) {
291 cmd := exec.Command("ssh", append(append(r.sshOpts, r.remote), args...)...)
292 if stdin != nil {
293 cmd.Stdin = stdin
294 }
295 var out, errOut strings.Builder
296 cmd.Stdout, cmd.Stderr = &out, &errOut
297 if err := cmd.Run(); err != nil {
298 return out.String() + errOut.String(), err
299 }
300 return out.String(), nil
301}