Kubernetes 高级工程师教程

第9章 调度器插件框架与自定义调度策略

从调度器的调度周期(Scheduling Cycle)与绑定周期(Binding Cycle)出发,深入解析 Scheduling Framework 的扩展点机制、Filter/Score/Bind 插件接口、NodeScore 算法实现,掌握自定义调度插件的开发方法与多调度器共存的生产实践。

系列 Kubernetes 高级工程师教程 篇章 核心内幕篇 章节 第9章 / 共46章 难度 ★★★★★ 预计阅读 58分钟 前置知识 调度基本概念、Go插件机制、k8s调度策略

9.1 调度器整体架构

Kubernetes 调度器(kube-scheduler)是控制平面中最计算密集的组件。它的核心职责是为新创建的 Pod 选择一个最佳节点。调度决策涉及资源匹配、亲和性约束、拓扑分布、数据局部性等多个维度,每个维度由一个或多个插件实现。理解调度器的架构是进行调度调优和自定义调度策略的基础。

1.1 调度器的两种运行模式

kube-scheduler 支持两种运行模式:

模式配置方式特点适用场景
默认模式命令行参数使用内置所有插件,按默认配置运行标准集群、快速部署
多调度器模式KubeSchedulerConfiguration自定义插件启停、权重、profile多租户、特殊调度需求

1.2 调度器的内部组件

SchedulerCache

pkg/internal/cache

调度器的本地缓存,维护节点信息(NodeInfo)、Pod 信息、镜像信息等。通过 Informer 从 apiserver 同步,为调度计算提供快速数据访问。

Framework

pkg/scheduler/framework

调度框架,管理所有插件的注册和执行。定义了调度周期的扩展点(Extension Points),插件按注册顺序在各扩展点执行。

PodQueue

pkg/internal/queue

待调度 Pod 的优先级队列。按 PriorityClass 排序,高优先级 Pod 先调度。支持主动排队(BackoffQ)和不可调度队列(UnschedulableQ)。

Binder

pkg/scheduler/framework

执行 Pod 到 Node 的绑定操作。通过更新 Pod.Spec.NodeName 或创建 Binding 对象实现。绑定是调度周期中唯一修改集群状态的操作。

VolumeBinder

pkg/scheduler/framework/plugins/volumebinding

处理存储卷绑定。在 Filter 阶段检查 PV/PVC 兼容性,在 Reserve 阶段预留存储资源,在 Bind 阶段完成 PVC 绑定。

Profile

pkg/scheduler/profile

调度配置档案。一个调度器可以运行多个 Profile,每个 Profile 有独立的插件配置,通过 schedulerName 字段选择使用哪个 Profile。

1.3 调度器的启动流程

Go · 调度器启动流程
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)
    }
}

9.2 调度周期与绑定周期

调度器的核心是 scheduleOne 函数,它处理一个 Pod 的完整调度流程。这个流程分为两个阶段:调度周期(Scheduling Cycle)和绑定周期(Binding Cycle)。

2.1 scheduleOne 的完整流程

Go · scheduleOne 核心流程
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——等待最终确认后才正式签约。

2.2 调度周期与绑定周期的分离

调度周期和绑定周期的分离是一个关键设计:

特性调度周期(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 机制缓解此问题,但不能完全避免。

9.3 Scheduling Framework 扩展点机制

Scheduling Framework 是 Kubernetes 1.19+ 引入的调度器扩展机制,取代了旧的 scheduler extender(HTTP 回调)方式。Framework 定义了一组扩展点(Extension Points),开发者可以在这些扩展点插入自定义逻辑。

3.1 扩展点全景图

Scheduling Framework 扩展点执行顺序 Pod 进入调度队列 │ ▼ [SortQueue] ← 排序插件:决定队列中 Pod 的优先级 │ ▼ === 调度周期 === │ ├─ [PreFilter] ← 前置过滤:检查 Pod 基本条件 │ (如 Pod 是否有合法的 NodeSelector) │ ├─ [Filter] ← 过滤节点:逐节点检查是否可调度 │ (如资源是否充足、Taint/Toleration 是否匹配) │ ├─ [PostFilter] ← 过滤后补救:无可行节点时的补救措施 │ (如抢占 Preemption) │ ├─ [PreScore] ← 评分前准备:为 Score 阶段准备共享状态 │ ├─ [Score] ← 节点评分:对每个可行节点打分(0-100) │ (如资源均衡度、亲和性匹配度) │ ├─ [NormalizeScore] ← 分数归一化:将各插件分数统一到 0-100 │ ▼ 选出最佳节点 │ ├─ [Reserve] ← 资源预留:在缓存中临时预留节点资源 │ ▼ === 绑定周期 === │ ├─ [Permit] ← 许可检查:可延迟绑定(等待外部条件) │ ├─ [PreBind] ← 绑定前准备:如 Volume 绑定 │ ├─ [Bind] ← 执行绑定:设置 Pod.Spec.NodeName │ ├─ [PostBind] ← 绑定后处理:清理和通知 │ ▼ Pod 绑定完成

3.2 插件接口定义

每个扩展点对应一个 Go 接口,自定义插件只需实现相应接口:

Go · Framework 插件接口定义
// 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
}

