| 1 |
#!/usr/bin/env bash |
| 2 |
|
| 3 |
if [[ ${DEBUG} -gt 0 ]]; then set -x; fi |
| 4 |
|
| 5 |
NETCONFPATH="${NETCONFPATH-/etc/cni/net.d}" |
| 6 |
|
| 7 |
function exec_list() { |
| 8 |
plist="$1" |
| 9 |
name="$2" |
| 10 |
cniVersion="$3" |
| 11 |
echo "$plist" | jq -c '.[]' | while read -r conf; do |
| 12 |
plugin_bin="$(echo "$conf" | jq -r '.type')" |
| 13 |
conf="$(echo "$conf" | jq -r ".name = \"$name\" | .cniVersion = \"$cniVersion\"")" |
| 14 |
if [ -n "$res" ]; then |
| 15 |
conf="$(echo "$conf" | jq -r ".prevResult=$res")" |
| 16 |
fi |
| 17 |
if ! res=$(echo "$conf" | $plugin_bin); then |
| 18 |
error "$name" "$res" |
| 19 |
elif [[ ${DEBUG} -gt 0 ]]; then |
| 20 |
echo "${res}" | jq -r . |
| 21 |
fi |
| 22 |
done |
| 23 |
} |
| 24 |
|
| 25 |
function error () { |
| 26 |
name="$1" |
| 27 |
res="$2" |
| 28 |
err_msg=$(echo "$res" | jq -r '.msg') |
| 29 |
if [ -z "$errmsg" ]; then |
| 30 |
err_msg=$res |
| 31 |
fi |
| 32 |
echo "${name} : error executing $CNI_COMMAND: $err_msg" |
| 33 |
exit 1 |
| 34 |
} |
| 35 |
|
| 36 |
function exec_plugins() { |
| 37 |
i=0 |
| 38 |
contid=$2 |
| 39 |
netns=$3 |
| 40 |
export CNI_COMMAND=$(echo $1 | tr '[:lower:]' '[:upper:]') |
| 41 |
export PATH=$CNI_PATH:$PATH |
| 42 |
export CNI_CONTAINERID=$contid |
| 43 |
export CNI_NETNS=$netns |
| 44 |
|
| 45 |
for netconf in $(echo "$NETCONFPATH"/*.conf | sort); do |
| 46 |
export CNI_IFNAME=$(printf eth%d $i) |
| 47 |
name=$(jq -r '.name' <"$netconf") |
| 48 |
cniVersion=$(jq -r '.cniVersion' <"$netconf") |
| 49 |
plist=$(jq '.plugins | select(.!=null)' <"$netconf") |
| 50 |
if [ -n "$plist" ]; then |
| 51 |
exec_list "$plist" "$name" "$cniVersion" |
| 52 |
else |
| 53 |
plugin=$(jq -r '.type' <"$netconf") |
| 54 |
|
| 55 |
if ! res=$($plugin <"$netconf"); then |
| 56 |
error "$name" "$res" |
| 57 |
elif [[ ${DEBUG} -gt 0 ]]; then |
| 58 |
echo "${res}" | jq -r . |
| 59 |
fi |
| 60 |
fi |
| 61 |
|
| 62 |
(( i++ )) || true |
| 63 |
done |
| 64 |
} |
| 65 |
|
| 66 |
if [ $# -ne 3 ]; then |
| 67 |
echo "Usage: $0 add|del CONTAINER-ID NETNS-PATH" |
| 68 |
echo " Adds or deletes the container specified by NETNS-PATH to the networks" |
| 69 |
echo " specified in \$NETCONFPATH directory" |
| 70 |
exit 1 |
| 71 |
fi |
| 72 |
|
| 73 |
exec_plugins $1 $2 $3 |