从调度器的调度周期(Scheduling Cycle)与绑定周期(Binding Cycle)出发,深入解析 Scheduling Framework 的扩展点机制、Filter/Score/Bind 插件接口、NodeScore 算法实现,掌握自定义调度插件的开发方法与多调度器共存的生产实践。
Kubernetes 调度器(kube-scheduler)是控制平面中最计算密集的组件。它的核心职责是为新创建的 Pod 选择一个最佳节点。调度决策涉及资源匹配、亲和性约束、拓扑分布、数据局部性等多个维度,每个维度由一个或多个插件实现。理解调度器的架构是进行调度调优和自定义调度策略的基础。
kube-scheduler 支持两种运行模式:
| 模式 | 配置方式 | 特点 | 适用场景 |
|---|---|---|---|
| 默认模式 | 命令行参数 | 使用内置所有插件,按默认配置运行 | 标准集群、快速部署 |
| 多调度器模式 | KubeSchedulerConfiguration | 自定义插件启停、权重、profile | 多租户、特殊调度需求 |
调度器的本地缓存,维护节点信息(NodeInfo)、Pod 信息、镜像信息等。通过 Informer 从 apiserver 同步,为调度计算提供快速数据访问。
调度框架,管理所有插件的注册和执行。定义了调度周期的扩展点(Extension Points),插件按注册顺序在各扩展点执行。
待调度 Pod 的优先级队列。按 PriorityClass 排序,高优先级 Pod 先调度。支持主动排队(BackoffQ)和不可调度队列(UnschedulableQ)。
执行 Pod 到 Node 的绑定操作。通过更新 Pod.Spec.NodeName 或创建 Binding 对象实现。绑定是调度周期中唯一修改集群状态的操作。
处理存储卷绑定。在 Filter 阶段检查 PV/PVC 兼容性,在 Reserve 阶段预留存储资源,在 Bind 阶段完成 PVC 绑定。
调度配置档案。一个调度器可以运行多个 Profile,每个 Profile 有独立的插件配置,通过 schedulerName 字段选择使用哪个 Profile。
func Run(ctx context.Context, cc *schedulerserver.Config) error {
// 1. 创建 Scheduler 对象
sched, err := scheduler.New(
cc.Client,
cc.InformerFactory,
cc.DynInformerFactory,
recorderFactory,
cc.Done(),
scheduler.WithProfiles(cc.ComponentConfig.Profiles...),
scheduler.WithAlgorithmSource(cc.ComponentConfig.AlgorithmSource),
scheduler.WithKubeConfig(cc.KubeConfig),
scheduler.WithSchedulingQueue(),
)
// 2. 启动 Informer(开始缓存集群状态)
cc.InformerFactory.Start(ctx.Done())
// 3. 等待缓存同步完成
cc.InformerFactory.WaitForCacheSync(ctx.Done())
// 4. 启动调度器主循环
sched.Run(ctx)
return nil
}
func (sched *Scheduler) Run(ctx context.Context) {
// 启动多个调度 goroutine(默认 1 个)
for i := 0; i < sched.threads; i++ {
go sched.scheduleOne(ctx)
}
}
调度器的核心是 scheduleOne 函数,它处理一个 Pod 的完整调度流程。这个流程分为两个阶段:调度周期(Scheduling Cycle)和绑定周期(Binding Cycle)。
func (sched *Scheduler) scheduleOne(ctx context.Context) {
// === 阶段 0: 从队列取出待调度 Pod ===
podInfo := sched.NextPod()
pod := podInfo.Pod
// 获取该 Pod 对应的 Framework Profile
fwk, err := sched.frameworkForPod(pod)
// === 调度周期开始 ===
// 阶段 1: PreFilter —— 前置检查
// 检查 Pod 是否满足基本条件(如至少有一个节点可用)
preFilterStatus := fwk.RunPreFilterPlugins(ctx, pod)
if !preFilterStatus.IsSuccess() {
sched.handleSchedulingFailure(pod, preFilterStatus)
return
}
// 阶段 2: Filter —— 过滤不可调度节点
// 遍历所有节点,对每个节点执行所有 Filter 插件
// 被所有 Filter 通过的节点进入候选列表
feasibleNodes, err := sched.findNodesThatFitPod(ctx, fwk, pod)
if len(feasibleNodes) == 0 {
sched.handleSchedulingFailure(pod, "no nodes available")
return
}
// 阶段 3: PostFilter —— 补救措施
// 如果没有可行节点,执行 PostFilter(如抢占)
if len(feasibleNodes) == 0 {
postFilterStatus := fwk.RunPostFilterPlugins(ctx, pod, nil)
// PostFilter 可能通过驱逐低优先级 Pod 来腾出资源
return
}
// 阶段 4: PreScore —— 评分前准备
preScoreStatus := fwk.RunPreScorePlugins(ctx, pod, feasibleNodes)
// 阶段 5: Score —— 节点评分
// 对每个候选节点执行所有 Score 插件
// 每个插件返回 0-100 的分数
// 最终分数 = Σ(插件分数 × 插件权重) / Σ(插件权重)
nodesList, err := sched.prioritizeNodes(ctx, fwk, pod, feasibleNodes)
// 阶段 6: NormalizeScore —— 分数归一化
fwk.RunNormalizeScorePlugins(ctx, pod, nodesList)
// 阶段 7: SelectHost —— 选择最佳节点
// 从评分最高的节点中选择(如果有多个同分,随机选一个)
suggestedHost, err := sched.selectHost(nodesList)
// === 调度周期结束 ===
// 阶段 8: Reserve —— 预留资源
// 在缓存中临时预留节点资源(防止并发调度冲突)
reserveStatus := fwk.RunReservePlugins(ctx, &framework.CycleState{}, pod, suggestedHost)
// === 绑定周期开始 ===
// 阶段 9: Permit —— 允许绑定检查
// Permit 插件可以延迟绑定(等待外部条件满足)
permitStatus := fwk.RunPermitPlugins(ctx, &framework.CycleState{}, pod, suggestedHost)
// 阶段 10: PreBind —— 绑定前准备
// 如:绑定 PVC 到 PV
preBindStatus := fwk.RunPreBindPlugins(ctx, &framework.CycleState{}, pod, suggestedHost)
// 阶段 11: Bind —— 执行绑定
// 将 Pod.Spec.NodeName 设置为选中的节点
bindStatus := fwk.RunBindPlugins(ctx, &framework.CycleState{}, pod, suggestedHost)
// === 绑定周期结束 ===
// 阶段 12: PostBind —— 绑定后清理
fwk.RunPostBindPlugins(ctx, &framework.CycleState{}, pod, suggestedHost)
}
调度器就像一个公司的招聘系统。Filter 阶段像简历筛选——先排除明显不满足硬性要求的候选人(节点)。Score 阶段像面试评分——对通过初筛的候选人从多个维度打分(技术能力、文化匹配、薪资期望等)。SelectHost 像发 Offer——选择综合评分最高的候选人。Bind 像签合同——正式确定雇佣关系。Reserve 像口头 Offer——先占住候选人,防止被其他公司抢走。Permit 像 background check——等待最终确认后才正式签约。
调度周期和绑定周期的分离是一个关键设计:
| 特性 | 调度周期(Scheduling Cycle) | 绑定周期(Binding Cycle) |
|---|---|---|
| 执行方式 | 同步、串行 | 异步、可并行 |
| 修改状态 | 只读(不修改集群状态) | 写入(修改 Pod.Spec.NodeName) |
| 失败处理 | Pod 重新入队 | 回滚 Reserve、Pod 重新入队 |
| 并发控制 | 单线程(默认) | 多 goroutine 并行 |
| 耗时段 | Filter + Score(计算密集) | PreBind + Bind(IO 密集,如 Volume 绑定) |
调度器默认只运行 1 个 scheduleOne goroutine(--concurrent-scheduler-syncs=1)。这意味着同一时刻只有一个 Pod 在被调度。虽然这简化了并发控制,但在大规模集群中可能成为瓶颈。可以增大到 2-4,但需要注意:并发调度可能导致资源竞争——两个 Pod 可能被调度到同一节点,导致资源超额分配。调度器通过 Reserve 机制缓解此问题,但不能完全避免。
Scheduling Framework 是 Kubernetes 1.19+ 引入的调度器扩展机制,取代了旧的 scheduler extender(HTTP 回调)方式。Framework 定义了一组扩展点(Extension Points),开发者可以在这些扩展点插入自定义逻辑。
每个扩展点对应一个 Go 接口,自定义插件只需实现相应接口:
// Filter 插件接口
type FilterPlugin interface {
Plugin
Filter(ctx context.Context, state *CycleState, pod *v1.Pod, nodeInfo *NodeInfo) *Status
}
// Score 插件接口
type ScorePlugin interface {
Plugin
Score(ctx context.Context, state *CycleState, pod *v1.Pod, nodeName string) (int64, *Status)
}
// ScoreExtensions —— NormalizeScore 方法
type ScoreExtensions interface {
NormalizeScore(ctx context.Context, state *CycleState, pod *v1.Pod, scores NodeScoreList) *Status
}
// Reserve 插件接口
type ReservePlugin interface {
Plugin
Reserve(ctx context.Context, state *CycleState, pod *v1.Pod, nodeName string) *Status
Unreserve(ctx context.Context, state *CycleState, pod *v1.Pod, nodeName string)
}
// Bind 插件接口
type BindPlugin interface {
Plugin
Bind(ctx context.Context, state *CycleState, pod *v1.Pod, nodeName string) *Status
}
// Permit 插件接口
type PermitPlugin interface {
Plugin
Permit(ctx context.Context, state *CycleState, pod *v1.Pod, nodeName string) (*Status, time.Duration)
}
// PostFilter 插件接口
type PostFilterPlugin interface {
Plugin
PostFilter(ctx context.Context, state *CycleState, pod *v1.Pod, filteredNodeStatusMap NodeToStatusMap) (*PostFilterResult, *Status)
}
// 所有插件的基础接口
type Plugin interface {
Name() string
}
| 插件名 | 扩展点 | 默认启用 | 功能 | 关键参数 |
|---|---|---|---|---|
NodeUnschedulable | Filter | 是 | 排除 Unschedulable 节点 | 无 |
NodeName | Filter | 是 | 匹配 spec.nodeName | 无 |
TaintToleration | Filter+Score | 是 | Taint/Toleration 匹配 | 权重可配置 |
NodeAffinity | Filter+Score | 是 | 节点亲和性 | 无 |
PodAffinity | Filter+Score | 是 | Pod 亲和/反亲和 | 无 |
NodeResourcesFit | Filter+Score | 是 | 资源请求检查与评分 | scoringStrategy |
NodePorts | Filter | 是 | 端口冲突检查 | 无 |
VolumeBinding | Filter+Reserve+Bind | 是 | PVC/PV 绑定 | bindMode |
VolumeRestrictions | Filter | 是 | 卷访问模式限制 | 无 |
ImageLocality | Score | 否 | 镜像本地性评分 | 需手动启用 |
InterPodAffinity | Filter+Score | 是 | Pod 间亲和性 | 无 |
DefaultBinder | Bind | 是 | 默认绑定逻辑 | 无 |
NodeVolumeLimits | Filter | 是 | 节点卷数量限制 | 无 |
PodTopologySpread | Filter+Score | 是 | 拓扑分布约束 | 无 |
DefaultPreemption | PostFilter | 是 | 默认抢占逻辑 | 无 |
Filter 阶段是调度周期中最耗时的部分——它需要对每个候选节点执行所有 Filter 插件。在大规模集群中,节点数量可能达到数千,Filter 的效率直接决定调度吞吐量。
func (sched *Scheduler) findNodesThatFitPod(ctx context.Context, fwk framework.Framework, pod *v1.Pod) ([]*v1.Node, error) {
// 1. 获取所有节点
allNodes := sched.Cache.NodeInfos()
// 2. 确定并行度
// 默认 parallelism = min(16, 节点数)
parallelism := parallelize.GetParallelism()
// 3. 并行执行 Filter
feasibleNodes := make([]*v1.Node, 0, len(allNodes))
parallelize.Until(ctx, len(allNodes), func(piece int) {
nodeInfo := allNodes[piece]
// 对单个节点执行所有 Filter 插件
status := fwk.RunFilterPlugins(ctx, state, pod, nodeInfo)
if status.IsSuccess() {
// 线程安全地添加到候选列表
feasibleNodes = append(feasibleNodes, nodeInfo.Node())
}
})
return feasibleNodes, nil
}
// RunFilterPlugins 依次执行所有注册的 Filter 插件
func (f *frameworkImpl) RunFilterPlugins(ctx context.Context, state *CycleState, pod *v1.Pod, nodeInfo *NodeInfo) *Status {
for _, pl := range f.filterPlugins {
status := pl.Filter(ctx, state, pod, nodeInfo)
if !status.IsSuccess() {
// 某个 Filter 失败,立即返回(短路)
return status.AsError()
}
}
return nil // 所有 Filter 通过
}
NodeResourcesFit 是最核心的 Filter 插件,检查节点是否有足够资源运行 Pod:
func (f *NodeResourcesFit) Filter(ctx context.Context, state *CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {
// 1. 获取 Pod 的资源请求
podRequest := computePodResourceRequest(pod)
// podRequest = {
// cpu: 500m (from requests)
// memory: 1Gi
// ephemeral-storage: 100Mi
// }
// 2. 获取节点的可用资源
// available = nodeCapacity - sum(podRequests of running pods)
// 注意:这里使用的是调度器缓存中的预估值,不是实时值
available := nodeInfo.Allocatable.Clone()
for _, runningPod := range nodeInfo.Pods {
available.Sub(computePodResourceRequest(runningPod.Pod))
}
// 3. 检查每种资源是否充足
insufficientResources := make([]v1.ResourceName, 0)
for resourceName, requested := range podRequest {
if available[resourceName] < requested {
insufficientResources = append(insufficientResources, resourceName)
}
}
if len(insufficientResources) > 0 {
return framework.NewStatus(
framework.Unschedulable,
fmt.Sprintf("Node didn't have enough resources: %v", insufficientResources),
)
}
return nil // 资源充足
}
// 注意:这里只检查 requests,不检查 limits
// 超卖(overcommit)是通过 limits/requests 比值控制的
func (pl *TaintToleration) Filter(ctx context.Context, state *CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {
node := nodeInfo.Node()
// 遍历节点的所有 Taint
for _, taint := range node.Spec.Taints {
// 检查 Pod 是否有对应的 Toleration
if !toleratesTaint(pod, taint) {
// 如果是不可容忍的 NoSchedule/NoExecute Taint
if taint.Effect == v1.TaintEffectNoSchedule {
return framework.NewStatus(framework.Unschedulable,
"node has taint not tolerated by pod")
}
// NoExecute Taint 由 NodeToleration controller 处理驱逐
// Filter 阶段只检查 NoSchedule
}
}
return nil
}
func toleratesTaint(pod *v1.Pod, taint v1.Taint) bool {
for _, toleration := range pod.Spec.Tolerations {
// 匹配条件:key、effect、value 都匹配
if toleration.Effect != taint.Effect {
continue
}
if toleration.Key != taint.Key && toleration.Key != "" {
continue
}
if toleration.Operator == v1.TolerationOpEqual {
if toleration.Value == taint.Value {
return true
}
} else if toleration.Operator == v1.TolerationOpExists {
return true // Exists 操作符不检查 value
}
}
return false
}
Score 阶段对通过 Filter 的候选节点进行评分,最终选择得分最高的节点。每个 Score 插件从不同维度评分,最终分数是各插件分数的加权平均。
func (sched *Scheduler) prioritizeNodes(ctx context.Context, fwk framework.Framework, pod *v1.Pod, feasibleNodes []*v1.Node) (framework.NodeScoreList, error) {
// 1. 获取所有 Score 插件及其权重
scorePlugins := fwk.ScorePlugins()
// [
// {plugin: NodeResourcesFit, weight: 1},
// {plugin: NodeAffinity, weight: 1},
// {plugin: PodAffinity, weight: 1},
// {plugin: TaintToleration, weight: 3},
// {plugin: PodTopologySpread, weight: 2},
// ]
// 2. 为每个插件创建评分结果数组
pluginScores := make([]framework.NodeScoreList, len(scorePlugins))
// 3. 并行执行每个插件的 Score 方法
for i, scorePlugin := range scorePlugins {
pluginScores[i] = make(framework.NodeScoreList, len(feasibleNodes))
parallelize.Until(ctx, len(feasibleNodes), func(j int) {
// 对单个节点执行单个插件的 Score
score, status := scorePlugin.Score(ctx, state, pod, feasibleNodes[j].Name)
pluginScores[i][j] = framework.NodeScore{
Name: feasibleNodes[j].Name,
Score: score,
}
})
}
// 4. 执行 NormalizeScore(将分数归一化到 0-100)
for i, scorePlugin := range scorePlugins {
if ext, ok := scorePlugin.(framework.ScoreExtensions); ok {
ext.NormalizeScore(ctx, state, pod, pluginScores[i])
}
}
// 5. 计算加权总分
result := make(framework.NodeScoreList, len(feasibleNodes))
for j := range feasibleNodes {
weightedScore := int64(0)
totalWeight := int64(0)
for i, scorePlugin := range scorePlugins {
weightedScore += pluginScores[i][j].Score * int64(scorePlugin.Weight)
totalWeight += int64(scorePlugin.Weight)
}
result[j] = framework.NodeScore{
Name: feasibleNodes[j].Name,
Score: weightedScore / totalWeight, // 加权平均
}
}
return result, nil
}
NodeResourcesFit 插件支持多种评分策略:
func (f *NodeResourcesFit) Score(ctx context.Context, state *CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {
nodeInfo, _ := f.handle.Snapshot().NodeInfos().Get(nodeName)
// 根据 scoringStrategy 选择不同的评分算法
switch f.strategy.Type {
case api.LeastAllocated:
// 最少已分配策略:优先选择资源利用率低的节点
// score = (1 - requested/capacity) * 100
// 效果:负载均衡
return f.leastAllocatedScore(pod, nodeInfo)
case api.MostAllocated:
// 最多已分配策略:优先选择资源利用率高的节点
// score = (requested/capacity) * 100
// 效果:紧凑放置,减少碎片
return f.mostAllocatedScore(pod, nodeInfo)
case api.RequestedToCapacityRatio:
// 请求/容量比策略:考虑多种资源的综合利用率
// 使用自定义打分函数
return f.requestedToCapacityRatioScore(pod, nodeInfo)
}
}
// LeastAllocated 算法
func (f *NodeResourcesFit) leastAllocatedScore(pod *v1.Pod, nodeInfo *framework.NodeInfo) (int64, *framework.Status) {
podRequest := computePodResourceRequest(pod)
nodeCapacity := nodeInfo.Allocatable
totalScore := int64(0)
numResources := 0
for resource, requested := range podRequest {
capacity := nodeCapacity[resource]
if capacity == 0 { continue }
// 已分配 = 节点上所有 Pod 的请求 + 当前 Pod 的请求
allocated := nodeInfo.Requested[resource] + requested
// 分数 = (1 - allocated/capacity) * 100
// 利用率越低,分数越高
score := (1 - float64(allocated)/float64(capacity)) * 100
totalScore += int64(score)
numResources++
}
return totalScore / int64(numResources), nil
}
| 评分策略 | 公式 | 效果 | 适用场景 |
|---|---|---|---|
| LeastAllocated | (1 - allocated/capacity) × 100 | 负载均衡 | 通用场景(默认) |
| MostAllocated | (allocated/capacity) × 100 | 紧凑放置 | 节点缩容、减少碎片 |
| RequestedToCapacityRatio | 自定义函数 | 精细控制 | 多资源权重调整 |
PodTopologySpread 实现 Pod 的拓扑分布约束(TopologySpreadConstraints),确保 Pod 在指定的拓扑域(如 zone、node)中均匀分布:
func (pl *PodTopologySpread) Score(ctx context.Context, state *CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {
// 1. 获取 Pod 的 TopologySpreadConstraints
constraints := getTopologySpreadConstraints(pod)
// 2. 对每个 constraint 计算分数
totalScore := int64(0)
for _, constraint := range constraints {
// 获取当前节点所属的拓扑域值
// 如 topologyKey="zone",当前节点 zone="us-east-1a"
nodeTopologyValue := getNodeTopologyValue(nodeName, constraint.TopologyKey)
// 统计该拓扑域中匹配的 Pod 数量
// count = 该 zone 中已有匹配 Pod 数 + 如果调度到此节点的数量
currentCount := pl.podSpreadCounts[constraint][nodeTopologyValue]
if schedulingToThisNode {
currentCount++
}
// 计算理想平均分布数
totalPods := getTotalMatchingPods(constraint)
numDomains := getNumDomains(constraint)
idealAvg := float64(totalPods) / float64(numDomains)
// 分数 = 100 - |currentCount - idealAvg| × penaltyFactor
// 偏差越小,分数越高
deviation := math.Abs(float64(currentCount) - idealAvg)
score := int64(100 - deviation * 100 / float64(totalPods+1))
totalScore += score
}
return totalScore / int64(len(constraints)), nil
}
当内置插件无法满足业务需求时,可以通过编写自定义调度插件来扩展调度器。自定义插件需要编译到调度器二进制中(通过 Go 的 init() 注册机制),或者通过 out-of-tree 插件方式运行。
假设我们需要一个插件,根据 Pod 对 GPU 型号的偏好选择节点(如优先选择有 A100 的节点):
package gpupreference
import (
"context"
"fmt"
"k8s.io/api/core/v1"
"k8s.io/kubernetes/pkg/scheduler/framework"
)
const Name = "GPUReference"
// GPUReference 插件结构
type GPUReference struct {
handle framework.Handle
}
// 实现 framework.Plugin 接口
func (g *GPUReference) Name() string { return Name }
// 实现 framework.ScorePlugin 接口
func (g *GPUReference) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {
// 1. 从 Pod 注解获取期望的 GPU 型号
desiredGPU := pod.Annotations["gpu-preference/model"]
if desiredGPU == "" {
return 0, framework.NewStatus(framework.Success)
}
// 2. 获取节点信息
nodeInfo, err := g.handle.Snapshot().NodeInfos().Get(nodeName)
if err != nil {
return 0, framework.AsStatus(err)
}
// 3. 检查节点是否有期望的 GPU
nodeGPUModel := nodeInfo.Node().Labels["gpu-model"]
if nodeGPUModel == desiredGPU {
// 精确匹配:最高分
return 100, framework.NewStatus(framework.Success)
}
// 4. 模糊匹配:同厂商不同型号给中等分数
if sameVendor(nodeGPUModel, desiredGPU) {
return 50, framework.NewStatus(framework.Success)
}
// 5. 不匹配:低分
return 10, framework.NewStatus(framework.Success)
}
// 注册插件
func New(_ context.Context, _ runtime.Object, h framework.Handle) (framework.Plugin, error) {
return &GPUReference{handle: h}, nil
}
// init 注册到 registry
func init() {
runtime.Must(factory.RegisterScorePlugin(
Name,
New,
100, // 插件权重
))
}
自定义插件需要在 KubeSchedulerConfiguration 中启用:
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: gpu-scheduler
plugins:
score:
enabled:
- name: GPUReference
weight: 10 # GPU 偏好的权重
- name: NodeResourcesFit
weight: 1
- name: PodTopologySpread
weight: 2
filter:
enabled:
- name: NodeUnschedulable
- name: NodeName
- name: TaintToleration
- name: NodeAffinity
- name: NodeResourcesFit
- name: VolumeBinding
# 自定义插件的配置参数
pluginConfig:
- name: GPUReference
args:
apiVersion: kubescheduler.config.k8s.io/v1
kind: GPUReferenceArgs
preferredGPUs:
- model: "A100"
fallback: "V100"
- model: "H100"
fallback: "A100"
如果不想修改调度器源码,可以使用 scheduler-plugins 项目(sigs.k8s.io/scheduler-plugins)开发 out-of-tree 插件:
# 1. 克隆 scheduler-plugins 项目
git clone https://github.com/kubernetes-sigs/scheduler-plugins.git
cd scheduler-plugins
# 2. 在 apis/config/v1 目录下定义插件配置类型
# cmd/scheduler/main.go 中注册自定义插件
# 3. 构建自定义调度器镜像
make scheduler-image
# 4. 部署自定义调度器
kubectl apply -f manifests/install/all-in-one.yaml
# 5. 在 Pod 中指定使用自定义调度器
cat <
当高优先级 Pod 无法找到可行节点时,调度器可以通过抢占(Preemption)机制驱逐低优先级 Pod,为高优先级 Pod 腾出资源。抢占逻辑由 PostFilter 扩展点的 DefaultPreemption 插件实现。
抢占只在以下条件同时满足时触发:
spec.priorityClassName 指向一个 PriorityClass,且 value > 0podDisruptionBudget 或 PDB 允许func (pl *DefaultPreemption) PostFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status) {
// 1. 获取所有候选节点(即使被 Filter 拒绝的)
allNodes := pl.handle.Snapshot().NodeInfos()
// 2. 对每个节点,尝试找出需要驱逐的 Pod 集合
type candidate struct {
node string
victims []*v1.Pod
}
candidates := []candidate{}
for _, nodeInfo := range allNodes {
// 3. 找出该节点上可以被驱逐的 Pod
victims, feasible := pl.findVictimsOnNode(ctx, state, pod, nodeInfo)
if feasible {
candidates = append(candidates, candidate{
node: nodeInfo.Node().Name,
victims: victims,
})
}
}
if len(candidates) == 0 {
return nil, framework.NewStatus(framework.Unschedulable, "no preemption candidates")
}
// 4. 选择最佳抢占候选(最少干扰原则)
bestCandidate := pl.pickBestNode(ctx, candidates, pod)
// 5. 执行驱逐
for _, victim := range bestCandidate.victims {
// 设置 DeletionGracePeriodSeconds=0 立即驱逐
err := pl.handle.ClientSet().CoreV1().Pods(victim.Namespace).
Delete(ctx, victim.Name, metav1.DeleteOptions{GracePeriodSeconds: &immediate})
if err != nil {
return nil, framework.AsStatus(err)
}
}
// 6. 返回选中的节点(Pod 将在下一轮调度中被调度到此节点)
return &framework.PostFilterResult{NominatedNodeName: bestCandidate.node}, nil
}
// findVictimsOnNode 找出节点上需要驱逐的 Pod
func (pl *DefaultPreemption) findVictimsOnNode(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) ([]*v1.Pod, bool) {
// 1. 获取节点上所有优先级低于 pod 的 Pod
potentialVictims := []*v1.Pod{}
for _, existingPod := range nodeInfo.Pods {
if existingPod.Pod.Spec.Priority != nil &&
*existingPod.Pod.Spec.Priority < *pod.Spec.Priority {
potentialVictims = append(potentialVictims, existingPod.Pod)
}
}
// 2. 按 PDB 约束过滤
// 确保驱逐后不会违反任何 PDB
pdbCompatibleVictims := pl.filterPDBCompatible(potentialVictims)
// 3. 尝试找出最小驱逐集合
// 贪心算法:从优先级最低的开始,逐个尝试驱逐
sort.Slice(pdbCompatibleVictims, func(i, j int) bool {
return *pdbCompatibleVictims[i].Spec.Priority < *pdbCompatibleVictims[j].Spec.Priority
})
victims := []*v1.Pod{}
releasedResources := framework.Resource{}
for _, victim := range pdbCompatibleVictims {
victims = append(victims, victim)
releasedResources.Add(computePodResourceRequest(victim))
// 检查释放的资源是否足够
if pl.hasEnoughResourcesAfterPreemption(pod, nodeInfo, releasedResources) {
// 验证驱逐后 Pod 能通过所有 Filter
if pl.canScheduleAfterPreemption(ctx, state, pod, nodeInfo, victims) {
return victims, true
}
}
}
return nil, false
}
抢占成功后,被抢占的 Pod 尚未真正退出(需要等待 graceful shutdown)。调度器通过 pod.Status.NominatedNodeName 记录抢占选中的节点:
在一个集群中可以运行多个调度器,每个 Pod 通过 spec.schedulerName 指定使用哪个调度器。这在多租户环境或特殊工作负载场景中很有用。
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
# Profile 1: 默认调度器
- schedulerName: default-scheduler
plugins:
score:
enabled:
- name: NodeResourcesFit
weight: 1
- name: PodTopologySpread
weight: 2
- name: TaintToleration
weight: 3
# Profile 2: GPU 专用调度器
- schedulerName: gpu-scheduler
plugins:
score:
enabled:
- name: GPUReference # 自定义插件
weight: 10
- name: NodeResourcesFit
weight: 1
- name: NodeAffinity
weight: 5
filter:
enabled:
- name: NodeUnschedulable
- name: NodeName
- name: TaintToleration
- name: NodeAffinity
- name: NodeResourcesFit
# Profile 3: 批处理调度器(紧凑放置)
- schedulerName: batch-scheduler
plugins:
score:
enabled:
- name: NodeResourcesFit
weight: 1
disabled:
- name: PodTopologySpread # 禁用拓扑分布
pluginConfig:
- name: NodeResourcesFit
args:
apiVersion: kubescheduler.config.k8s.io/v1
kind: NodeResourcesFitArgs
scoringStrategy:
type: MostAllocated # 紧凑放置策略
多个调度器在同一集群中运行时,可能产生资源竞争:两个调度器可能同时将 Pod 调度到同一节点,导致资源超额分配。这是因为每个调度器只维护自己的缓存视图,不感知其他调度器的决策。缓解措施:
1. 通过 nodeSelector 或 nodeAffinity 将不同调度器的 Pod 限制到不同节点池
2. 使用 schedulingGates(K8s 1.26+)控制 Pod 何时进入调度
3. 为每个调度器设置独立的 --leader-elect-resource-name 避免选举冲突
| 参数 | 默认值 | 影响 | 调优建议 |
|---|---|---|---|
--concurrent-scheduler-syncs | 1 | 并发调度数 | 大规模集群设 2-4 |
--percentage-of-nodes-to-score | 50(大集群) | 评分节点比例 | 大集群降低以提升吞吐 |
--pod-max-backoff-seconds | 10s | Pod 最大退避时间 | 影响重试频率 |
--pod-initial-backoff-seconds | 1s | Pod 初始退避 | 影响首次重试延迟 |
--leader-elect-renew-deadline | 10s | 选举续租截止 | 影响故障切换速度 |
--profiling | true | 是否启用 pprof | 生产可关闭 |
本实验开发一个 NetworkAware 调度插件,根据节点的网络延迟(通过节点标签标注)选择网络延迟最低的节点。
# 使用 scheduler-plugins 脚手架
git clone https://github.com/kubernetes-sigs/scheduler-plugins.git
cd scheduler-plugins
# 创建插件目录
mkdir -p pkg/networkaware
mkdir -p apis/config/v1/networkaware
# 插件结构:
# pkg/networkaware/
# plugin.go # 插件实现
# scoring.go # 评分逻辑
# apis/config/v1/networkaware/
# types.go # 配置类型定义
# defaults.go # 默认值
package networkaware
import (
"context"
"strconv"
"k8s.io/api/core/v1"
"k8s.io/kubernetes/pkg/scheduler/framework"
)
const Name = "NetworkAware"
type NetworkAware struct {
handle framework.Handle
latencyLabel string // 如 "network-latency-ms"
}
func (n *NetworkAware) Name() string { return Name }
func (n *NetworkAware) Score(ctx context.Context, state *framework.CycleState,
pod *v1.Pod, nodeName string) (int64, *framework.Status) {
nodeInfo, err := n.handle.Snapshot().NodeInfos().Get(nodeName)
if err != nil {
return 0, framework.AsStatus(err)
}
// 从节点标签读取网络延迟
latencyStr := nodeInfo.Node().Labels[n.latencyLabel]
if latencyStr == "" {
return 50, nil // 无延迟信息,给中等分数
}
latency, err := strconv.Atoi(latencyStr)
if err != nil {
return 0, framework.NewStatus(framework.Error, "invalid latency label")
}
// 分数 = 100 - latency(延迟越低分数越高)
// 假设延迟范围 0-100ms
score := int64(100 - latency)
if score < 0 { score = 0 }
return score, nil
}
func New(_ context.Context, _ runtime.Object, h framework.Handle) (framework.Plugin, error) {
return &NetworkAware{
handle: h,
latencyLabel: "network-latency-ms",
}, nil
}
func main() {
// 注册内置插件
app.RegisterAllPlugins()
// 注册自定义插件
app.WithPlugin(networkaware.Name, networkaware.New)
// 启动调度器
command := app.NewSchedulerCommand()
code := cli.Run(command)
os.Exit(code)
}
# 构建调度器镜像
make scheduler-image IMG=network-aware-scheduler:latest
# 部署调度器
kubectl apply -f manifests/network-aware-scheduler.yaml
# 为节点标注网络延迟
kubectl label node node-1 network-latency-ms=5
kubectl label node node-2 network-latency-ms=20
kubectl label node node-3 network-latency-ms=10
# 创建使用自定义调度器的 Pod
cat <
背景:某 ML 平台中,需要 GPU 的 Pod 被调度到没有 GPU 的节点,导致 Pod 启动失败。
根因:节点未正确标注 GPU 资源。nvidia device plugin 未正常运行,节点 Allocatable 中没有 nvidia.com/gpu 资源。NodeResourcesFit 插件检查 requests 时,如果节点没有该资源类型,视为 0 容量,但某些版本中 0 容量的资源检查被跳过。
解决:
kubectl get pods -n kube-system | grep nvidiakubectl describe node <node> | grep -A5 AllocatablerequiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - key: nvidia.com/gpu.present, operator: In, values: ["true"]背景:3000 节点集群中,Pod 从创建到调度的延迟 P99 达到 45 秒。
诊断:
# 查看调度延迟指标
kubectl get --raw /metrics | grep scheduler_scheduling_latency_seconds
# scheduler_scheduling_latency_seconds{operation="filter",quantile="0.99"} 12.5
# scheduler_scheduling_latency_seconds{operation="score",quantile="0.99"} 28.3
# scheduler_scheduling_latency_seconds{operation="binding",quantile="0.99"} 3.2
# Score 阶段耗时 28s —— 主要瓶颈
# 原因:percentage-of-nodes-to-score=50%,对 1500 个节点评分
# 查看队列中的 Pod 数量
kubectl get --raw /metrics | grep scheduler_pending_pods
# scheduler_pending_pods{queue="active"} 45
# scheduler_pending_pods{queue="backoff"} 120
解决:将 --percentage-of-nodes-to-score 降为 10%,调度延迟 P99 从 45s 降至 8s。代价是评分只基于 300 个节点,可能不是全局最优,但对于大多数场景足够。
| 现象 | 诊断命令 | 可能根因 | 解决方案 |
|---|---|---|---|
| Pod 卡在 Pending | kubectl describe pod | 无可行节点/资源不足 | 检查事件、扩容节点 |
| Pod 调度到错误节点 | 检查调度器日志 | 插件配置错误/权重不当 | 调整插件权重和配置 |
| 调度延迟高 | 查看 scheduler_scheduling_latency | 节点多/Filter 慢 | 降低 nodes-to-score、增加并发 |
| 抢占不生效 | 检查 PriorityClass | 优先级未设置/PDB 阻止 | 设置 PriorityClass、检查 PDB |
| 多调度器冲突 | 检查 Pod schedulerName | 调度器未隔离 | 使用 nodeSelector 隔离 |
| 拓扑分布不均 | kubectl get pod -o wide | TopologySpread 配置不当 | 调整 maxSkew 和 topologyKey |
| 调度器选举失败 | 检查 Lease 对象 | 网络分区/apiserver 不可达 | 检查网络和 apiserver |
--percentage-of-nodes-to-score 参数如何影响调度质量和吞吐量的权衡?设为 10% 时,最坏情况下选中的节点与全局最优节点的分数差距有多大?| 核心知识点 | 掌握程度 | 验证方式 |
|---|---|---|
| 调度器内部架构与组件交互 | ☐ 了解 ☐ 理解 ☐ 精通 | 能画出组件交互图 |
| 调度周期与绑定周期的分离设计 | ☐ 了解 ☐ 理解 ☐ 精通 | 能解释各阶段职责 |
| Scheduling Framework 扩展点机制 | ☐ 了解 ☐ 理解 ☐ 精通 | 能画出扩展点执行顺序图 |
| Filter/Score 插件接口与实现 | ☐ 了解 ☐ 理解 ☐ 精通 | 能阅读内置插件源码 |
| NodeScore 算法(LeastAllocated 等) | ☐ 了解 ☐ 理解 ☐ 精通 | 能计算不同策略下的评分 |
| 自定义调度插件开发 | ☐ 了解 ☐ 理解 ☐ 精通 | 能开发并部署自定义插件 |
| 抢占调度与 PostFilter 机制 | ☐ 了解 ☐ 理解 ☐ 精通 | 能分析抢占时序 |
| 多调度器共存配置 | ☐ 了解 ☐ 理解 ☐ 精通 | 能配置多 Profile 调度器 |