xref: /linux/tools/testing/selftests/net/lib.sh (revision f5c31bcf604db54470868f3118a60dc4a9ba8813)
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		out=$("$@")
26		local ret=$?
27		if ((!ret)); then
28			echo -n "$out"
29			return 0
30		fi
31
32		local current_time="$(date -u +%s%3N)"
33		if ((current_time - start_time > timeout)); then
34			echo -n "$out"
35			return 1
36		fi
37	done
38}
39
40cleanup_ns()
41{
42	local ns=""
43	local errexit=0
44	local ret=0
45
46	# disable errexit temporary
47	if [[ $- =~ "e" ]]; then
48		errexit=1
49		set +e
50	fi
51
52	for ns in "$@"; do
53		ip netns delete "${ns}" &> /dev/null
54		if ! busywait $BUSYWAIT_TIMEOUT ip netns list \| grep -vq "^$ns$" &> /dev/null; then
55			echo "Warn: Failed to remove namespace $ns"
56			ret=1
57		fi
58	done
59
60	[ $errexit -eq 1 ] && set -e
61	return $ret
62}
63
64cleanup_all_ns()
65{
66	cleanup_ns $NS_LIST
67}
68
69# setup netns with given names as prefix. e.g
70# setup_ns local remote
71setup_ns()
72{
73	local ns=""
74	local ns_name=""
75	local ns_list=""
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		else
82			eval ns='$'${ns_name}
83			cleanup_ns "$ns"
84
85		fi
86
87		if ! ip netns add "$ns"; then
88			echo "Failed to create namespace $ns_name"
89			cleanup_ns "$ns_list"
90			return $ksft_skip
91		fi
92		ip -n "$ns" link set lo up
93		ns_list="$ns_list $ns"
94	done
95	NS_LIST="$NS_LIST $ns_list"
96}
97