Files
Davanum Srinivas a3c868615c fix(license): normalise SPDX headers to Apache-2.0, and assert it (#197)
* chore(license): normalise SPDX headers to Apache-2.0 [machine generated]

MACHINE GENERATED. Every added line in this commit is
`SPDX-License-Identifier: Apache-2.0` and nothing else; every removed line is
the identifier it replaces, or the notice paragraph that followed it. Verified:
0 added lines are anything other than that SPDX line.

829 files. The repository ships Apache-2.0 -- LICENSE says so and GitHub
reports it -- while 676 Go files and 153 others declared a different
identifier, followed by a notice that contradicted it.

The copyright line, the comment style and the indentation are left alone. Files
carrying the short form, two SPDX lines with no notice paragraph, have the
identifier swapped and nothing else.

Markdown is excluded: there the identifier appears in prose describing the
mismatch rather than in a header, so rewriting it would turn the sentence into
a tautology. That file is handled in the next commit.

Three shapes needed care, and each is worth knowing about if this is ever
repeated. controller/api/prepend-license.go carries the block inside a Go raw
string, so the paragraph's last line ends with a backtick; the closing
delimiter is carried back onto the SPDX line rather than dropped, or the string
would be left unterminated. Two shell scripts under controller/hack/ word the
final sentence differently, so matching on the common ending alone misses them.
And controller/.golangci.yml prefixes each line with "# //", which has to be
stripped before the paragraph text can be recognised.

The templates that produce these headers are rewritten here too, so this commit
is self-consistent: the five addlicense boilerplates, the five goheader
templates in .golangci.yml, and the block in prepend-license.go. Every header
in the tree now names the same identifier.

Review the next commit. This one is a substitution.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* fix(license): one header template, and a check that reads it

The previous commit fixed the headers. This one stops them drifting again, and
is the part worth reviewing.

Nothing here could catch a header that named the wrong licence. addlicense only
ADDS a header to a file that has none; it never rewrites one already present.
So `make file-license-check` runs addlicense, finds every file already stamped,
produces no diff, and passes -- whatever the header says. agent/ is the proof:
its template and its check have both been correct all along, and six of its
files disagreed with them.

Three mechanisms defined the header and could disagree with each other: an
addlicense boilerplate per module, a goheader template in five .golangci.yml
files, and a hardcoded block in controller/api/prepend-license.go that stamps
generated API code. They are now one file, hack/license-header.tmpl, and every
module reads it.

make license-header-check replaces the per-module matrix and asserts two things
rather than one: that a header exists, and that it names Apache-2.0. The second
assertion is what this repository never had. Verified by planting a different
identifier in a file and confirming the check fails and names it.

Modules resolve the template through `git rev-parse --show-toplevel`, not a
relative path. A relative ../hack path silently changes meaning when a module
moves, which is how cli/ broke when it moved out of controller/.

The file set is the union of what the per-module targets already ignored, so
this covers exactly the files stamped today. 120 files carry no header at all
-- generated output, testdata, fixtures, build tooling, three .github files --
and widening the set to reach them is a separate change. Mixing headers that
are WRONG with headers that are MISSING would hide both.

Dockerfiles stay out: addlicense keys off the file extension and gives
Dockerfile.proto C-style // comments, which Docker cannot parse.

AGENTS.md's licence-header rule now describes the current state: one identifier,
added by `make license` rather than copied from a neighbouring file. The ban on
relicensing as a side effect of unrelated work stays.

The header-check job is renamed from "License headers (<module>)" to "License
headers". The merge gate calls this workflow whole rather than naming its jobs,
and the branch ruleset requires only `gate` and `DCO`, so no required check
changes name.

Verified: GOPROXY=off make build links all five binaries with no credentials;
golangci-lint goheader reports 0 issues on cli and controller; `make license`
is a no-op in all five modules; make license-header-check passes over 828 files
and fails on a planted mismatched header.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

stderr is not captured when reading addlicense's output. addlicense prints the
offending paths to stdout, while `go run` writes "go: downloading ..." on a
cold module cache and "exit status 1" on failure -- both to stderr. Folding the
two together reports a module download as a file with no header, which is how
the first CI run of this check failed while passing on a machine whose cache
was already warm. Reproduced locally against an empty GOMODCACHE.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

---------

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>
2026-08-18 20:42:45 -04:00

185 lines
4.3 KiB
Go

//go:build gofail
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package framework
import (
"bufio"
"context"
"io"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// ProcessConfig describes a helper process launched from the current test binary.
type ProcessConfig struct {
Command string
Args []string
WorkingDir string
Env []string
ReadyContains string
ReadyTimeout time.Duration
}
// Process wraps a helper process and its captured stdout/stderr.
type Process struct {
cmd *exec.Cmd
outputs *lockedOutput
ready chan struct{}
exited chan error
readyTimeout time.Duration
}
// StartProcess starts a helper process.
func StartProcess(t testing.TB, cfg ProcessConfig) *Process {
t.Helper()
command := cfg.Command
if command == "" {
command = os.Args[0]
}
cmd := exec.Command(command, cfg.Args...) // #nosec G204 -- e2e helpers intentionally launch test-controlled binaries.
cmd.Dir = cfg.WorkingDir
cmd.Env = append(os.Environ(), cfg.Env...)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
stderr, err := cmd.StderrPipe()
require.NoError(t, err)
if cfg.ReadyTimeout == 0 {
cfg.ReadyTimeout = 10 * time.Second
}
p := &Process{
cmd: cmd,
outputs: &lockedOutput{},
ready: make(chan struct{}),
exited: make(chan error, 1),
readyTimeout: cfg.ReadyTimeout,
}
var readyOnce sync.Once
readOutput := func(r io.Reader) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
p.outputs.add(line)
if cfg.ReadyContains != "" && strings.Contains(line, cfg.ReadyContains) {
readyOnce.Do(func() { close(p.ready) })
}
}
if err := scanner.Err(); err != nil {
p.outputs.add("failed to read process output: " + err.Error())
}
}
require.NoError(t, cmd.Start())
go readOutput(stdout)
go readOutput(stderr)
go func() {
p.exited <- cmd.Wait()
}()
return p
}
// WaitReady blocks until the configured readiness output is observed or the process exits.
func (p *Process) WaitReady(t testing.TB) {
t.Helper()
select {
case <-p.ready:
case err := <-p.exited:
require.FailNowf(t, "process exited before it was ready", "wait error: %v\nprocess output:\n%s", err, p.Output())
case <-time.After(p.readyTimeout):
require.FailNowf(t, "process did not become ready", "process output:\n%s", p.Output())
}
}
// WaitExit waits for the process to exit and returns its wait error.
func (p *Process) WaitExit(t testing.TB, timeout time.Duration) error {
t.Helper()
select {
case err := <-p.exited:
return err
case <-time.After(timeout):
require.FailNowf(t, "process did not exit", "process output:\n%s", p.Output())
return nil
}
}
// WaitForOutput waits until the process emits output containing substring.
func (p *Process) WaitForOutput(ctx context.Context, substring string) error {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
if strings.Contains(p.Output(), substring) {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}
// Kill terminates the process and returns its wait error.
func (p *Process) Kill(t testing.TB) error {
t.Helper()
require.NotNil(t, p.cmd.Process)
require.NoError(t, p.cmd.Process.Kill())
return p.WaitExit(t, 5*time.Second)
}
// Stop interrupts the process and kills it if it does not exit promptly.
func (p *Process) Stop(t testing.TB) {
t.Helper()
if p.cmd.Process == nil {
return
}
require.NoError(t, p.cmd.Process.Signal(os.Interrupt))
select {
case err := <-p.exited:
require.NoError(t, err, "process output:\n%s", p.Output())
case <-time.After(5 * time.Second):
require.NoError(t, p.cmd.Process.Kill())
err := <-p.exited
require.Error(t, err, "process should report an error after kill")
}
}
// Output returns captured stdout and stderr, line by line.
func (p *Process) Output() string {
return p.outputs.String()
}
type lockedOutput struct {
mu sync.Mutex
b strings.Builder
}
func (o *lockedOutput) add(line string) {
o.mu.Lock()
defer o.mu.Unlock()
o.b.WriteString(line)
o.b.WriteByte('\n')
}
func (o *lockedOutput) String() string {
o.mu.Lock()
defer o.mu.Unlock()
return o.b.String()
}