diff --git a/internal/cmd/runner/logging_test.go b/internal/cmd/runner/logging_test.go new file mode 100644 index 00000000..64dcff1d --- /dev/null +++ b/internal/cmd/runner/logging_test.go @@ -0,0 +1,101 @@ +package main + +import ( + "bytes" + "context" + "errors" + "log" + "log/slog" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + logf "sigs.k8s.io/controller-runtime/pkg/log" +) + +// lockedBuffer is a bytes.Buffer safe for the concurrent writes a process-wide +// log destination can receive. +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) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func (b *lockedBuffer) Reset() { + b.mu.Lock() + defer b.mu.Unlock() + b.buf.Reset() +} + +// installedOutput backs installedHandler. controller-runtime's SetLogger is +// first-write-wins and cannot be undone, so the handler installLogging is +// tested with must be the same one on every run in this process (-count=2 +// included); only its buffer is reset. +var ( + installedOutput = &lockedBuffer{} + installedHandler = slog.NewTextHandler(installedOutput, nil) +) + +// These tests cover the two helpers main() and run() call. They cannot prove +// that main() calls installLogging or that run() builds its root context with +// newRootContext — neither is reachable from a unit test. + +// Not parallel: installLogging mutates slog's default logger, the stdlib log +// package's output, and controller-runtime's global logger. +func TestInstallLogging(t *testing.T) { + prevWriter, prevFlags := log.Writer(), log.Flags() + + t.Run("slog default and controller-runtime's global logger reach the handler", func(t *testing.T) { + prevDefault := slog.Default() + t.Cleanup(func() { + slog.SetDefault(prevDefault) + // SetDefault with a non-default handler also redirects the stdlib + // log package; restoring the previous default does not undo that. + log.SetOutput(prevWriter) + log.SetFlags(prevFlags) + }) + installedOutput.Reset() + + installLogging(installedHandler) + + slog.Info("via slog default") + logf.Log.Info("fallback notice publish failed", "session", "ns/demo-agent") + logf.Log.Error(errors.New("bus closed"), "publish errored") + + out := installedOutput.String() + assert.Contains(t, out, "via slog default") + assert.Contains(t, out, "fallback notice publish failed") + assert.Contains(t, out, "session=ns/demo-agent") + assert.Contains(t, out, `level=ERROR msg="publish errored" err="bus closed"`) + }) + + assert.Same(t, prevWriter, log.Writer(), "stdlib log output restored after cleanup") + assert.Equal(t, prevFlags, log.Flags(), "stdlib log flags restored after cleanup") +} + +// log.FromContext is how respond_to_user, the dispatch loop and authz slot +// promotion log. +func TestNewRootContext_FromContextReachesHandler(t *testing.T) { + var buf bytes.Buffer + ctx, cancel := newRootContext(slog.NewTextHandler(&buf, nil)) + + logf.FromContext(ctx).Info("fallback notice publish failed", "session", "ns/demo-agent") + + assert.Contains(t, buf.String(), "fallback notice publish failed") + assert.Contains(t, buf.String(), "session=ns/demo-agent") + + assert.NoError(t, ctx.Err()) + cancel() + assert.ErrorIs(t, ctx.Err(), context.Canceled) +} diff --git a/internal/cmd/runner/main.go b/internal/cmd/runner/main.go index 479589f3..21e7d151 100644 --- a/internal/cmd/runner/main.go +++ b/internal/cmd/runner/main.go @@ -32,6 +32,7 @@ import ( "k8s.io/utils/clock" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + logf "sigs.k8s.io/controller-runtime/pkg/log" "github.com/authzed/openagentprimitives/pkg/agent/derivevalidator" "github.com/authzed/openagentprimitives/pkg/agent/llm" @@ -254,7 +255,7 @@ func main() { deplogs.Silence() logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})) - slog.SetDefault(logger) + installLogging(logger.Handler()) // run() owns its own context + manual SIGTERM/SIGINT handling (see below), // so the root command uses Execute() rather than ExecuteContext() — the @@ -326,6 +327,26 @@ func newCommand() *cobra.Command { return cmd } +// installLogging makes h the destination for both slog's default logger and +// controller-runtime's global logger. Without the second half, every +// log.FromContext call in runner-side code (respond_to_user's fallback-notice +// failures, the dispatch loop, authz slot promotion) on a context that carries +// no logger of its own is discarded. +func installLogging(h slog.Handler) { + slog.SetDefault(slog.New(h)) + ctrl.SetLogger(logr.FromSlogHandler(h)) +} + +// newRootContext returns run()'s cancellable root context, carrying a logr view +// of h. log.FromContext prefers a context's own logger over the global one +// installLogging sets, so this is defence in depth: nothing in this binary is +// known to claim controller-runtime's first-write-wins global ahead of main, +// but the lines routed here are error reports, and a context-carried logger +// keeps them reaching stderr even if a dependency someday does. +func newRootContext(h slog.Handler) (context.Context, context.CancelFunc) { + return context.WithCancel(logf.IntoContext(context.Background(), logr.FromSlogHandler(h))) +} + func run(cfg *config) error { hostname := cfg.hostname ns := cfg.agentSessionNamespace @@ -383,7 +404,7 @@ func run(cfg *config) error { // SIGTERM handling. The signal-consuming goroutine is started below, once // the signing memory + session scope exist, so it can record an explicit // Stopped lifecycle transition before cancelling the loop. - rootCtx, cancel := context.WithCancel(context.Background()) + rootCtx, cancel := newRootContext(slog.Default().Handler()) defer cancel() // loopRef is stored once the runner Loop is fully constructed (below). The