CNI接口很簡單,特別一些新手一定要克服恐懼心里,和我一探究竟,本文結(jié)合原理與實(shí)踐,認(rèn)真讀下來一定會(huì)對(duì)原理理解非常透徹。
環(huán)境介紹
我們安裝kubernetes時(shí)先不安裝CNI. 如果使用了sealyun離線包 那么修改下 kube/conf/master.sh
只留如下內(nèi)容即可:
[root@helix105 shell]# cat master.sh
kubeadm init --config ../conf/kubeadm.yaml
mkdir ~/.kube
cp /etc/kubernetes/admin.conf ~/.kube/config
kubectl taint nodes --all node-role.kubernetes.io/master-
清空CNI相關(guān)目錄:
rm -rf /opt/cni/bin/*
rm -rf /etc/cni/net.d/*
啟動(dòng)kubernetes, 如果已經(jīng)裝過那么kubeadm reset一下:
cd kube/shell && sh init.sh && sh master.sh
此時(shí)你的節(jié)點(diǎn)是notready的,你的coredns也沒有辦法分配到地址:
[root@helix105 shell]# kubectl get pod -n kube-system -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
coredns-5c98db65d4-5fh6c 0/1 Pending 0 54s <none> <none> <none> <none>
coredns-5c98db65d4-dbwmq 0/1 Pending 0 54s <none> <none> <none> <none>
kube-controller-manager-helix105.hfa.chenqian 1/1 Running 0 19s 172.16.60.105 helix105.hfa.chenqian <none> <none>
kube-proxy-k74ld 1/1 Running 0 54s 172.16.60.105 helix105.hfa.chenqian <none> <none>
kube-scheduler-helix105.hfa.chenqian 1/1 Running 0 14s 172.16.60.105 helix105.hfa.chenqian <none> <none>
[root@helix105 shell]# kubectl get node
NAME STATUS ROLES AGE VERSION
helix105.hfa.chenqian NotReady master 86s v1.15.0
安裝CNI
創(chuàng)建CNI配置文件
$ mkdir -p /etc/cni/net.d
$ cat >/etc/cni/net.d/10-mynet.conf <<EOF
{
"cniVersion": "0.2.0",
"name": "mynet",
"type": "bridge",
"bridge": "cni0",
"isGateway": true,
"ipMasq": true,
"ipam": {
"type": "host-local",
"subnet": "10.22.0.0/16",
"routes": [
{ "dst": "0.0.0.0/0" }
]
}
}
EOF
$ cat >/etc/cni/net.d/99-loopback.conf <<EOF
{
"cniVersion": "0.2.0",
"name": "lo",
"type": "loopback"
}
EOF
這里兩個(gè)配置一個(gè)是給容器塞一個(gè)網(wǎng)卡掛在網(wǎng)橋上的,另外一個(gè)配置負(fù)責(zé)擼(本地回環(huán))。。
配置完后會(huì)發(fā)現(xiàn)節(jié)點(diǎn)ready:
[root@helix105 shell]# kubectl get node
NAME STATUS ROLES AGE VERSION
helix105.hfa.chenqian Ready master 15m v1.15.0
但是coredns會(huì)一直處于ContainerCreating狀態(tài),是因?yàn)閎in文件還沒有:
failed to find plugin "bridge" in path [/opt/cni/bin]
plugins里實(shí)現(xiàn)了很多的CNI,如我們上面配置的bridge.
$ cd $GOPATH/src/github.com/containernetworking/plugins
$ ./build_linux.sh
$ cp bin/* /opt/cni/bin
$ ls bin/
bandwidth dhcp flannel host-local loopback portmap sbr tuning
bridge firewall host-device ipvlan macvlan ptp static vlan
這里有很多二進(jìn)制,我們學(xué)習(xí)的話不需要關(guān)注所有的,就看ptp(就簡單的創(chuàng)建了設(shè)備對(duì))或者bridge
再看coredns已經(jīng)能分配到地址了:
[root@helix105 plugins]# kubectl get pod -n kube-system -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
coredns-5c98db65d4-5fh6c 1/1 Running 0 3h10m 10.22.0.8 helix105.hfa.chenqian <none> <none>
coredns-5c98db65d4-dbwmq 1/1 Running 0 3h10m 10.22.0.9
看一下網(wǎng)橋,cni0上掛了兩個(gè)設(shè)備,與我們上面的cni配置里配置的一樣,type字段指定用哪個(gè)bin文件,bridge字段指定網(wǎng)橋名:
[root@helix105 plugins]# brctl show
bridge name bridge id STP enabled interfaces
cni0 8000.8ef6ac49c2f7 no veth1b28b06f
veth1c093940
原理
為了更好理解kubelet干嘛了,我們可以找一個(gè)腳本來解釋 script 這個(gè)腳本也可以用來測(cè)試你的CNI:
為了易讀,我刪除一些不重要的東西,原版腳本可以在連接中去拿
# 先創(chuàng)建一個(gè)容器,這里只為了拿到一個(gè)net namespace
contid=$(docker run -d --net=none golang:1.12.7 /bin/sleep 10000000)
pid=$(docker inspect -f '{{ .State.Pid }}' $contid)
netnspath=/proc/$pid/ns/net # 這個(gè)我們需要
kubelet啟動(dòng)pod時(shí)也是創(chuàng)建好容器就有了pod的network namespaces,再去把ns傳給cni 讓cni去配置
./exec-plugins.sh add $contid $netnspath # 傳入兩個(gè)參數(shù)給下一個(gè)腳本,containerid和net namespace路徑
docker run --net=container:$contid $@
NETCONFPATH=${NETCONFPATH-/etc/cni/net.d}
i=0
# 獲取容器id和網(wǎng)絡(luò)ns
contid=$2
netns=$3
# 這里設(shè)置了幾個(gè)環(huán)境變量,CNI命令行工具就可以獲取到這些參數(shù)
export CNI_COMMAND=$(echo $1 | tr '[:lower:]' '[:upper:]')
export PATH=$CNI_PATH:$PATH # 這個(gè)指定CNI bin文件的路徑
export CNI_CONTAINERID=$contid
export CNI_NETNS=$netns
for netconf in $(echo $NETCONFPATH/10-mynet.conf | sort); do
name=$(jq -r '.name' <$netconf)
plugin=$(jq -r '.type' <$netconf) # CNI配置文件的type字段對(duì)應(yīng)二進(jìn)制程序名
export CNI_IFNAME=$(printf eth%d $i) # 容器內(nèi)網(wǎng)卡名
# 這里執(zhí)行了命令行工具
res=$($plugin <$netconf) # 這里把CNI的配置文件通過標(biāo)準(zhǔn)輸入也傳給CNI命令行工具
if [ $? -ne 0 ]; then
# 把結(jié)果輸出到標(biāo)準(zhǔn)輸出,這樣kubelet就可以拿到容器地址等一些信息
errmsg=$(echo $res | jq -r '.msg')
if [ -z "$errmsg" ]; then
errmsg=$res
fi
echo "${name} : error executing $CNI_COMMAND: $errmsg"
exit 1
let "i=i+1"
done
總結(jié)一下:
CNI配置文件
容器ID
網(wǎng)絡(luò)ns
kubelet --------------> CNI command
^ |
| |
+------------------------+
結(jié)果標(biāo)準(zhǔn)輸出
bridge CNI實(shí)現(xiàn)
既然這么簡單,那么就可以去看看實(shí)現(xiàn)了:
//cmdAdd 負(fù)責(zé)創(chuàng)建網(wǎng)絡(luò)
func cmdAdd(args *skel.CmdArgs) error
//入?yún)?shù)都已經(jīng)寫到這里面了,前面的參數(shù)從環(huán)境變量讀取的,CNI配置從stdin讀取的
type CmdArgs struct {
ContainerID string
Netns string
IfName string
Args string
Path string
StdinData []byte
}
所以CNI配置文件除了name type這些特定字段,你自己也可以加自己的一些字段.然后自己去解析
然后啥事都得靠自己了
//這里創(chuàng)建了設(shè)備對(duì),并掛載到cni0王橋上
hostInterface, containerInterface, err := setupVeth(netns, br, args.IfName, n.MTU, n.HairpinMode, n.Vlan)
具體怎么掛的就是調(diào)用了netlink 這個(gè)庫,sealos在做內(nèi)核負(fù)載時(shí)同樣用了該庫。
err := netns.Do(func(hostNS ns.NetNS) error { //創(chuàng)建設(shè)備對(duì)
hostVeth, containerVeth, err := ip.SetupVeth(ifName, mtu, hostNS)
...
//配置容器內(nèi)的網(wǎng)卡名mac地址等
contIface.Name = containerVeth.Name
contIface.Mac = containerVeth.HardwareAddr.String()
contIface.Sandbox = netns.Path()
hostIface.Name = hostVeth.Name
return nil
})
...
// 根據(jù)index找到宿主機(jī)設(shè)備對(duì)名
hostVeth, err := netlink.LinkByName(hostIface.Name)
...
hostIface.Mac = hostVeth.Attrs().HardwareAddr.String()
// 把宿主機(jī)端設(shè)備對(duì)掛給網(wǎng)橋
if err := netlink.LinkSetMaster(hostVeth, br); err != nil {}
// 設(shè)置hairpin mode
if err = netlink.LinkSetHairpin(hostVeth, hairpinMode); err != nil {
}
// 設(shè)置vlanid
if vlanID != 0 {
err = netlink.BridgeVlanAdd(hostVeth, uint16(vlanID), true, true, false, true)
}
return hostIface, contIface, nil
最后把結(jié)果返回:
type Result struct {
CNIVersion string `json:"cniVersion,omitempty"`
Interfaces []*Interface `json:"interfaces,omitempty"`
IPs []*IPConfig `json:"ips,omitempty"`
Routes []*types.Route `json:"routes,omitempty"`
DNS types.DNS `json:"dns,omitempty"`
}
// 這樣kubelet就收到返回信息了
func (r *Result) PrintTo(writer io.Writer) error {
data, err := json.MarshalIndent(r, "", " ")
if err != nil {
return err
}
_, err = writer.Write(data)
return err
}
如:
{
"cniVersion": "0.4.0",
"interfaces": [ (this key omitted by IPAM plugins)
{
"name": "<name>",
"mac": "<MAC address>", (required if L2 addresses are meaningful)
"sandbox": "<netns path or hypervisor identifier>" (required for container/hypervisor interfaces, empty/omitted for host interfaces)
}
],
"ips": [
{
"version": "<4-or-6>",
"address": "<ip-and-prefix-in-CIDR>",
"gateway": "<ip-address-of-the-gateway>", (optional)
"interface": <numeric index into 'interfaces' list>
},
...
],
"routes": [ (optional)
{
"dst": "<ip-and-prefix-in-cidr>",
"gw": "<ip-of-next-hop>" (optional)
},
...
],
"dns": { (optional)
"nameservers": <list-of-nameservers> (optional)
"domain": <name-of-local-domain> (optional)
"search": <list-of-additional-search-domains> (optional)
"options": <list-of-options> (optional)
}
}
總結(jié)
CNI接口層面是非常簡單的,所以更多的就是在CNI本身的實(shí)現(xiàn)了,懂了上文這些就可以自己去實(shí)現(xiàn)一個(gè)CNI了,是不是很酷,也會(huì)讓大家更熟悉網(wǎng)絡(luò)以更從容的姿態(tài)排查網(wǎng)絡(luò)問題了。
掃碼關(guān)注sealyun
探討可加QQ群:98488045