blob: c84165d343c10507c19de95fcbd90e6e36f33baa [file] [log] [blame]
Hyunsun Moonf9cac592020-11-10 00:46:41 -08001#!/bin/bash -x
2
3set -o errexit
4set -o pipefail
5set -o nounset
6
7exec 3>&1
8exec &>>/var/log/$(basename $0).log
9
10PATH="$CNI_PATH:$(dirname "${BASH_SOURCE[0]}"):$PATH"
11CNI_CONF=$(cat /dev/stdin)
12
13get_peer_name() {
14 echo "$1-vdev"
15}
16
17get_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
25ipam() {
26 local plugin=$(echo $CNI_CONF | jq -r '.ipam.type')
27 local res=$(echo $"$CNI_CONF" | "$plugin" | jq -c '.')
28 echo $res
29}
30
31add_pair_ns() {
32 vfpci=$(echo $CNI_CONF | jq -r '.deviceID')
Hyunsun Moon1711b2c2021-05-07 15:31:01 -070033 mac=$(echo $CNI_CONF | jq -r '.runtimeConfig.mac // empty')
Hyunsun Moonf9cac592020-11-10 00:46:41 -080034 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
49delete_pair_ns() {
50 ip netns exec $CNI_CONTAINERID ip link del $CNI_IFNAME
51}
52
53case $CNI_COMMAND in
54ADD)
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 ;;
60DEL)
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 ;;
70esac