1#!/bin/bash 2# SPDX-License-Identifier: GPL-2.0 3 4############################################################################## 5# Defines 6 7WAIT_TIMEOUT=${WAIT_TIMEOUT:=20} 8BUSYWAIT_TIMEOUT=$((WAIT_TIMEOUT * 1000)) # ms 9 10# Kselftest framework requirement - SKIP code is 4. 11ksft_skip=4 12# namespace list created by setup_ns 13NS_LIST=() 14 15############################################################################## 16# Helpers 17busywait() 18{ 19 local timeout=$1; shift 20 21 local start_time="$(date -u +%s%3N)" 22 while true 23 do 24 local out 25 if out=$("$@"); then 26 echo -n "$out" 27 return 0 28 fi 29 30 local current_time="$(date -u +%s%3N)" 31 if ((current_time - start_time > timeout)); then 32 echo -n "$out" 33 return 1 34 fi 35 done 36} 37 38cleanup_ns() 39{ 40 local ns="" 41 local errexit=0 42 local ret=0 43 44 # disable errexit temporary 45 if [[ $- =~ "e" ]]; then 46 errexit=1 47 set +e 48 fi 49 50 for ns in "$@"; do 51 [ -z "${ns}" ] && continue 52 ip netns delete "${ns}" &> /dev/null 53 if ! busywait $BUSYWAIT_TIMEOUT ip netns list \| grep -vq "^$ns$" &> /dev/null; then 54 echo "Warn: Failed to remove namespace $ns" 55 ret=1 56 fi 57 done 58 59 [ $errexit -eq 1 ] && set -e 60 return $ret 61} 62 63cleanup_all_ns() 64{ 65 cleanup_ns "${NS_LIST[@]}" 66} 67 68# setup netns with given names as prefix. e.g 69# setup_ns local remote 70setup_ns() 71{ 72 local ns="" 73 local ns_name="" 74 local ns_list=() 75 local ns_exist= 76 for ns_name in "$@"; do 77 # Some test may setup/remove same netns multi times 78 if unset ${ns_name} 2> /dev/null; then 79 ns="${ns_name,,}-$(mktemp -u XXXXXX)" 80 eval readonly ${ns_name}="$ns" 81 ns_exist=false 82 else 83 eval ns='$'${ns_name} 84 cleanup_ns "$ns" 85 ns_exist=true 86 fi 87 88 if ! ip netns add "$ns"; then 89 echo "Failed to create namespace $ns_name" 90 cleanup_ns "${ns_list[@]}" 91 return $ksft_skip 92 fi 93 ip -n "$ns" link set lo up 94 ! $ns_exist && ns_list+=("$ns") 95 done 96 NS_LIST+=("${ns_list[@]}") 97} 98