Jeremy Ronquillo | 6be909e | 2020-08-24 09:36:13 -0700 | [diff] [blame] | 1 | #!/bin/bash -x |
| 2 | # |
| 3 | # Copyright 2019-present Open Networking Foundation |
| 4 | # |
Andy Bavier | 2c42773 | 2022-02-03 15:16:46 -0700 | [diff] [blame] | 5 | # SPDX-License-Identifier: Apache-2.0 |
Jeremy Ronquillo | 6be909e | 2020-08-24 09:36:13 -0700 | [diff] [blame] | 6 | |
| 7 | set -o errexit |
| 8 | set -o pipefail |
| 9 | set -o nounset |
| 10 | |
| 11 | exec 3>&1 |
| 12 | exec &>>/var/log/simple-ovs-cni.log |
| 13 | |
| 14 | PATH="$CNI_PATH:$(dirname "${BASH_SOURCE[0]}"):$PATH" |
| 15 | CNI_CONF=$(cat /dev/stdin) |
| 16 | |
| 17 | get_bridge() { |
| 18 | echo "br-$(echo $CNI_CONF | jq -r '.name')" |
| 19 | } |
| 20 | |
| 21 | ipam() { |
| 22 | local plugin=$(echo $CNI_CONF | jq -r '.ipam.type') |
| 23 | local res=$(echo $"$CNI_CONF" | "$plugin" | jq -c '.') |
| 24 | echo $res |
| 25 | } |
| 26 | |
| 27 | add_br_and_port() { |
| 28 | mkdir -p /var/run/netns/ |
| 29 | ln -sfT $CNI_NETNS /var/run/netns/$CNI_CONTAINERID |
| 30 | |
| 31 | local bridge=$(get_bridge) |
| 32 | local ip=$1 |
| 33 | |
| 34 | ovs-vsctl --may-exist add-br $bridge |
| 35 | ovs-vsctl add-port $bridge $CNI_IFNAME -- set Interface $CNI_IFNAME type=internal |
| 36 | |
| 37 | ip link set $CNI_IFNAME netns $CNI_CONTAINERID |
| 38 | ip netns exec $CNI_CONTAINERID ip addr add $ip dev $CNI_IFNAME |
| 39 | ip netns exec $CNI_CONTAINERID ip link set $CNI_IFNAME up |
| 40 | } |
| 41 | |
| 42 | delete_br_and_port() { |
| 43 | local bridge="br-$(echo $CNI_CONF | jq -r '.name')" |
| 44 | ovs-vsctl del-port $CNI_IFNAME |
| 45 | if [ -z "$(ovs-vsctl list-ports $bridge)" ]; then |
| 46 | ovs-vsctl del-br $bridge |
| 47 | fi |
| 48 | } |
| 49 | |
| 50 | case $CNI_COMMAND in |
| 51 | ADD) |
| 52 | res=$(ipam) |
Hyunsun | 84f0f17 | 2020-09-23 15:40:08 -0500 | [diff] [blame] | 53 | ip=$(echo $res | jq -r '.ips[0].address') |
Jeremy Ronquillo | 6be909e | 2020-08-24 09:36:13 -0700 | [diff] [blame] | 54 | add_br_and_port $ip |
Hyunsun | 84f0f17 | 2020-09-23 15:40:08 -0500 | [diff] [blame] | 55 | echo '{"cniVersion":"0.3.1"}' | jq -c --arg ip $ip '.ips[0].address = $ip' >&3 |
Jeremy Ronquillo | 6be909e | 2020-08-24 09:36:13 -0700 | [diff] [blame] | 56 | ;; |
| 57 | DEL) |
| 58 | set +o errexit |
| 59 | ipam |
| 60 | delete_br_and_port |
| 61 | set -o errexit |
| 62 | ;; |
| 63 | *) |
| 64 | echo "CNI_COMMAND=[ADD|DEL] only supported" |
| 65 | exit 1 |
| 66 | ;; |
| 67 | esac |