水平 Pod 自動調度資源 (HPA)

本文說明如何為 Google Cloud Managed Service for Prometheus 啟用水平自動調度 Pod 資源 (HPA)。您可以透過下列任一方式啟用 HPA:

您無法在同一個叢集中同時使用 Stackdriver 轉接器和 Prometheus 轉接器,因為兩者的資源定義重疊,詳情請參閱「疑難排解」。建議您只選擇一種 HPA 解決方案。

或者,GKE 也內建支援功能,可根據 Managed Service for Prometheus 中的指標自動調度資源。

使用 KEDA

KEDA (Kubernetes 事件導向自動調整資源配置) 是最新發布的自動配置器,使用 Prometheus 指標,並逐漸成為 Prometheus 社群中的熱門解決方案。

如要開始使用,請參閱 KEDA 說明文件,瞭解如何與 Google Cloud Managed Service for Prometheus 整合。

使用自訂指標 Stackdriver 轉接器

自轉接器 v0.13.1 版起,Custom Metrics Stackdriver Adapter 支援從 Managed Service for Prometheus 查詢指標。

如要使用自訂指標 Stackdriver 轉接器設定 HPA 設定範例,請按照下列步驟操作:

  1. 在叢集中設定代管收集。
  2. 在叢集中安裝自訂指標 Stackdriver 轉接器。

    kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/deploy/production/adapter_new_resource_model.yaml
    
  3. 部署範例 Prometheus 指標匯出工具和 HPA 資源:

    kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/examples/prometheus-to-sd/custom-metrics-prometheus-sd.yaml
    

    這個指令會部署匯出工具應用程式,用於發出指標 foo 和 HPA 資源。HPA 會將這個應用程式擴充至 5 個副本,以達到指標 foo 的目標值。

  4. 如果您使用 Workload Identity Federation for GKE,也必須將 Monitoring 檢視者角色授予轉接程式執行的服務帳戶。如果 Kubernetes 叢集未啟用 Workload Identity Federation for GKE,請略過這個步驟。

    export PROJECT_NUMBER=$(gcloud projects describe PROJECT_ID --format 'get(projectNumber)')
    gcloud projects add-iam-policy-binding projects/PROJECT_ID \
      --role roles/monitoring.viewer \
      --member=principal://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/custom-metrics/sa/custom-metrics-stackdriver-adapter
    
  5. 將下列設定放入名為 podmonitoring.yaml 的檔案,定義 PodMonitoring 資源。

    apiVersion: monitoring.googleapis.com/v1
    kind: PodMonitoring
    metadata:
      name: prom-example
    spec:
      selector:
        matchLabels:
          run: custom-metric-prometheus-sd
      endpoints:
      - port: 8080
        interval: 30s
    
  6. 部署新的 PodMonitoring 資源:

    kubectl -n default apply -f podmonitoring.yaml
    

    Managed Service for Prometheus 會在幾分鐘內處理從匯出工具抓取的指標,並使用長格式名稱將指標儲存在 Cloud Monitoring 中。Prometheus 指標會依據下列慣例儲存:

    • 前置字串 prometheus.googleapis.com。
    • 這個後置字串通常是 gauge、counter、summary 或 histogram 其中之一,但未輸入類型的指標可能會有 unknown 或 unknown:counter 後置字串。如要驗證後置字串,請使用 Metrics Explorer 在 Cloud Monitoring 中查詢指標。
  7. 更新已部署的 HPA,以便從 Cloud Monitoring 查詢指標。指標 foo 會擷取為 prometheus.googleapis.com/foo/gauge。如要讓已部署的 HorizontalPodAutoscaler 資源查詢指標,請在已部署的 HPA 中使用長格式名稱,但必須將所有正斜線 (/) 替換為管道字元 (|):prometheus.googleapis.com|foo|gauge。詳情請參閱 Custom Metrics Stackdriver Adapter 存放區的「Stackdriver 提供的指標」一節。

    1. 執行下列指令,更新已部署的 HPA:

      kubectl edit hpa custom-metric-prometheus-sd
      
    2. 將 pods.metric.name 欄位的值從 foo 變更為 prometheus.googleapis.com|foo|gauge。spec 區段應如下所示:

      spec:
         maxReplicas: 5
         metrics:
         - pods:
             metric:
               name: prometheus.googleapis.com|foo|gauge
             target:
               averageValue: "20"
               type: AverageValue
           type: Pods
         minReplicas: 1
      

    在這個範例中,HPA 設定會尋找指標 prometheus.googleapis.com/foo/gauge 的平均值,並將其設為 20。由於 Deployment 將指標值設為 40,HPA 控制器會將 Pod 數量增加至 maxReplicas (5) 欄位的值,嘗試將所有 Pod 的指標平均值降低至 20。

    HPA 查詢的範圍限定在安裝 HPA 資源的命名空間和叢集,因此其他叢集和命名空間中的相同指標不會影響自動調度資源。

  8. 執行下列指令,觀察工作負載向上擴充:

    kubectl get hpa custom-metric-prometheus-sd --watch
    

    REPLICAS 欄位的值從 1 變更為 5。

    NAME                          REFERENCE                                TARGETS        MINPODS   MAXPODS   REPLICAS   AGE
    custom-metric-prometheus-sd   Deployment/custom-metric-prometheus-sd   40/20          1         5         5          *
    
  9. 如要縮減 Deployment,請將目標指標值更新為高於匯出的指標值。在本範例中,Deployment 會將 prometheus.googleapis.com/foo/gauge 指標的值設為 40。如果將目標值設為高於 40 的數字,部署作業就會縮減。

    例如,使用 kubectl edit 將 HPA 設定中 pods.target.averageValue 欄位的值從 20 變更為 100。

    kubectl edit hpa custom-metric-prometheus-sd
    

    修改 spec 部分,使其與下列內容相符:

    spec:
      maxReplicas: 5
      metrics:
      - pods:
          metric:
            name: prometheus.googleapis.com|foo|gauge
          target:
            averageValue: "100"
            type: AverageValue
      type: Pods
      minReplicas: 1
    
  10. 執行下列指令,觀察工作負載縮減:

    kubectl get hpa custom-metric-prometheus-sd --watch
    

    REPLICAS 欄位的值從 5 變更為 1。根據設計,這項作業的速度會比增加 Pod 數量時慢:

    NAME                          REFERENCE                                TARGETS        MINPODS   MAXPODS   REPLICAS   AGE
    custom-metric-prometheus-sd   Deployment/custom-metric-prometheus-sd   40/100          1         5         1          *
    
  11. 如要清除已部署的範例,請執行下列指令:

    kubectl delete -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/deploy/production/adapter_new_resource_model.yaml
    kubectl delete -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/examples/prometheus-to-sd/custom-metrics-prometheus-sd.yaml
    kubectl delete podmonitoring/prom-example
    

