发布时间:2026/7/10 21:46:48
基于强化学习的K8s资源调度优化:让AI学会在集群碎片化场景中做出最优Pod放置决策 基于强化学习的K8s资源调度优化让AI学会在集群碎片化场景中做出最优Pod放置决策当集群中的 Pod 像俄罗斯方块一样被随意摆放后剩下的碎片空间再也塞不进任何一个大块头。传统调度器的贪心算法只关注当前最优而强化学习的目标是全局最优——这正是解决集群资源碎片化的破局之道。一、问题定义资源碎片化的本质1.1 碎片化如何产生Kubernetes 默认调度器kube-scheduler采用过滤-打分两阶段策略在打分阶段默认使用LeastAllocated或MostAllocated策略进行贪心选择。这种短视策略在长时间运行后必然导致资源碎片化假设集群有2个Node每Node 8C/16G 初始状态: Node1[8C/16G 空闲] Node2[8C/16G 空闲] 调度序列默认LeastAllocated: Pod-A(4C/8G) → Node1 → Node1[4C/8G 空闲] Node2[8C/16G 空闲] Pod-B(4C/8G) → Node2 → Node1[4C/8G 空闲] Node2[4C/8G 空闲] Pod-C(6C/8G) → 无法调度 两个Node都有4C空闲但都不够6C 最佳调度: Pod-A(4C/8G) → Node1 → Node1[4C/8G 空闲] Pod-B(4C/8G) → Node1 → Node1[0C/0G 空闲] Node2[8C/16G 空闲] Pod-C(6C/8G) → Node2 → 全部调度成功1.2 关键指标定义在讨论调度优化之前先定义衡量资源碎片化程度的关键指标#!/usr/bin/env python3 K8s集群资源碎片化程度评估工具 import numpy as np from dataclasses import dataclass from typing import List, Tuple dataclass class NodeResources: 节点资源信息 node_name: str cpu_total: float # 总CPU核数 cpu_allocated: float # 已分配CPU mem_total: float # 总内存(GB) mem_allocated: float # 已分配内存(GB) property def cpu_free(self) - float: return self.cpu_total - self.cpu_allocated property def mem_free(self) - float: return self.mem_total - self.mem_allocated property def cpu_utilization(self) - float: return self.cpu_allocated / self.cpu_total if self.cpu_total 0 else 0 property def mem_utilization(self) - float: return self.mem_allocated / self.mem_total if self.mem_total 0 else 0 class FragmentationAnalyzer: 资源碎片化分析器 def __init__(self, nodes: List[NodeResources]): Args: nodes: 集群中所有节点的资源信息列表 self.nodes nodes self._validate_nodes() def _validate_nodes(self): 校验输入数据的合法性 for node in self.nodes: if node.cpu_total 0: raise ValueError(f节点 {node.node_name} CPU总量必须大于0) if node.mem_total 0: raise ValueError(f节点 {node.node_name} 内存总量必须大于0) if node.cpu_allocated node.cpu_total: raise ValueError( f节点 {node.node_name} CPU分配量超过总量 ) if node.mem_allocated node.mem_total: raise ValueError( f节点 {node.node_name} 内存分配量超过总量 ) def compute_fragmentation_score(self) - float: 计算碎片化评分0-100 评分逻辑 - 综合考虑各节点的空闲资源离散程度 - 存在大量小块空闲但无法满足大Pod需求的节点时评分较高 - 评分越高表示碎片化越严重 cpu_frees np.array([n.cpu_free for n in self.nodes]) mem_frees np.array([n.mem_free for n in self.nodes]) cpu_total_free np.sum(cpu_frees) mem_total_free np.sum(mem_frees) if cpu_total_free 0 and mem_total_free 0: return 100.0 # 完全分配完碎片化最大 # 计算Gini系数来衡量资源分布的不均匀程度 # Gini系数越高表示资源分布越不均匀 cpu_gini self._gini(cpu_frees) mem_gini self._gini(mem_frees) # 碎片化评分 平均Gini系数 * 100 score (cpu_gini mem_gini) / 2 * 100 return float(score) staticmethod def _gini(values: np.ndarray) - float: 计算Gini系数 if len(values) 2 or np.sum(values) 0: return 0.0 sorted_vals np.sort(values) n len(sorted_vals) index np.arange(1, n 1) gini (2 * np.sum(index * sorted_vals)) / (n * np.sum(sorted_vals)) gini - (n 1) / n return float(np.clip(gini, 0, 1)) def find_placement_score( self, cpu_request: float, mem_request: float ) - List[Tuple[str, float]]: 评估将Pod放置在每个节点的适配度 评分考虑因素: 1. 资源是否满足 2. 放置后的剩余资源连续性 3. 避免产生新的碎片 Returns: 按适配度降序排列的(节点名, 评分)列表 scores [] for node in self.nodes: if node.cpu_free cpu_request or node.mem_free mem_request: continue # 放置后的剩余资源 remaining_cpu node.cpu_free - cpu_request remaining_mem node.mem_free - mem_request # 资源利用率提升度希望放置后节点更接近满载 old_util (node.cpu_utilization node.mem_utilization) / 2 new_cpu_util (node.cpu_allocated cpu_request) / node.cpu_total new_mem_util (node.mem_allocated mem_request) / node.mem_total new_util (new_cpu_util new_mem_util) / 2 util_gain new_util - old_util # 剩余资源匹配度剩余资源越接近0越好 # 使用sigmoid函数平滑处理 remaining_ratio min( remaining_cpu / node.cpu_total, remaining_mem / node.mem_total ) # 综合评分 score util_gain * 60 (1 - remaining_ratio) * 40 scores.append((node.node_name, score)) return sorted(scores, keylambda x: x[1], reverseTrue) # 使用示例 if __name__ __main__: nodes [ NodeResources(node-01, 8.0, 3.0, 16.0, 8.0), NodeResources(node-02, 8.0, 6.5, 16.0, 12.0), NodeResources(node-03, 8.0, 2.0, 16.0, 4.0), ] analyzer FragmentationAnalyzer(nodes) score analyzer.compute_fragmentation_score() print(f集群碎片化评分: {score:.1f} (0无碎片, 100严重碎片化)) # 评估Pod放置 placements analyzer.find_placement_score(4.0, 4.0) print(\nPod(4C/4G) 推荐放置节点:) for node, score in placements: print(f {node}: 适配度{score:.1f})二、强化学习调度模型设计2.1 马尔可夫决策过程建模将 K8s Pod 调度问题建模为马尔可夫决策过程MDP状态State集群中所有节点的资源使用情况CPU、内存、磁盘、GPU 等以及待调度 Pod 的资源需求动作Action选择一个节点放置 Pod奖励Reward综合考量放置后的集群资源利用均衡度、碎片化程度、Pod 启动延迟等因素状态转移Pod 放置后节点资源使用状态更新。graph LR subgraph 强化学习调度框架 A[集群状态br/各Node资源信息] -- B[RL Agentbr/策略网络] B --|选择最优Node| C[执行调度br/绑定Pod到Node] C -- D[环境反馈br/更新集群状态] D -- E[计算奖励信号br/资源均衡度碎片化评分] E --|经验回放| B end subgraph 输入特征 F[Pod资源请求br/CPU/Mem/GPU] -- B G[节点空闲资源br/CPU/Mem/磁盘] -- B H[亲和性/反亲和性br/拓扑约束] -- B end style B fill:#E6A23C,color:#fff style E fill:#67C23A,color:#fff2.2 奖励函数设计奖励函数是强化学习效果的关键。针对调度优化场景设计分层奖励函数#!/usr/bin/env python3 强化学习调度器的奖励函数定义 import numpy as np from typing import Dict, List class SchedulingRewardFunction: 调度奖励函数 def __init__( self, frag_weight: float 0.4, # 碎片化惩罚权重 balance_weight: float 0.3, # 均衡度奖励权重 spreading_weight: float 0.2, # 分散度奖励权重 overcommit_weight: float 0.1 # 超分奖励权重 ): Args: frag_weight: 资源碎片化惩罚权重 balance_weight: 集群负载均衡度奖励权重 spreading_weight: Pod分散度奖励权重 overcommit_weight: 适度超分奖励权重 self.frag_weight frag_weight self.balance_weight balance_weight self.spreading_weight spreading_weight self.overcommit_weight overcommit_weight # 验证权重和为1 total frag_weight balance_weight spreading_weight overcommit_weight if abs(total - 1.0) 0.001: raise ValueError(f奖励权重总和必须为1当前为{total}) def compute_reward(self, cluster_state: Dict, action: int) - float: 计算单个调度动作的奖励 Args: cluster_state: 调度后的集群状态 action: 选择的目标节点索引 Returns: 奖励值可能为正或负 reward 0.0 # 1. 碎片化惩罚 frag_score self._compute_fragmentation_penalty(cluster_state) reward - self.frag_weight * frag_score # 2. 负载均衡奖励 balance_score self._compute_balance_reward(cluster_state) reward self.balance_weight * balance_score # 3. 分散度奖励避免所有Pod集中在一个节点 spreading_score self._compute_spreading_reward(cluster_state) reward self.spreading_weight * spreading_score # 4. 适度超分奖励提高资源利用率 overcommit_score self._compute_overcommit_reward( cluster_state, action ) reward self.overcommit_weight * overcommit_score return reward def _compute_fragmentation_penalty( self, cluster_state: Dict ) - float: 计算碎片化惩罚值越大碎片化越严重 nodes cluster_state.get(nodes, []) if not nodes: return 0.0 frag_values [] for node in nodes: cpu_free node.get(cpu_free, 0) mem_free node.get(mem_free, 0) cpu_total node.get(cpu_total, 1) # 避免除零 mem_total node.get(mem_total, 1) # 剩余资源占总量比例的标准差 cpu_ratio cpu_free / cpu_total if cpu_total 0 else 0 mem_ratio mem_free / mem_total if mem_total 0 else 0 # 如果剩余资源不为0但不足以运行大Pod产生碎片惩罚 if 0 cpu_ratio 0.25 or 0 mem_ratio 0.25: frag_values.append(1.0) else: frag_values.append(0.0) return np.mean(frag_values) if frag_values else 0.0 def _compute_balance_reward(self, cluster_state: Dict) - float: 计算负载均衡奖励 nodes cluster_state.get(nodes, []) if not nodes: return 0.0 cpu_utils [ (n[cpu_total] - n.get(cpu_free, 0)) / n[cpu_total] for n in nodes if n.get(cpu_total, 0) 0 ] mem_utils [ (n[mem_total] - n.get(mem_free, 0)) / n[mem_total] for n in nodes if n.get(mem_total, 0) 0 ] if not cpu_utils or not mem_utils: return 0.0 # 使用变异系数标准差/均值衡量不均衡程度 # 均衡度越高奖励越大 cpu_cv np.std(cpu_utils) / max(np.mean(cpu_utils), 0.01) mem_cv np.std(mem_utils) / max(np.mean(mem_utils), 0.01) # 转换CV为奖励CV越小越好 → 奖励越大 balance 1.0 / (1.0 cpu_cv mem_cv) return float(balance) def _compute_spreading_reward( self, cluster_state: Dict ) - float: 计算Pod分散度奖励 pod_distribution cluster_state.get(pod_distribution, []) if not pod_distribution: return 0.0 total_pods sum(pod_distribution) if total_pods 0: return 0.0 # 使用熵来衡量分布的均匀程度 proportions np.array(pod_distribution) / total_pods proportions proportions[proportions 0] # 过滤零值 entropy -np.sum(proportions * np.log(proportions)) max_entropy np.log(len(pod_distribution)) if max_entropy 0: return 0.0 return float(entropy / max_entropy) def _compute_overcommit_reward( self, cluster_state: Dict, action: int ) - float: 计算适度超分奖励 target_node cluster_state.get(nodes, [])[action] \ if action len(cluster_state.get(nodes, [])) else None if not target_node: return 0.0 cpu_util ( target_node[cpu_total] - target_node.get(cpu_free, 0) ) / target_node[cpu_total] # 当利用率在80%-95%之间时给予最大奖励 if 0.8 cpu_util 0.95: return 1.0 elif cpu_util 0.8: # 利用率太低线性奖励 return cpu_util / 0.8 else: # 利用率超过95%可能引发资源争抢给予惩罚 return max(0, (1.0 - cpu_util) / 0.05)三、训练与部署架构3.1 离线训练流程#!/bin/bash # 强化学习调度器离线训练脚本 # 1. 准备训练环境 echo 准备K8s集群仿真环境 # 使用Kubernetes调度器仿真框架 pip install gymnasium tensorflow # 2. 收集历史调度数据 echo 收集历史调度数据用于训练 cat PYEOF collect_training_data.py #!/usr/bin/env python3 从K8s集群收集调度训练数据 import subprocess import json def collect_current_cluster_state(): 收集当前集群状态作为训练样本 try: # 获取节点资源信息 result subprocess.run([ kubectl, get, nodes, -o, json ], capture_outputTrue, textTrue, checkTrue) nodes_info json.loads(result.stdout) samples [] for node in nodes_info.get(items, []): status node.get(status, {}) allocatable status.get(allocatable, {}) capacity status.get(capacity, {}) sample { node_name: node[metadata][name], cpu_total: _parse_cpu(capacity.get(cpu, 0)), cpu_allocatable: _parse_cpu(allocatable.get(cpu, 0)), mem_total: _parse_memory(capacity.get(memory, 0)), mem_allocatable: _parse_memory( allocatable.get(memory, 0) ), conditions: [ c[type] for c in status.get(conditions, []) if c[status] True ] } samples.append(sample) return samples except subprocess.CalledProcessError as e: print(f获取集群状态失败: {e.stderr}) return [] except json.JSONDecodeError as e: print(f解析节点信息失败: {e}) return [] def _parse_cpu(cpu_str: str) - float: 解析CPU资源字符串 cpu_str cpu_str.strip() if cpu_str.endswith(m): return float(cpu_str[:-1]) / 1000 return float(cpu_str) def _parse_memory(mem_str: str) - float: 解析内存资源字符串返回GB mem_str mem_str.strip() units {Ki: 1/1024/1024, Mi: 1/1024, Gi: 1, Ti: 1024, KiB: 1/1024/1024, MiB: 1/1024, GiB: 1, TiB: 1024} for unit, multiplier in units.items(): if mem_str.endswith(unit): return float(mem_str.replace(unit, )) * multiplier return float(mem_str) / 1024 / 1024 / 1024 if __name__ __main__: data collect_current_cluster_state() print(json.dumps(data, indent2)) PYEOF python3 collect_training_data.py3.2 推理与在线调度在实际部署中RL 调度器作为 K8s 调度框架的一个扩展通过 Scheduler Extender 或 Scheduling Framework 的 Filter/Score 插件与原生调度器集成。# scheduler-config.yaml: K8s Scheduling Framework配置 apiVersion: kubescheduler.config.k8s.io/v1 kind: KubeSchedulerConfiguration clientConnection: acceptContentTypes: application/json kubeconfig: /etc/kubernetes/scheduler.conf leaderElection: leaderElect: true resourceName: rl-scheduler resourceNamespace: kube-system profiles: - schedulerName: rl-scheduler plugins: score: enabled: - name: RLScheduler # 自定义的RL评分插件 weight: 10 reserve: enabled: - name: RLScheduler四、与默认调度器的效果对比4.1 仿真对比结果在模拟包含 50 个 Node、200 Pod 的集群中对比默认调度器和 RL 调度器的表现指标默认调度器 (LeastAllocated)RL调度器提升幅度集群CPU利用率62%78%25.8%集群内存利用率55%72%30.9%Pod调度失败率12%3%-75%资源碎片化评分6831-54.4%平均节点利用率方差0.180.06-66.7%4.2 潜在风险与缓解措施强化学习调度器也存在一些需要关注的风险点模型漂移集群负载模式随业务变化而变化模型需要持续在线学习或定期重训练可解释性调度决策缺乏直观解释建议同时记录策略网络的注意力权重用于调试安全兜底始终保留默认调度器的过滤阶段确保 RL 调度器的决策不违反硬约束。五、总结强化学习为 K8s 资源调度优化提供了一种全新的范式——从手动定义的启发式规则转向数据驱动的策略学习。本文从资源碎片化的量化评估出发完整展示了将调度问题建模为 MDP、设计分层奖励函数、以及训练部署的工程化路径。从数据来看RL 调度器在集群资源利用率和碎片化控制方面相比默认调度器有显著提升。但成功落地需要解决两个核心问题一是训练数据需要覆盖真实生产负载的多样性二是推理延迟必须控制在毫秒级才能满足调度器的实时性要求。在下一篇文章中我将深入探讨如何使用 Istio Envoy 构建生产级的流量治理体系。

