首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >扩展 Kubernetes 之 CNI

扩展 Kubernetes 之 CNI

原创
作者头像
王磊-字节跳动
修改2020-10-20 00:50:33
2.9K1
修改2020-10-20 00:50:33
举报
文章被收录于专栏:01ZOO01ZOO

> 扩展 kubernetes 分为三种模式 webhook,binary 二进制,controller

简介

CNI 是什么

  • CNI: Container Network Interface 定义的是 将 container 插入 network, 和 将 container 从 network 移除的操作
  • CNI Plugin: 实现了 CNI 的二进制程序, 区别于 runtime, 调用方式为 runtime 调用 CNI plugin
  • Container = Linux network namespace, 可能是一个 pod 即多个 container 对应了一个 network namespace
  • Network 指 a group of entities that are uniquely addressable that can communicate amongst each other, Containers 可以加到一个或者多个 network 里

CNI Plugin 处于什么位置

image
image

CNI/CNI Plugins

CNI 项目包括两个部分

  1. The CNI specification documents 即 上面说的 CNI 的部分
    • libcni, 实现 CNI runtime 的 SDK,比如 kubernetes 里面的 NetworkPlugin 部分就使用了 libcni 来调用 CNI plugins. 这里面也有一些 interface,容易混淆,这个 interface 是对于 runtime 而言的,并不是对 plugin 的约束,比如 AddNetworkList, runtime 调用这个方法后,会按顺序执行对应 plugin 的 add 命令.
    • 值得一提的是 libcni 里面的 config caching:解决的是如果 ADD 之后配置变化了,如何 DEL 的问题.
    • skel provides skeleton code for a CNI plugin, 实现 CNI plugin 的骨架代码
    • cnitool 一个小工具,可以模拟 runtime 执行比如 libcni 的 AddNetworkList,触发执行 cni plugins
    • github.com/containernetworking/cni
  2. A set of reference and example plugins 即 CNI Plugin 的部分
    • Interface plugins: ptp, bridge, macvlan,...
    • "Chained" plugins: portmap, bandwidth, tuning
    • github.com/containernetworking/plugins

CNI Plugin 对 runtime 的假设

  1. Container runtime 先为 container 创建 network 再调用 plugins.
  2. Container runtime 决定 container 属于哪个网络,继而决定执行哪个 CNI plugin.
  3. Network configuration 为 JSON 格式,包含一些必选可选参数.
  4. 创建时 container runtime 串行添加 container 到各个 network (ADD).
  5. 销毁时 container runtime 逆序将 container 从各个 network 移除 (DEL).
  6. 单个 container 的 ADD/DEL 操作串行,但是多个 container 之间可以并发.
  7. ADD 之后必有 DEL,多次 DEL 操作幂等.
  8. ADD 操作不会执行两次(对于同样的 KEY-network name, CNI_CONTAINERID, CNI_IFNAME

CNI 的执行流程

  1. 基本操作: ADD, DEL, CHECK and VERSION
  2. Plugins 是二进制,当需要 network 操作时,runtime 执行二进制对应 命令
  3. 通过 stdin 向 plugin 输入 JSON 格式的配置文件,以及其他 container 相关的信息 比如:
    • ADD 操作的参数有 Container ID, Network namespace path, Network configuration, Extra arguments, Name of the interface inside the container, 返回 Interfaces list, IP configuration assigned to each interface, DNS information
    • DEL/CHECK 操作的参数 基本相同,具体参考 SPEC
  4. 通过 stdout 返回结果

输出参数示例

{
  "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)
  }
}

Network Configuration

Network Configuration 是 CNI 输入参数中最重要当部分, 可以存储在磁盘上

Network Configuration 示例

// ------------------------------------
{
  "cniVersion": "0.4.0",
  "name": "dbnet",
  "type": "bridge",
  // type (plugin) specific
  "bridge": "cni0",
  "ipam": {
    "type": "host-local",
    // ipam specific
    "subnet": "10.1.0.0/16",
    "gateway": "10.1.0.1"
  },
  "dns": {
    "nameservers": [ "10.1.0.1" ]
  }
}

