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 ret=0 42 43 for ns in "$@"; do 44 [ -z "${ns}" ] && continue 45 ip netns pids "${ns}" 2> /dev/null | xargs -r kill || true 46 ip netns delete "${ns}" &> /dev/null || true 47 if ! busywait $BUSYWAIT_TIMEOUT ip netns list \| grep -vq "^$ns$" &> /dev/null; then 48 echo "Warn: Failed to remove namespace $ns" 49 ret=1 50 fi 51 done 52 53 return $ret 54} 55 56cleanup_all_ns() 57{ 58 cleanup_ns "${NS_LIST[@]}" 59} 60 61# setup netns with given names as prefix. e.g 62# setup_ns local remote 63setup_ns() 64{ 65 local ns="" 66 local ns_name="" 67 local ns_list=() 68 local ns_exist= 69 for ns_name in "$@"; do 70 # Some test may setup/remove same netns multi times 71 if unset ${ns_name} 2> /dev/null; then 72 ns="${ns_name,,}-$(mktemp -u XXXXXX)" 73 eval readonly ${ns_name}="$ns" 74 ns_exist=false 75 else 76 eval ns='$'${ns_name} 77 cleanup_ns "$ns" 78 ns_exist=true 79 fi 80 81 if ! ip netns add "$ns"; then 82 echo "Failed to create namespace $ns_name" 83 cleanup_ns "${ns_list[@]}" 84 return $ksft_skip 85 fi 86 ip -n "$ns" link set lo up 87 ! $ns_exist && ns_list+=("$ns") 88 done 89 NS_LIST+=("${ns_list[@]}") 90} 91