← 中文资源

简体中文版本

在节点容量内放置 Pod

把 Pod 贪心地放到 CPU 与内存足够可分配的节点上,报告哪些 Pod 无法调度以及各节点的用量。

阅读英文原文

任务

按输入顺序逐个尝试放置,必须同时满足 CPU 与内存,放置后累加节点用量,未能放置的记入 unschedulable。

契约

  • 输入:JSON 对象:{ nodes: [{ name, allocatableCpu, allocatableMem }], pods: [{ name, cpu, mem }] }
  • 输出:JSON 对象:{ unschedulable: string[], used: [{ name, cpuUsed, memUsed }] }

样例

  1. 输入 {"nodes":[{"name":"n1","allocatableCpu":2,"allocatableMem":4096}],"pods":[{"name":"api","cpu":1,"mem":1024},{"name":"worker","cpu":1.5,"mem":2048}]} -> 期望 {"unschedulable":["worker"],"used":[{"name":"n1","cpuUsed":1,"memUsed":1024}]}。worker 需要的 CPU 超过了放置 api 之后的余量。
  2. 输入 {"nodes":[{"name":"n1","allocatableCpu":2,"allocatableMem":4096},{"name":"n2","allocatableCpu":2,"allocatableMem":4096}],"pods":[{"name":"api","cpu":1,"mem":1024},{"name":"worker","cpu":1.5,"mem":2048}]} -> 期望 {"unschedulable":[],"used":[{"name":"n1","cpuUsed":1,"memUsed":1024},{"name":"n2","cpuUsed":1.5,"memUsed":2048}]}。两个节点足以容纳两个 Pod。

参考实现

function solve({ nodes, pods }) {
      const remaining = nodes.map((n) => ({ name: n.name, cpu: n.allocatableCpu, mem: n.allocatableMem }));
      const unschedulable = [];
      for (const pod of pods) {
        const target = remaining.find((n) => n.cpu >= pod.cpu && n.mem >= pod.mem);
        if (!target) {
          unschedulable.push(pod.name);
          continue;
        }
        target.cpu -= pod.cpu;
        target.mem -= pod.mem;
      }
      const used = nodes.map((n, i) => ({
        name: n.name,
        cpuUsed: +(n.allocatableCpu - remaining[i].cpu).toFixed(2),
        memUsed: n.allocatableMem - remaining[i].mem,
      }));
      return { unschedulable, used };
    }

为什么有效

Pod 无法调度通常是容量记账问题,而不是调度器缺陷。确定性地算出放置结果,能把“真的满了”与“请求配置错了”区分开。

Pod 必须在同一节点上同时满足 CPU 与内存;只满足一项不算放置成功。