package main import ( "errors" "net" "os" "path/filepath" "syscall" "testing" "time" ) // TestNotifyReadyWritesToTheSocket: the whole contract. systemd hands the // process a unixgram socket path in NOTIFY_SOCKET and waits for READY=1 // before calling the unit started — which is what turns "exec'd" into // "actually serving" for the adopt pass's restart check. // // Uses os.MkdirTemp directly (NOT t.TempDir): t.TempDir embeds the test // name in the path it hands back, and AF_UNIX socket paths are capped at // sizeof(sockaddr_un.sun_path) — 108 bytes on Linux. A long test name under // a long TMPDIR pushes that over the limit and net.ListenPacket fails with // "invalid argument", which is a test-harness artifact, not evidence // unixgram sockets are unsupported here — so only the genuinely-unsupported // errors (EAFNOSUPPORT, EPERM) are allowed to skip the test; anything else, // including a too-long path, must fail loudly. func TestNotifyReadyWritesToTheSocket(t *testing.T) { dir, err := os.MkdirTemp("", "n") if err != nil { t.Fatalf("MkdirTemp: %v", err) } t.Cleanup(func() { os.RemoveAll(dir) }) sock := filepath.Join(dir, "n.sock") conn, err := net.ListenPacket("unixgram", sock) if err != nil { if errors.Is(err, syscall.EAFNOSUPPORT) || errors.Is(err, syscall.EPERM) { t.Skipf("unixgram unavailable here: %v", err) } t.Fatalf("ListenPacket(unixgram, %s): %v", sock, err) } defer conn.Close() t.Setenv("NOTIFY_SOCKET", sock) if err := NotifyReady(); err != nil { t.Fatalf("NotifyReady: %v", err) } buf := make([]byte, 64) conn.SetReadDeadline(time.Now().Add(2 * time.Second)) n, _, err := conn.ReadFrom(buf) if err != nil { t.Fatalf("nothing arrived on the notify socket: %v", err) } if got := string(buf[:n]); got != "READY=1" { t.Fatalf("sent %q, want READY=1", got) } } // TestNotifyReadyIsANoOpOutsideSystemd: the console runs under `go run`, in // tests and on a laptop, and none of those set NOTIFY_SOCKET. Absent is // normal, not an error. func TestNotifyReadyIsANoOpOutsideSystemd(t *testing.T) { t.Setenv("NOTIFY_SOCKET", "") if err := NotifyReady(); err != nil { t.Fatalf("NotifyReady with no socket = %v, want nil", err) } }