# Kubernetes CNI Cilium# 时间:20210908-[20:00-22:00]# 主题:Cilium Native Routing # 文档:# 作业:Cilium Native Routing
# FAQ:
INSTALL GUIDE WITH KUBEADM
### 先挂载bpf:#Mount bpf as a service:cat <<EOF | sudo tee /etc/systemd/system/sys-fs-bpf.mount[Unit]Description=Cilium BPF mountsDocumentation=https://docs.cilium.io/DefaultDependencies=noBefore=local-fs.target umount.targetAfter=swap.target[Mount]What=bpffsWhere=/sys/fs/bpfType=bpfOptions=rw,nosuid,nodev,noexec,relatime,mode=700[Install]WantedBy=multi-user.targetEOFsystemctl enable sys-fs-bpf.mountsystemctl restart sys-fs-bpf.mount#### 鉴于安装cilium在网上有非常多的教程,但是又没有一个完全或是具体的说明,加上版本的差异,造成挪过来以出现不可用的情况,加上CIlium又处于一个快速发展的阶段,所以,我们建议安装相关的手册以官网为主,其他网站内容为辅的手段进行学习。# 文档使用方式介绍:https://docs.cilium.io/en/v1.10/ ---> https://docs.cilium.io/en/v1.10/gettingstarted/#gs-install ---> https://docs.cilium.io/en/v1.10/gettingstarted/k8s-install-advanced/ ---> https://docs.cilium.io/en/v1.10/gettingstarted/k8s-install-kubeadm/ ---> https://docs.cilium.io/en/v1.10/gettingstarted/kubeproxy-free/#kubeproxy-free # 到这里我们就正式找到cilium安装过程without kube-proxy的guide。# 1. Note。版本说明:Cilium’s kube-proxy replacement depends on the Host-Reachable Services feature, therefore a v4.19.57, v5.1.16, v5.2.0 or more recent Linux kernel is required. Linux kernels v5.3 and v5.8 add additional features that Cilium can use to further optimize the kube-proxy replacement implementation.Note that v5.0.y kernels do not have the fix required to run the kube-proxy replacement since at this point in time the v5.0.y stable kernel is end-of-life (EOL) and not maintained anymore on kernel.org. For individual distribution maintained kernels, the situation could differ. Therefore, please check with your distribution.[root@k8s-1 ~]# uname -a # 我们此时推荐使用的Linux kernel versionLinux k8s-1 5.11.10-1.el7.elrepo.x86_64 #1 SMP Thu Mar 25 09:56:28 EDT 2021 x86_64 x86_64 x86_64 GNU/Linux# 2. Quick Start:# 2.1: kubeadm init --skip-phases=addon/kube-proxy ## 使用kubeadm安装kubernetes cluster的时候,skip kube-proxy 的 addons。# 2.2:如果系统中已经有了kube-proxy,如何处理:For existing installations with kube-proxy running as a DaemonSet, remove it by using the following commands below. Careful: Be aware that this will break existing service connections. It will also stop service related traffic until the Cilium replacement has been installed:$ kubectl -n kube-system delete ds kube-proxy$ # Delete the configmap as well to avoid kube-proxy being reinstalled during a kubeadm upgrade (works only for K8s 1.19 and newer)$ kubectl -n kube-system delete cm kube-proxy$ # Run on each node:$ iptables-restore <(iptables-save | grep -v KUBE)# 3. 使用HELM安装Cilium:[此时使用HELM 3]添加 Cilium的repo:helm repo add cilium https://helm.cilium.io/# 4.使用helm安装cilium:generate the required YAML files and deploy them:这里官网建议我们直接使用helm 去install cilium,我们这里建议使用helm template去生成相应的helm template,这样可以修改其中的部分字段。(当然这些需要修改的字段我们也可以在helm install的 时候特殊指定。不过通常我们还是习惯使用helm template生成template,然后再修改相应的字段,然后再使用kubectl apply -f cilium-xx.yaml)# helm template cilium cilium/cilium --version 1.10 --namespace kube-system --set kubeProxyReplacement=strict --set k8sServiceHost=192.168.2.21 --set k8sServicePort=6443# 5.由于我们这里是使用Native Routeing的方案,所以,我们需要做必要的修改:https://docs.cilium.io/en/v1.10/concepts/networking/routing/ # 参考这里Native Routing模块。# Disadvantages of the model #目前看来Cilium中认为使用Tunnel的弊端只有这里。# MTU OverheadDue to adding encapsulation headers, the effective MTU available for payload is lower than with native-routing (50 bytes per network packet for VXLAN). This results in a lower maximum throughput rate for a particular network connection. This can be largely mitigated by enabling jumbo frames (50 bytes of overhead for each 1500 bytes vs 50 bytes of overhead for each 9000 bytes). # 使用巨型帧:9000-50 来解决这个tunnel模式的mtu的overhead的问题。# 6.Native Routing:The native routing datapath is enabled with tunnel: disabled and enables the native packet forwarding mode. The native packet forwarding mode leverages the routing capabilities of the network Cilium runs on instead of performing encapsulation.# Cilium automatically enables IP forwarding in the Linux kernel when native routing is configured.In order to run the native routing mode, the network connecting the hosts on which Cilium is running on must be capable of forwarding IP traffic using addresses given to pods or other workloads.The Linux kernel on the node must be aware on how to forward packets of pods or other workloads of all nodes running Cilium. This can be achieved in two ways:The node itself does not know how to route all pod IPs but a router exists on the network that knows how to reach all other pods. In this scenario, the Linux node is configured to contain a default route to point to such a router. This model is used for cloud provider network integration. See Google Cloud, AWS ENI, and Azure IPAM for more details.Each individual node is made aware of all pod IPs of all other nodes and routes are inserted into the Linux kernel routing table to represent this. If all nodes share a single L2 network, then this can be taken care of by enabling the option auto-direct-node-routes: true. Otherwise, an additional system component such as a BGP daemon must be run to distribute the routes. See the guide Using kube-router to run BGP on how to achieve this using the kube-router project.ConfigurationThe following configuration options must be set to run the datapath in native routing mode:tunnel: disabled: Enable native routing mode.native-routing-cidr: x.x.x.x/y: Set the CIDR in which native routing can be performed.The following configuration options must be set to run the datapath in native routing mode:1.tunnel: disabled: Enable native routing mode.# tunnel: disabled2.native-routing-cidr: x.x.x.x/y: Set the CIDR in which native routing can be performed.# native-routing-cidr: "10.0.0.0/16"# If all nodes share a single L2 network, then this can be taken care of by enabling the option auto-direct-node-routes: true. Otherwise, an additional system component such as a BGP daemon must be run to distribute the routes. See the guide Using kube-router to run BGP on how to achieve this using the kube-router project.3.# 开启auto-direct-node-routes:true root@k8s-1:/home/cilium# cilium-agent -h| grep auto-direct-node-routes --auto-direct-node-routes Enable automatic L2 routing between nodes4.# enable-endpoint-routes:false # 设置为flaseroot@k8s-1:/home/cilium# cilium-agent -h| grep enable-endpoint-routes --enable-endpoint-routes Use per endpoint routes instead of routing via cilium_host# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— #[root@k8s-1 ~]# kubectl get pods -o wide -ANAMESPACE NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATESdefault cni-bd8jc 1/1 Running 0 24h 10.0.1.20 k8s-2 <none> <none>default cni-vdb9g 1/1 Running 0 24h 10.0.0.235 k8s-1 <none> <none>kube-system cilium-h5bhb 1/1 Running 0 24h 192.168.2.21 k8s-1 <none> <none>kube-system cilium-kmjjr 1/1 Running 0 24h 192.168.2.22 k8s-2 <none> <none>kube-system cilium-operator-6c8777f4fc-cg7jr 1/1 Running 0 24h 192.168.2.21 k8s-1 <none> <none>kube-system cilium-operator-6c8777f4fc-z8hhx 1/1 Running 0 24h 192.168.2.22 k8s-2 <none> <none>kube-system coredns-7f89b7bc75-kx96m 1/1 Running 0 4d1h 10.0.0.13 k8s-1 <none> <none>kube-system coredns-7f89b7bc75-pm9hw 1/1 Running 0 4d1h 10.0.0.69 k8s-1 <none> <none>kube-system etcd-k8s-1 1/1 Running 1 4d1h 192.168.2.21 k8s-1 <none> <none>kube-system kube-apiserver-k8s-1 1/1 Running 2 4d1h 192.168.2.21 k8s-1 <none> <none>kube-system kube-controller-manager-k8s-1 1/1 Running 1 4d1h 192.168.2.21 k8s-1 <none> <none>kube-system kube-scheduler-k8s-1 1/1 Running 1 4d1h 192.168.2.21 k8s-1 <none> <none>[root@k8s-1 ~]# [root@k8s-1 ~]# kubectl -nkube-system exec -it cilium-4krnr bash kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.root@k8s-1:/home/cilium# # 查询Cilium的信息:# https://docs.cilium.io/en/latest/operations/performance/tuning/#ebpf-host-routingroot@k8s-2:/home/cilium# cilium-agent -h | grep install-no-conntrack-iptables-rules --install-no-conntrack-iptables-rules Install Iptables rules to skip netfilter connection tracking on all pod traffic. This option is only effective when Cilium is running in direct routing and full KPR mode. Moreover, this option cannot be enabled when Cilium is running in a managed Kubernetes environment or in a chained CNI setup.root@k8s-1:/home/cilium# cilium statusKVStore: Ok DisabledKubernetes: Ok 1.20 (v1.20.5) [linux/amd64]Kubernetes APIs: ["cilium/v2::CiliumClusterwideNetworkPolicy", "cilium/v2::CiliumEndpoint", "cilium/v2::CiliumNetworkPolicy", "cilium/v2::CiliumNode", "core/v1::Namespace", "core/v1::Node", "core/v1::Pods", "core/v1::Service", "discovery/v1beta1::EndpointSlice", "networking.k8s.io/v1::NetworkPolicy"]KubeProxyReplacement: Strict [ens33 192.168.2.21 (Direct Routing)]Cilium: Ok 1.10.3 (v1.10.3-4145278)NodeMonitor: Listening for events on 128 CPUs with 64x4096 of shared memoryCilium health daemon: Ok IPAM: IPv4: 4/254 allocated from 10.0.0.0/24, BandwidthManager: DisabledHost Routing: BPF # Enhance Feature # https://docs.cilium.io/en/latest/operations/performance/tuning/#ebpf-host-routing# Host Routing: BPF # https://cilium.io/blog/2021/05/11/cni-benchmark#breaking-the-rules-ebpf-host-routingMasquerading: BPF [ens33] 10.0.0.0/24 [IPv4: Enabled, IPv6: Disabled]Controller Status: 30/30 healthyProxy Status: OK, ip 10.0.0.156, 0 redirects active on ports 10000-20000Hubble: Ok Current/Max Flows: 4095/4095 (100.00%), Flows/s: 8.40 Metrics: DisabledEncryption: DisabledCluster health: 2/2 reachable (2021-08-31T12:54:01Z)root@k8s-1:/home/cilium# #3.下载Cilium 二进制文件:wget https://github.com/cilium/cilium-cli/releases/download/v0.8.6/cilium-linux-amd64.tar.gz

