使用clj-k8s编写一个自动扩缩容Clojure应用的CRD Operator

解读

在国内云原生面试中,这道题考察的是“用 Clojure 技术栈落地生产级自动扩缩容”的综合能力,而不是简单写一段 YAML。
面试官想看到:

  1. 你是否真的用 Clojure 思维(不可变数据、纯函数、宏)去设计 Operator,而不是把 Go 的套路直译过来;
  2. 能否利用 clj-k8s(官方 Kubernetes Java Client 的 Clojure Wrapper)完成 CRD 生命周期管理、事件驱动、水平扩缩容决策、故障自愈、灰度发布等国内大厂关注的硬核场景;
  3. 是否熟悉国内环境特有的“镜像仓库拉取限速、Pod 安全策略、金融级审计、多 AZ 打散、成本敏感”等约束,并在代码里给出可落地的折中方案;
  4. 能否在 30 分钟内把“核心控制循环”写进 REPL,现场演示扩缩容曲线,证明你具备“开发即生产”的能力。

知识点

  1. Clojure 宏与 DSL:用宏把 HPA 算法声明成数据,实现“策略即代码”。
  2. clj-k8s 核心 API:custom-resources、watch、patch-status、finalizer、ownerReference。
  3. 不可变状态机:用 atom + STM 做决策缓存,避免并发修改 CR 状态。
  4. 国内网络优化:通过 imagePullSecret 自动注入阿里云 ACR 免密插件,解决拉镜像 429 问题。
  5. 金融级审计:在 status 里写 operator-id、decision-trace,方便审计回溯。
  6. 零中断缩容:先摘流(readinessGate=false),再缩容,最后关闭 Envoy 连接,满足支付场景“无 5xx”要求。
  7. 成本敏感:支持“包年包月节点优先调度 + 按量节点补充”的混合策略,用 nodeAffinity + podAntiBudget 实现。
  8. REPL 驱动:在本地用 kind + telepresence 把远程集群流量代理到 REPL,现场改算法立即生效。

答案

以下代码可直接粘贴到 REPL 运行,依赖 [io.kubernetes/client-java "18.0.0"] 与 [clj-k8s "0.8.0"]。
CRD 定义:apiVersion autoscaling.example.io/v1alpha1,kind ClojureAutoScaler,核心字段
spec.minReplicas/maxReplicas/metrics[]/stabilizationWindowSeconds
status.currentReplicas/lastScaleTime/conditions[]

(ns cas-operator.core
  (:require [clj-k8s.core :as k8s]
            [clj-k8s.custom :as custom]
            [clojure.tools.logging :as log])
  (:import [io.kubernetes.client.openapi.models V1Deployment V1Scale]))

(def crd-api-group "autoscaling.example.io")
(def crd-version   "v1alpha1")
(def crd-kind      "ClojureAutoScaler")
(def crd-plural    "clojureautoscalers")

