forked from cnidemo/cnidemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo
executable file
·87 lines (66 loc) · 1.96 KB
/
demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/bin/bash
# Redirect errors to log file
exec 2>>/var/log/demolog
echo "CNI_COMMAND: $CNI_COMMAND" >> /var/log/demolog
# Read network configuration from stdin
conf=$(cat /dev/stdin)
# Get custom attributes from network configuration
bridge=$(echo $conf| jq -r ".bridge")
gateway=$(echo $conf| jq -r ".gateway")
# Network namespace name
nsname=$CNI_CONTAINERID
# IPAM substitute
ip_addr=10.0.0.100/24
if [[ $CNI_COMMAND == "ADD" ]]; then
# Create named network namespace
mkdir -p /var/run/netns
ln -sfT $CNI_NETNS /var/run/netns/$nsname
# Create veth pair
ip link add veth_root type veth peer name veth_ns
# Connect veth_root to bridge
ip link set veth_root master $bridge
ip link set dev veth_root up
ip link set dev $bridge up
# Move veth_ns to namespace
ip link set veth_ns netns $nsname
# Rename veth_ns
ip -netns $nsname link set dev veth_ns down
ip -netns $nsname link set veth_ns name $CNI_IFNAME
ip -netns $nsname link set dev $CNI_IFNAME up
# IPAM
ip -netns $nsname addr add $ip_addr dev $CNI_IFNAME
# Routing
ip -netns $nsname route add default via $gateway
# MAC of added interface
mac=$(ip -netns $nsname link show $CNI_IFNAME| grep link| awk '{print$2}')
# Interface index of added interface
interface_index=$(ip -netns $nsname link show $CNI_IFNAME |grep $CNI_IFNAME |awk -F ':' '{print$1}')
OUTPUT_TEMPLATE='
{
"cniVersion": "0.3.1",
"interfaces": [
{
"name": "%s",
"mac": "%s",
"sandbox": "%s"
}
],
"ips": [
{
"version": "4",
"address": "%s",
"gateway": "%s",
"interface": %s
}
]
}'
OUTPUT=$(printf "$OUTPUT_TEMPLATE" $CNI_IFNAME $mac $CNI_NETNS $ip_addr $gateway $interface_index)
# Log result
echo $OUTPUT >> /var/log/demolog
# Stream the result back to container runtime in stdout
echo $OUTPUT
fi
if [[ $CNI_COMMAND == "DELETE" ]]; then
ip netns del $nsname || true
ip link del veth_root || true
fi