blob: 7fb89f42ca6273a08068d960b5349f21c405a00a [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package main
import (
"bytes"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
)
func TestValidateFlags(t *testing.T) {
tests := []struct {
name string
testScript string
runnerPath string
scriptList string
maxJobs int
wantErr bool
}{
{
name: "single script valid",
testScript: "foo.sh",
},
{
name: "script list valid",
runnerPath: "runner.sh",
scriptList: "list.txt",
maxJobs: 4,
},
{
name: "neither set",
wantErr: true,
},
{
name: "both set",
testScript: "foo.sh",
runnerPath: "runner.sh",
scriptList: "list.txt",
wantErr: true,
},
{
name: "runner without scriptlist",
testScript: "foo.sh",
runnerPath: "runner.sh",
wantErr: true,
},
{
name: "scriptlist without runner",
scriptList: "list.txt",
wantErr: true,
},
{
name: "negative jobs",
runnerPath: "runner.sh",
scriptList: "list.txt",
maxJobs: -1,
wantErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := validateFlags(tc.testScript, tc.runnerPath, tc.scriptList, tc.maxJobs)
if (err != nil) != tc.wantErr {
t.Fatalf("validateFlags() error = %v, wantErr = %v", err, tc.wantErr)
}
})
}
}
func TestResolvePath(t *testing.T) {
if got := resolvePath("/base/dir", ""); got != "/base/dir" {
t.Errorf("resolvePath(empty) = %q, want %q", got, "/base/dir")
}
if got := resolvePath("/base/dir", "sub/file"); got != "/base/dir/sub/file" {
t.Errorf("resolvePath(rel) = %q, want %q", got, "/base/dir/sub/file")
}
if got := resolvePath("/base/dir", "/abs/file"); got != "/abs/file" {
t.Errorf("resolvePath(abs) = %q, want %q", got, "/abs/file")
}
}
func TestReadScriptList(t *testing.T) {
dir := t.TempDir()
listPath := filepath.Join(dir, "scripts.list")
content := "# comment\n\n script_a \n\t# indented comment\nscript_b\n\n"
if err := os.WriteFile(listPath, []byte(content), 0644); err != nil {
t.Fatal(err)
}
got, err := readScriptList(listPath)
if err != nil {
t.Fatalf("readScriptList() error = %v", err)
}
if len(got) != 2 || got[0] != "script_a" || got[1] != "script_b" {
t.Fatalf("readScriptList() = %v, want [script_a script_b]", got)
}
}
func writeExecutable(t *testing.T, path, content string) {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0755); err != nil {
t.Fatal(err)
}
}
func TestRunScriptListFailuresAndSignalExit(t *testing.T) {
dir := t.TempDir()
runnerPath := filepath.Join(dir, "runner.sh")
writeExecutable(t, runnerPath, `#!/bin/bash
case "$1" in
pass_script)
echo "ok:$1"
exit 0
;;
fail_script)
echo "bad:$1"
exit 42
;;
sig_script)
echo "killing:$1"
kill -KILL $$
;;
esac
`)
listPath := filepath.Join(dir, "scripts.list")
if err := os.WriteFile(listPath, []byte("pass_script\nfail_script\nsig_script\n"), 0644); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
rc := runScriptList(scriptListConfig{
runnerPath: runnerPath,
listPath: listPath,
rootDir: dir,
maxJobs: 3,
stdout: &stdout,
stderr: &stderr,
})
if rc != 1 {
t.Fatalf("runScriptList() rc = %d, want 1", rc)
}
outStr := stdout.String()
for _, want := range []string{"ok:pass_script", "bad:fail_script", "killing:sig_script"} {
if !strings.Contains(outStr, want) {
t.Errorf("stdout missing %q:\n%s", want, outStr)
}
}
errStr := stderr.String()
if !strings.Contains(errStr, "fail_script (exit 42)") {
t.Errorf("stderr missing exit code failure:\n%s", errStr)
}
if !strings.Contains(errStr, "sig_script (signal: killed)") {
t.Errorf("stderr missing signal failure details:\n%s", errStr)
}
if strings.Contains(errStr, "exit -1") {
t.Errorf("stderr should not overwrite signal with exit -1:\n%s", errStr)
}
}
// watchGrandchildFifo creates a named FIFO in dir and starts a background
// reader that closes eofCh once a writer opens the FIFO and subsequently closes
// all write descriptors. In Linux do_exit(), exit_files() closes all open file
// descriptors before exit_notify() transitions the process to EXIT_ZOMBIE, so
// eofCh closes as soon as the grandchild terminates even when PID 1 in an
// isolated PID namespace (such as nsjail without /proc) leaves it unreaped.
func watchGrandchildFifo(t *testing.T, dir, pidFile string) (fifoPath, readyFifo string, eofCh <-chan struct{}) {
t.Helper()
fifoPath = filepath.Join(dir, "grandchild.fifo")
if err := syscall.Mkfifo(fifoPath, 0600); err != nil {
t.Fatalf("Mkfifo(%q) failed: %v", fifoPath, err)
}
readyFifo = filepath.Join(dir, "grandchild_ready.fifo")
if err := syscall.Mkfifo(readyFifo, 0600); err != nil {
t.Fatalf("Mkfifo(%q) failed: %v", readyFifo, err)
}
doneCh := make(chan struct{})
var (
mu sync.Mutex
openedRd *os.File
cleanupClosed bool
)
go func() {
defer close(doneCh)
f, err := os.OpenFile(fifoPath, os.O_RDONLY, 0)
if err != nil {
return
}
defer f.Close()
mu.Lock()
if cleanupClosed {
mu.Unlock()
return
}
openedRd = f
mu.Unlock()
_, _ = io.Copy(io.Discard, f)
}()
t.Cleanup(func() {
select {
case <-doneCh:
return
default:
}
if raw, err := os.ReadFile(pidFile); err == nil {
if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 {
_ = syscall.Kill(pid, syscall.SIGKILL)
}
}
// Unblock OpenFile(O_RDONLY) if no writer ever opened the FIFO.
if w, err := os.OpenFile(fifoPath, os.O_RDWR, 0); err == nil {
_ = w.Close()
}
// Unblock io.Copy if an unknown writer still holds the FIFO open.
mu.Lock()
cleanupClosed = true
f := openedRd
mu.Unlock()
if f != nil {
_ = f.SetReadDeadline(time.Now())
}
<-doneCh
})
return fifoPath, readyFifo, doneCh
}
func TestRunScriptListCleansUpOrphanedGrandchildren(t *testing.T) {
dir := t.TempDir()
pidFile := filepath.Join(dir, "orphan.pid")
fifoPath, readyFifo, eofCh := watchGrandchildFifo(t, dir, pidFile)
runnerPath := filepath.Join(dir, "runner.sh")
writeExecutable(t, runnerPath, `#!/bin/bash
(
exec >"`+fifoPath+`" 2>/dev/null
exec 3>"`+readyFifo+`"
exec 3>&-
exec sleep 60
) &
echo $! >"`+pidFile+`"
read -r _ <"`+readyFifo+`" || true
exit 0
`)
listPath := filepath.Join(dir, "scripts.list")
if err := os.WriteFile(listPath, []byte("orphan_test\n"), 0644); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
rc := runScriptList(scriptListConfig{
runnerPath: runnerPath,
listPath: listPath,
rootDir: dir,
maxJobs: 1,
stdout: &stdout,
stderr: &stderr,
})
if rc != 0 {
t.Fatalf("runScriptList() rc = %d, want 0 (stderr=%s)", rc, stderr.String())
}
raw, err := os.ReadFile(pidFile)
if err != nil {
t.Fatalf("reading orphan pid file: %v", err)
}
pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
if err != nil {
t.Fatalf("parsing orphan pid: %v", err)
}
// Wait for the kernel to close the grandchild's FIFO write descriptor upon exit.
select {
case <-eofCh:
case <-time.After(2 * time.Second):
_ = syscall.Kill(pid, syscall.SIGKILL)
t.Fatalf("orphaned grandchild pid %d was still alive after worker exited", pid)
}
}
func TestRunScriptListSignalTeardownDumpsPartialAndPriorFailures(t *testing.T) {
dir := t.TempDir()
startedFile := filepath.Join(dir, "started")
grandchildFile := filepath.Join(dir, "grandchild.pid")
failedDoneFile := filepath.Join(dir, "failed_done")
fifoPath, readyFifo, eofCh := watchGrandchildFifo(t, dir, grandchildFile)
runnerPath := filepath.Join(dir, "runner.sh")
writeExecutable(t, runnerPath, `#!/bin/bash
case "$1" in
early_fail)
echo "early-fail-output"
touch "`+failedDoneFile+`"
exit 7
;;
hanging_script)
echo "partial-line-from-hanging"
(
exec >"`+fifoPath+`" 2>/dev/null
exec 3>"`+readyFifo+`"
exec 3>&-
exec sleep 60
) &
echo $! >"`+grandchildFile+`"
read -r _ <"`+readyFifo+`" || true
touch "`+startedFile+`"
wait
;;
esac
`)
listPath := filepath.Join(dir, "scripts.list")
if err := os.WriteFile(listPath, []byte("early_fail\nhanging_script\n"), 0644); err != nil {
t.Fatal(err)
}
sigCh := make(chan os.Signal, 1)
go func() {
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
_, err1 := os.Stat(startedFile)
_, err2 := os.Stat(failedDoneFile)
if err1 == nil && err2 == nil {
// Give the early_fail worker a moment to finish recording its failure.
time.Sleep(100 * time.Millisecond)
sigCh <- syscall.SIGTERM
return
}
time.Sleep(20 * time.Millisecond)
}
sigCh <- syscall.SIGTERM
}()
var stdout, stderr bytes.Buffer
rc := runScriptList(scriptListConfig{
runnerPath: runnerPath,
listPath: listPath,
rootDir: dir,
maxJobs: 2,
stdout: &stdout,
stderr: &stderr,
sigCh: sigCh,
shutdownGrace: 300 * time.Millisecond,
killGrace: 300 * time.Millisecond,
})
if rc != 128+int(syscall.SIGTERM) {
t.Fatalf("runScriptList() rc = %d, want %d", rc, 128+int(syscall.SIGTERM))
}
raw, err := os.ReadFile(grandchildFile)
if err != nil {
t.Fatalf("reading grandchild pid file: %v", err)
}
pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
if err != nil {
t.Fatalf("parsing grandchild pid: %v", err)
}
select {
case <-eofCh:
case <-time.After(2 * time.Second):
_ = syscall.Kill(pid, syscall.SIGKILL)
t.Fatalf("grandchild pid %d survived SIGTERM teardown", pid)
}
outStr := stdout.String()
if !strings.Contains(outStr, "Partial output for in-flight script hanging_script") {
t.Errorf("stdout missing partial output header:\n%s", outStr)
}
if !strings.Contains(outStr, "partial-line-from-hanging") {
t.Errorf("stdout missing partial output body:\n%s", outStr)
}
errStr := stderr.String()
if !strings.Contains(errStr, "early_fail (exit 7)") {
t.Errorf("stderr missing prior failure:\n%s", errStr)
}
if !strings.Contains(errStr, "hanging_script") {
t.Errorf("stderr missing in-flight script name:\n%s", errStr)
}
}
func TestRunScriptListSigtermEscalatesToSigkill(t *testing.T) {
dir := t.TempDir()
startedFile := filepath.Join(dir, "started")
runnerPath := filepath.Join(dir, "runner.sh")
writeExecutable(t, runnerPath, `#!/bin/bash
trap '' TERM
echo "ignoring-sigterm"
touch "`+startedFile+`"
sleep 60
`)
listPath := filepath.Join(dir, "scripts.list")
if err := os.WriteFile(listPath, []byte("stubborn_script\n"), 0644); err != nil {
t.Fatal(err)
}
sigCh := make(chan os.Signal, 1)
go func() {
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if _, err := os.Stat(startedFile); err == nil {
sigCh <- syscall.SIGTERM
return
}
time.Sleep(20 * time.Millisecond)
}
sigCh <- syscall.SIGTERM
}()
start := time.Now()
var stdout, stderr bytes.Buffer
rc := runScriptList(scriptListConfig{
runnerPath: runnerPath,
listPath: listPath,
rootDir: dir,
maxJobs: 1,
stdout: &stdout,
stderr: &stderr,
sigCh: sigCh,
shutdownGrace: 150 * time.Millisecond,
killGrace: 200 * time.Millisecond,
})
elapsed := time.Since(start)
if rc != 128+int(syscall.SIGTERM) {
t.Fatalf("runScriptList() rc = %d, want %d", rc, 128+int(syscall.SIGTERM))
}
if elapsed > 5*time.Second {
t.Fatalf("teardown took too long: %v", elapsed)
}
if !strings.Contains(stdout.String(), "ignoring-sigterm") {
t.Errorf("stdout missing partial output:\n%s", stdout.String())
}
if !strings.Contains(stderr.String(), "stubborn_script") {
t.Errorf("stderr missing stubborn_script:\n%s", stderr.String())
}
}