Cilium Native Routing
HOST-Routing-[BPF]

# https://cilium.io/blog/2021/05/11/cni-benchmarkeBPF host-routing allows to bypass all of the iptables and upper stack overhead in the host namespace as well as some of the context-switching overhead when traversing through the Virtual Ethernet pairs. # Ingress: Network packets are picked up as early as possible from the network device facing the network and delivered directly into the network namespace of the Kubernetes Pod.# Egress: On the egress side, the packet still traverses the veth pair, is picked up by eBPF and delivered directly to the external facing network interface. The routing table is consulted directly from eBPF so this optimization is entirely transparent and compatible with any other services running on the system providing route distribution. For information on how to enable this feature, see eBPF Host-Routing in the tuning guide.Calico eBPF is applying some of the same bypasses to iptables but as we'll learn later on, is not quite identical. However, it proves that the most impact can by made by bypassing slow kernel subsystems such as iptables.
Requirements on the network
# 参考官网:# https://docs.cilium.io/en/v1.10/concepts/networking/routing/In order to run the native routing mode, the network connecting the hosts on which Cilium is running on must be capable of forwarding IP traffic using addresses given to pods or other workloads.The Linux kernel on the node must be aware on how to forward packets of pods or other workloads of all nodes running Cilium. This can be achieved in two ways:The node itself does not know how to route all pod IPs but a router exists on the network that knows how to reach all other pods. In this scenario, the Linux node is configured to contain a default route to point to such a router. This model is used for cloud provider network integration. See Google Cloud, AWS ENI, and Azure IPAM for more details.Each individual node is made aware of all pod IPs of all other nodes and routes are inserted into the Linux kernel routing table to represent this. If all nodes share a single L2 network, then this can be taken care of by enabling the option auto-direct-node-routes: true. Otherwise, an additional system component such as a BGP daemon must be run to distribute the routes. See the guide Using kube-router to run BGP on how to achieve this using the kube-router project.ConfigurationThe following configuration options must be set to run the datapath in native routing mode:# 1.tunnel: disabled: Enable native routing mode.# 2.native-routing-cidr: x.x.x.x/y: Set the CIDR in which native routing can be performed.# 3.If all nodes share a single L2 network, then this can be taken care of by enabling the option auto-direct-node-routes: true
同节点Pod之间通信
# env 描述:[root@k8s-2 ~]# kubectl get pods -o wide | grep k8s-2cc 1/1 Running 0 16m 10.0.1.211 k8s-2 <none> <none>cni-dq6rz 1/1 Running 0 17m 10.0.1.73 k8s-2 <none> <none>[root@k8s-2 ~]# 在 5.10 内核以后,Cilium 新增了 eBPF Host-Routing 功能,该功能更加速了 eBPF 数据面性能,新增了 bpf_redirect_peer 和 bpf_redirect_neigh 两个 redirect 方式,bpf_redirect_peer 可以理解成 bpf_redirect 的升级版,其将数据包直接送到 veth pair Pod 里面接口 eth0 上,而不经过宿主机的 lxc 接口,这样实现的好处是少进入一次 cpu backlog queue 队列,该特性引入后,路由模式下,Pod -> Pod 性能接近 Node -> Node 性能,同时 Cilium 数据面路径发生了较大的变化。# https://www.infoq.cn/article/p9vg2g9t49kpvhrckfwu1. 除了 host->Pod 外,所有路径都是经过接口跳着走的,最大变化是不再经过 Kernel 转发处理,也意味着来回流量路径不再经过 kernel 的 Netfilter 框架,kernel tc 等模块,大大提升了转发性能;2.redirect_peer 特性专用于 veth pair 类型接口,因为流量被直接重定向到 Pod 里面的接口,所以在宿主机 lxc 口上无法抓到进入 Pod 的流量,因 tcpdump 抓包点在 tc ingress hook 之前,所以可以抓到出 Pod 未经过 eBPF 处理的流量。我们在HOST NS中抓包:[root@k8s-2 ~]# kubectl exec -it cc -- ip a1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever10: eth0@if11: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default link/ether 16:ca:13:c3:7c:8f brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet 10.0.1.211/32 scope global eth0 valid_lft forever preferred_lft forever[root@k8s-2 ~]# kubectl exec -it cni-dq6rz -- ip a1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever8: eth0@if9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default link/ether e6:73:63:ca:dd:4c brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet 10.0.1.73/32 scope global eth0 valid_lft forever preferred_lft forever[root@k8s-2 ~]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq state UP group default qlen 1000 link/ether 00:0c:29:e2:bf:86 brd ff:ff:ff:ff:ff:ff inet 192.168.2.22/24 brd 192.168.2.255 scope global noprefixroute ens33 valid_lft forever preferred_lft forever inet6 fe80::a9cd:74a4:47fc:9fec/64 scope link noprefixroute valid_lft forever preferred_lft forever3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default link/ether 02:42:75:f5:10:87 brd ff:ff:ff:ff:ff:ff inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0 valid_lft forever preferred_lft forever4: cilium_net@cilium_host: <BROADCAST,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link/ether b2:6e:6f:c8:53:fc brd ff:ff:ff:ff:ff:ff inet6 fe80::b06e:6fff:fec8:53fc/64 scope link valid_lft forever preferred_lft forever5: cilium_host@cilium_net: <BROADCAST,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link/ether 52:9b:a0:7a:60:f9 brd ff:ff:ff:ff:ff:ff inet 10.0.1.123/32 scope link cilium_host valid_lft forever preferred_lft forever inet6 fe80::509b:a0ff:fe7a:60f9/64 scope link valid_lft forever preferred_lft forever7: lxc_health@if6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link/ether f2:bf:2f:84:81:fb brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet6 fe80::f0bf:2fff:fe84:81fb/64 scope link valid_lft forever preferred_lft forever9: lxc59b348afd5c1@if8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link/ether c2:63:ff:dd:de:bc brd ff:ff:ff:ff:ff:ff link-netnsid 1 inet6 fe80::c063:ffff:fedd:debc/64 scope link valid_lft forever preferred_lft forever11: lxc23801e340e9a@if10: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link/ether 1a:1a:f0:a8:a5:bf brd ff:ff:ff:ff:ff:ff link-netnsid 2 inet6 fe80::181a:f0ff:fea8:a5bf/64 scope link valid_lft forever preferred_lft forever[root@k8s-2 ~]# [root@k8s-2 ~]# kubectl exec -ti cc -- ping 10.0.1.73PING 10.0.1.73 (10.0.1.73): 56 data bytes64 bytes from 10.0.1.73: seq=0 ttl=63 time=0.123 ms^C--- 10.0.1.73 ping statistics ---1 packets transmitted, 1 packets received, 0% packet lossround-trip min/avg/max = 0.123/0.123/0.123 ms[root@k8s-2 ~]# 抓包结果:[root@k8s-2 ~]# tcpdump -ne -i lxc23801e340e9a tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on lxc23801e340e9a, link-type EN10MB (Ethernet), capture size 262144 bytes22:16:16.371807 16:ca:13:c3:7c:8f > 1a:1a:f0:a8:a5:bf, ethertype IPv4 (0x0800), length 98: 10.0.1.211 > 10.0.1.73: ICMP echo request, id 19968, seq 0, length 6422:16:21.607147 16:ca:13:c3:7c:8f > 1a:1a:f0:a8:a5:bf, ethertype ARP (0x0806), length 42: Request who-has 10.0.1.123 tell 10.0.1.211, length 2822:16:21.607205 1a:1a:f0:a8:a5:bf > 16:ca:13:c3:7c:8f, ethertype ARP (0x0806), length 42: Reply 10.0.1.123 is-at 1a:1a:f0:a8:a5:bf, length 28^C3 packets captured3 packets received by filter0 packets dropped by kernel[root@k8s-2 ~]# tcpdump -ne -i lxc59b348afd5c1tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on lxc59b348afd5c1, link-type EN10MB (Ethernet), capture size 262144 bytes22:16:16.371876 e6:73:63:ca:dd:4c > c2:63:ff:dd:de:bc, ethertype IPv4 (0x0800), length 98: 10.0.1.73 > 10.0.1.211: ICMP echo reply, id 19968, seq 0, length 6422:16:21.607134 e6:73:63:ca:dd:4c > c2:63:ff:dd:de:bc, ethertype ARP (0x0806), length 42: Request who-has 10.0.1.123 tell 10.0.1.73, length 2822:16:21.607181 c2:63:ff:dd:de:bc > e6:73:63:ca:dd:4c, ethertype ARP (0x0806), length 42: Reply 10.0.1.123 is-at c2:63:ff:dd:de:bc, length 28# 2.redirect_peer 特性专用于 veth pair 类型接口,因为流量被直接重定向到 Pod 里面的接口,所以在宿主机 lxc 口上无法抓到进入 Pod 的流量,因 tcpdump 抓包点在 tc ingress hook 之前,所以可以抓到出 Pod 未经过 eBPF 处理的流量。# 解释一下这句话所要表达的内容:什么叫做:只能抓到出去的包,而不能抓不到进来的包:tcpdump hook 要比 TC的hook更加靠前一些。就以 10.0.1.211所在Pod为例举例说明:10.0.1.211 对应的eth0@if11 的 if11 形成的veth pair lxc23801e340e9a@if10 此时在lxc23801e340e9a上抓包:可以看到:# 1. 从10.0.1.211 的pod去ping 10.0.1.73[root@k8s-2 ~]# kubectl exec -ti cc -- ping 10.0.1.73PING 10.0.1.73 (10.0.1.73): 56 data bytes64 bytes from 10.0.1.73: seq=0 ttl=63 time=0.123 ms[root@k8s-2 ~]# tcpdump -ne -i lxc23801e340e9a tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on lxc23801e340e9a, link-type EN10MB (Ethernet), capture size 262144 bytes22:16:16.371807 16:ca:13:c3:7c:8f > 1a:1a:f0:a8:a5:bf, ethertype IPv4 (0x0800), length 98: 10.0.1.211 > 10.0.1.73: ICMP echo request, id 19968, seq 0, length 64此时可以看到只有从pod 10.0.1.211 上出来的ICMP Request的数据包,而没有ICMP的Replay。此时:# redirect_peer 特性专用于 veth pair 类型接口,因为流量被直接重定向到 Pod 里面的接口,所以在宿主机 lxc 口上无法抓到进入 Pod 的流量,因 tcpdump 抓包点在 tc ingress hook 之前,所以可以抓到出 Pod 未经过 eBPF 处理的流量。这里需要明确的是:需要弄清楚这个,tcpdump和tc生效的位置。这个对于理解次模型非常重要!!!

