Hyunsun Moon | f9cac59 | 2020-11-10 00:46:41 -0800 | [diff] [blame] | 1 | #!/bin/bash -x |
| 2 | |
| 3 | set -o errexit |
| 4 | set -o pipefail |
| 5 | set -o nounset |
| 6 | |
| 7 | exec 3>&1 |
| 8 | exec &>>/var/log/$(basename $0).log |
| 9 | |
| 10 | PATH="$CNI_PATH:$(dirname "${BASH_SOURCE[0]}"):$PATH" |
| 11 | CNI_CONF=$(cat /dev/stdin) |
| 12 | |
| 13 | get_peer_name() { |
| 14 | echo "$1-vdev" |
| 15 | } |
| 16 | |
| 17 | get_mac_with_vfpci() { |
| 18 | local pf=$(readlink /sys/devices/pci*/*/$1/physfn | awk '{print substr($1,4)}') |
| 19 | local pfName=$(ls /sys/devices/pci*/*/$pf/net/ | head -1) |
| 20 | local idx=$(ls -l /sys/devices/pci*/*/$pf | awk -v vf=$1 'substr($11,4)==vf {print substr($9,7)}') |
| 21 | local mac=$(ip link show dev $pfName | awk -v idx="$idx" '$1=="vf" && $2==idx {print substr($4,1,17)}') |
| 22 | echo $mac |
| 23 | } |
| 24 | |
| 25 | ipam() { |
| 26 | local plugin=$(echo $CNI_CONF | jq -r '.ipam.type') |
| 27 | local res=$(echo $"$CNI_CONF" | "$plugin" | jq -c '.') |
| 28 | echo $res |
| 29 | } |
| 30 | |
| 31 | add_pair_ns() { |
| 32 | vfpci=$(echo $CNI_CONF | jq -r '.deviceID') |
Hyunsun Moon | 1711b2c | 2021-05-07 15:31:01 -0700 | [diff] [blame] | 33 | mac=$(echo $CNI_CONF | jq -r '.runtimeConfig.mac // empty') |
Hyunsun Moon | f9cac59 | 2020-11-10 00:46:41 -0800 | [diff] [blame] | 34 | if [ -z "$mac" ]; then |
| 35 | mac=$(get_mac_with_vfpci $vfpci) |
| 36 | fi |
| 37 | peer=$(get_peer_name $CNI_IFNAME) |
| 38 | ip=$1 |
| 39 | |
| 40 | mkdir -p /var/run/netns/ |
| 41 | ln -sfT $CNI_NETNS /var/run/netns/$CNI_CONTAINERID |
| 42 | |
| 43 | ip netns exec $CNI_CONTAINERID ip link add $CNI_IFNAME type veth peer name $peer |
| 44 | ip netns exec $CNI_CONTAINERID ip link set $CNI_IFNAME addr $mac up alias $vfpci |
| 45 | ip netns exec $CNI_CONTAINERID ip link set $peer up |
| 46 | ip netns exec $CNI_CONTAINERID ip addr add $ip dev $CNI_IFNAME |
| 47 | } |
| 48 | |
| 49 | delete_pair_ns() { |
| 50 | ip netns exec $CNI_CONTAINERID ip link del $CNI_IFNAME |
| 51 | } |
| 52 | |
| 53 | case $CNI_COMMAND in |
| 54 | ADD) |
| 55 | res=$(ipam) |
| 56 | ip=$(echo $res | jq -r '.ips[0].address') |
| 57 | add_pair_ns $ip |
| 58 | echo '{"cniVersion":"0.3.1"}' | jq -c --arg ip $ip '.ips[0].address = $ip' >&3 |
| 59 | ;; |
| 60 | DEL) |
| 61 | set +o errexit |
| 62 | ipam |
| 63 | delete_pair_ns |
| 64 | set -o errexit |
| 65 | ;; |
| 66 | *) |
| 67 | echo "CNI_COMMAND=[ADD|DEL] only supported" |
| 68 | exit 1 |
| 69 | ;; |
| 70 | esac |