Skip to content

Commit

Permalink
libnetwork/rootlessnetns: add readPidFile() helper
Browse files Browse the repository at this point in the history
Add a function to read a pidfile, this helps to avoid some duplication.

Signed-off-by: Paul Holzinger <[email protected]>
  • Loading branch information
Luap99 committed Apr 12, 2024
1 parent feb2281 commit 7281185
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions libnetwork/internal/rootlessnetns/netns_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,7 @@ func (n *Netns) setupPasta(nsPath string) error {

if systemd.RunsOnSystemd() {
// Treat these as fatal - if pasta failed to write a PID file something is probably wrong.
pidfile, err := os.ReadFile(pidPath)
if err != nil {
return fmt.Errorf("unable to open pasta PID file: %w", err)
}
pid, err := strconv.Atoi(strings.TrimSpace(string(pidfile)))
pid, err := readPidFile(pidPath)
if err != nil {
return fmt.Errorf("unable to decode pasta PID: %w", err)
}
Expand Down Expand Up @@ -255,16 +251,12 @@ func (n *Netns) setupSlirp4netns(nsPath string) error {

func (n *Netns) cleanupRootlessNetns() error {
pidFile := n.getPath(rootlessNetNsConnPidFile)
b, err := os.ReadFile(pidFile)
pid, err := readPidFile(pidFile)
if err == nil {
var i int
i, err = strconv.Atoi(strings.TrimSpace(string(b)))
if err == nil {
// kill the slirp process so we do not leak it
err = unix.Kill(i, unix.SIGTERM)
if err == unix.ESRCH {
err = nil
}
// kill the slirp/pasta process so we do not leak it
err = unix.Kill(pid, unix.SIGTERM)
if err == unix.ESRCH {
err = nil
}
}
return err
Expand Down Expand Up @@ -609,3 +601,11 @@ func refCount(dir string, inc int) (int, error) {

return currentCount, nil
}

func readPidFile(path string) (int, error) {
b, err := os.ReadFile(path)
if err != nil {
return 0, err
}
return strconv.Atoi(strings.TrimSpace(string(b)))
}

0 comments on commit 7281185

Please sign in to comment.