blob: b267ec145959c4b6b997ca626f3f614a036e124e [file]
// Copyright 2020 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 (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"syscall"
"time"
)
var (
testscript = flag.String("testscript", "", "test script to execute. Relative paths are relative to the location of the running script. Absolute paths are absolute.")
testroot = flag.String("testroot", "", "Root directory of the files needed to execute the test.")
runner = flag.String("runner", "", "Script runner executable invoked for each entry in -scriptlist.")
scriptlist = flag.String("scriptlist", "", "File containing newline-separated test script paths to run in parallel via -runner.")
jobs = flag.Int("jobs", 0, "Maximum number of scripts to run concurrently (0 = min(NumCPU, 8)).")
)
const (
defaultMaxJobs = 8
shutdownGraceDur = 2 * time.Second
killGraceDur = 1 * time.Second
)
type lockedBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *lockedBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *lockedBuffer) Bytes() []byte {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]byte, b.buf.Len())
copy(out, b.buf.Bytes())
return out
}
type activeWorker struct {
pgid int
done bool
buf *lockedBuffer
}
type scriptListConfig struct {
runnerPath string
listPath string
rootDir string
maxJobs int
stdout io.Writer
stderr io.Writer
sigCh <-chan os.Signal
shutdownGrace time.Duration
killGrace time.Duration
}
func validateFlags(testScript, runnerPath, scriptList string, maxJobs int) error {
if maxJobs < 0 {
return fmt.Errorf("-jobs must be non-negative, got %d", maxJobs)
}
if testScript != "" && scriptList != "" {
return errors.New("-testscript and -scriptlist are mutually exclusive")
}
if scriptList == "" && runnerPath != "" {
return errors.New("-runner requires -scriptlist")
}
if scriptList != "" && runnerPath == "" {
return errors.New("-runner is required when -scriptlist is set")
}
if testScript == "" && scriptList == "" {
return errors.New("either -testscript or -scriptlist is required")
}
return nil
}
func resolvePath(baseDir, p string) string {
if filepath.IsAbs(p) {
return p
}
return path.Join(baseDir, p)
}
func readScriptList(listPath string) ([]string, error) {
f, err := os.Open(listPath)
if err != nil {
return nil, err
}
defer f.Close()
var scripts []string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
scripts = append(scripts, line)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return scripts, nil
}
func runSingleScript(theTest, theRoot string) int {
// Make sure the test is executable.
if err := os.Chmod(theTest, 0755); err != nil {
fmt.Fprintf(os.Stderr, "Chmod %v failed: %v\n", theTest, err)
return 1
}
cmd := exec.Command(theTest)
cmd.Dir = theRoot
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return exitErr.ExitCode()
}
fmt.Fprintf(os.Stderr, "%v failed: %v\n", theTest, err)
return 1
}
return 0
}
func formatFailure(script string, waitErr error) string {
var exitErr *exec.ExitError
if errors.As(waitErr, &exitErr) && exitErr.ExitCode() >= 0 {
return fmt.Sprintf("%s (exit %d)", script, exitErr.ExitCode())
}
return fmt.Sprintf("%s (%v)", script, waitErr)
}
func runScriptList(cfg scriptListConfig) int {
if cfg.stdout == nil {
cfg.stdout = os.Stdout
}
if cfg.stderr == nil {
cfg.stderr = os.Stderr
}
if cfg.shutdownGrace <= 0 {
cfg.shutdownGrace = shutdownGraceDur
}
if cfg.killGrace <= 0 {
cfg.killGrace = killGraceDur
}
if err := os.Chmod(cfg.runnerPath, 0755); err != nil {
fmt.Fprintf(cfg.stderr, "Chmod %v failed: %v\n", cfg.runnerPath, err)
return 1
}
scripts, err := readScriptList(cfg.listPath)
if err != nil {
fmt.Fprintf(cfg.stderr, "Reading script list %v failed: %v\n", cfg.listPath, err)
return 1
}
if len(scripts) == 0 {
return 0
}
maxJobs := cfg.maxJobs
if maxJobs <= 0 {
maxJobs = runtime.NumCPU()
if maxJobs > defaultMaxJobs {
maxJobs = defaultMaxJobs
}
if maxJobs < 1 {
maxJobs = 1
}
}
if maxJobs > len(scripts) {
maxJobs = len(scripts)
}
var (
stateMu sync.Mutex
cancelled bool
inFlight = make(map[string]*activeWorker)
outMu sync.Mutex
failMu sync.Mutex
failed []string
)
workCh := make(chan string, len(scripts))
for _, s := range scripts {
workCh <- s
}
close(workCh)
sigCh := cfg.sigCh
if sigCh == nil {
ch := make(chan os.Signal, 2)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(ch)
sigCh = ch
}
var wg sync.WaitGroup
for range maxJobs {
wg.Add(1)
go func() {
defer wg.Done()
for script := range workCh {
w := &activeWorker{buf: &lockedBuffer{}}
cmd := exec.Command(cfg.runnerPath, script)
cmd.Dir = cfg.rootDir
cmd.Stdout = w.buf
cmd.Stderr = w.buf
cmd.WaitDelay = cfg.killGrace
// Place each worker in its own process group so signal/timeout
// teardown and post-exit cleanup terminate the entire worker
// process tree while preserving default SIGINT/SIGQUIT
// dispositions in children.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
stateMu.Lock()
if cancelled {
stateMu.Unlock()
return
}
startErr := cmd.Start()
if startErr == nil {
w.pgid = cmd.Process.Pid
inFlight[script] = w
}
stateMu.Unlock()
if startErr != nil {
failMu.Lock()
failed = append(failed, fmt.Sprintf("%s (start failed: %v)", script, startErr))
failMu.Unlock()
continue
}
waitErr := cmd.Wait()
pgid := w.pgid
if pgid > 0 {
// Kill any orphaned descendants still in the worker's
// process group after the worker exits.
_ = syscall.Kill(-pgid, syscall.SIGKILL)
}
stateMu.Lock()
w.done = true
w.pgid = 0
if cancelled && waitErr != nil {
// Leave inFlight entry so the signal handler dumps partial output.
stateMu.Unlock()
return
}
delete(inFlight, script)
wasCancelled := cancelled
stateMu.Unlock()
outMu.Lock()
_, _ = cfg.stdout.Write(w.buf.Bytes())
outMu.Unlock()
if waitErr != nil {
failMu.Lock()
failed = append(failed, formatFailure(script, waitErr))
failMu.Unlock()
}
if wasCancelled {
return
}
}
}()
}
workersDone := make(chan struct{})
go func() {
wg.Wait()
close(workersDone)
}()
select {
case <-workersDone:
failMu.Lock()
defer failMu.Unlock()
if len(failed) > 0 {
sort.Strings(failed)
fmt.Fprintf(cfg.stderr, "ERROR: %d test script(s) failed:\n", len(failed))
for _, f := range failed {
fmt.Fprintf(cfg.stderr, " - %s\n", f)
}
return 1
}
return 0
case sig := <-sigCh:
stateMu.Lock()
cancelled = true
pgids := make([]int, 0, len(inFlight))
for _, w := range inFlight {
if !w.done && w.pgid > 0 {
pgids = append(pgids, w.pgid)
}
}
stateMu.Unlock()
for _, pgid := range pgids {
_ = syscall.Kill(-pgid, syscall.SIGTERM)
}
select {
case <-workersDone:
case <-time.After(cfg.shutdownGrace):
// Re-snapshot only workers that have not yet exited/been reaped
// so we do not signal a recycled PID.
stateMu.Lock()
remainingPgids := make([]int, 0, len(inFlight))
for _, w := range inFlight {
if !w.done && w.pgid > 0 {
remainingPgids = append(remainingPgids, w.pgid)
}
}
stateMu.Unlock()
for _, pgid := range remainingPgids {
_ = syscall.Kill(-pgid, syscall.SIGKILL)
}
// Wait boundedly so a descendant that escaped the process group
// while holding stdout/stderr open cannot block dumping partial logs.
select {
case <-workersDone:
case <-time.After(cfg.killGrace):
}
}
stateMu.Lock()
names := make([]string, 0, len(inFlight))
partialOutputs := make(map[string][]byte, len(inFlight))
for name, w := range inFlight {
names = append(names, name)
partialOutputs[name] = w.buf.Bytes()
}
stateMu.Unlock()
sort.Strings(names)
outMu.Lock()
for _, name := range names {
fmt.Fprintf(cfg.stdout, "\n=== Partial output for in-flight script %s ===\n", name)
_, _ = cfg.stdout.Write(partialOutputs[name])
}
outMu.Unlock()
failMu.Lock()
priorFailures := append([]string(nil), failed...)
failMu.Unlock()
if len(priorFailures) > 0 {
sort.Strings(priorFailures)
fmt.Fprintf(cfg.stderr, "\nERROR: %d test script(s) failed prior to signal:\n", len(priorFailures))
for _, f := range priorFailures {
fmt.Fprintf(cfg.stderr, " - %s\n", f)
}
}
fmt.Fprintf(cfg.stderr, "\nERROR: received signal %v; %d test script(s) were still in flight:\n", sig, len(names))
for _, name := range names {
fmt.Fprintf(cfg.stderr, " - %s\n", name)
}
if s, ok := sig.(syscall.Signal); ok {
return 128 + int(s)
}
return 1
}
}
// This is a wrapper for running unit tests.
func main() {
flag.Parse()
if err := validateFlags(*testscript, *runner, *scriptlist, *jobs); err != nil {
fmt.Fprintf(os.Stderr, "Invalid flags: %v\n", err)
os.Exit(1)
}
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
fmt.Fprintf(os.Stderr, "Could not determine execution path: %v\n", err)
os.Exit(1)
}
theRoot := resolvePath(dir, *testroot)
if *scriptlist != "" {
os.Exit(runScriptList(scriptListConfig{
runnerPath: resolvePath(dir, *runner),
listPath: resolvePath(dir, *scriptlist),
rootDir: theRoot,
maxJobs: *jobs,
}))
}
os.Exit(runSingleScript(resolvePath(dir, *testscript), theRoot))
}