如何为 controller-manager 开启 pprof 诊断?

解读

在国内生产环境中,controller-manager 作为 Kubernetes 控制面的“大脑”,一旦 CPU 异常飙高、goroutine 泄漏或内存暴涨,pprof 是最直接、最轻量的定位手段。面试官问“怎么开”,不只是考命令,而是看你是否:

  1. 知道官方二进制默认已内置 pprof 的 http 端点,只是默认监听在127.0.0.1:10257且未开启认证;
  2. 能否在不重启组件的前提下热开启;
  3. 是否了解安全合规(暴露 0.0.0.0 需经过堡垒机、SLB 白名单或 VPN);
  4. 能否把线上应急与日常巡检流程串起来。

知识点

  • pprof 端点路径:/debug/pprof,子路径包括 /debug/pprof/profile、/debug/pprof/heap、/debug/pprof/goroutine 等。
  • controller-manager 的默认 secure port:10257,证书由 kube-controller-manager 自身向 --client-ca-file 指定的 CA 申请。
  • 开启方式:
    • 静态:修改 /etc/kubernetes/manifests/kube-controller-manager.yaml 的 command 字段,加 --profiling=true --bind-address=0.0.0.0(或只改 --bind-address)。
    • 动态:对 static pod 而言,保存即生效,kubelet 会秒级重建容器。
  • 权限控制:10257 端口已启用 TLS + client cert auth,只有集群 CA 签发的证书或kube-controller-manager 自身证书才能访问,因此无需额外 RBAC。
  • 抓取命令:
    go tool pprof https://localhost:10257/debug/pprof/profile
    
    若 bind-address 为 127.0.0.1,需登录到 master 节点本地执行;若改为 0.0.0.0,可通过堡垒机转发。
  • 关闭:--profiling=false 或直接删除参数并重启容器。

答案

  1. 登录到 master 节点,备份静态 Pod 清单:
    cp /etc/kubernetes/manifests/kube-controller-manager.yaml /etc/kubernetes/manifests/kube-controller-manager.yaml.bak
    
  2. 编辑清单,在 spec.containers[0].command 末尾追加:
    --profiling=true
    --bind-address=0.0.0.0
    
    若仅本地诊断,可保留默认 --bind-address=127.0.0.1。
  3. 保存退出,kubelet 检测到文件变化后自动重建 Pod;确认容器已监听 10257:
    ss -lntp | grep 10257
    
  4. 使用 pprof 工具抓取 30 秒 CPU 样本:
    go tool pprof -seconds=30 https://<master-ip>:10257/debug/pprof/profile
    
    由于端口已启用双向 TLS,需带上 kube-controller-manager 的客户端证书:
    go tool pprof -seconds=30 \
      -tls_cert=/etc/kubernetes/pki/controller-manager.crt \
      -tls_key=/etc/kubernetes/pki/controller-manager.key \
      https://<master-ip>:10257/debug/pprof/profile
    
  5. 分析完成后,回滚配置或显式关闭 profiling:
    --profiling=false
    

拓展思考

  • 高并发场景:若 controller-manager 因 HPA 抖动或大量 CRD 控制器导致 goroutine 暴涨,可结合 curl -k --cert ... --key ... https://<ip>:10257/debug/pprof/goroutine?debug=2 | grep -c ^goroutine 做巡检脚本,超过阈值即告警。
  • 安全加固:在公有云环境,建议通过 kubectl port-forward 或 apiserver 聚合层暴露 pprof,避免直接把 10257 放到公网 SLB;也可使用 Ingress + OAuth2-Proxy 做二次认证。
  • 横向对比:scheduler 的 pprof 端口是 10259,apiserver 是 6443 下的 /debug/pprof,但 apiserver 需要集群管理员的 client 证书或system:masters 组权限,流程类似,可举一反三。
  • 性能基线:上线前在压测环境先跑一遍基线 profile,把 heap in-use 与 CPU flat 指标落到 Prometheus(通过 pprof_exporter),后续出现回归可秒级 diff。