前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >扩展 Kubernetes 之 CNI

扩展 Kubernetes 之 CNI

原创
作者头像
王磊-字节跳动
修改于 2020-10-19 16:50:33
修改于 2020-10-19 16:50:33
3.4K0
举报
文章被收录于专栏: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 返回结果

输出参数示例

代码语言:txt
AI代码解释
复制
{
  "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 示例

代码语言:txt
AI代码解释
复制
// ------------------------------------
{
  "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 输入参数相同,返回参数见下面的示例
代码语言:txt
AI代码解释
复制
{
  "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 进行处理, 比如下面这个配置.
代码语言:txt
AI代码解释
复制
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 分配流程如下图:
代码语言:txt
AI代码解释
复制
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
代码语言:txt
AI代码解释
复制
#!/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 测试

代码语言:txt
AI代码解释
复制
$ 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 测试

代码语言:txt
AI代码解释
复制
$ kubectl apply -f https://raw.githubusercontent.com/s-matyukevich/bash-cni-plugin/master/01_gcp/test-deployment.yml

参考

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

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

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

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
猫眼域名曾变身 融资10亿元
躲在树上的域小名
2017/12/06
5940
猫眼域名曾变身 融资10亿元
丰巢科技获20.7亿投资,其域名为fcbox.com非fengchao.com
最近,韵达股份和申通快递双双发布公告宣布增资丰巢科技,丰巢新一轮融资达20.7亿元。犹记得去年1月,丰巢还获得25亿元的融资,资本实力强大。
躲在树上的域小名
2018/01/26
1.4K0
丰巢科技获20.7亿投资,其域名为fcbox.com非fengchao.com
家具平台谷居完成2000万元融资,启用长尾双拼域名
近日,基于VR设计的家居产品直供平台谷居宣布已经完成了A轮2000万元的融资,本轮融资由零点资本领投。谷居官网域名启用长尾双拼域名guju.com.cn。
躲在树上的域小名
2018/01/25
1.1K0
双拼域名yansuan.com被木雨林收购
拼音在中国通用程度,无需过多言语解释,大家都会懂。因此拼音域名在国内市场甚是吃香,备受投资人青睐。近日,投资人木雨林在朋友圈爆料称,收购了一枚双拼域名yansuan.com。
躲在树上的域小名
2018/01/23
2.8K0
双拼域名yansuan.com被木雨林收购
五位数终端收购的域名dongxiao.cn已启用
双拼域名因其简短好记、品相佳等有点在米市可谓是很抢手的品种之一,深得一些企业的青睐。近日,一双拼域名dongxiao.cn已被东孝互联网信息技术有限公司拿去建站了。
躲在树上的域小名
2018/01/25
1.3K0
五位数终端收购的域名dongxiao.cn已启用
上千亿巨头撑腰 双拼妥妥被他拿了
拼音是中国独有的,因此拼音域名在中国占据了绝对的优势,也因此备受投资人和终端的青睐。接到米友孙小勇的爆料,他拿下一枚双拼kangmei.cn。
躲在树上的域小名
2018/01/17
5280
上千亿巨头撑腰 双拼妥妥被他拿了
滚雷进口车获5亿元投资 品牌双拼给力十足
滚雷进口车1月19日对外宣布已经获得中国远洋海运集团旗下物流基金的5亿人民币战略性投资,其官网采用品牌双拼域名。
躲在树上的域小名
2018/01/22
5430
滚雷进口车获5亿元投资 品牌双拼给力十足
xiaomao.com7位数高价成交,并已启用建站
  2017年08月,有媒体曾报道过广东百万藏书信息科技有限公司七位数高价收购域名xiaomao.com的消息。但当时该域名并未被启用,Whois信息也被隐藏,并不能完全确认。
躲在树上的域小名
2018/01/18
1.2K0
xiaomao.com7位数高价成交,并已启用建站
同程艺龙合并:在品牌域名上从未小气过!
躲在树上的域小名
2018/01/03
1.4K0
同程艺龙合并:在品牌域名上从未小气过!
趣店推“大白汽车”业务 启用域名dabaiqiche.com
成立于2014年的趣店正式推出汽车金融服务产品---大白汽车分期(下称“大白汽车”),以最低10%首付、贷款周期可达4年、审核门槛低等优势切入汽车金融业务,以汽车融资租赁为布局关键。
躲在树上的域小名
2018/01/25
8840
趣店推“大白汽车”业务 启用域名dabaiqiche.com
心有灵犀启用品牌域名 获近千万投资
躲在树上的域小名
2017/11/30
5920
海信域名亮眼 超7亿收购东芝电视
躲在树上的域小名
2017/12/06
8660
海信域名亮眼 超7亿收购东芝电视
双拼市场好!米友售出域名chuijia.com
双拼域名在域名圈内一直备受关注与青睐,近段时间米友潘星在微博爆料,已售出域名chuijia.com。
躲在树上的域小名
2018/01/17
1.8K0
双拼市场好!米友售出域名chuijia.com
双拼域名sanwa.com被重新启用建站
近期,一个双拼域名sanwa.com被启用建站,该域名曾在在2016年11月以3.15万美金(近22万元)的价格结拍,随后成功交易。
躲在树上的域小名
2018/01/17
2K0
水星家纺品牌双拼夺人眼球 已挂牌上市
躲在树上的域小名
2017/11/29
8770
水星家纺品牌双拼夺人眼球 已挂牌上市
这400万域名值 斗鱼直播完成D轮融资
躲在树上的域小名
2017/11/29
1.9K1
这400万域名值  斗鱼直播完成D轮融资
一条视频获C+融资 两个域名神助攻
视频是现如今比较热门的行业之一,出现了很多视频的产品,比如快手、美拍、一条视频等。1 月 22 日,“一条” 完成了 C+轮融资,京东、东博资本领投,现有投资方挚信资本跟投。融资完成之后,这家公司的估值达到 5 亿美元。
躲在树上的域小名
2018/01/23
9440
一条视频获C+融资 两个域名神助攻
“推特”启用20万元的双拼域名tuite.com
躲在树上的域小名
2017/12/21
2.8K0
“推特”启用20万元的双拼域名tuite.com
联众互动收购3家棋牌游戏公司,其域名买自蔡文胜手中
近日,联众互动以人民币4.25亿元收购三家棋牌类游戏公司,其中包括1.50亿元收购深圳讯游网络科技有限公司总股权的100%;2.20亿元收购南京好运美成电子科技有限公司;5500万元收购厦门亿玩堂网络科技有限公司100%股权。目前联众互动的股票大涨。
躲在树上的域小名
2018/01/19
1.2K0
娱乐八卦号们怎么办?域名帮你找答案
躲在树上的域小名
2017/12/01
9300
娱乐八卦号们怎么办?域名帮你找答案
相关推荐
猫眼域名曾变身 融资10亿元
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档