3.3 内置插件清单

插件名扩展点默认启用功能关键参数
NodeUnschedulableFilter是排除 Unschedulable 节点无
NodeNameFilter是匹配 spec.nodeName无
TaintTolerationFilter+Score是Taint/Toleration 匹配权重可配置
NodeAffinityFilter+Score是节点亲和性无
PodAffinityFilter+Score是Pod 亲和/反亲和无
NodeResourcesFitFilter+Score是资源请求检查与评分scoringStrategy
NodePortsFilter是端口冲突检查无
VolumeBindingFilter+Reserve+Bind是PVC/PV 绑定bindMode
VolumeRestrictionsFilter是卷访问模式限制无
ImageLocalityScore否镜像本地性评分需手动启用
InterPodAffinityFilter+Score是Pod 间亲和性无
DefaultBinderBind是默认绑定逻辑无
NodeVolumeLimitsFilter是节点卷数量限制无
PodTopologySpreadFilter+Score是拓扑分布约束无
DefaultPreemptionPostFilter是默认抢占逻辑无

9.4 Filter 插件源码解析

Filter 阶段是调度周期中最耗时的部分——它需要对每个候选节点执行所有 Filter 插件。在大规模集群中,节点数量可能达到数千,Filter 的效率直接决定调度吞吐量。

4.1 findNodesThatFitPod 的并行过滤

Go · 并行 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 通过
}

4.2 NodeResourcesFit 插件源码

NodeResourcesFit 是最核心的 Filter 插件,检查节点是否有足够资源运行 Pod:

Go · NodeResourcesFit Filter 实现
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 比值控制的

4.3 TaintToleration 插件源码

Go · TaintToleration Filter 实现
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
}

9.5 Score 插件与 NodeScore 算法

Score 阶段对通过 Filter 的候选节点进行评分,最终选择得分最高的节点。每个 Score 插件从不同维度评分,最终分数是各插件分数的加权平均。

5.1 prioritizeNodes 的评分流程

Go · prioritizeNodes 评分流程
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
}

5.2 NodeResourcesFit 的评分策略

NodeResourcesFit 插件支持多种评分策略:

Go · NodeResourcesFit Score 实现
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自定义函数精细控制多资源权重调整

5.3 PodTopologySpread 插件

PodTopologySpread 实现 Pod 的拓扑分布约束(TopologySpreadConstraints),确保 Pod 在指定的拓扑域(如 zone、node)中均匀分布:

Go · PodTopologySpread Score 实现(简化)
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
}

9.6 自定义调度插件开发

当内置插件无法满足业务需求时,可以通过编写自定义调度插件来扩展调度器。自定义插件需要编译到调度器二进制中(通过 Go 的 init() 注册机制),或者通过 out-of-tree 插件方式运行。

6.1 自定义插件示例:GPU 拓感知调度

假设我们需要一个插件,根据 Pod 对 GPU 型号的偏好选择节点(如优先选择有 A100 的节点):

Go · 自定义 Score 插件
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,  // 插件权重
    ))
}

6.2 调度器配置

自定义插件需要在 KubeSchedulerConfiguration 中启用:

YAML · 调度器配置
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"

6.3 Out-of-Tree 插件开发

如果不想修改调度器源码,可以使用 scheduler-plugins 项目(sigs.k8s.io/scheduler-plugins)开发 out-of-tree 插件:

Bash · 使用 scheduler-plugins 项目
# 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 <

9.7 抢占调度与 PostFilter 机制

当高优先级 Pod 无法找到可行节点时,调度器可以通过抢占(Preemption)机制驱逐低优先级 Pod,为高优先级 Pod 腾出资源。抢占逻辑由 PostFilter 扩展点的 DefaultPreemption 插件实现。

