Skip to content

Instantly share code, notes, and snippets.

@clementnuss
Last active March 29, 2021 12:00
Show Gist options
  • Save clementnuss/104dfa85b1f18cedc61e7983dadb1691 to your computer and use it in GitHub Desktop.
Save clementnuss/104dfa85b1f18cedc61e7983dadb1691 to your computer and use it in GitHub Desktop.
Bash script permitting to intercept CNI calls and log env, stdin, stdout, stderr
#!/bin/bash
# Auther Clément Nussbaumer <clement@astutus.org>, Aug 2020
#
# CNI interception script: permits to do live debugging of CNI calls.
# Usage: rename the real cni binary file with by prepending the orginal binary name with real_
# E.g. for multus, real_multus. Now put this script in place the binary:
# Concretely, name it `multus` if you want to intercept multus calls.
cni=$(echo $0 | awk '{split($0,r,"/"); print r[length(r)]}')
echo 'intercepted '$cni' cni with command: ' $CNI_COMMAND ' and caller: ' $(ps -o comm= $PPID) | logger -t cni
stdin="$([[ -p /dev/stdin ]] && cat -)"
dir=/tmp/cni_logging;
if [ ! -d $dir ]; then
mkdir $dir
fi
current_time=$(date "+%Y.%m.%d-%H.%M.%S.")
current_millis=$(($(date +%N) / 1000))
if [[ $CNI_COMMAND = 'VERSION' ]]; then
file_name=/dev/zero
else
file_name=$dir/$current_time$current_millis'-'$cni'-'$CNI_COMMAND
fi
env | grep -e 'CNI_' > $file_name'_env'
# source of this clever snippet of code: https://stackoverflow.com/a/41069638
# if you want to understand how this "magic" work, read this: https://wiki.bash-hackers.org/howto/redirection_tutorial
: catch STDOUT STDERR cmd args..
catch()
{
eval "$({
__2="$(
{ __1="$("${@:3}")"; } 2>&1;
ret=$?;
printf '%q=%q\n' "$1" "$__1" >&2;
exit $ret
)"
ret="$?";
printf '%s=%q\n' "$2" "$__2" >&2;
printf '( exit %q )' "$ret" >&2;
} 2>&1 )";
}
: pipe_stdin
pipe_stdin()
{
(/opt/cni/bin/real_$cni <<EOF
$stdin
EOF
)
}
catch stdout stderr pipe_stdin $@
echo $stdin > $file_name'_stdin'
echo $stdout > $file_name'_stdout'
echo $stderr > $file_name'_stderr'
#printf '%s' "$stdout" | logger -t cni # uncomment if you want to show the output of the CNI call
printf '%s\n' "${stdout}"
printf '%s\n' "$stderr" 1>&2
@clementnuss
Copy link
Author

Initial revision of this interception script. Can be used to e.g. intercept calls to a CNI, for debugging purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment