可自动伸缩的 Kubernetes DNS 服务

Autoscaling the Kubernetes DNS Service

September 12, 2018 - 2 minute read -
kubernetes

总结

集群中的 DNS 服务,使用了基于 cluster-proportional-autoscaler-amd64 镜像的 deployment ,来实现 DNS 服务的 Autoscaling (水平自动伸缩)。

简单的说,Autoscaling deployment 控制的 DNS pods 数量,会按照集群的大小,成一定比例地进行自动伸缩,其核心,目前是基于集群的 CPU 总核数或是集群的 Node 数量。

在调整 Autoscaling 控制参数时,原则上,集群中的 Node 如果多是小实例的话,应该使用 Node 的数量作为伸缩指标,为大实例的话,应该使用 CPU 总核数作为指标。

Autoscaling Deployment Object

apiVersion: apps/v1
kind: Deployment
... ...
command:
  - /cluster-proportional-autoscaler
  - --namespace=kube-system
  - --configmap=kube-dns-autoscaler
  - --target=<SCALE_TARGET>
  - --default-params={"linear":{"coresPerReplica":256,"nodesPerReplica":16}}
... ...
  • 检查 kube-system namespace 中,是否存在 deploy/kube-dns-autoscaler 来确定 DNS Service 是否启用了 Autoscaling。
  • SCALE_TARGET 的格式是 <object-type>/<object-name> e.g: deploy/kube-dns
  • 它从指定的 configMap 中读取配置,如果 configMap 不存在,就会使用命令行指定的默认参数。
  • 如果这个 deployment 是由 Addon Manager 所控制,则需要从 master 节点上手动修改这个 manifest,不然对资源对象的直接修改会被重置掉。
  • 对 configMap 的修改不受 Addon Manager 的影响。

调整 Autoscaling 参数

  • 修改 configMap 的内容,来更新 Autoscaling 的参数,不需要重启 deployment,它会监控 configMap 数据的变化,即时生效,调整 DNS pods 的数量。
  • configMap 数据的格式 linear: '{"coresPerReplica":256,"min":1,"nodesPerReplica":16}', 具体参考:cluster-proportional-autoscaler-amd64
  • 当集群中的 Nodes 是比较大的实例类型(多CPU)时,应该使用 coresPerReplica 来控制 deployment 的副本数量
  • 相反地,当 Node 都是小型的实例类型,应该是用 nodePerReplica 来控制副本数量。
  • DNS deployment replicas 数量的算法是 : replicas = max( ceil( cores * 1/coresPerReplica ) , ceil( nodes * 1/nodesPerReplica ) )

理解 DNS Autoscaling 的工作原理

  • 区别于 DNS 服务,autoscaling 服务是一个单独部署的 cluster-proportional-autoscaler 应用。
  • Autoscaler 的 pod 运行着一个 k8s 客户端,周期性地从 kubernetes API server 中拉取集群的节点数和 CPU 核心数。
  • 通过配置的伸缩参数,结合上述步骤获取到的当前集群中的 nodes 和 cores 数量,计算得到 DNS backends 应有的副本数量,最后将该副本数量应用到 DNS backends 的 deployment 上。
  • 伸缩参数通过 ConfigMap 传递给 autoscaler,并且在每次计算周期内,都会重新从 ConfigMap 获取配置参数,来计算最新的副本数量。
  • 更改伸缩参数不需要 rebuilding 或是 重新启动 autoscaler pod。
  • autoscaler 提供了一个控制器接口,支持两种控制模式:linearladder

ConfigMap 的配置的举例说明

e.g.:

data:
  linear: |-
    {
      "coresPerReplica": 2,
      "nodesPerReplica": 1,
      "min": 1,
      "max": 100,
      "preventSinglePointFailure": true
    }

算法:

replicas = max( ceil( cores * 1/coresPerReplica ) , ceil( nodes * 1/nodesPerReplica ) )
replicas = min(replicas, max)
replicas = max(replicas, min)

解释:

preventSinglePointFailure 设置为 true 时,同时 node 的数量大于1,控制器会确保至少有两个副本存在。

在上面的实例中,可以看到,集群总共有 4 个 nodes, 13 cores.

上面的伸缩配置参数表明,每一个副本对应至少 1 个 node ("nodesPerReplica": 1),结合公式,我们需要 ceil(4 * 1/1) = 4 个副本 来对应所有的 4 个 nodes.

同样的道理,每一个副本也对应至少 2 个 cores, 计算得到,我们需要 ceil(13 * 1/2) = 7 个副本来对应所有的 13 个 cores。

最终,控制器会选择其中比较大的数值,这里是 7 作为最终副本的数量。

从最终的结果上,可以看到 coresPerReplicanodesPerReplica中,总会有一个被忽略掉。

所有的 min,maxpreventSinglePointFailure 都是可选的,如果没有指定的话,min 默认为 1,

preventSinglePointFailure 默认为 false.

注意:

  • coresPerReplicanodesPerReplica 都是浮点数
  • min 小于 1 时,副本数量会被设置为 1.