7.1 抢占的触发条件

抢占只在以下条件同时满足时触发:

  • Pod 的 spec.priorityClassName 指向一个 PriorityClass,且 value > 0
  • Filter 阶段没有找到任何可行节点
  • 被抢占的 Pod 的优先级低于当前 Pod
  • 被抢占的 Pod 没有设置 podDisruptionBudget 或 PDB 允许
  • 抢占后,高优先级 Pod 能通过所有 Filter 插件

7.2 DefaultPreemption 的执行流程

Go · DefaultPreemption PostFilter 实现(简化)
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
}

7.3 NominatedNodeName 机制

抢占成功后,被抢占的 Pod 尚未真正退出(需要等待 graceful shutdown)。调度器通过 pod.Status.NominatedNodeName 记录抢占选中的节点:

抢占后的调度时序 T+0s: 高优先级 Pod 无法调度,触发抢占 T+0s: 调度器选中 Node-A,驱逐低优先级 Pod-X T+0s: 设置 Pod.Status.NominatedNodeName = "node-a" T+0s: 高优先级 Pod 重新入队 T+0s: Pod-X 收到 SIGTERM,开始 graceful shutdown(默认 30s) T+1s: 调度器再次尝试调度高优先级 Pod - Filter 阶段:Node-A 仍被 Pod-X 占用(资源未释放) - 但 NominatedNodeName="node-a",调度器优先检查此节点 - 如果仍不可行,Pod 重新入队等待 T+30s: Pod-X 完全退出,资源释放 T+31s: 调度器再次尝试调度高优先级 Pod - Filter 阶段:Node-A 现在有足够资源 - Pod 被调度到 Node-A

9.8 多调度器共存与调度器配置

在一个集群中可以运行多个调度器,每个 Pod 通过 spec.schedulerName 指定使用哪个调度器。这在多租户环境或特殊工作负载场景中很有用。

8.1 多调度器配置示例

YAML · 多 Profile 调度器配置
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        # 紧凑放置策略

8.2 调度器隔离的注意事项

⚠️ 多调度器的资源竞争

多个调度器在同一集群中运行时,可能产生资源竞争:两个调度器可能同时将 Pod 调度到同一节点,导致资源超额分配。这是因为每个调度器只维护自己的缓存视图,不感知其他调度器的决策。缓解措施:

1. 通过 nodeSelector 或 nodeAffinity 将不同调度器的 Pod 限制到不同节点池
2. 使用 schedulingGates(K8s 1.26+)控制 Pod 何时进入调度
3. 为每个调度器设置独立的 --leader-elect-resource-name 避免选举冲突

8.3 调度器关键参数速查

kube-scheduler 关键参数速查
参数默认值影响调优建议
--concurrent-scheduler-syncs1并发调度数大规模集群设 2-4
--percentage-of-nodes-to-score50(大集群)评分节点比例大集群降低以提升吞吐
--pod-max-backoff-seconds10sPod 最大退避时间影响重试频率
--pod-initial-backoff-seconds1sPod 初始退避影响首次重试延迟
--leader-elect-renew-deadline10s选举续租截止影响故障切换速度
--profilingtrue是否启用 pprof生产可关闭

9.9 动手实验:开发并部署自定义调度插件

本实验开发一个 NetworkAware 调度插件,根据节点的网络延迟(通过节点标签标注)选择网络延迟最低的节点。

Step 1:初始化插件项目

Bash
# 使用 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    # 默认值

Step 2:实现插件

Go · pkg/networkaware/plugin.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
}

Step 3:注册并构建调度器

Go · cmd/scheduler/main.go
func main() {
    // 注册内置插件
    app.RegisterAllPlugins()
    
    // 注册自定义插件
    app.WithPlugin(networkaware.Name, networkaware.New)
    
    // 启动调度器
    command := app.NewSchedulerCommand()
    code := cli.Run(command)
    os.Exit(code)
}
Bash
# 构建调度器镜像
make scheduler-image IMG=network-aware-scheduler:latest

# 部署调度器
kubectl apply -f manifests/network-aware-scheduler.yaml

Step 4:测试自定义调度

Bash
# 为节点标注网络延迟
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 <

9.10 生产案例与排障

10.1 案例:GPU Pod 调度到无 GPU 节点

