Add a couple of helpers which can be used by tests which need to run a
specific bash command on a different target than the local system, be it
either another netns or a remote system accessible through ssh.

The __run_on() function is passed through $1 the target on which the
command should be executed while run_on() is passed the name of the
interface that is then used to retrieve the target from the TARGETS
array.

Signed-off-by: Ioana Ciornei <[email protected]>
---
Changes in v4:
- reworked the helpers so that no global variable is used and
  information is passed only through parameters
Changes in v3:
- s/TARGET/CUR_TARGET
- always fallback on running a command locally when either TARGETS is
  not declared or there is no entry for a specific interface
Changes in v2:
- patch is new

 tools/testing/selftests/net/lib.sh | 38 ++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)

diff --git a/tools/testing/selftests/net/lib.sh 
b/tools/testing/selftests/net/lib.sh
index b40694573f4c..6c0d613a4de5 100644
--- a/tools/testing/selftests/net/lib.sh
+++ b/tools/testing/selftests/net/lib.sh
@@ -670,3 +670,41 @@ cmd_jq()
        # return success only in case of non-empty output
        [ ! -z "$output" ]
 }
+
+__run_on()
+{
+       local target=$1; shift
+       local type args
+
+       IFS=':' read -r type args <<< "$target"
+
+       case "$type" in
+       netns)
+               # Execute command in network namespace
+               # args contains the namespace name
+               ip netns exec "$args" "$@"
+               ;;
+       ssh)
+               # Execute command via SSH args contains user@host
+               ssh -n "$args" "$@"
+               ;;
+       local|*)
+               # Execute command locally. This is also the fallback
+               # case for when the interface's target is not found in
+               # the TARGETS array.
+               "$@"
+               ;;
+       esac
+}
+
+run_on()
+{
+       local iface=$1; shift
+       local target="local:"
+
+       if declare -p TARGETS &>/dev/null; then
+               target="${TARGETS[$iface]}"
+       fi
+
+       __run_on "$target" "$@"
+}
-- 
2.25.1


Reply via email to