xref: /linux/tools/testing/selftests/net/lib.sh (revision 860a9bed265146b10311bcadbbcef59c3af4454d)
1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3
4##############################################################################
5# Defines
6
7: "${WAIT_TIMEOUT:=20}"
8
9BUSYWAIT_TIMEOUT=$((WAIT_TIMEOUT * 1000)) # ms
10
11# Kselftest framework constants.
12ksft_pass=0
13ksft_fail=1
14ksft_xfail=2
15ksft_skip=4
16
17# namespace list created by setup_ns
18NS_LIST=""
19
20##############################################################################
21# Helpers
22
23__ksft_status_merge()
24{
25	local a=$1; shift
26	local b=$1; shift
27	local -A weights
28	local weight=0
29
30	for i in "$@"; do
31		weights[$i]=$((weight++))
32	done
33
34	if [[ ${weights[$a]} > ${weights[$b]} ]]; then
35		echo "$a"
36		return 0
37	else
38		echo "$b"
39		return 1
40	fi
41}
42
43ksft_status_merge()
44{
45	local a=$1; shift
46	local b=$1; shift
47
48	__ksft_status_merge "$a" "$b" \
49		$ksft_pass $ksft_xfail $ksft_skip $ksft_fail
50}
51
52ksft_exit_status_merge()
53{
54	local a=$1; shift
55	local b=$1; shift
56
57	__ksft_status_merge "$a" "$b" \
58		$ksft_xfail $ksft_pass $ksft_skip $ksft_fail
59}
60
61loopy_wait()
62{
63	local sleep_cmd=$1; shift
64	local timeout_ms=$1; shift
65
66	local start_time="$(date -u +%s%3N)"
67	while true
68	do
69		local out
70		out=$("$@")
71		local ret=$?
72		if ((!ret)); then
73			echo -n "$out"
74			return 0
75		fi
76
77		local current_time="$(date -u +%s%3N)"
78		if ((current_time - start_time > timeout_ms)); then
79			echo -n "$out"
80			return 1
81		fi
82
83		$sleep_cmd
84	done
85}
86
87busywait()
88{
89	local timeout_ms=$1; shift
90
91	loopy_wait : "$timeout_ms" "$@"
92}
93
94cleanup_ns()
95{
96	local ns=""
97	local errexit=0
98	local ret=0
99
100	# disable errexit temporary
101	if [[ $- =~ "e" ]]; then
102		errexit=1
103		set +e
104	fi
105
106	for ns in "$@"; do
107		ip netns delete "${ns}" &> /dev/null
108		if ! busywait $BUSYWAIT_TIMEOUT ip netns list \| grep -vq "^$ns$" &> /dev/null; then
109			echo "Warn: Failed to remove namespace $ns"
110			ret=1
111		fi
112	done
113
114	[ $errexit -eq 1 ] && set -e
115	return $ret
116}
117
118cleanup_all_ns()
119{
120	cleanup_ns $NS_LIST
121}
122
123# setup netns with given names as prefix. e.g
124# setup_ns local remote
125setup_ns()
126{
127	local ns=""
128	local ns_name=""
129	local ns_list=""
130	for ns_name in "$@"; do
131		# Some test may setup/remove same netns multi times
132		if unset ${ns_name} 2> /dev/null; then
133			ns="${ns_name,,}-$(mktemp -u XXXXXX)"
134			eval readonly ${ns_name}="$ns"
135		else
136			eval ns='$'${ns_name}
137			cleanup_ns "$ns"
138
139		fi
140
141		if ! ip netns add "$ns"; then
142			echo "Failed to create namespace $ns_name"
143			cleanup_ns "$ns_list"
144			return $ksft_skip
145		fi
146		ip -n "$ns" link set lo up
147		ns_list="$ns_list $ns"
148	done
149	NS_LIST="$NS_LIST $ns_list"
150}
151