client/systray: shut down cleanly on termination signals (#22583)

Route SIGINT and SIGTERM through systray.Quit so the native tray loop
returns and invokes the exit callback. Stop signal delivery when Run returns.

Treat watcher cancellation as normal shutdown rather than terminating the
process with log.Fatal, and interrupt the reconnect delay when canceled.
Serialize exit cleanup with menu rebuilds.

Add subprocess tests for SIGINT, SIGTERM and the Quit menu action using a
private session bus and a fake LocalAPI.

Fixes #22582

Change-Id: I2360e203d4cc9bf3f0245133e9535d353b780e2c

Signed-off-by: fQwQf <supertjz123@foxmail.com>
This commit is contained in:
fQwQf authored and GitHub committed 2026-11-23 09:25:34 -06:00
1 parent 693839367f
commit 0345103edd
3 files changed
+146 -20

No files matched your search

+116
View File
@@ -0,0 +1,116 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package systray
import (
"bytes"
"os"
"os/exec"
"syscall"
"testing"
"time"
dbus "github.com/godbus/dbus/v5"
"tailscale.com/client/local"
)
func TestShutdownProcess(t *testing.T) {
if socket := os.Getenv("TS_SYSTRAY_SHUTDOWN_SOCKET"); socket != "" {
new(Menu).Run(&local.Client{Socket: socket, UseSocketOnly: true})
}
}
// TestShutdownSignals exercises the real tray loop and signal handlers in a
// subprocess, isolated from the desktop and the test runner's signal handlers.
func TestShutdownSignals(t *testing.T) {
if _, err := exec.LookPath("dbus-daemon"); err != nil {
t.Skip("dbus-daemon not available")
}
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
sig os.Signal
}{
{"interrupt", syscall.SIGINT},
{"terminated", syscall.SIGTERM},
{"menu_quit", nil},
} {
t.Run(tc.name, func(t *testing.T) {
addr := startSessionBus(t)
registered := startFakeWatcher(t, addr)
socket := startFakeLocalAPI(t)
cmd := exec.Command(executable, "-test.run=^TestShutdownProcess$")
cmd.Env = append(os.Environ(),
"DBUS_SESSION_BUS_ADDRESS="+addr,
"TS_SYSTRAY_SHUTDOWN_SOCKET="+socket,
"GORACE=atexit_sleep_ms=0",
)
var output bytes.Buffer
cmd.Stdout, cmd.Stderr = &output, &output
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
done := make(chan struct{})
var waitErr error
go func() {
waitErr = cmd.Wait()
close(done)
}()
t.Cleanup(func() {
cmd.Process.Kill()
<-done
})
select {
case <-registered:
case <-done:
t.Fatalf("tray exited before registering: %v\n%s", waitErr, &output)
case <-time.After(10 * time.Second):
t.Fatal("tray did not register")
}
obj, layoutCall := waitForMenuLayout(t, addr, cmd.Process.Pid, "Quit")
if tc.sig != nil {
if err := cmd.Process.Signal(tc.sig); err != nil {
t.Fatal(err)
}
} else {
var revision uint32
var layout struct {
ID int32
Properties map[string]dbus.Variant
Children []dbus.Variant
}
if err := layoutCall.Store(&revision, &layout); err != nil {
t.Fatal(err)
}
quitID := int32(-1)
for _, child := range layout.Children {
item := layout
if err := dbus.Store([]any{child.Value()}, &item); err == nil && item.Properties["label"].Value() == "Quit" {
quitID = item.ID
break
}
}
if quitID < 0 {
t.Fatal("Quit item not found")
}
if err := obj.Call("com.canonical.dbusmenu.Event", 0, quitID, "clicked", dbus.MakeVariant(int32(0)), uint32(0)).Err; err != nil {
t.Fatal(err)
}
}
select {
case <-done:
if waitErr != nil {
t.Fatalf("tray did not exit cleanly after %s: %v\n%s", tc.name, waitErr, &output)
}
case <-time.After(5 * time.Second):
cmd.Process.Kill()
<-done
t.Fatalf("tray remained running after %s\n%s", tc.name, &output)
}
})
}
}
+16 -11
View File
@@ -57,13 +57,14 @@ func (menu *Menu) Run(client *local.Client) {
menu.lc = client
menu.updateState()
// exit cleanly on SIGINT and SIGTERM
// Stop the tray loop, which calls onExit to clean up background work.
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(interrupt)
go func() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
select {
case <-interrupt:
menu.onExit()
systray.Quit()
case <-menu.bgCtx.Done():
}
}()
@@ -513,21 +514,23 @@ func onClick(ctx context.Context, item *systray.MenuItem, fn func(ctx context.Co
}
// watchIPNBus subscribes to the tailscale event bus and sends state updates to chState.
// This method does not return.
// It returns when the menu exits.
func (menu *Menu) watchIPNBus() {
for {
if err := menu.watchIPNBusInner(); err != nil {
log.Println(err)
if errors.Is(err, context.Canceled) {
// If the context got canceled, we will never be able to
// reconnect to IPN bus, so exit the process.
log.Fatalf("watchIPNBus: %v", err)
return
}
log.Println(err)
}
// If our watch connection breaks, wait a bit before reconnecting. No
// reason to spam the logs if e.g. tailscaled is restarting or goes
// down.
time.Sleep(3 * time.Second)
select {
case <-menu.bgCtx.Done():
return
case <-time.After(3 * time.Second):
}
}
}
@@ -540,7 +543,7 @@ func (menu *Menu) watchIPNBusInner() error {
for {
select {
case <-menu.bgCtx.Done():
return nil
return menu.bgCtx.Err()
default:
n, err := watcher.Next()
if err != nil {
@@ -845,6 +848,8 @@ func newMullvadPeers(status *ipnstate.Status) mullvadPeers {
// onExit is called by the systray package when the menu is exiting.
func (menu *Menu) onExit() {
log.Printf("exiting")
menu.mu.Lock()
defer menu.mu.Unlock()
if menu.bgCancel != nil {
menu.bgCancel()
}
+14 -9
View File
@@ -216,9 +216,7 @@ func TestRun(t *testing.T) {
registered := startFakeWatcher(t, busAddr)
sock := startFakeLocalAPI(t)
// Run the systray app. It has no clean way to shut down (systray.Quit
// triggers a log.Fatal in the IPN bus watcher), so it is left running
// until the test process exits.
// Run the tray in this process to inspect its initial menu.
menu := new(Menu)
go menu.Run(&local.Client{Socket: sock, UseSocketOnly: true})
@@ -229,14 +227,21 @@ func TestRun(t *testing.T) {
t.Fatal("timed out waiting for StatusNotifierItem registration")
}
// Fetch the menu layout. GetLayout blocks server-side until the
// initial menu has been fully built by onReady.
waitForMenuLayout(t, busAddr, os.Getpid(),
"Connected", "This Device: self-host (100.64.0.1)", "Exit Nodes", "Recommended: exit1", "Quit",
)
}
// waitForMenuLayout finds the tray's menu on the given session bus and
// returns the menu object and first layout containing all the expected labels.
func waitForMenuLayout(t *testing.T, busAddr string, pid int, wants ...string) (dbus.BusObject, *dbus.Call) {
t.Helper()
conn, err := dbus.Connect(busAddr)
if err != nil {
t.Fatalf("connecting to session bus: %v", err)
}
defer conn.Close()
itemName := fmt.Sprintf("org.kde.StatusNotifierItem-%d-1", os.Getpid())
t.Cleanup(func() { conn.Close() })
itemName := fmt.Sprintf("org.kde.StatusNotifierItem-%d-1", pid)
// Find the menu the way a StatusNotifierHost does, via the item's
// Menu property, rather than assuming the object path the systray
@@ -253,10 +258,10 @@ func TestRun(t *testing.T) {
obj := conn.Object(itemName, menuPath)
// Poll until every expected label shows up. The systray library
// waits for onReady to build the menu before answering GetLayout. It
// answers the very first GetLayout with a depth of 1 regardless of
// what was asked for (and schedules a refresh), so submenu entries
// like the exit node list only appear on later calls.
wants := []string{"Connected", "This Device: self-host (100.64.0.1)", "Exit Nodes", "Recommended: exit1", "Quit"}
var layout string
var missing []string
deadline := time.Now().Add(30 * time.Second)
@@ -271,7 +276,7 @@ func TestRun(t *testing.T) {
}
}
if len(missing) == 0 {
break
return obj, call
}
}
if time.Now().After(deadline) {