简介
SPEC 规范:IP Address Management (IPAM) Interface
IPAM作用/职责
背景
以dhcp ipam 为例
和 CNI 的关系
To lessen the burden(负担) and make IP management strategy be orthogonal(正交) to the type of CNI plugin, we define a second type of plugin – IP Address Management Plugin (IPAM plugin)
The IPAM plugin must determine the interface IP/subnet, Gateway and Routes and return this information to the “main” plugin to apply. The IPAM plugin may obtain the information via a protocol (e.g. dhcp), data stored on a local filesystem, the “ipam” section of the Network Configuration file or a combination of the above.
几个重要的点
- Like CNI plugins, the IPAM plugins are invoked by running an executable. CNI和ipam 都是可执行文件
- The executable is searched for in a predefined list of paths(说白了就是跟CNI 插件一个地址 默认
/opt/cni/bin
), indicated to the CNI plugin via CNI_PATH - The IPAM Plugin must receive all the same environment variables that were passed in to the CNI plugin. Just like the CNI plugin, IPAM plugins receive the network configuration via stdin. CNI/IPAM通过 stdin 和 stdout 和外界交互, 环境变量也是共享的
- Success must be indicated by a zero return code and the JSON being printed to stdout
接口规范
k8s 提供了对CNI 和 ipam 的代码 skeleton,Package skel provides skeleton code for a CNI/IPAM plugin.In particular, it implements argument parsing and validation.
官方提供的ipam:host-local/static/dhcp,其main 方法都是
func main() {
skel.PluginMain(cmdAdd, cmdCheck, cmdDel, version.All, bv.BuildString("static-ipam"))
}
只需实现cmdAdd, cmdCheck, cmdDel 即可
CNI | IPAM | |
---|---|---|
cmdAdd | Add container to network | 返回一个可用的ip |
cmdCheck | Check container’s networking is as expected | |
cmdDel | Delete container from network | 将传入的ip回收 |
cmdAdd
请求参数model
// github.com/containernetworking/cni/pkg/skel/skel.go
type CmdArgs struct {
ContainerID string
Netns string
IfName string
Args string
Path string
StdinData []byte
}
Args 包括了一些额外的KeyValue,分号分割
IgnoreUnknown=1;
K8S_POD_NAMESPACE=default;
K8S_POD_NAME=fm-barge-backend-stable-5b498b6ff8-6bn2w;
K8S_POD_INFRA_CONTAINER_ID=3f1abf20f3060a67a5e49f75847eb91d2feb6cbe1e76dd52db2242063fb0e178
cmdAdd 的返回
// github.com/containernetworking/cni/pkg/types/current/types.go
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"`
}
calico-ipam
源码中涉及的一些概念
- A workload is a container or VM that Calico handles the virtual networking for. In Kubernetes, workloads are pods.
- A workload endpoint is the virtual network interface a workload uses to connect to the Calico network.
- IP pools are ranges of IP addresses that Calico uses for workload endpoints.
- When we stood up the Kubernetes cluster, we set the pod CIDR, which is the range of IP addresses Kubernetes thinks the pods should be in. Many Kubernetes components use this setting to determine if an IP belongs to a pod, so you normally want all IP pools you configure to be subsets of the pod CIDR. 一个集群可以只有一个ipPool 也可以有多个;Calico support for specifying IP pools on a per-pod, per-node and per-namespace.
- Within Calico’s IPAM engine, these IP pools are subdivided into smaller chunks – called blocks – which are then assigned to particular nodes in the cluster. Blocks are allocated dynamically to nodes as the number of running pods grows or shrinks. IPPool 会被切分为 IPBlock,block size可调整,一个node 可以绑定多个block(有的网络方案设定了一个node 可以运行的pod的上限)。PS: 一个node 多个block,加上node 和 block的亲和性关系,是calico-ipam 复杂性的主要来源。
- BlockAffinity, 存储block和Node的亲和关系。calico-ipam 会优先从和node 亲和的block 中寻找空闲ip,如果未找到,则从其它node 亲和block的block 上寻找ip。PS:有点像go调度器的work steal
calico 在etcd 中的存储结构
/calico
/ipam/v2
/assignment/ipv4/block/$block, 比如 10.21.1.128-26
/handle/$handle , 比如k8s-pod-network.00208aef31021ac8506e9aaac88793f581ee396a7cebd6040c52fb941b51584f
/host/$nodes
/ipv4/block/$block, 比如10.21.120.0-26
/resources/v3/projectcalico.org
/bgpconfigurations/default
/bgppeers
/clusterinformations/default
/felixconfigurations
/default
/node.xxx
/ippools
/每个ippool 都有一个路径
/nodes
/每个node 都有一个路径
/profiles
/每个namespace都有一个路径
/workloadendpoints/$namespace
/$namespace 下的pod
部分路径的值
// calico/ipam/v2/assignment/ipv4/block/$block 的值
// 维护已分配的IP地址(Allocation数组)和未分配的IP地址(Uanllocated数组)
// 维护block中运行的Pod
{
"cidr": "10.21.117.0/26",
"affinity": null, "strictAffinity": false,
"allocations": [null, 1, null, ...], // 长度与block size 一样,index 是该block 的第几个 ip,值是这个ip 是第几个被分配的,等于len(attributes)
"unallocated": [2, 0, 54, 42, ...], //长度=block size-len(attributes),值为该block 的第几个 ip
"attributes": [
{
"handle_id": "k8s-pod-network.972b0db0f6e449e81ca213ecfb376c6dd732727d0fe15a3a7f58006ae8f377b2", //网络名+容器名
"secondary": {
"namespace": "default",
"node": "$nodename",
"pod": "$podname"
}
}, ...],
"deleted": false
}
// calico/ipam/v2/handle/k8s-pod-network.972b0db0f6e449e81ca213ecfb376c6dd732727d0fe15a3a7f58006ae8f377b2
// 保存pod与block的对应关系,在释放IP的过程中用于查找block
// HandleID由网络名和容器ID组合而成
{
"block":{"10.21.117.0/26":1},
"deleted":false
}
// /calico/resources/v3/projectcalico.org/ippools/default-pool
{
"kind":"IPPool",
"apiVersion":"projectcalico.org/v3",
"metadata":{"name":"default-pool","uid":"f2d937d9-a616-4214-a31c-b3194a63fe55","creationTimestamp":"2020-05-07T10:34:42Z"},
"spec":{
"cidr":"10.21.0.0/17",
"vxlanMode":"Never",
"ipipMode":"Never",
"blockSize":26,
"nodeSelector":"staticip != \"1\""
}
}
源码分析
projectcalico/cni-plugin 与cni 插件共用一个二进制文件,根据命令参数提供不同的功能。 Calico IPAM源码解析
代码结构
github.com/projectcalico/libcalico-go/lib
/ipam
/interface.go // 定义了ip分配与释放接口
/ipam.go
/backend
/api
/api.go // 定义了存储层接口
/etcd
/etcdv3
/k8s
// github.com/projectcalico/libcalico-go/lib/ipam/interface.go
type Interface interface {
// 给特定host 安排一个 ip
AssignIP(ctx context.Context, args AssignIPArgs) error
// 自动分派一个ip
AutoAssign(ctx context.Context, args AutoAssignArgs) ([]cnet.IPNet, []cnet.IPNet, error)
// 释放ip
ReleaseIPs(ctx context.Context, ips []cnet.IP) ([]cnet.IP, error)
...
}
// github.com/projectcalico/libcalico-go/lib/ipam/ipam.go
type ipamClient struct {
client bapi.Client
pools PoolAccessorInterface
blockReaderWriter blockReaderWriter
}
// Client is the interface to the backend datastore. 实现有etcdV3Client/kubeClient
// github.com/projectcalico/libcalico-go/lib/backend/api/api.go
type Client interface {
Create(ctx context.Context, object *model.KVPair) (*model.KVPair, error)
Update(ctx context.Context, object *model.KVPair) (*model.KVPair, error)
Get(ctx context.Context, key model.Key, revision string) (*model.KVPair, error)
...
}
在 ip的分配释放过程中,会伴随着 block、BlockAffinity,handle 数据的增删改,来保持数据的一致性。
支持静态ip
docker中部署服务一个很常见的问题 每次部署,pod的ip 都会发生改变,这对mysql、redis等基础服务就很不友好,因此有必要将ip“固定”。常见的是:使用servie 解决内部连通性, 使用ingress + service 解决外部连通性。但对于一些网络来说,使用service 很不方便,比如macvlan等,性能也很差,换个思路:将一个服务与ip绑定起来 ==> 指定服务所属的ip
Requesting a specific IP address
代码 calico-ipam 实现了pod.yaml 上使用一个annotation 来指定ip,calico-ipam 即可返回指定ip 的功能。
annotations:
"cni.projectcalico.org/ipAddrs": "[\"192.168.0.1\"]"
基本原理是
- 从 CmdArgs.Args拿到K8S_POD_NAME (github.com/projectcalico/cni-plugin/internal/pkg/utils/utils.go/GetIdentifiers)
- 进而查询k8s 集群api 拿到 pod的annotations 信息(github.com/projectcalico/cni-plugin/pkg/k8s/k8s.go/CmdAddK8s)
- 将ip 作为ipam 的返回结果,用于CNI 插件设定容器
笔者依照该思想自己实现了一个qiankunli/static-ipam