// ------------------------------------
{
  "cniVersion": "0.4.0",
  "name": "pci",
  "type": "ovs",
  // type (plugin) specific
  "bridge": "ovs0",
  "vxlanID": 42,
  "ipam": {
    "type": "dhcp",
    "routes": [ { "dst": "10.3.0.0/16" }, { "dst": "10.4.0.0/16" } ]
  },
  // args may be ignored by plugins
  "args": {
    "labels" : {
        "appVersion" : "1.0"
    }
  }
}

IPAM plugin

  • IPAM (IP Address Management) plugin 作为 CNI plugin 的一部分存在
  • 之所以设计成两部分是因为 Ip 分配的逻辑 在很多 CNI plugin 之间可以复用
  • CNI plugin 负责调用 IPAM plugin
  • IPAM plugin 完成确定 ip/subnet/gateway/route 的操作,然后返回给 main plugin
  • IPAM plugin 可能通过例如 dhcp 协议分配 ip,并在本地存储相关信息
  • IPAM plugin 和 CNI plugin 输入参数相同,返回参数见下面的示例
{
  "cniVersion": "0.4.0",
  "ips": [
      {
          "version": "<4-or-6>",
          "address": "<ip-and-prefix-in-CIDR>",
          "gateway": "<ip-address-of-the-gateway>"  (optional)
      },
      ...
  ],
  "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-search-domains>              (optional)
    "options": <list-of-options>                    (optional)
  }
}

CNI plugins

plugins 项目中有几个 cni team 维护的常用 plugin, 并且进行了分类 (尽管 main plugin 可能会调用其他 plugin, 但是对于实现来讲,几种 plugin 的对外接口并无区别):

  • Main: bridge, loopback, vlan, macvlan, ipvlan, host-device, ptp, Windows bridge, Windows overlay
  • IPAM: host-local, DHCP, static
  • Meta: bandwidth, firewall, flannel, portmap, source-based routing, tuning

常见 CNI plugins

IPAM host-local

  • host-local 的应用范围很广: kubenet、bridge、ptp、ipvlan 等 cni 插件的 IPAM 部分常配置成由 host-local 进行处理, 比如下面这个配置.
root@VM-4-10-ubuntu:/etc/cni/net.d/multus# cat bridge.conf
{
  "cniVersion": "0.1.0",
  "name": "bridge",
  "type": "bridge",
  "bridge": "cbr0",
  "mtu": 1500,
  "addIf": "eth0",
  "isGateway": true,
  "forceAddress": true,
  "ipMasq": false,
  "hairpinMode": false,
  "promiscMode": true,
  "ipam": {
    "type": "host-local",
    "subnet": "10.4.10.0/24",
    "gateway": "10.4.10.1",
    "routes": [
      { "dst": "0.0.0.0/0" }
    ]
  }
}
  • host-local 在本地完成对 subnet 中的 ip 的分配, 这里值得注意的是: subnet = node 的 podcidr, 这在 node_ipam_controller 中完成, 原始分配的范围来自 ControllerManager 的配置; 即 常见的 IP 分配流程如下图:
graph TD
ControllerManager配置subnet --> NodeSpec中生成子subnet 
NodeSpec中生成子subnet --> CNIAgent在各个node上生成配置文件,写入子subnet 
CNIAgent在各个node上生成配置文件,写入子subnet --> CNIplugin在子subnet中分配Ip

MAIN bridge

brige模式,即网桥模式。在node上创建一个linux bridge,并通过 vethpair 的方式在容器中设置网卡和 IP。只要为容器配置一个二层可达的网关:比如给网桥配置IP,并设置为容器ip的网关。容器的网络就能建立起来。

