netns.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright (c) 2016 Arista Networks, Inc.
  2. // Use of this source code is governed by the Apache License 2.0
  3. // that can be found in the COPYING file.
  4. // Package netns provides a utility function that allows a user to
  5. // perform actions in a different network namespace
  6. package netns
  7. import (
  8. "fmt"
  9. )
  10. const (
  11. netNsRunDir = "/var/run/netns/"
  12. selfNsFile = "/proc/self/ns/net"
  13. )
  14. // Callback is a function that gets called in a given network namespace.
  15. // The user needs to check any errors from any calls inside this function.
  16. type Callback func() error
  17. // File descriptor interface so we can mock for testing
  18. type handle interface {
  19. close() error
  20. fd() int
  21. }
  22. // The file descriptor associated with a network namespace
  23. type nsHandle int
  24. // setNsByName wraps setNs, allowing specification of the network namespace by name.
  25. // It returns the file descriptor mapped to the given network namespace.
  26. func setNsByName(nsName string) error {
  27. netPath := netNsRunDir + nsName
  28. handle, err := getNs(netPath)
  29. if err != nil {
  30. return fmt.Errorf("Failed to getNs: %s", err)
  31. }
  32. err = setNs(handle)
  33. handle.close()
  34. if err != nil {
  35. return fmt.Errorf("Failed to setNs: %s", err)
  36. }
  37. return nil
  38. }