xref: /linux/tools/testing/selftests/net/lib.sh (revision 8be4d31cb8aaeea27bde4b7ddb26e28a89062ebf)
1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3
4net_dir=$(dirname "$(readlink -e "${BASH_SOURCE[0]}")")
5source "$net_dir/lib/sh/defer.sh"
6
7##############################################################################
8# Defines
9
10: "${WAIT_TIMEOUT:=20}"
11
12# Whether to pause on after a failure.
13: "${PAUSE_ON_FAIL:=no}"
14
15BUSYWAIT_TIMEOUT=$((WAIT_TIMEOUT * 1000)) # ms
16
17# Kselftest framework constants.
18ksft_pass=0
19ksft_fail=1
20ksft_xfail=2
21ksft_skip=4
22
23# namespace list created by setup_ns
24NS_LIST=()
25
26# Exit status to return at the end. Set in case one of the tests fails.
27EXIT_STATUS=0
28# Per-test return value. Clear at the beginning of each test.
29RET=0
30
31##############################################################################
32# Helpers
33
34__ksft_status_merge()
35{
36	local a=$1; shift
37	local b=$1; shift
38	local -A weights
39	local weight=0
40
41	local i
42	for i in "$@"; do
43		weights[$i]=$((weight++))
44	done
45
46	if [[ ${weights[$a]} > ${weights[$b]} ]]; then
47		echo "$a"
48		return 0
49	else
50		echo "$b"
51		return 1
52	fi
53}
54
55ksft_status_merge()
56{
57	local a=$1; shift
58	local b=$1; shift
59
60	__ksft_status_merge "$a" "$b" \
61		$ksft_pass $ksft_xfail $ksft_skip $ksft_fail
62}
63
64ksft_exit_status_merge()
65{
66	local a=$1; shift
67	local b=$1; shift
68
69	__ksft_status_merge "$a" "$b" \
70		$ksft_xfail $ksft_pass $ksft_skip $ksft_fail
71}
72
73loopy_wait()
74{
75	local sleep_cmd=$1; shift
76	local timeout_ms=$1; shift
77
78	local start_time="$(date -u +%s%3N)"
79	while true
80	do
81		local out
82		if out=$("$@"); then
83			echo -n "$out"
84			return 0
85		fi
86
87		local current_time="$(date -u +%s%3N)"
88		if ((current_time - start_time > timeout_ms)); then
89			echo -n "$out"
90			return 1
91		fi
92
93		$sleep_cmd
94	done
95}
96
97busywait()
98{
99	local timeout_ms=$1; shift
100
101	loopy_wait : "$timeout_ms" "$@"
102}
103
104# timeout in seconds
105slowwait()
106{
107	local timeout_sec=$1; shift
108
109	loopy_wait "sleep 0.1" "$((timeout_sec * 1000))" "$@"
110}
111
112until_counter_is()
113{
114	local expr=$1; shift
115	local current=$("$@")
116
117	echo $((current))
118	((current $expr))
119}
120
121busywait_for_counter()
122{
123	local timeout=$1; shift
124	local delta=$1; shift
125
126	local base=$("$@")
127	busywait "$timeout" until_counter_is ">= $((base + delta))" "$@"
128}
129
130slowwait_for_counter()
131{
132	local timeout=$1; shift
133	local delta=$1; shift
134
135	local base=$("$@")
136	slowwait "$timeout" until_counter_is ">= $((base + delta))" "$@"
137}
138
139# Check for existence of tools which are built as part of selftests
140# but may also already exist in $PATH
141check_gen_prog()
142{
143	local prog_name=$1; shift
144
145	if ! which $prog_name >/dev/null 2>/dev/null; then
146		PATH=$PWD:$PATH
147		if ! which $prog_name >/dev/null; then
148			echo "'$prog_name' command not found; skipping tests"
149			exit $ksft_skip
150		fi
151	fi
152}
153
154remove_ns_list()
155{
156	local item=$1
157	local ns
158	local ns_list=("${NS_LIST[@]}")
159	NS_LIST=()
160
161	for ns in "${ns_list[@]}"; do
162		if [ "${ns}" != "${item}" ]; then
163			NS_LIST+=("${ns}")
164		fi
165	done
166}
167
168cleanup_ns()
169{
170	local ns=""
171	local ret=0
172
173	for ns in "$@"; do
174		[ -z "${ns}" ] && continue
175		ip netns pids "${ns}" 2> /dev/null | xargs -r kill || true
176		ip netns delete "${ns}" &> /dev/null || true
177		if ! busywait $BUSYWAIT_TIMEOUT ip netns list \| grep -vq "^$ns$" &> /dev/null; then
178			echo "Warn: Failed to remove namespace $ns"
179			ret=1
180		else
181			remove_ns_list "${ns}"
182		fi
183	done
184
185	return $ret
186}
187
188cleanup_all_ns()
189{
190	cleanup_ns "${NS_LIST[@]}"
191}
192
193# setup netns with given names as prefix. e.g
194# setup_ns local remote
195setup_ns()
196{
197	local ns_name=""
198	local ns_list=()
199	for ns_name in "$@"; do
200		# avoid conflicts with local var: internal error
201		if [ "${ns_name}" = "ns_name" ]; then
202			echo "Failed to setup namespace '${ns_name}': invalid name"
203			cleanup_ns "${ns_list[@]}"
204			exit $ksft_fail
205		fi
206
207		# Some test may setup/remove same netns multi times
208		if [ -z "${!ns_name}" ]; then
209			eval "${ns_name}=${ns_name,,}-$(mktemp -u XXXXXX)"
210		else
211			cleanup_ns "${!ns_name}"
212		fi
213
214		if ! ip netns add "${!ns_name}"; then
215			echo "Failed to create namespace $ns_name"
216			cleanup_ns "${ns_list[@]}"
217			return $ksft_skip
218		fi
219		ip -n "${!ns_name}" link set lo up
220		ip netns exec "${!ns_name}" sysctl -wq net.ipv4.conf.all.rp_filter=0
221		ip netns exec "${!ns_name}" sysctl -wq net.ipv4.conf.default.rp_filter=0
222		ns_list+=("${!ns_name}")
223	done
224	NS_LIST+=("${ns_list[@]}")
225}
226
227# Create netdevsim with given id and net namespace.
228create_netdevsim() {
229    local id="$1"
230    local ns="$2"
231
232    modprobe netdevsim &> /dev/null
233    udevadm settle
234
235    echo "$id 1" | ip netns exec $ns tee /sys/bus/netdevsim/new_device >/dev/null
236    local dev=$(ip netns exec $ns ls /sys/bus/netdevsim/devices/netdevsim$id/net)
237    ip -netns $ns link set dev $dev name nsim$id
238    ip -netns $ns link set dev nsim$id up
239
240    echo nsim$id
241}
242
243create_netdevsim_port() {
244    local nsim_id="$1"
245    local ns="$2"
246    local port_id="$3"
247    local perm_addr="$4"
248    local orig_dev
249    local new_dev
250    local nsim_path
251
252    nsim_path="/sys/bus/netdevsim/devices/netdevsim$nsim_id"
253
254    echo "$port_id $perm_addr" | ip netns exec "$ns" tee "$nsim_path"/new_port > /dev/null || return 1
255
256    orig_dev=$(ip netns exec "$ns" find "$nsim_path"/net/ -maxdepth 1 -name 'e*' | tail -n 1)
257    orig_dev=$(basename "$orig_dev")
258    new_dev="nsim${nsim_id}p$port_id"
259
260    ip -netns "$ns" link set dev "$orig_dev" name "$new_dev"
261    ip -netns "$ns" link set dev "$new_dev" up
262
263    echo "$new_dev"
264}
265
266# Remove netdevsim with given id.
267cleanup_netdevsim() {
268    local id="$1"
269
270    if [ -d "/sys/bus/netdevsim/devices/netdevsim$id/net" ]; then
271        echo "$id" > /sys/bus/netdevsim/del_device
272    fi
273}
274
275tc_rule_stats_get()
276{
277	local dev=$1; shift
278	local pref=$1; shift
279	local dir=${1:-ingress}; shift
280	local selector=${1:-.packets}; shift
281
282	tc -j -s filter show dev $dev $dir pref $pref \
283	    | jq ".[1].options.actions[].stats$selector"
284}
285
286tc_rule_handle_stats_get()
287{
288	local id=$1; shift
289	local handle=$1; shift
290	local selector=${1:-.packets}; shift
291	local netns=${1:-""}; shift
292
293	tc $netns -j -s filter show $id \
294	    | jq ".[] | select(.options.handle == $handle) | \
295		  .options.actions[0].stats$selector"
296}
297
298# attach a qdisc with two children match/no-match and a flower filter to match
299tc_set_flower_counter() {
300	local -r ns=$1
301	local -r ipver=$2
302	local -r dev=$3
303	local -r flower_expr=$4
304
305	tc -n $ns qdisc add dev $dev root handle 1: prio bands 2 \
306			priomap 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
307
308	tc -n $ns qdisc add dev $dev parent 1:1 handle 11: pfifo
309	tc -n $ns qdisc add dev $dev parent 1:2 handle 12: pfifo
310
311	tc -n $ns filter add dev $dev parent 1: protocol ipv$ipver \
312			flower $flower_expr classid 1:2
313}
314
315tc_get_flower_counter() {
316	local -r ns=$1
317	local -r dev=$2
318
319	tc -n $ns -j -s qdisc show dev $dev handle 12: | jq .[0].packets
320}
321
322ret_set_ksft_status()
323{
324	local ksft_status=$1; shift
325	local msg=$1; shift
326
327	RET=$(ksft_status_merge $RET $ksft_status)
328	if (( $? )); then
329		retmsg=$msg
330	fi
331}
332
333log_test_result()
334{
335	local test_name=$1; shift
336	local opt_str=$1; shift
337	local result=$1; shift
338	local retmsg=$1
339
340	printf "TEST: %-60s  [%s]\n" "$test_name $opt_str" "$result"
341	if [[ $retmsg ]]; then
342		printf "\t%s\n" "$retmsg"
343	fi
344}
345
346pause_on_fail()
347{
348	if [[ $PAUSE_ON_FAIL == yes ]]; then
349		echo "Hit enter to continue, 'q' to quit"
350		read a
351		[[ $a == q ]] && exit 1
352	fi
353}
354
355handle_test_result_pass()
356{
357	local test_name=$1; shift
358	local opt_str=$1; shift
359
360	log_test_result "$test_name" "$opt_str" " OK "
361}
362
363handle_test_result_fail()
364{
365	local test_name=$1; shift
366	local opt_str=$1; shift
367
368	log_test_result "$test_name" "$opt_str" FAIL "$retmsg"
369	pause_on_fail
370}
371
372handle_test_result_xfail()
373{
374	local test_name=$1; shift
375	local opt_str=$1; shift
376
377	log_test_result "$test_name" "$opt_str" XFAIL "$retmsg"
378	pause_on_fail
379}
380
381handle_test_result_skip()
382{
383	local test_name=$1; shift
384	local opt_str=$1; shift
385
386	log_test_result "$test_name" "$opt_str" SKIP "$retmsg"
387}
388
389log_test()
390{
391	local test_name=$1
392	local opt_str=$2
393
394	if [[ $# -eq 2 ]]; then
395		opt_str="($opt_str)"
396	fi
397
398	if ((RET == ksft_pass)); then
399		handle_test_result_pass "$test_name" "$opt_str"
400	elif ((RET == ksft_xfail)); then
401		handle_test_result_xfail "$test_name" "$opt_str"
402	elif ((RET == ksft_skip)); then
403		handle_test_result_skip "$test_name" "$opt_str"
404	else
405		handle_test_result_fail "$test_name" "$opt_str"
406	fi
407
408	EXIT_STATUS=$(ksft_exit_status_merge $EXIT_STATUS $RET)
409	return $RET
410}
411
412log_test_skip()
413{
414	RET=$ksft_skip retmsg= log_test "$@"
415}
416
417log_test_xfail()
418{
419	RET=$ksft_xfail retmsg= log_test "$@"
420}
421
422log_info()
423{
424	local msg=$1
425
426	echo "INFO: $msg"
427}
428
429tests_run()
430{
431	local current_test
432
433	for current_test in ${TESTS:-$ALL_TESTS}; do
434		in_defer_scope \
435			$current_test
436	done
437}
438
439# Whether FAILs should be interpreted as XFAILs. Internal.
440FAIL_TO_XFAIL=
441
442check_err()
443{
444	local err=$1
445	local msg=$2
446
447	if ((err)); then
448		if [[ $FAIL_TO_XFAIL = yes ]]; then
449			ret_set_ksft_status $ksft_xfail "$msg"
450		else
451			ret_set_ksft_status $ksft_fail "$msg"
452		fi
453	fi
454}
455
456check_fail()
457{
458	local err=$1
459	local msg=$2
460
461	check_err $((!err)) "$msg"
462}
463
464check_err_fail()
465{
466	local should_fail=$1; shift
467	local err=$1; shift
468	local what=$1; shift
469
470	if ((should_fail)); then
471		check_fail $err "$what succeeded, but should have failed"
472	else
473		check_err $err "$what failed"
474	fi
475}
476
477xfail()
478{
479	FAIL_TO_XFAIL=yes "$@"
480}
481
482xfail_on_slow()
483{
484	if [[ $KSFT_MACHINE_SLOW = yes ]]; then
485		FAIL_TO_XFAIL=yes "$@"
486	else
487		"$@"
488	fi
489}
490
491omit_on_slow()
492{
493	if [[ $KSFT_MACHINE_SLOW != yes ]]; then
494		"$@"
495	fi
496}
497
498xfail_on_veth()
499{
500	local dev=$1; shift
501	local kind
502
503	kind=$(ip -j -d link show dev $dev |
504			jq -r '.[].linkinfo.info_kind')
505	if [[ $kind = veth ]]; then
506		FAIL_TO_XFAIL=yes "$@"
507	else
508		"$@"
509	fi
510}
511
512mac_get()
513{
514	local if_name=$1
515
516	ip -j link show dev $if_name | jq -r '.[]["address"]'
517}
518
519kill_process()
520{
521	local pid=$1; shift
522
523	# Suppress noise from killing the process.
524	{ kill $pid && wait $pid; } 2>/dev/null
525}
526
527check_command()
528{
529	local cmd=$1; shift
530
531	if [[ ! -x "$(command -v "$cmd")" ]]; then
532		log_test_skip "$cmd not installed"
533		return $EXIT_STATUS
534	fi
535}
536
537require_command()
538{
539	local cmd=$1; shift
540
541	if ! check_command "$cmd"; then
542		exit $EXIT_STATUS
543	fi
544}
545
546ip_link_add()
547{
548	local name=$1; shift
549
550	ip link add name "$name" "$@"
551	defer ip link del dev "$name"
552}
553
554ip_link_set_master()
555{
556	local member=$1; shift
557	local master=$1; shift
558
559	ip link set dev "$member" master "$master"
560	defer ip link set dev "$member" nomaster
561}
562
563ip_link_set_addr()
564{
565	local name=$1; shift
566	local addr=$1; shift
567
568	local old_addr=$(mac_get "$name")
569	ip link set dev "$name" address "$addr"
570	defer ip link set dev "$name" address "$old_addr"
571}
572
573ip_link_has_flag()
574{
575	local name=$1; shift
576	local flag=$1; shift
577
578	local state=$(ip -j link show "$name" |
579		      jq --arg flag "$flag" 'any(.[].flags.[]; . == $flag)')
580	[[ $state == true ]]
581}
582
583ip_link_is_up()
584{
585	ip_link_has_flag "$1" UP
586}
587
588ip_link_set_up()
589{
590	local name=$1; shift
591
592	if ! ip_link_is_up "$name"; then
593		ip link set dev "$name" up
594		defer ip link set dev "$name" down
595	fi
596}
597
598ip_link_set_down()
599{
600	local name=$1; shift
601
602	if ip_link_is_up "$name"; then
603		ip link set dev "$name" down
604		defer ip link set dev "$name" up
605	fi
606}
607
608ip_addr_add()
609{
610	local name=$1; shift
611
612	ip addr add dev "$name" "$@"
613	defer ip addr del dev "$name" "$@"
614}
615
616ip_route_add()
617{
618	ip route add "$@"
619	defer ip route del "$@"
620}
621
622bridge_vlan_add()
623{
624	bridge vlan add "$@"
625	defer bridge vlan del "$@"
626}
627
628wait_local_port_listen()
629{
630	local listener_ns="${1}"
631	local port="${2}"
632	local protocol="${3}"
633	local pattern
634	local i
635
636	pattern=":$(printf "%04X" "${port}") "
637
638	# for tcp protocol additionally check the socket state
639	[ ${protocol} = "tcp" ] && pattern="${pattern}0A"
640	for i in $(seq 10); do
641		if ip netns exec "${listener_ns}" awk '{print $2" "$4}' \
642		   /proc/net/"${protocol}"* | grep -q "${pattern}"; then
643			break
644		fi
645		sleep 0.1
646	done
647}
648