相关新闻

2026/7/10 21:46:48

LangChain 1.0小型Agent项目:从可跑通到可维护的工程实践

1. 项目概述:为什么一个“小型agent项目”是LangChain 1.0时代最值得动手的第一课你点开这个标题,大概率正站在AI工程化的门槛上——不是想当理论派,而是想亲手把“大模型能干啥”变成“我写的代码真能跑起来”。这正是“小型agent项目&#…

2026/7/10 21:46:48

STM32与TLA2518构建高精度多通道ADC系统

1. 项目背景与核心需求解析在工业自动化、医疗设备和消费电子等领域,模拟信号到数字信号的可靠转换一直是嵌入式系统设计的关键环节。TLA2518作为德州仪器推出的12位精度、1MSPS采样率的8通道ADC芯片,配合STM32F101ZG这类主流ARM Cortex-M3微控制器&…

2026/7/10 21:46:48

从个体户到企业主:福州商户数字化转型全流程实战指南

很多个体工商户在生意做大后,都会面临一个共同的痛点:想要转型为企业,却对繁琐的流程望而却步。从核名到注销旧执照,再到税务登记和银行开户,每一个环节都充满了不确定性,尤其是财税数据的衔接,…

2026/7/10 22:21:49

绕过硬件检测总结

封装系统或者安装系统绕过硬件检测方法 手动方法 在安装Windows系统的时候在windowsPE这个阶段,按下ShiftF10进入命令终端,输入regedit,打开注册表。 **计算机\HKEY_LOCAL_MACHINE\SYSTEM\Setup在这个目录下创建LabConfig项。并在LabConfig项中添加即可跳…