詳情請參閱 Custom Metrics Stackdriver Adapter 存放區中的 Prometheus 範例,或參閱「調度應用程式資源」。

使用 Prometheus 轉接器

現有的 prometheus-adapter 設定只要稍加修改,即可用於自動調度資源。與使用上游 Prometheus 相比,設定 prometheus-adapter 以使用 Managed Service for Prometheus 進行資源調度時,有兩項額外限制:

相較於上游 Prometheus,Managed Service for Prometheus 可能需要稍長的時間才能提供資料,因此設定過於積極的自動調度資源邏輯,可能會導致不必要的行為。雖然無法保證資料更新間隔,但資料傳送至 Managed Service for Prometheus 後,通常 3 到 7 秒內即可查詢,不含任何網路延遲。

prometheus-adapter 發出的所有查詢都屬於全域範圍。也就是說,如果兩個命名空間中的應用程式發出名稱相同的指標,使用該指標的 HPA 設定會根據這兩個應用程式的資料調度資源。建議您一律在 PromQL 中使用 namespace 或 cluster 篩選器,以免使用不正確的資料進行資源調度。

如要使用 prometheus-adapter 和代管收集功能設定 HPA 設定範例,請按照下列步驟操作:

  1. 在叢集中設定代管收集。
  2. 在叢集中部署 Prometheus 前端 UI Proxy。如果您使用 Workload Identity Federation for GKE,也必須設定及授權服務帳戶。
  3. 部署 prometheus-engine 存放區中 examples/hpa/ 目錄內的資訊清單:
    • example-app.yaml:會發出指標的範例 Deployment 和 Service。
    • pod-monitoring.yaml:設定抓取範例指標的資源。
    • hpa.yaml:為工作負載設定資源調度作業的 HPA 資源。
  4. 請確認叢集已安裝 prometheus-adapter。只要將範例安裝資訊清單部署至叢集,即可完成這項操作。這個資訊清單的設定如下:

    • 查詢部署在 default 命名空間中的前端 Proxy。
    • 發出 PromQL,計算並傳回範例部署作業的 http_requests_per_second 指標。
  5. 在不同的終端機工作階段中,分別執行下列指令:

    1. 產生 HTTP 負載並傳送至 prometheus-example-app 服務:
      kubectl run -i --tty load-generator --rm --image=busybox:1.28 --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://prometheus-example-app; done"
    2. 監控水平 Pod 自動調度資源:
      kubectl get hpa prometheus-example-app --watch
    3. 觀察工作負載向上擴充:
      kubectl get po -lapp.kubernetes.io/name=prometheus-example-app --watch
  6. 使用 Ctrl+C 停止產生 HTTP 負載,並觀察工作負載縮減。