背景:某 ML 平台中,需要 GPU 的 Pod 被调度到没有 GPU 的节点,导致 Pod 启动失败。

根因:节点未正确标注 GPU 资源。nvidia device plugin 未正常运行,节点 Allocatable 中没有 nvidia.com/gpu 资源。NodeResourcesFit 插件检查 requests 时,如果节点没有该资源类型,视为 0 容量,但某些版本中 0 容量的资源检查被跳过。

解决:

  • 确保 nvidia device plugin 正常运行:kubectl get pods -n kube-system | grep nvidia
  • 验证节点资源:kubectl describe node <node> | grep -A5 Allocatable
  • 添加 NodeAffinity 作为双重保险:requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - key: nvidia.com/gpu.present, operator: In, values: ["true"]

10.2 案例:调度延迟过高导致服务降级

背景:3000 节点集群中,Pod 从创建到调度的延迟 P99 达到 45 秒。

诊断:

Bash · 诊断命令
# 查看调度延迟指标
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 个节点,可能不是全局最优,但对于大多数场景足够。

10.3 排障指南速查

调度器排障速查表
现象诊断命令可能根因解决方案
Pod 卡在 Pendingkubectl describe pod无可行节点/资源不足检查事件、扩容节点
Pod 调度到错误节点检查调度器日志插件配置错误/权重不当调整插件权重和配置
调度延迟高查看 scheduler_scheduling_latency节点多/Filter 慢降低 nodes-to-score、增加并发
抢占不生效检查 PriorityClass优先级未设置/PDB 阻止设置 PriorityClass、检查 PDB
多调度器冲突检查 Pod schedulerName调度器未隔离使用 nodeSelector 隔离
拓扑分布不均kubectl get pod -o wideTopologySpread 配置不当调整 maxSkew 和 topologyKey
调度器选举失败检查 Lease 对象网络分区/apiserver 不可达检查网络和 apiserver

9.11 章末思考题与知识检查

思考题

  1. 原理题:调度周期和绑定周期为什么需要分离?如果将绑定操作放在调度周期内同步执行,会有什么问题?从并发性和性能两个角度分析。
  2. 原理题:NodeResourcesFit 的 LeastAllocated 和 MostAllocated 策略分别适合什么场景?在一个需要频繁扩缩容的弹性集群中,应该选择哪种策略?为什么?
  3. 实操题:编写一个自定义 Score 插件,优先选择当前时间负载最低的节点(通过从 Prometheus 查询节点实时 CPU 利用率)。需要考虑哪些工程问题(缓存、超时、错误处理)?
  4. 原理题:抢占调度中,NominatedNodeName 机制的作用是什么?如果被抢占的 Pod 在 graceful shutdown 期间释放了资源,但高优先级 Pod 尚未被重新调度,另一个 Pod 抢占了同一节点,会发生什么?
  5. 设计题:在一个多租户集群中,不同租户对调度有不同的需求(租户 A 需要低延迟、租户 B 需要成本最低、租户 C 需要 GPU 感知)。设计一个多调度器方案,包括调度器配置、节点隔离策略和 Pod 模板。
  6. 原理题:--percentage-of-nodes-to-score 参数如何影响调度质量和吞吐量的权衡?设为 10% 时,最坏情况下选中的节点与全局最优节点的分数差距有多大?
  7. 实操题:给定一个 Pod 卡在 Pending 状态,写出完整的诊断命令序列,从 Pod 事件到调度器日志到节点资源检查,覆盖所有可能的原因。

知识点检查表

核心知识点掌握程度验证方式
调度器内部架构与组件交互☐ 了解 ☐ 理解 ☐ 精通能画出组件交互图
调度周期与绑定周期的分离设计☐ 了解 ☐ 理解 ☐ 精通能解释各阶段职责
Scheduling Framework 扩展点机制☐ 了解 ☐ 理解 ☐ 精通能画出扩展点执行顺序图
Filter/Score 插件接口与实现☐ 了解 ☐ 理解 ☐ 精通能阅读内置插件源码
NodeScore 算法(LeastAllocated 等)☐ 了解 ☐ 理解 ☐ 精通能计算不同策略下的评分
自定义调度插件开发☐ 了解 ☐ 理解 ☐ 精通能开发并部署自定义插件
抢占调度与 PostFilter 机制☐ 了解 ☐ 理解 ☐ 精通能分析抢占时序
多调度器共存配置☐ 了解 ☐ 理解 ☐ 精通能配置多 Profile 调度器