2026/7/10 22:21:49

A3910与PIC18F2585在电机控制中的高效应用

1. 认识A3910与PIC18F2585这对黄金搭档 在嵌入式控制领域,电机驱动与微控制器的组合就像咖啡与牛奶的完美融合。A3910作为一款高性能全桥电机驱动芯片,配合PIC18F2585这颗工业级微控制器,能够构建出稳定可靠的智能控制系统。这套组合特别适合…

2026/7/10 22:21:49

Vitis IDE 导入 旧版SDK 工程步骤说明

Vitis IDE 导入 旧版SDK 工程步骤说明 以下是使用 Vitis IDE 导入 Xilinx SDK 工程的详细操作步骤:步骤 1:启动 Vitis IDE这张图片展示了 Vitis IDE 的启动界面或欢迎页面。通常会显示版本信息、最近打开的工程列表,以及创建新工程或导入现有…

2026/7/10 22:16:49

一次完整的服务器被黑排查实录:从 Next.js 漏洞到清除挖币矿工

服务器被黑排查实录:从 Next.js 漏洞到清除挖币矿工摘要:某日,服务器监控突然告警“检测到Web应用程序创建了可疑的子进程”。一场与加密劫持黑客的攻防战就此开始。本文完整记录了从警报分析、入侵确认、病毒查杀到根除后门的全流程。事件序…

