cmd/gitbay-runner/main.go

272 lines · 8411 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		if err := logCmd.Wait(); err != nil {
190			if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 3 {
191				close(cancelled)
192			}
193		}
194	}()
195	defer func() {
196		select {
197		case <-cancelled:
198			log.Printf("build %d: cancelled", j.ID)
199		default:
200			if sink.broken() {
201				log.Printf("build %d: log stream lost; stored log is incomplete", j.ID)
202			}
203		}
204		pipe.Close()
205		<-logExited
206	}()
207
208	gitSSH := strings.TrimSpace("ssh " + strings.Join(r.sshOpts, " "))
209	cloneURL := r.cloneBase + "/" + j.Repo + ".git"
210	fmt.Fprintf(sink, "$ git clone %s (%.10s)\n", cloneURL, j.SHA)
211	for _, args := range [][]string{
212		{"clone", "-q", cloneURL, dir},
213		{"-C", dir, "checkout", "-q", j.SHA},
214	} {
215		cmd := exec.Command("git", args...)
216		cmd.Env = append(os.Environ(), "GIT_SSH_COMMAND="+gitSSH, "GIT_TERMINAL_PROMPT=0")
217		cmd.Stdout, cmd.Stderr = sink, sink
218		if err := cmd.Run(); err != nil {
219			fmt.Fprintf(sink, "git %s: %v\n", args[0], err)
220			return false
221		}
222	}
223
224	deadline := time.Now().Add(r.timeout)
225	for _, step := range j.Steps {
226		fmt.Fprintf(sink, "$ %s\n", step)
227		cmd := exec.Command("sh", "-c", step)
228		cmd.Dir = dir
229		cmd.Env = append(os.Environ(),
230			"GITBAY_REPO="+j.Repo, "GITBAY_SHA="+j.SHA, "GITBAY_REF="+j.Ref, "GITBAY_JOB="+j.Job, "CI=true")
231		for name, value := range j.Secrets {
232			cmd.Env = append(cmd.Env, name+"="+value)
233		}
234		cmd.Stdout, cmd.Stderr = sink, sink
235		if err := cmd.Start(); err != nil {
236			fmt.Fprintf(sink, "start: %v\n", err)
237			return false
238		}
239		done := make(chan error, 1)
240		go func() { done <- cmd.Wait() }()
241		select {
242		case err := <-done:
243			if err != nil {
244				fmt.Fprintf(sink, "step failed: %v\n", err)
245				return false
246			}
247		case <-cancelled:
248			cmd.Process.Kill()
249			<-done
250			return false
251		case <-time.After(time.Until(deadline)):
252			cmd.Process.Kill()
253			fmt.Fprintf(sink, "build timed out after %s\n", r.timeout)
254			return false
255		}
256	}
257	return true
258}
259
260// ssh runs one control command against the server and returns stdout.
261func (r *runner) ssh(stdin io.Reader, args ...string) (string, error) {
262	cmd := exec.Command("ssh", append(append(r.sshOpts, r.remote), args...)...)
263	if stdin != nil {
264		cmd.Stdin = stdin
265	}
266	var out, errOut strings.Builder
267	cmd.Stdout, cmd.Stderr = &out, &errOut
268	if err := cmd.Run(); err != nil {
269		return out.String() + errOut.String(), err
270	}
271	return out.String(), nil
272}