ADD 流程:

  1. setupBridge: brdige 组件创建一个指定名字的网桥,如果网桥已经存在,就使用已有的网桥, promiscMode 打开时开启混杂模式, 这一步关心的参数为 MTU, PromiscMode, Vlan
  2. setupVeth: 在容器空间创建 vethpair,将 node 端的 veth 设备连接到网桥上
  3. 如果由 ipam 配置:从ipam获取一个给容器使用的 ip,并根据返回的数据计算出容器对应的网关
  4. 进入容器网络名字空间,修改容器中网卡名和网卡ip,以及配置路由,并进行 arp 广播(注意我们只为vethpair的容器端配置ip,node端是没有ip的)
  5. 如果IsGW=true,将网桥配置为网关,具体方法是:将第三步计算得到的网关IP配置到网桥上,同时根据需要将网桥上其他ip删除。最后开启网桥的ip_forward内核参数;
  6. 如果IPMasq=true,使用iptables增加容器私有网网段到外部网段的masquerade规则,这样容器内部访问外部网络时会进行snat,在很多情况下配置了这条路由后容器内部才能访问外网。(这里代码中会做exist检查,防止生成重复的iptables规则)
  7. 配置结束,整理当前网桥的信息,并返回给调用者

MAIN host-device

本段来自

相比前面两种cni main组件,host-device显得十分简单因为他就只会做两件事情:

  • 收到ADD命令时,host-device根据命令参数,将网卡移入到指定的网络namespace(即容器中)。
  • 收到DEL命令时,host-device根据命令参数,将网卡从指定的网络namespace移出到root namespace。

在bridge和ptp组件中,就已经有“将vethpair的一端移入到容器的网络namespace”的操作。那这个host-device不是多此一举吗?

并不是。host-device组件有其特定的使用场景。假设集群中的每个node上有多个网卡,其中一个网卡配置了node的IP。而其他网卡都是属于一个网络的,可以用来做容器的网络,我们只需要使用host-device,将其他网卡中的某一个丢到容器里面就行。

host-device模式的使用场景并不多。它的好处是:bridge、ptp 等方案中,node上所有容器的网络报文都是通过node上的一块网卡出入的,host-device方案中每个容器独占一个网卡,网络流量不会经过node的网络协议栈,隔离性更强。缺点是:在node上配置数十个网卡,可能并不好管理;另外由于不经过node上的协议栈,所以kube-proxy直接废掉。k8s集群内的负载均衡只能另寻他法了。

META portmap

meta组件通常进行一些额外的网络配置(tuning),或者二次调用(flannel)

portmap 的主要作用是修改防火墙 iptables 规则, 配置 SNAT,DNAT 和端口转发

实践

用 bash 实现一个 bridge CNI plugin

  1. 在机器上准备 cni 配置和 网桥 (这一步实践也可以在 cni plugin 中 ensure) brctl addbr cni0;ip link set cni0 up; ip addr add <bridge-ip>/24 dev cni0
  2. 安装 nmap 和 jq
  3. bash-cni 脚本,完整脚本参考自 bash-cni
#!/bin/bash -e

if [[ ${DEBUG} -gt 0 ]]; then set -x; fi

exec 3>&1 # make stdout available as fd 3 for the result
exec &>> /var/log/bash-cni-plugin.log

IP_STORE=/tmp/reserved_ips # all reserved ips will be stored there

echo "CNI command: $CNI_COMMAND" 

stdin=`cat /dev/stdin`
echo "stdin: $stdin"

# 分配 ip,从所有 ip 中选择没有 reserved 的, 同时更新到 store 的reserved ip 列表
allocate_ip(){
	for ip in "${all_ips[@]}"
	do
		reserved=false
		for reserved_ip in "${reserved_ips[@]}"
		do
			if [ "$ip" = "$reserved_ip" ]; then
				reserved=true
				break
			fi
		done
		if [ "$reserved" = false ] ; then
			echo "$ip" >> $IP_STORE
			echo "$ip"
			return
		fi
	done
}

