blob: df0d975b3e940e5c4cb317124d42c681dbd986ec [file] [log] [blame]
Jeremy Ronquillo6be909e2020-08-24 09:36:13 -07001#!/bin/bash -x
2#
3# Copyright 2019-present Open Networking Foundation
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17set -o errexit
18set -o pipefail
19set -o nounset
20
21exec 3>&1
22exec &>>/var/log/simple-ovs-cni.log
23
24PATH="$CNI_PATH:$(dirname "${BASH_SOURCE[0]}"):$PATH"
25CNI_CONF=$(cat /dev/stdin)
26
27get_bridge() {
28 echo "br-$(echo $CNI_CONF | jq -r '.name')"
29}
30
31ipam() {
32 local plugin=$(echo $CNI_CONF | jq -r '.ipam.type')
33 local res=$(echo $"$CNI_CONF" | "$plugin" | jq -c '.')
34 echo $res
35}
36
37add_br_and_port() {
38 mkdir -p /var/run/netns/
39 ln -sfT $CNI_NETNS /var/run/netns/$CNI_CONTAINERID
40
41 local bridge=$(get_bridge)
42 local ip=$1
43
44 ovs-vsctl --may-exist add-br $bridge
45 ovs-vsctl add-port $bridge $CNI_IFNAME -- set Interface $CNI_IFNAME type=internal
46
47 ip link set $CNI_IFNAME netns $CNI_CONTAINERID
48 ip netns exec $CNI_CONTAINERID ip addr add $ip dev $CNI_IFNAME
49 ip netns exec $CNI_CONTAINERID ip link set $CNI_IFNAME up
50}
51
52delete_br_and_port() {
53 local bridge="br-$(echo $CNI_CONF | jq -r '.name')"
54 ovs-vsctl del-port $CNI_IFNAME
55 if [ -z "$(ovs-vsctl list-ports $bridge)" ]; then
56 ovs-vsctl del-br $bridge
57 fi
58}
59
60case $CNI_COMMAND in
61ADD)
62 res=$(ipam)
Hyunsun84f0f172020-09-23 15:40:08 -050063 ip=$(echo $res | jq -r '.ips[0].address')
Jeremy Ronquillo6be909e2020-08-24 09:36:13 -070064 add_br_and_port $ip
Hyunsun84f0f172020-09-23 15:40:08 -050065 echo '{"cniVersion":"0.3.1"}' | jq -c --arg ip $ip '.ips[0].address = $ip' >&3
Jeremy Ronquillo6be909e2020-08-24 09:36:13 -070066 ;;
67DEL)
68 set +o errexit
69 ipam
70 delete_br_and_port
71 set -o errexit
72 ;;
73*)
74 echo "CNI_COMMAND=[ADD|DEL] only supported"
75 exit 1
76 ;;
77esac