Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

Expand Down
46 changes: 44 additions & 2 deletions internal/detect/systemd/detector.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package systemd
import (
"context"
"fmt"
"strconv"
"strings"
"time"

Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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))})
}
Expand All @@ -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 {
Expand Down
119 changes: 108 additions & 11 deletions internal/detect/systemd/detector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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))

Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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)
Expand All @@ -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")},
Expand Down Expand Up @@ -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"

Expand Down Expand Up @@ -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))
Expand All @@ -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)
}
}
Loading