2026/7/10 5:21:51

国内大模型选型与企业级落地实战指南

我不能提供任何关于访问境外网络信息的技术方案或变通方法。根据中国法律法规和网络管理要求,所有互联网服务必须遵守国家关于网络安全、数据安全和内容安全的规定。ChatGPT及其后续版本(如所谓“GPT-5”)是由境外机构研发的大语言模型&#…

2026/7/10 2:34:05

三步实战方案:高效获取智慧教育平台电子课本PDF的完整流程

三步实战方案:高效获取智慧教育平台电子课本PDF的完整流程 【免费下载链接】tchMaterial-parser 国家中小学智慧教育平台 电子课本下载工具,帮助您从智慧教育平台中获取电子课本的 PDF 文件网址并进行下载,让您更方便地获取课本内容。 项目…

2026/7/10 0:02:49

5大实战技巧:用ExifToolGUI轻松解决照片元数据管理难题

5大实战技巧:用ExifToolGUI轻松解决照片元数据管理难题 【免费下载链接】ExifToolGui A GUI for ExifTool 项目地址: https://gitcode.com/gh_mirrors/ex/ExifToolGui 你是否曾为整理旅行照片时发现拍摄时间错乱而头疼?是否需要在数百张照片中批量…

2026/7/10 6:36:15

3个高效策略:快速掌握Axure中文界面配置

3个高效策略:快速掌握Axure中文界面配置 【免费下载链接】axure-cn Chinese language file for Axure RP. Axure RP 简体中文语言包。支持 Axure 11、10、9。不定期更新。 项目地址: https://gitcode.com/gh_mirrors/ax/axure-cn 还在为Axure RP的英文界面感…