run_in_ns.sh 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/bin/bash
  2. #
  3. # Copyright (c) 2022 Project CHIP Authors
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # This script executes the command given as an argument within
  18. # CHIP_ROOT in a specific network namespace.
  19. NETWORK_NAMESPACE="default"
  20. function show_usage() {
  21. cat <<EOF
  22. Usage: $0 namespace command
  23. Execute the command given as an argument in a specific network namespace.
  24. Example:
  25. scripts/run_in_ns.sh MatterNet "ip a"
  26. Use "default" as a namespace argument to use the host network namespace directly.
  27. EOF
  28. }
  29. if [[ $# -lt 2 ]]; then
  30. show_usage >&2
  31. exit 1
  32. fi
  33. NETWORK_NAMESPACE=$1
  34. shift
  35. if [[ $NETWORK_NAMESPACE == "default" ]]; then
  36. "$@"
  37. else
  38. if [ ! -f /var/run/netns/"$NETWORK_NAMESPACE" ]; then
  39. echo "$NETWORK_NAMESPACE network namespace does not exist"
  40. show_usage >&2
  41. exit 1
  42. fi
  43. echo "Run command: $@ in $NETWORK_NAMESPACE namespace"
  44. if [ "$EUID" -ne 0 ]; then
  45. sudo env PATH="$PATH" ip netns exec "$NETWORK_NAMESPACE" "$@"
  46. else
  47. ip netns exec "$NETWORK_NAMESPACE" "$@"
  48. fi
  49. fi