From ffcc7836f32ef45312cd1c993369f44812d563e1 Mon Sep 17 00:00:00 2001 From: Francois Marier Date: Thu, 3 Dec 2026 20:22:32 -0700 Subject: [PATCH] cmd/tta,tstest/natlab/vmtest: add vmtest for port mapping deletion Add a TTA /stop-tailscaled command that sends SIGTERM to tailscaled and waits for the process to exit. TestPortmapDelete uses it to check that the tailscale client deletes its PCP, NAT-PMP or UPnP mapping when it shuts down cleanly. Fixes #21713 Change-Id: I2dfb6468fbe8dbe2483fefd83590fdda7b2e8fb2 Signed-off-by: Francois Marier --- cmd/tta/restart_tailscaled_linux.go | 61 +++++++++++++++++++++---- cmd/tta/tta.go | 17 +++++++ tstest/natlab/vmtest/portmapper_test.go | 54 ++++++++++++++++++++++ tstest/natlab/vmtest/vmtest.go | 29 ++++++++++++ 4 files changed, 151 insertions(+), 10 deletions(-) diff --git a/cmd/tta/restart_tailscaled_linux.go b/cmd/tta/restart_tailscaled_linux.go index accf2b404..17f5f0164 100644 --- a/cmd/tta/restart_tailscaled_linux.go +++ b/cmd/tta/restart_tailscaled_linux.go @@ -4,24 +4,72 @@ package main import ( + "context" + "errors" "fmt" "os" "strconv" "strings" + "syscall" + "time" ) func init() { restartTailscaled = restartTailscaledLinux + stopTailscaled = stopTailscaledLinux } // restartTailscaledLinux finds the tailscaled process by walking /proc and // sends it SIGKILL. On gokrazy, the supervisor will restart tailscaled within // a few seconds. The PID of the process that was killed is returned. func restartTailscaledLinux() (int, error) { - ents, err := os.ReadDir("/proc") + proc, err := findTailscaled() if err != nil { return 0, err } + if err := proc.Kill(); err != nil { + return 0, fmt.Errorf("killing tailscaled pid %d: %w", proc.Pid, err) + } + return proc.Pid, nil +} + +// stopTailscaledLinux finds the tailscaled process by walking /proc, sends it +// SIGTERM and waits for it to exit. Gokrazy doesn't restart a process that +// exits successfully. The PID of the process that was stopped is returned. +func stopTailscaledLinux(ctx context.Context) (int, error) { + proc, err := findTailscaled() + if err != nil { + return 0, err + } + pid := proc.Pid + if err := proc.Signal(syscall.SIGTERM); err != nil { + return 0, fmt.Errorf("terminating tailscaled pid %d: %w", pid, err) + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for { + err := proc.Signal(syscall.Signal(0)) // signal 0 to check for process existence + if errors.Is(err, os.ErrProcessDone) { + return pid, nil + } + if err != nil { + return 0, fmt.Errorf("checking tailscaled pid %d: %w", pid, err) + } + select { + case <-ctx.Done(): + return 0, fmt.Errorf("tailscaled pid %d still running after SIGTERM: %w", pid, ctx.Err()) + case <-ticker.C: + } + } +} + +func findTailscaled() (*os.Process, error) { + ents, err := os.ReadDir("/proc") + if err != nil { + return nil, err + } for _, e := range ents { pid, err := strconv.Atoi(e.Name()) if err != nil { @@ -34,14 +82,7 @@ func restartTailscaledLinux() (int, error) { if strings.TrimSpace(string(comm)) != "tailscaled" { continue } - proc, err := os.FindProcess(pid) - if err != nil { - return 0, err - } - if err := proc.Kill(); err != nil { - return 0, fmt.Errorf("killing tailscaled pid %d: %w", pid, err) - } - return pid, nil + return os.FindProcess(pid) } - return 0, fmt.Errorf("tailscaled process not found in /proc") + return nil, fmt.Errorf("tailscaled process not found in /proc") } diff --git a/cmd/tta/tta.go b/cmd/tta/tta.go index 86a7f5bbd..9a17a951f 100644 --- a/cmd/tta/tta.go +++ b/cmd/tta/tta.go @@ -430,6 +430,18 @@ func main() { } fmt.Fprintf(w, "killed tailscaled pid %d (supervisor will respawn)\n", pid) }) + ttaMux.HandleFunc("/stop-tailscaled", func(w http.ResponseWriter, r *http.Request) { + if stopTailscaled == nil { + http.Error(w, "stop-tailscaled not supported on this platform", http.StatusNotImplemented) + return + } + pid, err := stopTailscaled(r.Context()) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + fmt.Fprintf(w, "stopped tailscaled pid %d\n", pid) + }) ttaMux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) { logBuf.mu.Lock() defer logBuf.mu.Unlock() @@ -654,6 +666,11 @@ var wgServerUp func(w http.ResponseWriter, r *http.Request) // and is nil on non-Linux. var restartTailscaled func() (pid int, err error) +// stopTailscaled sends SIGTERM to the local tailscaled process and waits for +// it to exit. It is set by restart_tailscaled_linux.go and is nil on +// non-Linux. +var stopTailscaled func(ctx context.Context) (pid int, err error) + // logBuffer is a bytes.Buffer that is safe for concurrent use // intended to capture early logs from the process, even if // gokrazy's syslog streaming isn't working or yet working. diff --git a/tstest/natlab/vmtest/portmapper_test.go b/tstest/natlab/vmtest/portmapper_test.go index 67ebfe763..00a0797e5 100644 --- a/tstest/natlab/vmtest/portmapper_test.go +++ b/tstest/natlab/vmtest/portmapper_test.go @@ -10,6 +10,7 @@ import ( "time" "tailscale.com/tailcfg" + "tailscale.com/tstest" "tailscale.com/tstest/natlab/vmtest" "tailscale.com/tstest/natlab/vnet" ) @@ -170,6 +171,59 @@ func TestPortmapCreate(t *testing.T) { } } +// TestPortmapDelete checks that a node deletes its port mapping when +// tailscaled shuts down cleanly. +func TestPortmapDelete(t *testing.T) { + tests := []struct { + name string + svc vnet.NetworkService + }{ + {"pcp-only", vnet.PCP}, + {"pmp-only", vnet.NATPMP}, + {"upnp-only", vnet.UPnP}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + env := vmtest.New(t) + pinger := hard(env) + n := env.NumNodes() + router := env.AddNetwork( + fmt.Sprintf("2.%d.%d.%d", n, n, n), // public IP + fmt.Sprintf("10.7.%d.1/24", n), + vnet.HardNAT, + tt.svc, + ) + target := env.AddNode(fmt.Sprintf("node-%d", n), router) + env.Start() + + endpoint := checkPing(t, env, pinger, target, true) + mappings := router.PortMappings() + if len(mappings) != 1 { + t.Fatalf("got port mappings %v, want one", mappings) + } + for wan, pm := range mappings { + if pm.Service != tt.svc { + t.Fatalf("got port mappings %v, want one made with %v", mappings, tt.svc) + } + if wan.String() != endpoint { + t.Fatalf("got port mappings %v, want one for ping endpoint %v", mappings, endpoint) + } + } + + env.StopTailscaled(target) + if err := tstest.WaitFor(10*time.Second, func() error { + if m := router.PortMappings(); len(m) != 0 { + return fmt.Errorf("port mappings %v still present after clean shutdown", m) + } + return nil + }); err != nil { + t.Fatal(err) + } + }) + } +} + // TestPortmapRenew checks that a node renews its port mapping before it // expires when its router grants a short lifetime. func TestPortmapRenew(t *testing.T) { diff --git a/tstest/natlab/vmtest/vmtest.go b/tstest/natlab/vmtest/vmtest.go index f49aa17c7..6991b8b70 100644 --- a/tstest/natlab/vmtest/vmtest.go +++ b/tstest/natlab/vmtest/vmtest.go @@ -1599,6 +1599,35 @@ func (e *Env) RestartTailscaled(n *Node) { } } +// StopTailscaled sends SIGTERM to tailscaled on n and waits for the process +// to exit. Its supervisor (gokrazy) doesn't restart a process that exits +// successfully. It fatals the test on error. +// +// Stopping tailscaled is only supported on gokrazy nodes. +func (e *Env) StopTailscaled(n *Node) { + e.t.Helper() + if !n.os.IsGokrazy { + e.t.Fatalf("StopTailscaled(%s): only supported on gokrazy nodes (have %q)", n.name, n.os.Name) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, "GET", "http://unused/stop-tailscaled", nil) + if err != nil { + e.t.Fatalf("StopTailscaled(%s): %v", n.name, err) + } + res, err := n.agent.HTTPClient.Do(req) + if err != nil { + e.t.Fatalf("StopTailscaled(%s): %v", n.name, err) + } + body, _ := io.ReadAll(res.Body) + res.Body.Close() + if res.StatusCode != 200 { + e.t.Fatalf("StopTailscaled(%s): %s: %q", n.name, res.Status, body) + } + e.t.Logf("[%s] %s", n.name, strings.TrimSpace(string(body))) +} + // AddRoute adds a kernel static route on the given node, pointing prefix at // via. It uses TTA's /add-route handler, so it works on any node where TTA // is running (which is all of them — DontJoinTailnet only skips