

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 Amazon ECS Fargate 上抓取 Redis OSS Prometheus 指標的教學課程
<a name="ContainerInsights-Prometheus-Setup-redis-ecs"></a>

本教學課程提供實作介紹，讓您在 Amazon ECS Fargate 叢集中湊集範例 Redis OSS 應用程式的 Prometheus 指標。CloudWatch 代理程式會根據容器的 Docker 標籤，自動探索 Redis OSS Prometheus 匯出工具目標，並支援 Prometheus 指標。

Redis OSS (https://redis.io/) 是一個開放原始碼 (BSD 授權)、記憶體內資料結構存儲，可用作資料庫、快取和訊息代理程式。如需詳細資訊，請參閱 [redis](https://redis.io/)。

redis\_exporter (授權的 MIT 授權) 可用於在指定的連接埠上公開 Redis OSS Prometheus 指標 (預設：0.0.0.0:9121)。如需詳細資訊，請參閱 [redis\_exporter](https://github.com/oliver006/redis_exporter)。

本教學課程會使用下列兩個 Docker Hub 儲存庫中的 Docker 影像：
+ [redis](https://hub.docker.com/_/redis?tab=description)
+ [redis\_exporter](https://hub.docker.com/r/oliver006/redis_exporter)

**必要條件**

若要從 Amazon ECS 的範例 Prometheus 工作負載收集指標，您必須在叢集中執行 Container Insights。如需安裝 Container Insights 的相關資訊，請參閱 [在 Amazon ECS 上設定 Container Insights](deploy-container-insights-ECS.md)。

**Topics**
+ [設定 Amazon ECS Fargate 叢集環境變數](#ContainerInsights-Prometheus-Setup-redis-ecs-variable)
+ [設定 Amazon ECS Fargate 叢集的網路環境變數](#ContainerInsights-Prometheus-Setup-redis-ecs-variable2)
+ [安裝範例 Redis OSS 工作負載](#ContainerInsights-Prometheus-Setup-redis-ecs-install-workload)
+ [設定 CloudWatch 代理程式，以湊集 Redis OSS Prometheus 指標](#ContainerInsights-Prometheus-Setup-redis-ecs-agent)
+ [檢視 Redis OSS 指標](#ContainerInsights-Prometheus-Setup-redis-view)

## 設定 Amazon ECS Fargate 叢集環境變數
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-variable"></a>

**若要設定 Amazon ECS Fargate 叢集環境變數**

1. 安裝 Amazon ECS CLI (如果您尚未安裝)。如需詳細資訊，請參閱[安裝 Amazon ECS CLI](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_CLI_installation.html)。

1. 設定新的 Amazon ECS 叢集名稱和區域。例如：

   ```
   ECS_CLUSTER_NAME=ecs-fargate-redis-tutorial
   AWS_DEFAULT_REGION=ca-central-1
   ```

1. (選用) 如果您還沒有要在其中安裝範例 Redis OSS 工作負載和 CloudWatch 代理程式的 Amazon ECS Fargate 叢集，您可以輸入下列命令，進而建立一個叢集。

   ```
   ecs-cli up --capability-iam \
   --cluster $ECS_CLUSTER_NAME \
   --launch-type FARGATE \
   --region $AWS_DEFAULT_REGION
   ```

   此命令的預期結果如下所示：

   ```
   INFO[0000] Created cluster   cluster=ecs-fargate-redis-tutorial region=ca-central-1
   INFO[0001] Waiting for your cluster resources to be created...
   INFO[0001] Cloudformation stack status   stackStatus=CREATE_IN_PROGRESS
   VPC created: vpc-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Cluster creation succeeded.
   ```

## 設定 Amazon ECS Fargate 叢集的網路環境變數
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-variable2"></a>

**若要設定 Amazon ECS Fargate 叢集的網路環境變數**

1. 設定 Amazon ECS 叢集的 VPC 和子網路 ID。如果您在先前的程序中建立了新的叢集，您會在最終命令的結果中看到這些值。否則，請使用您要與 Redis 搭配使用的現有叢集的 ID。

   ```
   ECS_CLUSTER_VPC={{vpc-xxxxxxxxxxxxxxxxx}}
   ECS_CLUSTER_SUBNET_1={{subnet-xxxxxxxxxxxxxxxxx}}
   ECS_CLUSTER_SUBNET_2={{subnet-xxxxxxxxxxxxxxxxx}}
   ```

1. 在本教學課程中，我們將在 Amazon ECS 叢集 VPC 的預設安全群組中安裝 Redis OSS 應用程式和 CloudWatch 代理程式。預設安全群組允許相同安全群組內的所有網路連線，因此 CloudWatch 代理程式可以擷取 Redis OSS 容器上公開的 Prometheus 指標。在實際生產環境中，您可能想要為 Redis OSS 應用程式和 CloudWatch 代理程式建立專用安全群組，並為其設定自訂許可。

   輸入以下命令以獲取預設安全群組 ID。

   ```
   aws ec2 describe-security-groups \
   --filters Name=vpc-id,Values=$ECS_CLUSTER_VPC  \
   --region $AWS_DEFAULT_REGION
   ```

   然後，透過輸入以下命令來設定 Fargate 叢集預設 安全群組變數，將 {{my-default-security-group}} 取代為您從之前命令中找到的值。

   ```
   ECS_CLUSTER_SECURITY_GROUP={{my-default-security-group}}
   ```

## 安裝範例 Redis OSS 工作負載
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-install-workload"></a>

**若要安裝公開 Prometheus 指標的範例 Redis OSS 工作負載**

1. 輸入下列命令來下載 Redis OSS CloudFormation 範本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/sample_traffic/redis/redis-traffic-sample.yaml
   ```

1. 輸入下列指令，設定要為 Redis OSS 建立的 IAM 角色名稱。

   ```
   REDIS_ECS_TASK_ROLE_NAME=redis-prometheus-demo-ecs-task-role-name
   REDIS_ECS_EXECUTION_ROLE_NAME=redis-prometheus-demo-ecs-execution-role-name
   ```

1. 輸入下列命令以安裝範例 Redis OSS 工作負載。

   ```
   aws cloudformation create-stack --stack-name Redis-Prometheus-Demo-ECS-$ECS_CLUSTER_NAME-fargate-awsvpc \
       --template-body file://redis-traffic-sample.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET_1 \
                    ParameterKey=TaskRoleName,ParameterValue=$REDIS_ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$REDIS_ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_DEFAULT_REGION
   ```

 CloudFormation 堆疊會建立四個資源：
+ 一個 ECS 任務角色
+ 一個 ECS 任務執行角色
+ 一個 Redis OSS 任務定義
+ 一個 Redis OSS 服務

在 Redis OSS 的任務定義中，定義了兩個容器：
+ 主要容器執行簡易的 Redis OSS 應用程式，並開啟連接埠 6379 以進行存取。
+ 另一個容器會執行 Redis OSS 匯出工具程序，以公開連接埠 9121 上的 Prometheus 指標。這是由 CloudWatch 代理程式探索及湊集的容器。定義下列 Docker 標籤，以便 CloudWatch 代理程式可以基於此發現這個容器。

  ```
  ECS_PROMETHEUS_EXPORTER_PORT: 9121
  ```

## 設定 CloudWatch 代理程式，以湊集 Redis OSS Prometheus 指標
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-agent"></a>

**若要設定 CloudWatch 代理程式，以湊集 Redis OSS Prometheus 指標**

1. 輸入下列命令，以下載最新版本的 `cwagent-ecs-prometheus-metric-for-awsvpc.yaml`。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml
   ```

1. 使用文字編輯器開啟檔案，然後在 `resource:CWAgentConfigSSMParameter` 區段中的 `value` 金鑰查找完整的 CloudWatch 代理程式組態。

   然後，在此處顯示的 `ecs_service_discovery` 區段，使用基於 `ECS_PROMETHEUS_EXPORTER_PORT` 的預設設定啟用 `docker_label` 型服務探索，而其會與我們在 Redis OSS ECS 任務定義中定義的 Docker 標籤相符。因此，我們不需要在本節中進行任何變更：

   ```
   ecs_service_discovery": {
     "sd_frequency": "1m",
     "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
   *  "docker_label": {
     },*
     ...
   ```

   對於 `metric_declaration` 區段，預設的設定不允許任何 Redis OSS 指標。新增下列區段，以允許 Redis OSS 指標。請務必遵循現有的縮排模式。

   ```
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily"]],
     "metric_selectors": [
       "^redis_net_(in|out)put_bytes_total$",
       "^redis_(expired|evicted)_keys_total$",
       "^redis_keyspace_(hits|misses)_total$",
       "^redis_memory_used_bytes$",
       "^redis_connected_clients$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily","cmd"]],
     "metric_selectors": [
       "^redis_commands_total$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily","db"]],
     "metric_selectors": [
       "^redis_db_keys$"
     ]
   },
   ```

1. 如果您已在 Amazon ECS 叢集中部署 CloudWatch 代理程式 CloudFormation，您可以輸入下列命令來建立變更集。

   ```
   ECS_LAUNCH_TYPE=FARGATE
   CREATE_IAM_ROLES=True
   ECS_CLUSTER_SUBNET=$ECS_CLUSTER_SUBNET_1
   ECS_TASK_ROLE_NAME={{your_selected_ecs_task_role_name}}
   ECS_EXECUTION_ROLE_NAME={{your_selected_ecs_execution_role_name}}
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-$ECS_CLUSTER_NAME-$ECS_LAUNCH_TYPE-awsvpc \
       --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSLaunchType,ParameterValue=$ECS_LAUNCH_TYPE \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION} \
       --change-set-name redis-scraping-support
   ```

1. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 檢閱新建立的變更集 `redis-scraping-support`。您應該會看到一個可套用至 `CWAgentConfigSSMParameter` 資源的變更。輸入下列命令，以執行變更集並重新執行 CloudWatch 代理程式任務。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-$ECS_LAUNCH_TYPE-awsvpc \
   --region ${AWS_DEFAULT_REGION}
   ```

1. 請等候約 10 秒鐘，然後輸入下列命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-$ECS_LAUNCH_TYPE-awsvpc \
   --region ${AWS_DEFAULT_REGION}
   ```

1. 如果您是第一次在叢集上安裝具有 Prometheus 指標收集的 CloudWatch 代理程式，請輸入下列命令：

   ```
   ECS_LAUNCH_TYPE=FARGATE
   CREATE_IAM_ROLES=True
   ECS_CLUSTER_SUBNET=$ECS_CLUSTER_SUBNET_1
   ECS_TASK_ROLE_NAME={{your_selected_ecs_task_role_name}}
   ECS_EXECUTION_ROLE_NAME={{your_selected_ecs_execution_role_name}}
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-$ECS_CLUSTER_NAME-$ECS_LAUNCH_TYPE-awsvpc \
       --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSLaunchType,ParameterValue=$ECS_LAUNCH_TYPE \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION}
   ```

## 檢視 Redis OSS 指標
<a name="ContainerInsights-Prometheus-Setup-redis-view"></a>

此教學課程會將下列指標傳送至 CloudWatch 中的 **ECS/ContainerInsights/Prometheus** 命名空間。您可以使用 CloudWatch 主控台查看該命名空間中的指標。


| 指標名稱 | 維度 | 
| --- | --- | 
| `redis_net_input_bytes_total` | ClusterName、`TaskDefinitionFamily` | 
| `redis_net_output_bytes_total` | ClusterName、`TaskDefinitionFamily` | 
| `redis_expired_keys_total` | ClusterName、`TaskDefinitionFamily` | 
| `redis_evicted_keys_total` | ClusterName、`TaskDefinitionFamily` | 
| `redis_keyspace_hits_total` | ClusterName、`TaskDefinitionFamily` | 
| `redis_keyspace_misses_total` | ClusterName、`TaskDefinitionFamily` | 
| `redis_memory_used_bytes` | ClusterName、`TaskDefinitionFamily` | 
| `redis_connected_clients` | ClusterName、`TaskDefinitionFamily` | 
| `redis_commands_total` | ` ClusterName`, `TaskDefinitionFamily`, `cmd` | 
| `redis_db_keys` | `ClusterName`, `TaskDefinitionFamily`, `db` | 

**注意**  
**cmd** 維度的數值可以是：`append`、`client`、`command`、`config`、`dbsize`、`flushall`、`get`、`incr`、`info` `latency` 或 `slowlog`。  
**db** 維度的數值可以是 `db0` 至 `db15`。

您也可以為 Redis OSS Prometheus 指標建立 CloudWatch 儀表板。

**若要建立 Redis OSS Prometheus 指標的儀表板**

1. 建立環境變數，取代下面的數值，以符合您的部署。

   ```
   DASHBOARD_NAME={{your_cw_dashboard_name}}
   ECS_TASK_DEF_FAMILY=redis-prometheus-demo-$ECS_CLUSTER_NAME-fargate-awsvpc
   ```

1. 輸入下列命令建立儀表板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/redis/cw_dashboard_redis.json \
   | sed "s/{{YOUR_AWS_REGION}}/${REGION_NAME}/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/${CLUSTER_NAME}/g" \
   | sed "s/{{YOUR_NAMESPACE}}/${NAMESPACE}/g" \
   ```