跨节点通信
from-container BPF 程序分析
# env:^C[root@k8s-1 ~]# kubectl get pods -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATEScni-2hmps 1/1 Running 0 29s 10.0.0.4 k8s-1 <none> <none>cni-hm9m7 1/1 Running 0 29s 10.0.1.64 k8s-2 <none> <none>[root@k8s-1 ~]# [root@k8s-1 ~]# [root@k8s-1 ~]# [root@k8s-1 ~]# kubectl exec -it cni-2hmps -- ping 10.0.1.64 PING 10.0.1.64 (10.0.1.64): 56 data bytes64 bytes from 10.0.1.64: seq=0 ttl=62 time=0.681 ms64 bytes from 10.0.1.64: seq=1 ttl=62 time=0.594 ms^C--- 10.0.1.64 ping statistics ---2 packets transmitted, 2 packets received, 0% packet lossround-trip min/avg/max = 0.594/0.637/0.681 ms[root@k8s-1 ~]# 在HOST NS中查看veth pair的tc信息:[root@k8s-2 ~]# tc filter show dev lxc23801e340e9a ingressfilter protocol all pref 1 bpf chain 0 filter protocol all pref 1 bpf chain 0 handle 0x1 bpf_lxc.o:[from-container] direct-action not_in_hw tag e6d16ab039dd3408 [root@k8s-2 ~]# tc filter show dev lxc59b348afd5c1 ingressfilter protocol all pref 1 bpf chain 0 filter protocol all pref 1 bpf chain 0 handle 0x1 bpf_lxc.o:[from-container] direct-action not_in_hw tag c8417a60698f6d32 [root@k8s-2 ~]# ##1.0##################### # 1.BPF 代码都在 Cilium 源代码的 bpf/ 目录中。为避免本文过长,将只贴出核心调用栈。大致调用栈如下:__section("from-container")handle_xgress // bpf/bpf_lxc.c |-validate_ethertype(skb, &proto) |-switch (proto) { case ETH_P_IP: tail_handle_ipv4 // bpf/bpf_lxc.c |-handle_ipv4_from_lxc // bpf/bpf_lxc.c |-if dst is k8s Service | lb4_local() | |-ct_create4 | |-lb4_lookup_backend | |-lb4_xlate | |-policy_can_egress4() | |-if tunnel | encap vxlan | else // direct routing, pass to kernel stack (continue normal routing) | ipv4_l3() // dec TTL, set src/dst MAC | asm_set_seclabel_identity(skb); // set identity to skb |-return TC_ACT_OK; }所做的事情:1.对包进行验证,并提取出 L3 proto(协议类型)。2.如果 L3 proto 是 IPv4,调用 tail_handle_ipv4() 进行处理。3.tail_handle_ipv4() 进一步调用 handle_ipv4_from_lxc(),后者完成: 3.1:Service 负载均衡,即从 Service 的后端 Pod 中选择一个合适的,这里假设选择 NODE2 上的 POD4。 3.2:创建或更新连接跟踪(CT)记录。 3.3:执行 DNAT,将包的 dst_ip 由 ServiceIP 改成 POD4_IP。 3.4:进行容器出向(egress)安全策略验证,这里假设没有安全策略,因此能通过验证。 3.5:对包进行封装,或者通过主机进行路由,本文只看直接路由的情况。在送回协议栈之前,调用 ipv4_l3() 设置 TTL、MAC 地址等:intipv4_l3(struct __ctx_buff *ctx, int l3_off, __u8 *smac, __u8 *dmac, struct iphdr *ip4){ ipv4_dec_ttl(ctx, l3_off, ip4)); if (smac) eth_store_saddr(ctx, smac, 0); eth_store_daddr(ctx, dmac, 0); return CTX_ACT_OK;}以上假设都成立的情况下,BPF 程序最后返回 TC_ACK_OK,这个包就进入内核协议 栈继续处理了。##1.0##################### ##2.0##################### 此时数据包进入HOST NS中:eBPF host-routing allows to bypass all of the iptables and upper stack overhead in the host namespace as well as some of the context-switching overhead when traversing through the Virtual Ethernet pairs. Network packets are picked up as early as possible from the network device facing the network and delivered directly into the network namespace of the Kubernetes Pod. On the egress side, the packet still traverses the veth pair, is picked up by eBPF and delivered directly to the external facing network interface. The routing table is consulted directly from eBPF so this optimization is entirely transparent and compatible with any other services running on the system providing route distribution. For information on how to enable this feature, see eBPF Host-Routing in the tuning guide.此时查询HOST NS中的路由表
HOST NS 路由查询[报文出节点[k8s-1]方向]
# env:[root@k8s-1 ~]# kubectl get pods -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATEScni-bhq9h 1/1 Running 0 60m 10.0.0.53 k8s-1 <none> <none>cni-dq6rz 1/1 Running 0 60m 10.0.1.73 k8s-2 <none> <none>[root@k8s-1 ~]# [root@k8s-1 ~]# route -n Kernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 192.168.2.1 0.0.0.0 UG 100 0 0 ens3310.0.0.0 10.0.0.76 255.255.255.0 UG 0 0 0 cilium_host10.0.0.76 0.0.0.0 255.255.255.255 UH 0 0 0 cilium_host10.0.1.0 192.168.2.22 255.255.255.0 UG 0 0 0 ens33 # 匹配到此条目172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0192.168.2.0 0.0.0.0 255.255.255.0 U 100 0 0 ens33[root@k8s-1 ~]# # 查看ens33的tc 信息:[root@k8s-1 ~]# tc filter show dev ens33 egressfilter protocol all pref 1 bpf chain 0 filter protocol all pref 1 bpf chain 0 handle 0x1 bpf_netdev_ens33.o:[to-netdev] direct-action not_in_hw tag 776e35350adbd7a0 [root@k8s-1 ~]# # to-netdev BPF 程序分析调用栈如下,__section("to-netdev")to_netdev |-policy_clear_mark |-src_id = resolve_srcid_ipv4 | |-lookup_ip4_remote_endpoint | |-ipcache_lookup4 |-ipv4_host_policy_egress(src_id) |-policy_can_egress4 |-ret = ct_lookup4() |-switch (ret) { case CT_NEW : ct_create4(); break; case CT_ESTABLISHED: case CT_RELATED : case CT_REPLY : break; default : ret = DROP; break; } return ret;粗略地说,对于我们这个 case,这段 BPF 其实并不会做什么实际的事情,程序最后返回 TC_ACK_OK 放行。
报文进入另外一个节点[k8s-2]
// kernel source tree, 5.11ixgbe_poll |-ixgbe_clean_rx_irq |-if support XDP offload | skb = ixgbe_run_xdp() |-skb = ixgbe_construct_skb() |-ixgbe_rx_skb |-napi_gro_receive |-napi_skb_finish(dev_gro_receive(skb)) |-netif_receive_skb_internal |-if generic XDP | |-if do_xdp_generic() != XDP_PASS | return NET_RX_DROP |-__netif_receive_skb(skb) |-__netif_receive_skb_one_core |-__netif_receive_skb_core(&pt_prev) |-for tap in taps: | deliver_skb |-sch_handle_ingress // net/core/dev.c |-tcf_classify // net/sched/cls_api.c |-for tp in tps: tp->classify |-cls_bpf_classify // net/sched/cls_bpf.c大致过程:1.网卡收包如果网卡支持 XDP offload,并且有 XDP 程序,就会执行 XDP 程序。我们这里没有启 用 XDP。2.创建 skb。3.GRO,对分片的包进行重组。Generic XDP 处理:如果网卡不支持 XDP offload,那 XDP 程序会从 step 2 延后到这里执行。4.Tap 处理(此处没有)。TC ingress 处理,支持包括 BPF 在内的 TC 程序。其中的 sch_handle_ingress() 会进入 TC ingress hook 执行处理。查看加载的 BPF 程序查看 ingress 方向加载的 BPF:[root@k8s-2 ~]# tc filter show dev ens33 ingressfilter protocol all pref 1 bpf chain 0 filter protocol all pref 1 bpf chain 0 handle 0x1 bpf_netdev_ens33.o:[from-netdev] direct-action not_in_hw tag 697bc2349ac2ea82 [root@k8s-2 ~]# from-netdev BPF 程序分析调用栈:__section("from-netdev")from_netdev |-handle_netdev |-validate_ethertype |-do_netdev |-identity = resolve_srcid_ipv4() // 从 ctx 中提取 src identity |-ctx_store_meta(CB_SRC_IDENTITY, identity) // 将 identity 存储到 ctx->cb[CB_SRC_IDENTITY] |-ep_tail_call(ctx, CILIUM_CALL_IPV4_FROM_LXC) // 尾调用到 endpoint BPF | |------------------------------ |__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_IPV4_FROM_LXC)tail_handle_ipv4_from_netdev |-tail_handle_ipv4 |-handle_ipv4 |-ep = lookup_ip4_endpoint() |-ipv4_local_delivery(ctx, ep) |-tail_call_dynamic(ctx, &POLICY_CALL_MAP, ep->lxc_id);主要逻辑:1.调用 handle_netdev() 处理将从宿主机进入 Cilium 管理的网络的流量,具体事情:1.1解析这个包所属的 identity(Cilium 依赖 identity 做安全策略),并存储到包的结构体中。 对于 direct routing 模式,从 ipcache 中根据 IP 查询 identity。 对于 tunnel 模式,直接从 VxLAN 头中携带过来了。1.2尾调用到 tail_handle_ipv4_from_netdev()。2.tail_handle_ipv4_from_netdev() 进一步调用 tail_handle_ipv4(),后者再调用 handle_ipv4()。handle_ipv4() 做的事情:2.1查找 dst_ip 对应的 endpoint(即 对端节点的POD)。2.2调用 ipv4_local_delivery() 执行处理,这个函数会根据 endpoint id 直接尾调用到 endpoint (对端节点的POD) 的 BPF 程序。 ## 所以lxc0xxxx 就没有egress的filter。# to-container BPF 程序分析这次尾调用到达的是 to-container BPF 程序。调用栈:__section("to-container")handle_to_container // bpf/bpf_lxc.c |-inherit_identity_from_host(skb, &identity) // -> bpf/lib/identity.h |-tail_ipv4_to_endpoint // bpf/bpf_lxc.c |-ipv4_policy // bpf/bpf_lxc.c |-policy_can_access_ingress // bpf/lib/policy.h |-__policy_can_access // bpf/lib/policy.h |-if p = map_lookup_elem(l3l4_key); p // L3+L4 policy | return TC_ACK_OK |-if p = map_lookup_elem(l4only_key); p // L4-Only policy | return TC_ACK_OK |-if p = map_lookup_elem(l3only_key); p // L3-Only policy | return TC_ACK_OK |-if p = map_lookup_elem(allowall_key); p // Allow-all policy | return TC_ACK_OK |-return DROP_POLICY; // DROP所做的事情也很清楚:提取包的 src identity 信息,这个信息此时已经在包的元数据里面了。调用 tail_ipv4_to_endpoint(),这个函数会进一步调用 ipv4_policy() 执行 容器入向(ingress)安全策略检查。如果包没有被策略拒绝,就会被转发到 lxc00dd 的对端,即 POD的网卡 eth0。
HOST-Routing