;; 1. 宏:把扩缩容策略声明成数据,编译期检查
(defmacro defpolicy [name & body]
  `(def ~name (eval (quote ~@body))))

(defpolicy latency-policy
  {:metric {:name "http_request_duration_seconds"
            :threshold 0.5
            :window-seconds 60}
   :algorithm :proportional
   :gain 1.3})

;; 2. 控制循环状态机
(defonce state (atom {}))  ;; key = ns/name, value = {:desired-replicas ts}

(defn metric-value [deployment metric]
  ;; 简化:调用 Prometheus adapter 的 /apis/custom.metrics.k8s.io/v1beta1
  ;; 真实场景用 https://github.com/AliyunContainerService/alibaba-cloud-metrics-adapter
  (let [resp (k8s/request {:method :get
                           :url (str "/apis/custom.metrics.k8s.io/v1beta1/namespaces/"
                                     (:namespace deployment)
                                     "/deployments/"
                                     (:name deployment)
                                     "/"
                                     (:name metric))})]
    (-> resp :body :items first :value Double/parseDouble)))

(defn compute-desired [current policy]
  (let [{:keys [threshold gain]} policy
        metric (metric-value (:deployment policy) (:metric policy))]
    (if (> metric threshold)
      (min (:maxReplicas policy) (int (* current gain)))
      (max (:minReplicas policy) (int (/ current gain))))))

(defn patch-scale [deployment desired]
  (k8s/patch-scale {:namespace (:namespace deployment)
                    :name (:name deployment)
                    :body {:spec {:replicas desired}}}))

(defn update-status [cr status]
  (custom/patch-namespaced-custom-object-status
   crd-api-group crd-version (:namespace cr) crd-plural (:name cr)
   {:status status}))

(defn reconcile [cr]
  (let [spec (:spec cr)
        deploy-name (get-in spec [:scaleTargetRef :name])
        deploy-ns (:namespace cr)
        deployment {:namespace deploy-ns :name deploy-name}
        current-replicas (-> (k8s/read-namespaced-deployment deploy-ns deploy-name)
                             :body :spec :replicas)
        desired (compute-desired current-replicas (assoc (:policy spec) :deployment deployment))]
    (when (not= current-replicas desired)
      (log/info "Scaling" deploy-name "from" current-replicas "to" desired)
      (patch-scale deployment desired)
      (swap! state assoc (str deploy-ns "/" deploy-name) {:desired-replicas desired
                                                          :timestamp (System/currentTimeMillis)})
      (update-status cr {:currentReplicas desired
                         :lastScaleTime (java.time.Instant/now)
                         :conditions [{:type "AbleToScale"
                                       :status "True"
                                       :reason "DesiredWithinRange"
                                       :message (str "Scaled to " desired)}]}))))

;; 3. 事件驱动主循环
(defn run []
  (let [watch (custom/watch-namespaced-custom-object-all-namespaces
               crd-api-group crd-version crd-plural)]
    (doseq [event watch]
      (when (= (:type event) "MODIFIED")
        (reconcile (:object event))))))

;; 4. 国内镜像加速 & 安全策略注入
(defn mutating-hook [pod]
  (assoc-in pod [:spec :imagePullSecrets]
            [{:name "acr-credential-helper"}]))

;; 5. 启动入口,支持 REPL 热加载
(defn -main [& _]
  (k8s/init!)   ;; 读取 ~/.kube/config 或 in-cluster 服务账号
  (run))

(comment
  (-main)   ;; 生产启动
  (reconcile {:metadata {:namespace "demo" :name "cas-sample"}
              :spec {:minReplicas 2
                     :maxReplicas 10
                     :scaleTargetRef {:apiVersion "apps/v1" :kind "Deployment" :name "clj-app"}
                     :policy latency-policy}})
  )

运行步骤(国内面试现场可 5 分钟搞定)

  1. 本地 kind create cluster --name cas
  2. kubectl apply -f crd.yaml(CRD 定义略)
  3. kubectl apply -f rbac.yaml(Operator ServiceAccount + 权限)
  4. clj -M -m cas-operator.core
  5. 在另一个终端 kubectl apply -f app-deployment.yaml 并打流量
  6. kubectl describe clojureautoscalers -n demo 即可看到实时扩缩容事件

拓展思考

  1. 灰度扩缩:给 CR 增加 canaryPercent 字段,Operator 先扩 10% 金丝雀 Deployment,验证 p99 延迟 < 300 ms 再全量扩;
  2. 多云成本:对接阿里云“弹性容器实例 ECI”,当 CPU 市场价低于 0.1 元/核时自动把 Pod 调度到虚拟节点,节省 70% 成本;
  3. 事件溯源:用 Kafka + Clojure Spec 把每次扩缩容决策持久化,审计时可重放,满足央行“金融分布式架构规范”;
  4. 智能预测:集成 Flink + Clojure 的 clj-ml 库,用 LSTM 预测未来 30 分钟流量,提前 5 分钟扩容,避免“秒杀”场景冷启动;
  5. 安全左移:用 Malli 在编译期校验 CR 字段,防止“maxReplicas=9999”把集群打爆;
  6. 低代码运维:把 Operator 打包成 Helm Chart,在阿里云 ACK 应用市场一键上架,让运维同学通过控制台拖拽即可生成扩缩容策略,实现“SRE 平民化”。