在 Kubernetes 部署 Grid 4 时,如何设置 HPA 根据队列长度自动扩容 Chrome 节点?
解读
面试官真正想验证的是:
- 你是否理解 Selenium Grid 4 的事件驱动架构(Router-Queue-Node 模型);
- 能否把“队列长度”这一 业务指标 转换成 Kubernetes 可识别的 自定义指标;
- 是否熟悉 国内主流云厂商(阿里云 ACK、腾讯云 TKE、华为云 CCE)对 Custom Metrics API 的合规实现;
- 能否给出 可落地的灰度发布与成本控制方案,而不是照搬官方 Demo。
知识点
- Grid 4 队列本质:Router 内存中的
NewSessionQueue,通过/se/grid/newsessionqueue/queue暴露长度。 - 自定义指标链路:
Grid Exporter → Prometheus → Prometheus Adapter → Custom Metrics API → HPA v2。 - 国内合规细节:
- 阿里云 ACK 需开启 arms-prometheus,并授权 RAM 角色 允许 adapter 访问 sls 指标;
- 腾讯云 TKE 使用 云原生监控(TMP),需把 exporter 打成 qci.io 镜像仓库地址;
- 华为云 CCE 需关闭 Istio 自动注入,否则 adapter 注册失败。
- HPA 对象关键字段:
metrics.type=Objectobject.metric.name=selenium_grid_session_queue_sizetarget.type=Value且 target.averageValue 而非 averageUtilization(队列长度是绝对值)。
- 扩容边界:
- 设置 maxReplicas ≤ 节点池最大可用弹性 IP 数,防止国内 VPC 私网 IP 耗尽;
- 配合 cluster-autoscaler 的 priority expander,优先弹出 包年包月 节点,降低按量成本。
答案
- 构建镜像:官方镜像
selenium/node-chrome已带/se/node/status探针,只需再打一个 sidecar exporter 容器,每 5 s 调用http://localhost:5555/se/grid/newsessionqueue/queue并把长度写成 Prometheus 格式 暴露在:8080/metrics。 - 部署 Prometheus Adapter:
- 使用国内源镜像
registry.cn-hangzhou.aliyuncs.com/acs/metrics-adapter:v0.10.0; - 在 ConfigMap 中新增一条规则:
- seriesQuery: 'selenium_grid_session_queue_size' resources: overrides: namespace: {resource: "namespace"} pod: {resource: "pod"} name: matches: "^(.*)" as: "selenium_grid_session_queue_size" metricsQuery: '<<.Series>>{<<.LabelMatchers>>}'
- 使用国内源镜像
- 注册 Custom Metrics API:
- 在 ACK 中执行
kubectl apply -f https://aliacs-k8s.oss-cn-beijing.aliyuncs.com/metrics-adapter/rbac.yaml; - 验证
kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1能返回selenium_grid_session_queue_size。
- 在 ACK 中执行
- 创建 HPA:
apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: selenium-chrome-hpa namespace: selenium-grid spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: selenium-chrome-node minReplicas: 2 maxReplicas: 100 metrics: - type: Object object: describedObject: apiVersion: v1 kind: Service name: selenium-router metric: name: selenium_grid_session_queue_size target: type: Value value: "5" behavior: scaleUp: stabilizationWindowSeconds: 15 policies: - type: Pods value: 20 periodSeconds: 30 scaleDown: stabilizationWindowSeconds: 300 policies: - type: Pods value: 5 periodSeconds: 60 - 验证:
- 使用 阿里云服务网格 ASM 注入压测流量,观察
kubectl describe hpa中Replicas: 2→22在 30 s 内完成; - 压测停止 5 min 后,副本数按 5 个/分钟 优雅缩容,避免 按量计费 瞬间拉高。
- 使用 阿里云服务网格 ASM 注入压测流量,观察
拓展思考
- 多队列场景:Grid 4 支持 会话映射到不同 Node 标签(如
browserVersion=115.0),可为每个标签建 独立的 HPA,但需给 exporter 增加label_selector参数,避免指标重复。 - 零冷启动:把 Chrome 节点镜像预置 chrome-headless-shell 与 字体缓存层,并使用 阿里云 ECI 弹性容器实例 的 镜像缓存 能力,可把扩容时间从 90 s 降到 15 s。
- 成本治理:
- 通过 KEDA 的 ScaledJob 模式,把 Chrome 节点跑成 Job 而非 Deployment,测试完即销毁,按秒计费;
- 结合 阿里云节省计划 与 spot 实例,把 maxReplicas 中 70% 调度到抢占式节点,成本再降 60%。
- 可观测性:在 Grafana 大盘 中增加 队列长度→扩容延迟→测试通过率 的 三阶联动图,方便测试经理向 PMO 证明自动化扩容带来的 回归测试耗时缩短 与 上线窗口提前 的 量化收益。