疑難排解

Custom Metrics Stackdriver Adapter 使用的資源定義名稱與 Prometheus Adapter (prometheus-adapter) 中的名稱相同。名稱重疊代表在同一個叢集中執行多個轉接器會導致錯誤。

如果叢集先前已安裝 Custom Metrics Stackdriver Adapter,在其中安裝 Prometheus Adapter 可能會因名稱衝突而擲回 FailedGetObjectMetric 等錯誤。如要解決這個問題,您可能需要刪除先前由自訂指標轉接器註冊的 v1beta1.external.metrics.k8s.io、v1beta1.custom.metrics.k8s.io 和 v1beta2.custom.metrics.k8s.io apiservices。

疑難排解提示:

  • 部分 Cloud Monitoring 系統指標 (例如 Pub/Sub 指標) 會延遲 60 秒以上。由於 Prometheus Adapter 會使用目前的時間戳記執行查詢,因此使用 Prometheus Adapter 查詢這些指標可能會錯誤地導致沒有資料。如要查詢延遲指標,請在 PromQL 中使用 offset 修飾符,將查詢的時間偏移調整為所需值。

  • 如要確認前端 UI Proxy 是否正常運作,且沒有權限問題,請在終端機中執行下列指令:

    kubectl -n NAMESPACE_NAME port-forward svc/frontend 9090
    

    接著,開啟另一個終端機,並執行下列指令:

    curl --silent 'localhost:9090/api/v1/series?match%5B%5D=up'
    

    如果前端 UI Proxy 正常運作,第二個終端機中的回應會類似下列內容:

    curl --silent 'localhost:9090/api/v1/series?match%5B%5D=up' | jq .
    {
      "status": "success",
      "data": [
         ...
      ]
    }
    

    如果收到 403 錯誤,表示前端 UI Proxy 設定不正確。如要瞭解如何解決 403 錯誤,請參閱設定及授權服務帳戶指南。

  • 執行下列指令,確認自訂指標 apiserver 是否可用:

    kubectl get apiservices.apiregistration.k8s.io v1beta1.custom.metrics.k8s.io
    

    如果 apiserver 可用,回應會類似下列內容:

    $ kubectl get apiservices.apiregistration.k8s.io v1beta1.custom.metrics.k8s.io
    NAME                            SERVICE                         AVAILABLE   AGE
    v1beta1.custom.metrics.k8s.io   monitoring/prometheus-adapter   True        33m
    
  • 如要確認 HPA 是否正常運作,請執行下列指令:

    $ kubectl describe hpa prometheus-example-app
    Name:                                  prometheus-example-app
    Namespace:                             default
    Labels:                                
    Annotations:                           
    Reference:                             Deployment/prometheus-example-app
    Metrics:                               ( current / target )
    "http_requests_per_second" on pods:  11500m / 10
    Min replicas:                          1
    Max replicas:                          10
    Deployment pods:                       2 current / 2 desired
    Conditions:
    Type            Status  Reason              Message
    ----            ------  ------              -------
    AbleToScale     True    ReadyForNewScale    recommended size matches current size
    ScalingActive   True    ValidMetricFound    the HPA was able to successfully calculate a replica count from pods metric http_requests_per_second
    ScalingLimited  False   DesiredWithinRange  the desired count is within the acceptable range
    Events:
    Type     Reason               Age                   From                       Message
    ----     ------               ----                  ----                       -------
    Normal   SuccessfulRescale    47s                   horizontal-pod-autoscaler  New size: 2; reason: pods metric http_requests_per_second above target
    

    如果回應包含 FailedGetPodsMetric 等陳述式,表示 HPA 失敗。以下範例說明 HPA 失敗時,對 describe 呼叫的回應:

    $ kubectl describe hpa prometheus-example-app
    Name:                                  prometheus-example-app
    Namespace:                             default
    Reference:                             Deployment/prometheus-example-app
    Metrics:                               ( current / target )
      "http_requests_per_second" on pods:   / 10
    Min replicas:                          1
    Max replicas:                          10
    Deployment pods:                       1 current / 1 desired
    Conditions:
      Type            Status  Reason               Message
      ----            ------  ------               -------
      AbleToScale     True    ReadyForNewScale     recommended size matches current size
      ScalingActive   False   FailedGetPodsMetric  the HPA was unable to compute the replica count: unable to get metric http_requests_per_second: unable to fetch metrics from custom metrics API: the server could not find the metric http_requests_per_second for pods
      ScalingLimited  False   DesiredWithinRange   the desired count is within the acceptable range
    Events:
      Type     Reason               Age                   From                       Message
      ----     ------               ----                  ----                       -------
      Warning  FailedGetPodsMetric  104s (x11 over 16m)   horizontal-pod-autoscaler  unable to get metric http_requests_per_second: unable to fetch metrics from custom metrics API: the server could not find the metric http_requests_per_second for pods
    

    如果 HPA 失敗,請確認您使用 load-generator 產生指標。您可以使用下列指令,直接查看自訂指標 API:

    kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/" | jq .
    

    如果成功,輸出結果會與下列內容相似:

    $ kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/" | jq .
      {
      "kind": "APIResourceList",
      "apiVersion": "v1",
      "groupVersion": "custom.metrics.k8s.io/v1beta1",
      "resources": [
         {
            "name": "namespaces/http_requests_per_second",
            "singularName": "",
            "namespaced": false,
            "kind": "MetricValueList",
            "verbs": [
            "get"
            ]
         },
         {
            "name": "pods/http_requests_per_second",
            "singularName": "",
            "namespaced": true,
            "kind": "MetricValueList",
            "verbs": [
            "get"
            ]
         }
      ]
      }
    

    如果沒有指標,輸出內容中的 "resources" 下方就不會有任何資料,例如:

    kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/" | jq .
    {
    "kind": "APIResourceList",
    "apiVersion": "v1",
    "groupVersion": "custom.metrics.k8s.io/v1beta1",
    "resources": []
    }