Skip to content

Commit

Permalink
pkg/netns: simplify UnmountNS()
Browse files Browse the repository at this point in the history
Removing one level of nesting with a early return.

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
  • Loading branch information
Luap99 committed Nov 8, 2024
1 parent 13a63dc commit 50126e3
Showing 1 changed file with 24 additions and 23 deletions.
47 changes: 24 additions & 23 deletions pkg/netns/netns_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,33 +260,34 @@ func newNSPath(nsPath string) (ns.NetNS, error) {
// UnmountNS unmounts the given netns path
func UnmountNS(nsPath string) error {
// Only unmount if it's been bind-mounted (don't touch namespaces in /proc...)
if !strings.HasPrefix(nsPath, "/proc/") {
// EINVAL means the path exists but is not mounted, just try to remove the path below
if err := unix.Unmount(nsPath, unix.MNT_DETACH); err != nil && !errors.Is(err, unix.EINVAL) {
// If path does not exists we can return without error as we have nothing to do.
if errors.Is(err, unix.ENOENT) {
return nil
}

return fmt.Errorf("failed to unmount NS: at %s: %w", nsPath, err)
if strings.HasPrefix(nsPath, "/proc/") {
return nil
}
// EINVAL means the path exists but is not mounted, just try to remove the path below
if err := unix.Unmount(nsPath, unix.MNT_DETACH); err != nil && !errors.Is(err, unix.EINVAL) {
// If path does not exists we can return without error as we have nothing to do.
if errors.Is(err, unix.ENOENT) {
return nil
}

for {
if err := os.Remove(nsPath); err != nil {
if errors.Is(err, unix.EBUSY) {
// mount is still busy, sleep a moment and try again to remove
logrus.Debugf("Netns %s still busy, try removing it again in 10ms", nsPath)
time.Sleep(10 * time.Millisecond)
continue
}
// If path does not exists we can return without error.
if errors.Is(err, unix.ENOENT) {
break
}
return fmt.Errorf("failed to remove ns path: %w", err)
return fmt.Errorf("failed to unmount NS: at %s: %w", nsPath, err)
}

for {
if err := os.Remove(nsPath); err != nil {
if errors.Is(err, unix.EBUSY) {
// mount is still busy, sleep a moment and try again to remove
logrus.Debugf("Netns %s still busy, try removing it again in 10ms", nsPath)
time.Sleep(10 * time.Millisecond)
continue
}
// If path does not exists we can return without error.
if errors.Is(err, unix.ENOENT) {
break
}
break
return fmt.Errorf("failed to remove ns path: %w", err)
}
break
}

return nil
Expand Down

0 comments on commit 50126e3

Please sign in to comment.