From 1dd22b3f4d3c0161172720f6f3c99cb0ea4e8809 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Thu, 12 Nov 2026 17:07:24 +0100 Subject: [PATCH] feat: show the holder's role and a whole-unit hint for systemd services Matching stays cgroup-based: workers of nginx-style services hold the port too, and signalling them is undone by the master. The explanation now says whether the holder is the main process and that systemctl stop ends the whole unit. --- CHANGELOG.md | 1 + CLAUDE.md | 1 + README.md | 2 +- internal/detect/systemd/detector.go | 46 ++++++++- internal/detect/systemd/detector_test.go | 119 ++++++++++++++++++++--- 5 files changed, 155 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21d39b2..9a0e941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and ### Added - `--plain` prints one tab-separated line per socket (port, protocol, address, PID, source, name) for `grep` and `awk`. Combining it with `--json` is an error. +- A systemd explanation shows whether the port holder is the main process of the unit or a child, and hints that `systemctl stop` ends the whole unit. ## [0.3.0] - 2026-11-12 diff --git a/CLAUDE.md b/CLAUDE.md index 8211053..a697ee3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,4 +39,5 @@ go run ./cmd/portwhy 3000 ## Decisions on record - macOS socket data comes from an own `lsof`/`netstat` parser (`internal/socket`); `gopsutil` is not adopted. Spike outcome: it was not added or run (no network access), but from memory its macOS connection listing also shells out to `lsof` (unverified), so it would add a dependency without removing the external tool, and without root `lsof` sees only own processes either way, which the `netstat` merge (PID 0 for invisible owners) covers. Revisit only if the parser proves fragile. Process data (`ps`) follows in the process-reader ticket. +- The systemd detector matches the whole cgroup of a unit, not only its MainPID: nginx-style workers also hold the port, and a signal to a worker is undone by the master respawning it, so only `systemctl stop` frees the port. The explanation shows the holder's role and a hint that the whole unit stops. - Podman and dev-server heuristics are v0.2; `wait`/`free` subcommands only if demand appears. diff --git a/README.md b/README.md index cc74462..8b0c367 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ When several apply, the precedence is `2` > `3` > `0` > `1`. - portwhy never stops PID 1 or itself, re-checks the process start time before signalling (PID reuse), and verifies afterwards that the port is free. - A process owned by another user is reported with a `sudo` hint. portwhy never escalates silently. - A port held by a process that portwhy cannot see is never reported as free. -- Hints warn when the cause will come back, for example a Docker restart policy or a systemd `Restart=` setting. +- Hints warn when the cause will come back, for example a Docker restart policy or a systemd `Restart=` setting. A systemd explanation says whether the port holder is the main process of the unit and warns that `systemctl stop` ends the whole unit. --- diff --git a/internal/detect/systemd/detector.go b/internal/detect/systemd/detector.go index f5ff7df..341b624 100644 --- a/internal/detect/systemd/detector.go +++ b/internal/detect/systemd/detector.go @@ -3,6 +3,7 @@ package systemd import ( "context" "fmt" + "strconv" "strings" "time" @@ -17,6 +18,15 @@ import ( // Detector explains a socket whose owner runs inside a systemd service. It // never matches when systemctl cannot be queried (not installed, systemd not // running, unit unknown), so the next detector in the chain takes over. +// +// Matching is cgroup-based on purpose: every process of the unit matches, not +// only its MainPID. For services such as nginx the master and the workers both +// hold the port; a MainPID-only match would send the workers to the generic +// fallback, where a signal is undone by the master respawning them and the +// port stays busy. Stopping the unit is what frees the port. Because that ends +// the whole unit, the explanation names the holder's role (main or child +// process) and says so in a hint; the prompt shows the exact command and +// confirmation stays mandatory. type Detector struct { query execx.Runner stop execx.Runner @@ -58,11 +68,12 @@ func (d *Detector) Detect(ctx context.Context, _ socket.Socket, p *proc.Process) return nil, false } - out, err := d.query.Run(ctx, "systemctl", systemctlArgs(unit.User, "show", "-p", "Restart", "--value", unit.Name)...) + out, err := d.query.Run(ctx, "systemctl", systemctlArgs(unit.User, "show", "-p", "Restart", "-p", "MainPID", unit.Name)...) if err != nil { return nil, false } - restart := strings.TrimSpace(string(out)) + props := parseProperties(string(out)) + restart := props["Restart"] scope := "system" if unit.User { @@ -77,6 +88,9 @@ func (d *Detector) Detect(ctx context.Context, _ socket.Socket, p *proc.Process) }, Terminator: newTerminator(d.stop, unit, d.uid), } + if role := holderRole(p.PID, props["MainPID"]); role != "" { + e.Details = append(e.Details, detect.Detail{Key: "Role", Value: role}) + } if !p.Started.IsZero() { e.Details = append(e.Details, detect.Detail{Key: "Uptime", Value: detect.FormatUptime(d.now().Sub(p.Started))}) } @@ -86,9 +100,37 @@ func (d *Detector) Detect(ctx context.Context, _ socket.Socket, p *proc.Process) e.Hints = append(e.Hints, fmt.Sprintf( "Restart=%s: systemd restarts the process after a plain kill; stopping the unit keeps it down", clean)) } + e.Hints = append(e.Hints, "systemctl stop ends the whole unit, including every process in it") return e, true } +// parseProperties reads the Key=Value lines of systemctl show output, so the +// order of the properties does not matter. Values are trimmed. +func parseProperties(output string) map[string]string { + props := make(map[string]string) + for _, line := range strings.Split(output, "\n") { + key, value, found := strings.Cut(line, "=") + if !found { + continue + } + props[strings.TrimSpace(key)] = strings.TrimSpace(value) + } + return props +} + +// holderRole describes how the holder relates to the unit's main process. It +// returns "" when MainPID is missing, zero or not a positive number. +func holderRole(pid int, mainPID string) string { + main, err := strconv.Atoi(mainPID) + if err != nil || main <= 0 { + return "" + } + if pid == main { + return "main process of the unit" + } + return fmt.Sprintf("child process of the unit (main PID %d)", main) +} + // systemctlArgs builds the argument list of a systemctl call, selecting the // per-user manager when user is set. func systemctlArgs(user bool, args ...string) []string { diff --git a/internal/detect/systemd/detector_test.go b/internal/detect/systemd/detector_test.go index 7793a7a..1c0d477 100644 --- a/internal/detect/systemd/detector_test.go +++ b/internal/detect/systemd/detector_test.go @@ -36,8 +36,29 @@ func newTestDetector(query, stop execx.Runner, uid int) *Detector { return d } +// showRunner answers the show call with the given Restart value and no +// MainPID line. func showRunner(key, restart string) *execx.Fake { - return &execx.Fake{Responses: map[string][]byte{key: []byte(restart + "\n")}} + return showOutput(key, "Restart="+restart+"\n") +} + +func showOutput(key, output string) *execx.Fake { + return &execx.Fake{Responses: map[string][]byte{key: []byte(output)}} +} + +const ( + showSystem = "systemctl show -p Restart -p MainPID postgresql.service" + showUser = "systemctl --user show -p Restart -p MainPID foo.service" + stopHint = "systemctl stop ends the whole unit, including every process in it" +) + +func hasHint(hints []string, want string) bool { + for _, h := range hints { + if h == want { + return true + } + } + return false } func detail(details []detect.Detail, key string) string { @@ -50,7 +71,7 @@ func detail(details []detect.Detail, key string) string { } func TestDetector_ExplainsSystemService(t *testing.T) { - query := showRunner("systemctl show -p Restart --value postgresql.service", "always") + query := showRunner("systemctl show -p Restart -p MainPID postgresql.service", "always") got, ok := newTestDetector(query, &execx.Fake{}, 1000).Detect(context.Background(), testSocket, process(systemCgroup)) @@ -81,7 +102,7 @@ func TestDetector_ExplainsSystemService(t *testing.T) { } func TestDetector_ExplainsUserService(t *testing.T) { - query := showRunner("systemctl --user show -p Restart --value foo.service", "no") + query := showRunner("systemctl --user show -p Restart -p MainPID foo.service", "no") got, ok := newTestDetector(query, &execx.Fake{}, 1000).Detect(context.Background(), testSocket, process(userCgroup)) @@ -109,12 +130,12 @@ func TestDetector_RestartHint(t *testing.T) { } for _, tt := range tests { t.Run("Restart="+tt.restart, func(t *testing.T) { - query := showRunner("systemctl show -p Restart --value postgresql.service", tt.restart) + query := showRunner("systemctl show -p Restart -p MainPID postgresql.service", tt.restart) got, _ := newTestDetector(query, &execx.Fake{}, 0).Detect(context.Background(), testSocket, process(systemCgroup)) - if hasHint := len(got.Hints) > 0; hasHint != tt.wantHint { - t.Errorf("hint present = %v, want %v (hints %v)", hasHint, tt.wantHint, got.Hints) + if gotHint := len(got.Hints) > 1; gotHint != tt.wantHint { + t.Errorf("hint present = %v, want %v (hints %v)", gotHint, tt.wantHint, got.Hints) } if tt.wantHint && !strings.Contains(got.Hints[0], "Restart="+tt.restart) { t.Errorf("hint %q does not name Restart=%s", got.Hints[0], tt.restart) @@ -133,8 +154,8 @@ func TestDetector_FallsBackSilently(t *testing.T) { query execx.Runner p *proc.Process }{ - {"systemctl missing", &execx.Fake{Errors: map[string]error{"systemctl show -p Restart --value postgresql.service": missing}}, process(systemCgroup)}, - {"systemd not running", &execx.Fake{Errors: map[string]error{"systemctl show -p Restart --value postgresql.service": errors.New("System has not been booted with systemd")}}, process(systemCgroup)}, + {"systemctl missing", &execx.Fake{Errors: map[string]error{"systemctl show -p Restart -p MainPID postgresql.service": missing}}, process(systemCgroup)}, + {"systemd not running", &execx.Fake{Errors: map[string]error{"systemctl show -p Restart -p MainPID postgresql.service": errors.New("System has not been booted with systemd")}}, process(systemCgroup)}, {"no process", &execx.Fake{}, nil}, {"no cgroup", &execx.Fake{}, process("")}, {"scope only", &execx.Fake{}, process("/user.slice/user-1000.slice/session-3.scope")}, @@ -163,7 +184,7 @@ func TestDetector_OtherUsersUserUnitIsNotMatched(t *testing.T) { } func TestDetector_CleansExternalStrings(t *testing.T) { - query := showRunner("systemctl show -p Restart --value postgresql.service", "always\x1b[2J") + query := showOutput(showSystem, "Restart=always\x1b[2J\nMainPID=7\x1b[2J\n") p := process(systemCgroup) p.Name = "evil\x1b[2Jname" @@ -306,8 +327,8 @@ func TestDetector_OwnUnitIsNotMatched(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { query := &execx.Fake{Responses: map[string][]byte{ - "systemctl show -p Restart --value postgresql.service": []byte("no\n"), - "systemctl --user show -p Restart --value foo.service": []byte("no\n"), + "systemctl show -p Restart -p MainPID postgresql.service": []byte("Restart=no\nMainPID=812\n"), + "systemctl --user show -p Restart -p MainPID foo.service": []byte("Restart=no\nMainPID=812\n"), }} _, ok := NewDetector(query, &execx.Fake{}, 1000, tt.ownCgroup).Detect(context.Background(), testSocket, process(tt.cgroup)) @@ -321,3 +342,79 @@ func TestDetector_OwnUnitIsNotMatched(t *testing.T) { }) } } + +func TestDetector_RoleOfHolder(t *testing.T) { + tests := []struct { + name string + output string + wantRole string + wantRow bool + }{ + {"master is the main process", "MainPID=812\nRestart=no\n", "main process of the unit", true}, + {"worker is a child process", "MainPID=800\nRestart=no\n", "child process of the unit (main PID 800)", true}, + {"property order does not matter", "Restart=no\nMainPID=800\n", "child process of the unit (main PID 800)", true}, + {"MainPID missing", "Restart=no\n", "", false}, + {"MainPID zero", "MainPID=0\nRestart=no\n", "", false}, + {"MainPID empty", "MainPID=\nRestart=no\n", "", false}, + {"MainPID garbage", "MainPID=abc\nRestart=no\n", "", false}, + {"MainPID negative", "MainPID=-5\nRestart=no\n", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + query := showOutput(showSystem, tt.output) + + got, ok := newTestDetector(query, &execx.Fake{}, 0).Detect(context.Background(), testSocket, process(systemCgroup)) + + if !ok { + t.Fatal("Detect() did not match") + } + if v := detail(got.Details, "Role"); v != tt.wantRole { + t.Errorf("Role = %q, want %q", v, tt.wantRole) + } + if !hasHint(got.Hints, stopHint) { + t.Errorf("hints %v lack %q", got.Hints, stopHint) + } + }) + } +} + +func TestDetector_RoleFollowsProcess(t *testing.T) { + query := showOutput(showSystem, "MainPID=812\nRestart=no\n") + + got, _ := newTestDetector(query, &execx.Fake{}, 0).Detect(context.Background(), testSocket, process(systemCgroup)) + + var keys []string + for _, d := range got.Details { + keys = append(keys, d.Key) + } + want := []string{"Scope", "Process", "Role", "Uptime"} + if strings.Join(keys, ",") != strings.Join(want, ",") { + t.Errorf("detail keys = %v, want %v", keys, want) + } +} + +func TestDetector_UserUnitQueriesUserManager(t *testing.T) { + query := showOutput(showUser, "MainPID=900\nRestart=on-failure\n") + + got, ok := newTestDetector(query, &execx.Fake{}, 1000).Detect(context.Background(), testSocket, process(userCgroup)) + + if !ok { + t.Fatal("Detect() did not match") + } + if v := detail(got.Details, "Role"); v != "child process of the unit (main PID 900)" { + t.Errorf("Role = %q", v) + } + if !hasHint(got.Hints, stopHint) { + t.Errorf("hints %v lack %q", got.Hints, stopHint) + } +} + +func TestDetector_ShowFailureFallsBack(t *testing.T) { + query := &execx.Fake{Errors: map[string]error{showSystem: errors.New("exit status 1")}} + + got, ok := newTestDetector(query, &execx.Fake{}, 0).Detect(context.Background(), testSocket, process(systemCgroup)) + + if ok || got != nil { + t.Errorf("Detect() = %v, %v, want no match", got, ok) + } +}