e2e/ci_test.go

419f6dfdc5489a0c6374e36dd1ebbfca68040056
gitbay/e2e/ci_test.go history · blame · raw

376 lines · 16107 bytes

  1package e2e
  2
  3import (
  4	"bytes"
  5	"fmt"
  6	"os"
  7	"os/exec"
  8	"path/filepath"
  9	"strings"
 10	"testing"
 11	"time"
 12)
 13
 14// runnerOnce processes at most one pending build with the given key.
 15func (i *instance) runnerOnce(t *testing.T, key string, extra ...string) string {
 16	t.Helper()
 17	opts := fmt.Sprintf("-p %d -i %s -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=%s -o BatchMode=yes",
 18		i.port, key, filepath.Join(i.sshDir, "known_hosts"))
 19	// -isolation none: these tests exercise claiming, logs, statuses and
 20	// cancellation, not the sandbox, and the suite must run on a machine
 21	// without podman. The isolation tests are in isolation_podman_test.go
 22	// and skip visibly when it is absent (#144).
 23	args := []string{"-once",
 24		"-remote", "git@127.0.0.1",
 25		"-ssh-opts", opts,
 26		"-isolation", "none",
 27		"-clone-base", fmt.Sprintf("ssh://git@127.0.0.1:%d", i.port),
 28		"-workdir", t.TempDir()}
 29	args = append(args, extra...)
 30	cmd := exec.Command(i.runner, args...)
 31	cmd.Env = append(os.Environ(), "XDG_CONFIG_HOME="+t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null")
 32	out, err := cmd.CombinedOutput()
 33	if err != nil {
 34		t.Fatalf("runner: %v\n%s", err, out)
 35	}
 36	return string(out)
 37}
 38
 39// A failed build mails the repo owner with the log tail; green builds
 40// stay silent.
 41func TestBuildFailureMail(t *testing.T) {
 42	t.Parallel()
 43	smtp := startFakeSMTP(t)
 44	inst := startInstanceWith(t, fmt.Sprintf(
 45		"[mail]\nsmtp_host = %q\nfrom = \"noreply@gitbay.test\"\n", smtp.addr))
 46	inst.runner = buildRunner(t)
 47	aliceKey := inst.newKey(t, "alice")
 48	inst.admin(t, "admin", "user", "create", "alice", "--key", aliceKey+".pub",
 49		"--email", "alice@example.test", "--verified")
 50	runnerKey := inst.newKey(t, "ci")
 51	inst.admin(t, "admin", "user", "create", "ci", "--key", runnerKey+".pub", "--admin")
 52
 53	if _, errOut, code := inst.ssh(t, aliceKey, "", "repo", "create", "alice/app"); code != 0 {
 54		t.Fatalf("repo create: %s", errOut)
 55	}
 56	work := t.TempDir()
 57	env := inst.gitEnv(aliceKey)
 58	mustGit(t, work, env, "clone", inst.sshURL("alice/app"), "w")
 59	dir := filepath.Join(work, "w")
 60	os.MkdirAll(filepath.Join(dir, ".gitbay"), 0o755)
 61	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte(
 62		"jobs:\n  ok:\n    steps:\n      - echo fine\n  broken:\n    steps:\n      - echo the dataset went stale && false\n"), 0o644)
 63	mustGit(t, dir, env, "checkout", "-q", "-b", "main")
 64	mustGit(t, dir, env, "add", ".")
 65	mustGit(t, dir, env, "commit", "-q", "-m", "base")
 66	mustGit(t, dir, env, "push", "-q", "origin", "main")
 67
 68	inst.runnerOnce(t, runnerKey) // broken (sorts first)
 69	inst.runnerOnce(t, runnerKey) // ok
 70	mail := smtp.waitFor(t, "alice@example.test", "failed")
 71	if !strings.Contains(mail, "broken") || !strings.Contains(mail, "the dataset went stale") ||
 72		!strings.Contains(mail, "/alice/app/builds/") {
 73		t.Fatalf("failure mail missing detail:\n%s", mail)
 74	}
 75	// Only the failure mailed: no message mentions the green job.
 76	for _, m := range smtp.mailTo("alice@example.test") {
 77		if strings.Contains(m, "build") && strings.Contains(m, " ok ") && strings.Contains(m, "failed") == false {
 78			t.Fatalf("green build mailed:\n%s", m)
 79		}
 80	}
 81}
 82
 83func TestCI(t *testing.T) {
 84	t.Parallel()
 85	inst := startInstance(t)
 86	inst.runner = buildRunner(t)
 87	aliceKey := inst.newKey(t, "alice")
 88	inst.admin(t, "admin", "user", "create", "alice", "--key", aliceKey+".pub")
 89	runnerKey := inst.newKey(t, "ci")
 90	inst.admin(t, "admin", "user", "create", "ci", "--key", runnerKey+".pub", "--admin")
 91
 92	if _, errOut, code := inst.ssh(t, aliceKey, "", "repo", "create", "alice/app"); code != 0 {
 93		t.Fatalf("repo create: %s", errOut)
 94	}
 95	work := t.TempDir()
 96	env := inst.gitEnv(aliceKey)
 97	mustGit(t, work, env, "clone", inst.sshURL("alice/app"), "w")
 98	dir := filepath.Join(work, "w")
 99	os.MkdirAll(filepath.Join(dir, ".gitbay"), 0o755)
100	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte(
101		"jobs:\n  ok:\n    steps:\n      - echo hello from $GITBAY_JOB\n  broken:\n    steps:\n      - \"false\"\n"), 0o644)
102	os.WriteFile(filepath.Join(dir, "f.txt"), []byte("x\n"), 0o644)
103	mustGit(t, dir, env, "checkout", "-q", "-b", "main")
104	mustGit(t, dir, env, "add", ".")
105	mustGit(t, dir, env, "commit", "-q", "-m", "base")
106	mustGit(t, dir, env, "push", "-q", "origin", "main")
107	sha := strings.TrimSpace(mustGit(t, dir, env, "rev-parse", "HEAD"))
108
109	// The push queued one pending build per job, with pending statuses.
110	out, _, _ := inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
111	if !strings.Contains(out, "broken\tpending") || !strings.Contains(out, "ok\tpending") {
112		t.Fatalf("builds not queued:\n%s", out)
113	}
114	out, _, _ = inst.ssh(t, aliceKey, "", "status", "list", "alice/app", sha)
115	if !strings.Contains(out, "ci/ok") || !strings.Contains(out, "pending") {
116		t.Fatalf("pending statuses missing:\n%s", out)
117	}
118
119	// Non-admins cannot claim jobs.
120	if _, _, code := inst.ssh(t, aliceKey, "", "runner", "next"); code != 4 {
121		t.Fatalf("non-admin claimed a build: exit %d", code)
122	}
123
124	// The runner processes both jobs ("broken" sorts first).
125	inst.runnerOnce(t, runnerKey)
126	inst.runnerOnce(t, runnerKey)
127
128	out, _, _ = inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
129	if !strings.Contains(out, "ok\tsuccess") || !strings.Contains(out, "broken\tfailure") {
130		t.Fatalf("build outcomes wrong:\n%s", out)
131	}
132	// Logs captured the step output and the failure.
133	var okN, brokenN string
134	for _, l := range strings.Split(strings.TrimSpace(out), "\n") {
135		f := strings.Split(l, "\t")
136		if f[1] == "ok" {
137			okN = f[0]
138		} else {
139			brokenN = f[0]
140		}
141	}
142	out, _, _ = inst.ssh(t, aliceKey, "", "build", "log", "alice/app", okN)
143	if !strings.Contains(out, "hello from ok") {
144		t.Fatalf("ok log:\n%s", out)
145	}
146	out, _, _ = inst.ssh(t, aliceKey, "", "build", "log", "alice/app", brokenN)
147	if !strings.Contains(out, "step failed") {
148		t.Fatalf("broken log:\n%s", out)
149	}
150	// Statuses resolved, with target URLs pointing at the build pages.
151	out, _, _ = inst.ssh(t, aliceKey, "", "status", "list", "alice/app", sha, "--json")
152	if !strings.Contains(out, `"ci/ok","state":"success"`) && !strings.Contains(out, `"state":"success"`) {
153		t.Fatalf("status not success:\n%s", out)
154	}
155	if !strings.Contains(out, "/alice/app/builds/") {
156		t.Fatalf("status target url missing:\n%s", out)
157	}
158
159	// Web: list page and log page.
160	status, body := inst.get(t, "/alice/app/builds")
161	if status != 200 || !strings.Contains(body, "ok") || !strings.Contains(body, "failure") {
162		t.Fatalf("builds page: %d\n%s", status, body)
163	}
164	if _, body = inst.get(t, "/alice/app/builds/"+okN); !strings.Contains(body, "hello from ok") {
165		t.Fatalf("build log page:\n%s", body)
166	}
167
168	// --- secrets: stdin in, names-only out, injected into the build env ---
169	if _, errOut, code := inst.ssh(t, aliceKey, "hunter2\n", "repo", "secret", "set", "alice/app", "MY_TOKEN"); code != 0 {
170		t.Fatalf("secret set: %s", errOut)
171	}
172	if _, _, code := inst.ssh(t, aliceKey, "x\n", "repo", "secret", "set", "alice/app", "bad-name"); code != 2 {
173		t.Fatal("bad secret name accepted")
174	}
175	out, _, _ = inst.ssh(t, aliceKey, "", "repo", "secret", "list", "alice/app")
176	if !strings.Contains(out, "MY_TOKEN") || strings.Contains(out, "hunter2") {
177		t.Fatalf("secret list leaked or missed: %s", out)
178	}
179
180	// --- schedules and manual trigger ---
181	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte(
182		"jobs:\n  usesecret:\n    steps:\n      - echo token=$MY_TOKEN\n  nightly:\n    schedule: \"0 6 * * 1\"\n    steps:\n      - echo scheduled ran\n"), 0o644)
183	mustGit(t, dir, env, "add", ".")
184	mustGit(t, dir, env, "commit", "-q", "-m", "secrets and schedule")
185	mustGit(t, dir, env, "push", "-q", "origin", "main")
186
187	// The push queued only the unscheduled job.
188	out, _, _ = inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
189	if !strings.Contains(out, "usesecret\tpending") || strings.Contains(out, "nightly") {
190		t.Fatalf("scheduled job queued on push:\n%s", out)
191	}
192	inst.runnerOnce(t, runnerKey)
193	out, _, _ = inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
194	usecretN := strings.Split(out, "\t")[0]
195	out, _, _ = inst.ssh(t, aliceKey, "", "build", "log", "alice/app", usecretN)
196	if !strings.Contains(out, "token=hunter2") {
197		t.Fatalf("secret not injected:\n%s", out)
198	}
199	// The scheduled job runs on demand via trigger.
200	if _, errOut, code := inst.ssh(t, aliceKey, "", "build", "trigger", "alice/app", "nightly"); code != 0 {
201		t.Fatalf("trigger: %s", errOut)
202	}
203	if _, _, code := inst.ssh(t, aliceKey, "", "build", "trigger", "alice/app", "nosuch"); code != 3 {
204		t.Fatal("triggered a job that does not exist")
205	}
206	inst.runnerOnce(t, runnerKey)
207	out, _, _ = inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
208	if !strings.Contains(out, "nightly\tsuccess") {
209		t.Fatalf("triggered build did not run:\n%s", out)
210	}
211	// Removing the secret stops injection.
212	if _, _, code := inst.ssh(t, aliceKey, "", "repo", "secret", "remove", "alice/app", "MY_TOKEN"); code != 0 {
213		t.Fatal("secret remove failed")
214	}
215
216	// --- tag-triggered jobs ---
217	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte(
218		"jobs:\n  test:\n    steps:\n      - echo branch build\n  publish:\n    tags: \"v*\"\n    steps:\n      - echo publishing $GITBAY_REF\n"), 0o644)
219	mustGit(t, dir, env, "add", ".")
220	mustGit(t, dir, env, "commit", "-q", "-m", "tag job")
221	mustGit(t, dir, env, "push", "-q", "origin", "main")
222	// The branch push queued only the branch job.
223	out, _, _ = inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
224	if strings.Contains(out, "publish") {
225		t.Fatalf("tag job queued on branch push:\n%s", out)
226	}
227	// An annotated tag queues the tag job, with the peeled commit as sha.
228	mustGit(t, dir, env, "tag", "-a", "-m", "rel", "v1.0.0")
229	mustGit(t, dir, env, "push", "-q", "origin", "v1.0.0")
230	headSHA := strings.TrimSpace(mustGit(t, dir, env, "rev-parse", "HEAD"))
231	out, _, _ = inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
232	if !strings.Contains(out, "publish\tpending\t"+headSHA[:10]) || !strings.Contains(out, "v1.0.0") {
233		t.Fatalf("tag build missing or unpeeled:\n%s", out)
234	}
235	// A non-matching tag queues nothing.
236	mustGit(t, dir, env, "tag", "nightly-1")
237	mustGit(t, dir, env, "push", "-q", "origin", "nightly-1")
238	out2, _, _ := inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
239	if strings.Count(out2, "publish") != strings.Count(out, "publish") {
240		t.Fatalf("non-matching tag queued a build:\n%s", out2)
241	}
242	inst.runnerOnce(t, runnerKey) // branch "test" job
243	inst.runnerOnce(t, runnerKey) // tag "publish" job
244	out, _, _ = inst.ssh(t, aliceKey, "", "build", "list", "alice/app")
245	if !strings.Contains(out, "publish\tsuccess") {
246		t.Fatalf("tag build did not run:\n%s", out)
247	}
248	// schedule and tags together are refused.
249	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte(
250		"jobs:\n  both:\n    schedule: \"0 6 * * *\"\n    tags: \"v*\"\n    steps: [echo x]\n"), 0o644)
251	mustGit(t, dir, env, "add", ".")
252	mustGit(t, dir, env, "commit", "-q", "-m", "both triggers")
253	mustGit(t, dir, env, "push", "-q", "origin", "main")
254	shaBoth := strings.TrimSpace(mustGit(t, dir, env, "rev-parse", "HEAD"))
255	out, _, _ = inst.ssh(t, aliceKey, "", "status", "list", "alice/app", shaBoth)
256	if !strings.Contains(out, "ci/config") || !strings.Contains(out, "failure") {
257		t.Fatalf("mutually exclusive triggers not refused:\n%s", out)
258	}
259
260	// A broken ci.yml surfaces as a failed ci/config status.
261	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte("jobs: {bad name: {steps: [x]}}\n"), 0o644)
262	mustGit(t, dir, env, "add", ".")
263	mustGit(t, dir, env, "commit", "-q", "-m", "break config")
264	mustGit(t, dir, env, "push", "-q", "origin", "main")
265	sha2 := strings.TrimSpace(mustGit(t, dir, env, "rev-parse", "HEAD"))
266	out, _, _ = inst.ssh(t, aliceKey, "", "status", "list", "alice/app", sha2)
267	if !strings.Contains(out, "ci/config") || !strings.Contains(out, "failure") {
268		t.Fatalf("config failure status missing:\n%s", out)
269	}
270}
271
272// runnerJobs runs a runner with -jobs n until it has nothing left to do,
273// and returns its output. Unlike runnerOnce it is not bounded to one
274// build, so it is stopped when the queue drains.
275func (i *instance) runnerJobs(t *testing.T, key, repo string, jobs int) string {
276	t.Helper()
277	opts := fmt.Sprintf("-p %d -i %s -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=%s -o BatchMode=yes",
278		i.port, key, filepath.Join(i.sshDir, "known_hosts"))
279	cmd := exec.Command(i.runner,
280		"-jobs", fmt.Sprint(jobs),
281		"-poll", "200ms",
282		"-isolation", "none",
283		"-remote", "git@127.0.0.1",
284		"-ssh-opts", opts,
285		"-clone-base", fmt.Sprintf("ssh://git@127.0.0.1:%d", i.port),
286		"-workdir", t.TempDir())
287	cmd.Env = append(os.Environ(), "XDG_CONFIG_HOME="+t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null")
288	var buf bytes.Buffer
289	cmd.Stdout, cmd.Stderr = &buf, &buf
290	if err := cmd.Start(); err != nil {
291		t.Fatal(err)
292	}
293	defer func() { cmd.Process.Kill(); cmd.Wait() }()
294
295	// Wait for every queued build to leave the pending and running states.
296	deadline := time.Now().Add(60 * time.Second)
297	for time.Now().Before(deadline) {
298		out, _, code := i.ssh(t, key, "", "build", "list", repo, "--json")
299		if code == 0 && !strings.Contains(out, `"status":"pending"`) &&
300			!strings.Contains(out, `"status":"running"`) {
301			break
302		}
303		time.Sleep(200 * time.Millisecond)
304	}
305	return buf.String()
306}
307
308// -jobs N runs N builds at once. ClaimBuild has always been a single
309// transaction that selects and updates, so several workers claiming
310// together is safe; the runner simply never used more than one (#115).
311func TestRunnerConcurrentJobs(t *testing.T) {
312	t.Parallel()
313	inst := startInstance(t)
314	inst.runner = buildRunner(t)
315	aliceKey := inst.newKey(t, "alice")
316	inst.admin(t, "admin", "user", "create", "alice", "--key", aliceKey+".pub", "--admin")
317	if _, errOut, code := inst.ssh(t, aliceKey, "", "repo", "create", "alice/app"); code != 0 {
318		t.Fatalf("repo create: %s", errOut)
319	}
320
321	// Four jobs, each sleeping longer than the poll interval, so serial
322	// execution and concurrent execution are distinguishable.
323	ci := "jobs:\n"
324	for _, name := range []string{"one", "two", "three", "four"} {
325		ci += fmt.Sprintf("  %s:\n    steps:\n      - sleep 1\n      - echo done-%s\n", name, name)
326	}
327	env := inst.gitEnv(aliceKey)
328	work := t.TempDir()
329	mustGit(t, work, env, "clone", inst.sshURL("alice/app"), "w")
330	dir := filepath.Join(work, "w")
331	os.MkdirAll(filepath.Join(dir, ".gitbay"), 0o755)
332	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte(ci), 0o644)
333	mustGit(t, dir, env, "checkout", "-q", "-b", "main")
334	mustGit(t, dir, env, "add", ".")
335	mustGit(t, dir, env, "commit", "-q", "-m", "ci")
336	mustGit(t, dir, env, "push", "-q", "origin", "main")
337
338	out := inst.runnerJobs(t, aliceKey, "alice/app", 4)
339
340	listing, _, code := inst.ssh(t, aliceKey, "", "build", "list", "alice/app", "--json")
341	if code != 0 {
342		t.Fatalf("build list failed:\n%s", out)
343	}
344	for _, name := range []string{"one", "two", "three", "four"} {
345		if !strings.Contains(listing, `"job":"`+name+`"`) {
346			t.Fatalf("%s never ran:\n%s\n%s", name, listing, out)
347		}
348	}
349	if strings.Contains(listing, `"status":"pending"`) || strings.Contains(listing, `"status":"running"`) {
350		t.Fatalf("builds did not finish:\n%s", listing)
351	}
352	// Overlap, asserted from the runner's own log rather than from wall
353	// clock: elapsed time also covers four concurrent clones and the
354	// polling this test does, and would make a slow machine look serial.
355	// Every build announces itself when it starts and again when it
356	// finishes, so concurrency is "a build started before the first one
357	// finished".
358	started, firstFinish := 0, -1
359	for _, line := range strings.Split(out, "\n") {
360		switch {
361		case strings.Contains(line, "alice/app"):
362			started++
363		case strings.Contains(line, ": success"), strings.Contains(line, ": failure"):
364			if firstFinish < 0 {
365				firstFinish = started
366			}
367		}
368	}
369	if started != 4 {
370		t.Fatalf("%d builds started, want 4:\n%s", started, out)
371	}
372	if firstFinish < 2 {
373		t.Errorf("only %d build(s) had started when the first finished; -jobs 4 ran them serially\n%s",
374			firstFinish, out)
375	}
376}