package checks import ( "bytes" "encoding/json" "errors" "go/version" "io/fs" "os" "path" "path/filepath" "regexp" "slices" "strings" "sync" ) // Run is a command's exit code and output. Evidence is what was read // from the whole output as it was produced (the Output kept may be only // its tail); without it nothing is concluded from the output. type Run struct { Code int Output string Evidence *Evidence } // Go's progress lines there are neither evidence nor a disqualification. var neutralLine = regexp.MustCompile(`^go: (?:no module dependencies to download|downloading \S+ \S+)$`) var offlineRefusal = regexp.MustCompile(`^go: (?:download go1\.[0-9a-z.]+ for [a-z0-9]+/[a-z0-9]+: )?(?:[^\s@:]+@[^\s@:]+: module lookup disabled by GOPROXY=off|golang\.org/toolchain@v0\.0\.1-go1\.[0-9a-z.]+-[a-z0-9]+: verifying module: checksum database disabled by GOSUMDB=off)$`) // A failure of the gate's own, beyond dependencies it could not fetch: a // failing test, a panic, or a compiler or vet diagnostic other than Go // failing to fetch a module (offline, or into the read-only cache, which // is how a build in the check profile reports a module the cache lacks). // These lines only decide what does not count against the stage's // evidence; they never establish it. var independentFailure = regexp.MustCompile(`(?m)^(?:--- FAIL: |panic: |\S+\.go:[0-9]+(?::[0-9]+)?: )`) var offlineDiagnostic = regexp.MustCompile(`^\S+\.go:[0-9]+(?::[0-9]+)?: (?:module lookup disabled by GOPROXY=off|(?:mkdir|open) /opt/go-mod/cache/download/\S+: read-only file system)$`) // NeedsNetwork reports whether a failed gate could neither pass nor fail // honestly offline. Only Equipo's own dependency stage can show it: the // stage failed, its whole output was read, and every line is Go refusing // an offline download. The gate's output is the candidate's, so it can // only keep a failure a failure: read whole, it must show no failing // test (plain or go test -json), panic, build failure or diagnostic // other than Go failing to fetch a module. Evidence that is missing or // incomplete keeps it a failure. func NeedsNetwork(stage, gate Run) bool { s, g := stage.Evidence, gate.Evidence if stage.Code == 0 || gate.Code == 0 || s == nil || g == nil { return false } s.mu.Lock() staged := s.complete() && s.refusals > 0 && s.others == 0 s.mu.Unlock() g.mu.Lock() defer g.mu.Unlock() return staged && g.complete() && !g.failure } // maxEvidenceLine bounds one line; a longer one makes the evidence // incomplete rather than unread. const maxEvidenceLine = 64 << 10 // Evidence classifies every line of a command's output as it is // produced, before any tail is kept. It is complete only when every // stream it was given was closed whole. type Evidence struct { mu sync.Mutex open int broken, failure bool refusals, others int } // EvidenceStream is one output stream's writer. Close when the stream // ended whole; Abort when it was cut short or could not be read. type EvidenceStream struct { e *Evidence partial []byte long bool done bool } // NewEvidence returns evidence fed by n streams. func NewEvidence(n int) (*Evidence, []*EvidenceStream) { e := &Evidence{open: n} streams := make([]*EvidenceStream, n) for i := range streams { streams[i] = &EvidenceStream{e: e} } return e, streams } // Scan is the evidence of an output read whole. func Scan(output string) *Evidence { e, w := NewEvidence(1) w[0].Write([]byte(output)) w[0].Close() return e } func (w *EvidenceStream) Write(p []byte) (int, error) { n := len(p) for len(p) > 0 { i := bytes.IndexByte(p, '\n') chunk := p if i >= 0 { chunk = p[:i] } if !w.long { if len(w.partial)+len(chunk) > maxEvidenceLine { w.long, w.partial = true, nil } else { w.partial = append(w.partial, chunk...) } } if i < 0 { break } w.line() p = p[i+1:] } return n, nil } func (w *EvidenceStream) line() { w.e.mu.Lock() defer w.e.mu.Unlock() if w.long { w.e.broken = true } else { w.e.classify(strings.TrimSuffix(string(w.partial), "\r")) } w.partial, w.long = w.partial[:0], false } // Close records the stream's last line and that it ended whole. func (w *EvidenceStream) Close() error { if w.done { return nil } if len(w.partial) > 0 || w.long { w.line() } w.done = true w.e.mu.Lock() w.e.open-- w.e.mu.Unlock() return nil } // Abort records that the stream did not end whole. func (w *EvidenceStream) Abort() { w.e.mu.Lock() w.e.broken = true w.e.mu.Unlock() } func (e *Evidence) complete() bool { return e.open == 0 && !e.broken } func (e *Evidence) classify(line string) { if (independentFailure.MatchString(line) && !offlineDiagnostic.MatchString(line)) || jsonFailure(line) { e.failure = true } switch trimmed := strings.TrimSpace(line); { case trimmed == "" || neutralLine.MatchString(trimmed): case offlineRefusal.MatchString(trimmed): e.refusals++ default: e.others++ } } // jsonFailure reports a go test -json event that failed: a test or a // package (fail), or a build (build-fail). func jsonFailure(line string) bool { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "{") { return false } var ev struct{ Action string } return json.Unmarshal([]byte(line), &ev) == nil && (ev.Action == "fail" || ev.Action == "build-fail") } // GoModuleDirs lists the directories under root ("." first) holding a // module's go.mod whose dependencies come from the module cache: not // vendored, and not under vendor or testdata or a directory Go ignores // (a leading dot or underscore). Symlinks are not followed. func GoModuleDirs(root string) []string { dir, err := os.OpenRoot(root) if err != nil { return nil } defer dir.Close() var out []string _ = fs.WalkDir(dir.FS(), ".", func(name string, d fs.DirEntry, err error) error { if err != nil || len(out) >= 64 { return fs.SkipDir } if d.IsDir() { if base := d.Name(); name != "." && (ignoredDir(base)) { return fs.SkipDir } return nil } if d.Name() != "go.mod" || !d.Type().IsRegular() { return nil } if info, err := dir.Lstat(path.Join(path.Dir(name), "vendor/modules.txt")); err != nil || !info.Mode().IsRegular() { out = append(out, path.Dir(name)) } return nil }) slices.Sort(out) return out } func ignoredDir(base string) bool { return base == "vendor" || base == "testdata" || strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") } // DependencyStage is the argv of Equipo's own dependency stage: `go mod // download` in each module directory, stopping at the first failure. It // works on copies of go.mod and go.sum (-modfile), so the tree the gate // then checks is exactly the candidate's. func DependencyStage(dirs []string) []string { const script = `t=$(mktemp -d) || exit 1 i=0 for d; do i=$((i+1)); mkdir -p "$t/$i" || exit 1 cp -- "$d/go.mod" "$t/$i/go.mod" || exit 1 if [ -f "$d/go.sum" ]; then cp -- "$d/go.sum" "$t/$i/go.sum" || exit 1; fi (cd -- "$d" && go mod download -modfile="$t/$i/go.mod") || exit $? done` return append([]string{"/usr/bin/bash", "-c", script, "equipo-dependencies"}, dirs...) } // GoRequirement is what a repository's own files ask of the Go toolchain. type GoRequirement struct { // Minimum is the highest go or toolchain directive in any go.mod. Minimum string // Make are the releases Makefiles pin. make runs with // GOTOOLCHAIN=local (gotoolchain.Environment), so a newer patch of // the same minor release stands in. Make []string // Exact are the releases other gate files pin. Nothing overrides // those, so only that release runs them. Exact []string } // GoRequirementFile reports whether a repository file is read for its Go // requirement: a go.mod (not a vendored or test-data copy), a Makefile or // .mk file, or an Amadan gate file. func GoRequirementFile(name string) bool { for _, part := range strings.Split(path.Dir(name), "/") { if part != "." && ignoredDir(part) && part != ".amadan" { return false } } base := path.Base(name) return base == "go.mod" || base == "Makefile" || base == "makefile" || base == "GNUmakefile" || path.Ext(name) == ".mk" || name == ".amadan/ci" || strings.HasPrefix(name, ".amadan/ci.d/") } var goDirective = regexp.MustCompile(`(?m)^[ \t]*(go|toolchain)[ \t]+(\S+)[ \t]*(?://.*)?$`) var toolchainPin = regexp.MustCompile(`\bGOTOOLCHAIN[ \t]*(?::=|::=|\?=|=)[ \t]*['"]?(go1\.[0-9]+(?:\.[0-9]+)?(?:(?:rc|beta)[0-9]+)?)(\+auto|\+path)?`) // ReadGoRequirement reads the requirement from files named by // GoRequirementFile (path to content). func ReadGoRequirement(files map[string][]byte) GoRequirement { var r GoRequirement raise := func(v string) { if version.IsValid(v) && (r.Minimum == "" || version.Compare(v, r.Minimum) > 0) { r.Minimum = v } } for name, body := range files { text := string(body) if path.Base(name) == "go.mod" { for _, m := range goDirective.FindAllStringSubmatch(text, -1) { v := m[2] if m[1] == "go" { v = "go" + v } raise(v) } continue } makefile := path.Base(name) != "ci" && !strings.HasPrefix(name, ".amadan/") for _, m := range toolchainPin.FindAllStringSubmatch(text, -1) { switch { case m[2] != "": raise(m[1]) case makefile: r.Make = append(r.Make, m[1]) default: r.Exact = append(r.Exact, m[1]) } } } return r } // Unmet reports whether the local toolchain (go1.x.y) cannot honour r. func (r GoRequirement) Unmet(local string) bool { if r.Minimum != "" && version.Compare(local, r.Minimum) < 0 { return true } for _, pin := range r.Make { if version.Lang(pin) != version.Lang(local) || version.Compare(local, pin) < 0 { return true } } for _, pin := range r.Exact { if version.Compare(local, pin) != 0 { return true } } return false } // RunnerGoVersion is the release of the Go tree at goRoot, from the first // line of its VERSION file. func RunnerGoVersion(goRoot string) (string, error) { raw, err := os.ReadFile(filepath.Join(goRoot, "VERSION")) if err != nil { return "", err } v, _, _ := strings.Cut(string(raw), "\n") if v = strings.TrimSpace(v); !version.IsValid(v) { return "", errors.New("go root has no release version") } return v, nil }