

 **帮助改进此页面** 

要帮助改进本用户指南，请选择位于每个页面右侧窗格中的**在 GitHub 上编辑此页面**链接。

# 使用 Prometheus 监控集群指标
<a name="prometheus"></a>

 [Prometheus](https://prometheus.io/) 是一个用于抓取端点的监控和时间序列数据库。提供查询、聚合和存储收集的数据的功能。您还可以将其用于警报和警报聚合。本主题介绍如何将 Prometheus 设置为托管或开源选项。一个常见用例为监控 Amazon EKS 控制面板指标。

Amazon Managed Service for Prometheus 是一项与 Prometheus 兼容的监控和警报服务，可以轻松实现对容器化应用程序和基础设施的大规模监控。这是一项完全托管的服务，可自动扩展指标的提取、存储、查询和警报。这项服务还集成了 AWS 安全服务，可以快速安全地访问您的数据。您可以使用开源 PromQL 查询语言来查询指标并发出警报。此外，您还可以使用 Amazon Managed Service for Prometheus 中的警报管理器来设置关键警报的提醒规则。然后，您可以将这些关键警报作为通知发送到某个 Amazon SNS 主题。

可以通过多种方式将 Prometheus 与 Amazon EKS 结合使用：
+ 您可以在首次创建 Amazon EKS 集群时开启 Prometheus 指标，也可以为现有集群创建自己的 Prometheus 抓取程序。本主题涵盖了这两个选项。
+ 您可以使用 Helm 部署 Prometheus。有关更多信息，请参阅 [使用 Helm 部署 Prometheus](deploy-prometheus.md)。
+ 您可以查看 Prometheus 格式的控制面板原始指标。有关更多信息，请参阅 [获取 Prometheus 格式的控制面板原始指标](view-raw-metrics.md)。

## 第 1 步：开启 Prometheus 指标
<a name="turn-on-prometheus-metrics"></a>

**重要**  
适用于 Prometheus 的 Amazon 托管服务资源不在集群生命周期内，需要独立于集群进行维护。删除集群时，请务必同时删除所有适用的抓取器以停止适用的费用。有关更多信息，请参阅*《Amazon Managed Service for Prometheus 用户指南》*中的[查找和删除抓取程序](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-collector-how-to.html#AMP-collector-list-delete)。

Prometheus 通过一个名为抓取的拉取模型从集群中发现和收集指标。设置抓取程序以从您的集群基础设施和容器化应用程序中收集数据。当您开启发送 Prometheus 指标的选项时，Amazon Managed Service for Prometheus 会提供一个完全托管的无代理抓取程序。

如果尚未创建集群，您可以在首次创建集群时开启向 Prometheus 发送指标的选项。在 Amazon EKS 控制台中，此选项位于创建新集群的**配置可观测性**步骤中。有关更多信息，请参阅 [创建一个 Amazon EKS 集群。](create-cluster.md)。

如果您已经有现有的集群，则可以创建自己的 Prometheus 抓取程序。要在 Amazon EKS 控制台中执行此操作，请导航到集群的**可观测性**选项卡，然后选择**添加抓取器**按钮。如果您更愿意使用 AWS API 或 AWS CLI 执行此操作，请参阅《Amazon Managed Service for Prometheus User Guide》**中的 [Create a scraper](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-collector-how-to.html#AMP-collector-create)。

使用 Amazon EKS 控制台创建抓取程序时，可以使用以下选项。

 **抓取程序别名**   
（可选）输入抓取程序的唯一别名。

 **目标位置**   
选择 Amazon Managed Service for Prometheus 工作区。工作区是专用于存储和查询 Prometheus 指标的逻辑空间。借助此工作区，您将能够查看有权访问该工作区账户的 Prometheus 指标。**创建新工作区**选项指示 Amazon EKS 使用您提供的**工作区别名**，来代表您创建工作区。您可以使用**选择现有工作区**选项，从下拉列表中选择一个现有工作区。有关工作区的更多信息，请参阅《Amazon Managed Service for Prometheus 用户指南》**中的[管理工作区](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-manage-ingest-query.html)。

 **服务访问**   
本节总结了您在发送 Prometheus 指标时授予的权限：  
+ 允许 Amazon Managed Service for Prometheus 描述抓取的 Amazon EKS 集群
+ 允许远程写入 Amazon Managed Prometheus 工作区
如果 `AmazonManagedScraperRole` 已存在，抓取程序会进行使用。选择 `AmazonManagedScraperRole` 链接以查看**权限详细信息**。如果 `AmazonManagedScraperRole` 尚不存在，请选择**查看权限详细信息**链接，查看您通过发送 Prometheus 指标授予的特定权限。

 **子网**   
根据需要修改抓取程序将继承的子网。如果需要添加灰显的子网选项，请返回创建集群**指定网络**步骤。

 **抓取程序配置**   
根据需要修改 YAML 格式的抓取程序进行配置。为此，请使用表单或上传替换的 YAML 文件。有关更多信息，请参阅《Amazon Managed Service for Prometheus 用户指南》**中的[抓取程序配置](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-collector-how-to.html#AMP-collector-configuration)。

Amazon Managed Service for Prometheus 指的是与集群一起创建的无代理抓取程序，作为 AWS 托管的收集器。有关 AWS 托管的收集器的更多信息，请参阅《Amazon Managed Service for Prometheus 用户指南》**中的 [使用 AWS 托管收集器摄取指标](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-collector.html)。

**重要**  
如果您使用 AWS CLI 或 AWS API 创建 Prometheus 抓取程序，则需要调整其配置，向抓取程序授予集群内的权限。有关更多信息，请参阅《Amazon Managed Service for Prometheus 用户指南》**中的[配置您的 Amazon EKS 集群](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-collector-how-to.html#AMP-collector-eks-setup)。
如果您在 2024 年 11 月 11 日之前创建了使用 `aws-auth` `ConfigMap` 而非访问条目的 Prometheus 抓取程序，则需要对其进行更新才能从 Amazon EKS 集群控制面板访问其他指标。有关更新的配置，请参阅《Amazon Managed Service for Prometheus 用户指南》**中的[手动配置 Amazon EKS 以获取抓取工具访问权限](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-collector-how-to.html#AMP-collector-eks-manual-setup)。

## 第 2 步：使用 Prometheus 指标
<a name="use-prometheus-metrics"></a>

有关为集群开启 Prometheus 指标后如何使用这些指标的详细信息，请参阅《[Amazon Managed Service for Prometheus User Guide](https://docs.aws.amazon.com/prometheus/latest/userguide/what-is-Amazon-Managed-Service-Prometheus.html)》。

## 第 3 步：管理 Prometheus 抓取程序
<a name="viewing-prometheus-scraper-details"></a>

要管理抓取程序，请在 Amazon EKS 控制台中选择**可观测性**选项卡。一个显示集群抓取程序列表的表格，包括抓取程序 ID、别名、状态和创建日期等信息。您可以添加更多抓取程序、编辑抓取程序、删除抓取程序或查看有关当前抓取程序的更多信息。

要查看有关抓取程序的更多详细信息，请选择抓取程序 ID 链接。例如，您可以查看 ARN、环境、工作空间 ID、IAM 角色、配置和网络信息。您可以使用抓取程序 ID 作为 Amazon Managed Service for Prometheus API 操作的输入，例如 [https://docs.aws.amazon.com/prometheus/latest/APIReference/API_DescribeScraper.html](https://docs.aws.amazon.com/prometheus/latest/APIReference/API_DescribeScraper.html)、[https://docs.aws.amazon.com/prometheus/latest/APIReference/API_UpdateScraper.html](https://docs.aws.amazon.com/prometheus/latest/APIReference/API_UpdateScraper.html) 和 [https://docs.aws.amazon.com/prometheus/latest/APIReference/API_DeleteScraper.html](https://docs.aws.amazon.com/prometheus/latest/APIReference/API_DeleteScraper.html)。有关使用 Prometheus API 的更多信息，请参阅 [Amazon Managed Service for Prometheus API Reference](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-APIReference.html)。

# 使用 Helm 部署 Prometheus
<a name="deploy-prometheus"></a>

您可以使用 Helm 将 Prometheus 部署到集群中，而不使用 Amazon Managed Service for Prometheus。如果您已安装有 Helm，则可使用 `helm version` 命令来检查您的版本。Helm 是 Kubernetes 集群的包管理器。有关 Helm 及其安装方法的更多信息，请参阅 [使用 Helm 在 Amazon EKS 上部署应用程序](helm.md)。

在为您的 Amazon EKS 集群配置 Helm 后，您可以使用它来部署 Prometheus，步骤如下。

1. 创建 Prometheus 命名空间。

   ```
   kubectl create namespace prometheus
   ```

1. 添加 `prometheus-community` 图表存储库。

   ```
   helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
   ```

1. 部署 Prometheus。

   ```
   helm upgrade -i prometheus prometheus-community/prometheus \
       --namespace prometheus \
       --set alertmanager.persistence.storageClass="gp2" \
       --set server.persistentVolume.storageClass="gp2"
   ```
**注意**  
如果您在执行此命令时收到错误 `Error: failed to download "stable/prometheus" (hint: running helm repo update may help)`，请运行 `helm repo update prometheus-community`，然后尝试再次运行第 2 步命令。

   如果您收到错误 `Error: rendered manifests contain a resource that already exists`，请运行 `helm uninstall your-release-name -n namespace `，然后尝试再次运行第 3 步命令。

1. 确认 `prometheus` 命名空间中的所有容器组（pod）均处于 `READY` 状态。

   ```
   kubectl get pods -n prometheus
   ```

   示例输出如下。

   ```
   NAME                                             READY   STATUS    RESTARTS   AGE
   prometheus-alertmanager-59b4c8c744-r7bgp         1/2     Running   0          48s
   prometheus-kube-state-metrics-7cfd87cf99-jkz2f   1/1     Running   0          48s
   prometheus-node-exporter-jcjqz                   1/1     Running   0          48s
   prometheus-node-exporter-jxv2h                   1/1     Running   0          48s
   prometheus-node-exporter-vbdks                   1/1     Running   0          48s
   prometheus-pushgateway-76c444b68c-82tnw          1/1     Running   0          48s
   prometheus-server-775957f748-mmht9               1/2     Running   0          48s
   ```

1. 使用 `kubectl` 将 Prometheus 控制台端口转发到本地计算机。

   ```
   kubectl --namespace=prometheus port-forward deploy/prometheus-server 9090
   ```

1. 在 Web 浏览器中打开 `http://localhost:9090` 来查看 Prometheus 控制台。

1. 从 **- insert metric at cursor (- 在光标位置插入指标)** 菜单选择一个指标，然后选择 **Execute (执行)**。选择 **Graph (图表)** 选项卡显示一段时间内的指标。下图显示了一段时间内的 `container_memory_usage_bytes`。  
![\[Prometheus 指标\]](http://docs.aws.amazon.com/zh_cn/eks/latest/userguide/images/prometheus-metric.png)

1. 在顶部导航栏中，选择 **Status (状态)**，然后选择 **Targets (目标)**。  
![\[Prometheus 控制台\]](http://docs.aws.amazon.com/zh_cn/eks/latest/userguide/images/prometheus.png)

   使用服务发现连接到 Prometheus 的所有 Kubernetes 终端节点将显示。

# 获取 Prometheus 格式的控制面板原始指标
<a name="view-raw-metrics"></a>

Kubernetes 控制面板公开了许多以 [Prometheus 格式](https://github.com/prometheus/docs/blob/master/content/docs/instrumenting/exposition_formats.md)表示的指标。这些指标对于监控和分析非常有用。这些指标通过指标端点在内部公开，无需完全部署 Prometheus 即可访问。但是，随着时间的推移，部署 Prometheus 更加容易，即可实现指标分析。

要查看原始指标输出，请替代 `endpoint` 并运行以下命令。

```
kubectl get --raw endpoint
```

此命令允许您传递任何端点路径，并返回原始响应。输出结果逐行列出了不同指标，每行都包含指标名称、标签和值。

```
metric_name{tag="value"[,...]} value
```

## 从 API 服务器获取指标
<a name="fetch-metrics"></a>

常规 API 服务器端点在 Amazon EKS 控制面板上公开。此端点主要用于查看特定指标。

```
kubectl get --raw /metrics
```

示例输出如下。

```
[...]
# HELP rest_client_requests_total Number of HTTP requests, partitioned by status code, method, and host.
# TYPE rest_client_requests_total counter
rest_client_requests_total{code="200",host="127.0.0.1:21362",method="POST"} 4994
rest_client_requests_total{code="200",host="127.0.0.1:443",method="DELETE"} 1
rest_client_requests_total{code="200",host="127.0.0.1:443",method="GET"} 1.326086e+06
rest_client_requests_total{code="200",host="127.0.0.1:443",method="PUT"} 862173
rest_client_requests_total{code="404",host="127.0.0.1:443",method="GET"} 2
rest_client_requests_total{code="409",host="127.0.0.1:443",method="POST"} 3
rest_client_requests_total{code="409",host="127.0.0.1:443",method="PUT"} 8
# HELP ssh_tunnel_open_count Counter of ssh tunnel total open attempts
# TYPE ssh_tunnel_open_count counter
ssh_tunnel_open_count 0
# HELP ssh_tunnel_open_fail_count Counter of ssh tunnel failed open attempts
# TYPE ssh_tunnel_open_fail_count counter
ssh_tunnel_open_fail_count 0
```

此原始输出逐字返回 API 服务器公开的内容。

## 使用 `metrics.eks.amazonaws.com` 获取控制面板指标
<a name="fetch-metrics-prometheus"></a>

对于 Kubernetes 版本 `1.28` 及以上版本的集群，Amazon EKS 还会在 API 组 `metrics.eks.amazonaws.com` 下公开指标。这些指标包括控制面板组件，例如 `kube-scheduler` 和 `kube-controller-manager`。

**注意**  
如果有可能会阻止在集群上新建 `APIService` 资源 `v1.metrics.eks.amazonaws.com` 的 Webhook 配置，则指标端点功能可能不可用。您可以通过在 `kube-apiserver` 审计日志中搜索 `v1.metrics.eks.amazonaws.com` 关键词进行验证。

### 获取 `kube-scheduler` 指标
<a name="fetch-metrics-scheduler"></a>

使用以下命令来检索 `kube-scheduler` 指标。

```
kubectl get --raw "/apis/metrics.eks.amazonaws.com/v1/ksh/container/metrics"
```

示例输出如下。

```
# TYPE scheduler_pending_pods gauge
scheduler_pending_pods{queue="active"} 0
scheduler_pending_pods{queue="backoff"} 0
scheduler_pending_pods{queue="gated"} 0
scheduler_pending_pods{queue="unschedulable"} 18
# HELP scheduler_pod_scheduling_attempts [STABLE] Number of attempts to successfully schedule a pod.
# TYPE scheduler_pod_scheduling_attempts histogram
scheduler_pod_scheduling_attempts_bucket{le="1"} 79
scheduler_pod_scheduling_attempts_bucket{le="2"} 79
scheduler_pod_scheduling_attempts_bucket{le="4"} 79
scheduler_pod_scheduling_attempts_bucket{le="8"} 79
scheduler_pod_scheduling_attempts_bucket{le="16"} 79
scheduler_pod_scheduling_attempts_bucket{le="+Inf"} 81
[...]
```

### 获取 `kube-controller-manager` 指标
<a name="fetch-metrics-controller"></a>

使用以下命令来检索 `kube-controller-manager` 指标。

```
kubectl get --raw "/apis/metrics.eks.amazonaws.com/v1/kcm/container/metrics"
```

示例输出如下。

```
[...]
workqueue_work_duration_seconds_sum{name="pvprotection"} 0
workqueue_work_duration_seconds_count{name="pvprotection"} 0
workqueue_work_duration_seconds_bucket{name="replicaset",le="1e-08"} 0
workqueue_work_duration_seconds_bucket{name="replicaset",le="1e-07"} 0
workqueue_work_duration_seconds_bucket{name="replicaset",le="1e-06"} 0
workqueue_work_duration_seconds_bucket{name="replicaset",le="9.999999999999999e-06"} 0
workqueue_work_duration_seconds_bucket{name="replicaset",le="9.999999999999999e-05"} 19
workqueue_work_duration_seconds_bucket{name="replicaset",le="0.001"} 109
workqueue_work_duration_seconds_bucket{name="replicaset",le="0.01"} 139
workqueue_work_duration_seconds_bucket{name="replicaset",le="0.1"} 181
workqueue_work_duration_seconds_bucket{name="replicaset",le="1"} 191
workqueue_work_duration_seconds_bucket{name="replicaset",le="10"} 191
workqueue_work_duration_seconds_bucket{name="replicaset",le="+Inf"} 191
workqueue_work_duration_seconds_sum{name="replicaset"} 4.265655885000002
[...]
```

### 了解调度器和控制器管理器指标
<a name="scheduler-controller-metrics"></a>

下表描述了可用于 Prometheus 样式获取的调度器和控制器管理器指标。有关这些指标的更多信息，请参阅 Kubernetes 文档中的 [Kubernetes Metrics Reference](https://kubernetes.io/docs/reference/instrumentation/metrics/)。


| 指标 | 控制面板组件 | 描述 | 
| --- | --- | --- | 
|  scheduler\$1pending\$1pods  |  调度器  |  等待调度到节点上执行的容器组（pod）数量。  | 
|  scheduler\$1schedule\$1attempts\$1total  |  调度器  |  尝试调度容器组（pod）的次数。  | 
|  scheduler\$1preemption\$1tapts\$1total  |  调度器  |  调度器尝试通过驱逐优先级较低的容器组（pod）来调度优先级较高的容器组（pod）的次数。  | 
|  scheduler\$1preemption\$1victims  |  调度器  |  为容纳优先级更高的容器组（pod）腾出空间而被选中驱逐的容器组（pod）的数量。  | 
|  scheduler\$1pod\$1scheduling\$1attempts  |  调度器  |  成功尝试调度容器组（pod）的次数。  | 
|  scheduler\$1scheduling\$1attempt\$1duration\$1seconds  |  调度器  |  表示调度器能够根据可用资源和调度规则等各种因素找到容器组（pod）的合适运行位置的速度。  | 
|  scheduler\$1pod\$1scheduling\$1sli\$1duration\$1seconds  |  调度器  |  从容器组（pod）进入调度队列之时起调度容器组（pod）的端到端延迟。这可能涉及多次尝试调度。  | 
|  cronjob\$1controller\$1job\$1creation\$1skew\$1duration\$1skeond  |  控制器管理器  |  从计划运行 cronjob 到创建相应作业的时间。  | 
|  workqueue\$1depth  |  控制器管理器  |  当前工作队列的深度。  | 
|  workqueue\$1adds\$1total  |  控制器管理器  |  工作队列处理的添加总数。  | 
|  workqueue\$1queue\$1duration\$1seconds  |  控制器管理器  |  显示项目在被请求之前在工作队列中停留的时长（以秒为单位）。  | 
|  workqueue\$1work\$1duration\$1seconds  |  控制器管理器  |  工作队列中项目的处理时长（以秒为单位）。  | 

## 部署 Prometheus 抓取工具持续抓取指标
<a name="deploy-prometheus-scraper"></a>

要部署 Prometheus 抓取工具持续抓取指标，请使用以下配置：

```
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: prometheus-conf
data:
  prometheus.yml: |-
    global:
      scrape_interval: 30s
    scrape_configs:
    # apiserver metrics
    - job_name: apiserver-metrics
      kubernetes_sd_configs:
      - role: endpoints
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        insecure_skip_verify: true
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - source_labels:
          [
            __meta_kubernetes_namespace,
            __meta_kubernetes_service_name,
            __meta_kubernetes_endpoint_port_name,
          ]
        action: keep
        regex: default;kubernetes;https
    # Scheduler metrics
    - job_name: 'ksh-metrics'
      kubernetes_sd_configs:
      - role: endpoints
      metrics_path: /apis/metrics.eks.amazonaws.com/v1/ksh/container/metrics
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        insecure_skip_verify: true
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - source_labels:
          [
            __meta_kubernetes_namespace,
            __meta_kubernetes_service_name,
            __meta_kubernetes_endpoint_port_name,
          ]
        action: keep
        regex: default;kubernetes;https
    # Controller Manager metrics
    - job_name: 'kcm-metrics'
      kubernetes_sd_configs:
      - role: endpoints
      metrics_path: /apis/metrics.eks.amazonaws.com/v1/kcm/container/metrics
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        insecure_skip_verify: true
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - source_labels:
          [
            __meta_kubernetes_namespace,
            __meta_kubernetes_service_name,
            __meta_kubernetes_endpoint_port_name,
          ]
        action: keep
        regex: default;kubernetes;https
---
apiVersion: v1
kind: Pod
metadata:
  name: prom-pod
spec:
  containers:
  - name: prom-container
    image: prom/prometheus
    ports:
    - containerPort: 9090
    volumeMounts:
    - name: config-volume
      mountPath: /etc/prometheus/
  volumes:
  - name: config-volume
    configMap:
      name: prometheus-conf
```

容器组（pod）需要以下权限才能访问新的指标端点。

```
{
  "effect": "allow",
  "apiGroups": [
    "metrics.eks.amazonaws.com"
  ],
  "resources": [
    "kcm/metrics",
    "ksh/metrics"
  ],
  "verbs": [
    "get"
  ] },
```

要修补正在使用的角色，请使用以下命令。

```
kubectl patch clusterrole <role-name> --type=json -p='[
  {
    "op": "add",
    "path": "/rules/-",
    "value": {
      "verbs": ["get"],
      "apiGroups": ["metrics.eks.amazonaws.com"],
      "resources": ["kcm/metrics", "ksh/metrics"]
    }
  }
]'
```

然后，您可以通过将 Prometheus 抓取程序的端口代理到本地端口来查看 Prometheus 控制面板。

```
kubectl port-forward pods/prom-pod 9090:9090
```

对于您的 Amazon EKS 集群，Kubernetes 控制面板核心指标也将摄取到 `AWS/EKS` 命名空间下的 Amazon CloudWatch 指标中。要查看这些指标，请打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch/home#logs:prefix=/aws/eks)，然后从左侧导航窗格中选择**所有指标**。在**指标**选择页面上，为您的集群选择 `AWS/EKS` 命名空间和指标维度。