# 实现 cni plugin 的4个命令
case $CNI_COMMAND in
ADD)
	network=$(echo "$stdin" | jq -r ".network") # network 配置
	subnet=$(echo "$stdin" | jq -r ".subnet")   # 子网配置
	subnet_mask_size=$(echo $subnet | awk -F  "/" '{print $2}') 

	all_ips=$(nmap -sL $subnet | grep "Nmap scan report" | awk '{print $NF}') # 所有ip
	all_ips=(${all_ips[@]})
	skip_ip=${all_ips[0]}
	gw_ip=${all_ips[1]}
	reserved_ips=$(cat $IP_STORE 2> /dev/null || printf "$skip_ip\n$gw_ip\n") # reserving 10.244.0.0 and 10.244.0.1 预留 ip
	reserved_ips=(${reserved_ips[@]})
	printf '%s\n' "${reserved_ips[@]}" > $IP_STORE # 预留 ip 存储到文件
	container_ip=$(allocate_ip)
	
	# ---- 以上是 ip 分配流程

	mkdir -p /var/run/netns/
	ln -sfT $CNI_NETNS /var/run/netns/$CNI_CONTAINERID

	rand=$(tr -dc 'A-F0-9' < /dev/urandom | head -c4)
	host_if_name="veth$rand"
	ip link add $CNI_IFNAME type veth peer name $host_if_name 

	ip link set $host_if_name up 
	ip link set $host_if_name master cni0 

	ip link set $CNI_IFNAME netns $CNI_CONTAINERID
	ip netns exec $CNI_CONTAINERID ip link set $CNI_IFNAME up
	ip netns exec $CNI_CONTAINERID ip addr add $container_ip/$subnet_mask_size dev $CNI_IFNAME
	ip netns exec $CNI_CONTAINERID ip route add default via $gw_ip dev $CNI_IFNAME
	
	# ------ 以上是创建 veth, 绑定到 网桥,设置 容器端的 ip, route 的过程

	mac=$(ip netns exec $CNI_CONTAINERID ip link show eth0 | awk '/ether/ {print $2}')
echo "{
  \"cniVersion\": \"0.3.1\",
  \"interfaces\": [                                            
      {
          \"name\": \"eth0\",
          \"mac\": \"$mac\",                            
          \"sandbox\": \"$CNI_NETNS\" 
      }
  ],
  \"ips\": [
      {
          \"version\": \"4\",
          \"address\": \"$container_ip/$subnet_mask_size\",
          \"gateway\": \"$gw_ip\",          
          \"interface\": 0 
      }
  ]
}" >&3

;;

DEL)
	ip=$(ip netns exec $CNI_CONTAINERID ip addr show eth0 | awk '/inet / {print $2}' | sed  s%/.*%% || echo "")
	if [ ! -z "$ip" ]
	then
		sed -i "/$ip/d" $IP_STORE
	fi
;;

GET)
	echo "GET not supported"
	exit 1
;;

VERSION)
echo '{
  "cniVersion": "0.3.1", 
  "supportedVersions": [ "0.3.0", "0.3.1", "0.4.0" ] 
}' >&3
;;

*)
  echo "Unknown cni commandn: $CNI_COMMAND" 
  exit 1
;;

esac

使用 cni-tool 测试

$ ip netns add testing
$ CNI_PATH=/opt/cni/bin/ CNI_IFNAME=test CNI_CONTAINERID=testing cnitool add mynet /var/run/netns/testing
{
    "cniVersion": "0.3.1",
    "interfaces": [
        {
            "name": "eth0",
            "sandbox": "/var/run/netns/testing"
        }
    ],
    "ips": [
        {
            "version": "4",
            "interface": 0,
            "address": "10.244.149.16/24",
            "gateway": "10.244.149.1"
        }
    ],
    "dns": {}
}

使用 k8s yaml 测试

$ kubectl apply -f https://raw.githubusercontent.com/s-matyukevich/bash-cni-plugin/master/01_gcp/test-deployment.yml

参考

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
    • CNI 是什么
      • CNI Plugin 处于什么位置
      • CNI/CNI Plugins
        • CNI Plugin 对 runtime 的假设
          • CNI 的执行流程
            • Network Configuration
              • IPAM plugin
                • CNI plugins
                • 常见 CNI plugins
                  • IPAM host-local
                    • MAIN bridge
                      • MAIN host-device
                        • META portmap
                        • 实践
                          • 用 bash 实现一个 bridge CNI plugin
                            • 使用 cni-tool 测试
                              • 使用 k8s yaml 测试
                              • 参考
                              相关产品与服务
                              容器服务
                              腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                              领券
                              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档