Cloud9にCloudWatch Agentを入れて、メモリ使用率を監視してみた

# はじめに
Cloud9で複数のシミュレータを稼働させていますが、ときどきメモリ不足により停止していることがありました。

いちいちCloud9にログインしてメモリや起動状況を確認するのも面倒だし、後からいつシミュレータが停止したのかを追跡できるように、Cloud9に**CloudWatch Agent**を導入して簡単に監視できる仕組みを作りました。

今回はCloud9にCloudWatch Agentを導入する方法をご紹介します。


# Cloud9とは？
Cloud9はAWSが提供する統合開発環境(IDE)であり、AWSワークショップなどでもよく使われています。

デフォルトでAWS CLIやpythonが利用できるので、開発環境の構築が面倒な場合はCloud9を使って開発するのも手かと思います。

また、EC2を立ててsshで通信するなどの経験があまりない方にとっても、Cloud9の場合は複雑な設定がなくAWSコンソールから起動できるため、非常に取り組みやすいサービスだと思います。


# CloudWatch Agentとは？
前段で説明したCloud9もベースはEC2インスタンスの上で動いており、Cloud9というサービスが統合開発環境として扱えるように設定されています。

EC2インスタンスのメトリクスは、CloudWatch上でCPU使用率やネットワーク送受信量などの**標準メトリクス**を確認することができます。

一方で、メモリ使用率やディスクI/Oなどのメトリクスは、標準メトリクスには含まれていません。
これらのメトリクスを監視するためには、**CloudWatch Agent**をEC2インスタンスにインストール＆CloudWatchへデータ送信するように設定する必要があります。


# Cloud9にCloudWatch Agentを設定していく
では、これから順を追ってCloud9へCloudWatch Agentの設定方法を説明していきます。
ただし、Cloud9が既に構築されていることは前提条件とします。


## Cloud9のIAMロールを更新する
CloudWatch Agentを使用するためには、```CloudWatchAgentAdminPolicy```というロールがアタッチされている必要があります。

まず、```IAM```→```ロール```と進み、Cloud9にアタッチされているロールを確認します。
対象のロールに対して、Cloud

![設定したCloud9のIAMロール.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3706974/be8844d9-d303-169a-894a-2df3fecf2335.png)


## CloudWatch Agentのインストール
以下コマンドを実施して、CloudWatch Agentをインストールします。

```
sudo yum install amazon-cloudwatch-agent
```

途中で```Is this ok [y/d/N]: y```と聞かれますが、```y```で問題ありません。
```
{{user_name}}:~/environment $ sudo yum install amazon-cloudwatch-agent
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
250 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package amazon-cloudwatch-agent.x86_64 0:1.300033.0-1.amzn2 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===================================================================================================================================================================================================
 Package                                                Arch                                  Version                                              Repository                                 Size
===================================================================================================================================================================================================
Installing:
 amazon-cloudwatch-agent                                x86_64                                1.300033.0-1.amzn2                                   amzn2-core                                 95 M

Transaction Summary
===================================================================================================================================================================================================
Install  1 Package

Total download size: 95 M
Installed size: 360 M
Is this ok [y/d/N]: y
Downloading packages:
amazon-cloudwatch-agent-1.300033.0-1.amzn2.x86_64.rpm                                                                                                                       |  95 MB  00:00:01     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
create group cwagent, result: 0
create user cwagent, result: 0
  Installing : amazon-cloudwatch-agent-1.300033.0-1.amzn2.x86_64                                                                                                                               1/1 
  Verifying  : amazon-cloudwatch-agent-1.300033.0-1.amzn2.x86_64                                                                                                                               1/1 

Installed:
  amazon-cloudwatch-agent.x86_64 0:1.300033.0-1.amzn2                                                                                                                                              

Complete!
```

## CloudWatch Agentを設定する
CloudWatch Agentをインストールしたら、早速設定していきます。
以下コマンドを実行します
```
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
```

すると設定ウィザードに従い、質問に回答していきます。
以下選択は私の環境の場合のため、適宜環境に応じて変更してください。

まずはLinuxなので1を選択します。
```
{{user_name}}:~/environment $ sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
================================================================
= Welcome to the Amazon CloudWatch Agent Configuration Manager =
=                                                              =
= CloudWatch Agent allows you to collect metrics and logs from =
= your host and send them to CloudWatch. Additional CloudWatch =
= charges may apply.                                           =
================================================================
On which OS are you planning to use the agent?
1. linux
2. windows
3. darwin
default choice: [1]:
1
```

EC2なので1を選択します。
```
Trying to fetch the default region based on ec2 metadata...
I! imds retry client will retry 1 timesAre you using EC2 or On-Premises hosts?
1. EC2
2. On-Premises
default choice: [1]:
1
```

デフォルトの1を選択します。
```
Which user are you planning to run the agent?
1. cwagent
2. root
3. others
default choice: [1]:
1
```

StatsD daemonを起動するので1を選択します。
```
Do you want to turn on StatsD daemon?
1. yes
2. no
default choice: [1]:
1
```

ポートはデフォルトでよいです。
```
Which port do you want StatsD daemon to listen to?
default choice: [8125]
```

デフォルトの1を選択します。
```
What is the collect interval for StatsD daemon?
1. 10s
2. 30s
3. 60s
default choice: [1]:
```

デフォルトの4（60秒間隔）を選択します。
```
What is the aggregation interval for metrics collected by StatsD daemon?
1. Do not aggregate
2. 10s
3. 30s
4. 60s
default choice: [4]:
```

CollectDを有効します。Collectdは後でインストールします。
```
Do you want to monitor metrics from CollectD? WARNING: CollectD must be installed or the Agent will fail to start
1. yes
2. no
default choice: [1]:
```

デフォルトの1を選択します。
```
Do you want to monitor any host metrics? e.g. CPU, memory, etc.
1. yes
2. no
default choice: [1]:
```

デフォルトの1を選択します。今回の目的のメトリクスです。
```
Do you want to monitor cpu metrics per core?
1. yes
2. no
default choice: [1]:
```

デフォルトの1を選択します。
```
Do you want to add ec2 dimensions (ImageId, InstanceId, InstanceType, AutoScalingGroupName) into all of your metrics if the info is available?
1. yes
2. no
default choice: [1]:
```

デフォルトの1を選択します。
```
Do you want to aggregate ec2 dimensions (InstanceId)?
1. yes
2. no
default choice: [1]:
```

デフォルトの4を選択します。
```
Would you like to collect your metrics at high resolution (sub-minute resolution)? This enables sub-minute resolution for all metrics, but you can customize for specific metrics in the output json file.
1. 1s
2. 10s
3. 30s
4. 60s
default choice: [4]:
```

今回は最も収集メトリクスの多い```3 Advanced```を選択します。
```
Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:
3
```

Advancdを選択すると、現状Configが表示されます。
```
Current config as follows:
{
        "agent": {
                "metrics_collection_interval": 60,
                "run_as_user": "cwagent"
        },
        "metrics": {
                "aggregation_dimensions": [
                        [
                                "InstanceId"
                        ]
                ],
                "append_dimensions": {
                        "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
                        "ImageId": "${aws:ImageId}",
                        "InstanceId": "${aws:InstanceId}",
                        "InstanceType": "${aws:InstanceType}"
                },
                "metrics_collected": {
                        "collectd": {
                                "metrics_aggregation_interval": 60
                        },
                        "cpu": {
                                "measurement": [
                                        "cpu_usage_idle",
                                        "cpu_usage_iowait",
                                        "cpu_usage_user",
                                        "cpu_usage_system"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ],
                                "totalcpu": false
                        },
                        "disk": {
                                "measurement": [
                                        "used_percent",
                                        "inodes_free"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "diskio": {
                                "measurement": [
                                        "io_time",
                                        "write_bytes",
                                        "read_bytes",
                                        "writes",
                                        "reads"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        },
                        "netstat": {
                                "measurement": [
                                        "tcp_established",
                                        "tcp_time_wait"
                                ],
                                "metrics_collection_interval": 60
                        },
                        "statsd": {
                                "metrics_aggregation_interval": 60,
                                "metrics_collection_interval": 10,
                                "service_address": ":8125"
                        },
                        "swap": {
                                "measurement": [
                                        "swap_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        }
                }
        }
}
```

デフォルトの1を選択します。
```
Are you satisfied with the above config? Note: it can be manually customized after the wizard completes to add additional items.
1. yes
2. no
default choice: [1]:
```

他のAgentはないので```2 no```を選択します。
```
Do you have any existing CloudWatch Log Agent (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html) configuration file to import for migration?
1. yes
2. no
default choice: [2]:
```

logを取得するので```1 yes```を選択します。
```
Do you want to monitor any log files?
1. yes
2. no
default choice: [1]:
```

ログファイル場所として```/var/log/messages```を入力します。
```
Log file path:
/var/log/messages
```

ロググループ名は```messages```とします。
```
Log group name:
default choice: [messages]
```

ロググループクラスは```1 STANDARD```を選択します。
```
Log group class:
1. STANDARD
2. INFREQUENT_ACCESS
default choice: [1]:
```

ログストリーム名はデフォルトにします。
```
Log stream name:
default choice: [{instance_id}]
```

ログ保持期間はデフォルトの1日を設定します。
（デフォルトは-1なのでご注意ください）
```
Log Group Retention in days
1. -1
2. 1
3. 3
4. 5
5. 7
6. 14
7. 30
8. 60
9. 90
10. 120
11. 150
12. 180
13. 365
14. 400
15. 545
16. 731
17. 1096
18. 1827
19. 2192
20. 2557
21. 2922
22. 3288
23. 3653
default choice: [1]:
```

他に監視したいログファイルはないので```2 no```を選択します。
```
Do you want to specify any additional log files to monitor?
1. yes
2. no
default choice: [1]:
2
```

今回はX-rayを使用しないので```2 no```を選択します。
```
Do you want the CloudWatch agent to also retrieve X-ray traces?
1. yes
2. no
default choice: [1]:
2
```

設定ファイルが生成され、表示されます。
```
Existing config JSON identified and copied to:  /opt/aws/amazon-cloudwatch-agent/etc/backup-configs
Saved config file to /opt/aws/amazon-cloudwatch-agent/bin/config.json successfully.
Current config as follows:
{
        "agent": {
                "metrics_collection_interval": 60,
                "run_as_user": "cwagent"
        },
        "logs": {
                "logs_collected": {
                        "files": {
                                "collect_list": [
                                        {
                                                "file_path": "/var/log/messages",
                                                "log_group_class": "STANDARD",
                                                "log_group_name": "messages",
                                                "log_stream_name": "{instance_id}",
                                                "retention_in_days": 1
                                        }
                                ]
                        }
                }
        },
        "metrics": {
                "aggregation_dimensions": [
                        [
                                "InstanceId"
                        ]
                ],
                "append_dimensions": {
                        "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
                        "ImageId": "${aws:ImageId}",
                        "InstanceId": "${aws:InstanceId}",
                        "InstanceType": "${aws:InstanceType}"
                },
                "metrics_collected": {
                        "collectd": {
                                "metrics_aggregation_interval": 60
                        },
                        "cpu": {
                                "measurement": [
                                        "cpu_usage_idle",
                                        "cpu_usage_iowait",
                                        "cpu_usage_user",
                                        "cpu_usage_system"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ],
                                "totalcpu": false
                        },
                        "disk": {
                                "measurement": [
                                        "used_percent",
                                        "inodes_free"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "diskio": {
                                "measurement": [
                                        "io_time",
                                        "write_bytes",
                                        "read_bytes",
                                        "writes",
                                        "reads"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        },
                        "netstat": {
                                "measurement": [
                                        "tcp_established",
                                        "tcp_time_wait"
                                ],
                                "metrics_collection_interval": 60
                        },
                        "statsd": {
                                "metrics_aggregation_interval": 60,
                                "metrics_collection_interval": 10,
                                "service_address": ":8125"
                        },
                        "swap": {
                                "measurement": [
                                        "swap_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        }
                }
        }
}
Please check the above content of the config.
The config file is also located at /opt/aws/amazon-cloudwatch-agent/bin/config.json.
Edit it manually if needed.
```

設定ファイルをSSM(Systems Manager)のパラメータストアに保存するか聞かれます。
今回は保存しない（ローカルのみ）でよいので、```2 no```を選択します。
```
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:
2
```

これでウィザード設定が完了します。
```
Program exits now.
```

## Collectdのインストール
ウィザードで出てきたCollectdを以下コマンドでインストールします。
先ほど作成したCloudWatch Agent設定ファイルのあるディレクトリに移動し、設定ファイル```config.json```を指定します。

```
cd /opt/aws/amazon-cloudwatch-agent/bin/
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:config.json
```

途中で```Is this ok [y/d/N]:```と聞かれますが、```y```と回答します。
```
{{user_name}}:~/environment $ sudo amazon-linux-extras install collectd
Installing collectd
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Cleaning repos: amzn2-core amzn2extra-collectd amzn2extra-docker amzn2extra-epel amzn2extra-kernel-5.10 amzn2extra-lamp-mariadb10.2-php7.2 amzn2extra-python3.8 epel hashicorp
45 metadata files removed
22 sqlite files removed
0 metadata files removed
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                                                                                                                                                                       | 3.6 kB  00:00:00     
amzn2extra-collectd                                                                                                                                                                                              | 3.0 kB  00:00:00     
amzn2extra-docker                                                                                                                                                                                                | 2.9 kB  00:00:00     
amzn2extra-epel                                                                                                                                                                                                  | 3.0 kB  00:00:00     
amzn2extra-kernel-5.10                                                                                                                                                                                           | 3.0 kB  00:00:00     
amzn2extra-lamp-mariadb10.2-php7.2                                                                                                                                                                               | 3.0 kB  00:00:00     
amzn2extra-python3.8                                                                                                                                                                                             | 2.9 kB  00:00:00     
epel/x86_64/metalink                                                                                                                                                                                             | 8.7 kB  00:00:00     
https://ftp.kaist.ac.kr/pub/epel/7/x86_64/repodata/repomd.xml: [Errno 14] curl#35 - "Recv failure: Connection reset by peer"
Trying other mirror.
epel                                                                                                                                                                                                             | 4.7 kB  00:00:00     
hashicorp                                                                                                                                                                                                        | 1.4 kB  00:00:00     
(1/19): amzn2-core/2/x86_64/group_gz                                                                                                                                                                             | 2.7 kB  00:00:00     
(2/19): amzn2-core/2/x86_64/updateinfo                                                                                                                                                                           | 830 kB  00:00:00     
(3/19): amzn2extra-docker/2/x86_64/primary_db                                                                                                                                                                    | 106 kB  00:00:00     
(4/19): amzn2extra-epel/2/x86_64/updateinfo                                                                                                                                                                      |   76 B  00:00:00     
(5/19): amzn2extra-epel/2/x86_64/primary_db                                                                                                                                                                      | 1.8 kB  00:00:00     
(6/19): amzn2extra-kernel-5.10/2/x86_64/updateinfo                                                                                                                                                               |  53 kB  00:00:00     
(7/19): amzn2extra-collectd/2/x86_64/primary_db                                                                                                                                                                  |  60 kB  00:00:00     
(8/19): amzn2extra-collectd/2/x86_64/updateinfo                                                                                                                                                                  |   76 B  00:00:00     
(9/19): amzn2extra-docker/2/x86_64/updateinfo                                                                                                                                                                    |  15 kB  00:00:00     
(10/19): amzn2extra-lamp-mariadb10.2-php7.2/2/x86_64/updateinfo                                                                                                                                                  |   76 B  00:00:00     
(11/19): amzn2extra-python3.8/2/x86_64/updateinfo                                                                                                                                                                | 4.4 kB  00:00:00     
(12/19): amzn2extra-python3.8/2/x86_64/primary_db                                                                                                                                                                |  60 kB  00:00:00     
(13/19): amzn2extra-lamp-mariadb10.2-php7.2/2/x86_64/primary_db                                                                                                                                                  | 506 kB  00:00:00     
(14/19): amzn2extra-kernel-5.10/2/x86_64/primary_db                                                                                                                                                              |  24 MB  00:00:00     
(15/19): epel/x86_64/group_gz                                                                                                                                                                                    | 100 kB  00:00:00     
(16/19): epel/x86_64/primary_db                                                                                                                                                                                  | 7.0 MB  00:00:00     
(17/19): hashicorp/x86_64/primary                                                                                                                                                                                | 229 kB  00:00:00     
(18/19): amzn2-core/2/x86_64/primary_db                                                                                                                                                                          |  72 MB  00:00:01     
(19/19): epel/x86_64/updateinfo                                                                                                                                                                                  | 1.0 MB  00:00:00     
hashicorp                                                                                                                                                                                                                     1665/1665
300 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package collectd.x86_64 0:5.8.1-1.amzn2.0.2 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================================================================================================================================================
 Package                                            Arch                                             Version                                                        Repository                                                     Size
========================================================================================================================================================================================================================================
Installing:
 collectd                                           x86_64                                           5.8.1-1.amzn2.0.2                                              amzn2extra-collectd                                           706 k

Transaction Summary
========================================================================================================================================================================================================================================
Install  1 Package

Total download size: 706 k
Installed size: 2.0 M
Is this ok [y/d/N]: y
Downloading packages:
collectd-5.8.1-1.amzn2.0.2.x86_64.rpm                                                                                                                                                                            | 706 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : collectd-5.8.1-1.amzn2.0.2.x86_64                                                                                                                                                                                    1/1 
  Verifying  : collectd-5.8.1-1.amzn2.0.2.x86_64                                                                                                                                                                                    1/1 

Installed:
  collectd.x86_64 0:5.8.1-1.amzn2.0.2                                                                                                                                                                                                   

Complete!
  2  httpd_modules                   available    [ =1.0  =stable ]
  3  memcached1.5                    available    \
        [ =1.5.1  =1.5.16  =1.5.17 ]
  9  R3.4                            available    [ =3.4.3  =stable ]
 10  rust1                           available    \
        [ =1.22.1  =1.26.0  =1.26.1  =1.27.2  =1.31.0  =1.38.0
          =stable ]
 17 *lamp-mariadb10.2-php7.2=latest  enabled      \
        [ =10.2.10_7.2.0  =10.2.10_7.2.4  =10.2.10_7.2.5
          =10.2.10_7.2.8  =10.2.10_7.2.11  =10.2.10_7.2.13
          =10.2.10_7.2.14  =10.2.10_7.2.16  =10.2.10_7.2.17
          =10.2.10_7.2.19  =10.2.10_7.2.22  =10.2.10_7.2.23
          =10.2.10_7.2.24  =stable ]
 18  libreoffice                     available    \
        [ =5.0.6.2_15  =5.3.6.1  =stable ]
 19  gimp                            available    [ =2.8.22 ]
 20 †docker=latest                   enabled      \
        [ =17.12.1  =18.03.1  =18.06.1  =18.09.9  =stable ]
 21  mate-desktop1.x                 available    \
        [ =1.19.0  =1.20.0  =stable ]
 22  GraphicsMagick1.3               available    \
        [ =1.3.29  =1.3.32  =1.3.34  =stable ]
 23 †tomcat8.5                       available    \
        [ =8.5.31  =8.5.32  =8.5.38  =8.5.40  =8.5.42  =8.5.50
          =stable ]
 24  epel=latest                     enabled      [ =7.11  =stable ]
 25  testing                         available    [ =1.0  =stable ]
 26  ecs                             available    [ =stable ]
 27 †corretto8                       available    \
        [ =1.8.0_192  =1.8.0_202  =1.8.0_212  =1.8.0_222  =1.8.0_232
          =1.8.0_242  =stable ]
 32  lustre2.10                      available    \
        [ =2.10.5  =2.10.8  =stable ]
 33 †java-openjdk11                  available    [ =11  =stable ]
 34  lynis                           available    [ =stable ]
 36  BCC                             available    [ =0.x  =stable ]
 37  mono                            available    [ =5.x  =stable ]
 38  nginx1                          available    [ =stable ]
 40  mock                            available    [ =stable ]
 43  livepatch                       available    [ =stable ]
 44 †python3.8=latest                enabled      [ =stable ]
 45  haproxy2                        available    [ =stable ]
 46  collectd=latest                 enabled      [ =stable ]
 47  aws-nitro-enclaves-cli          available    [ =stable ]
 48  R4                              available    [ =stable ]
  _  kernel-5.4                      available    [ =stable ]
 50  selinux-ng                      available    [ =stable ]
 52  tomcat9                         available    [ =stable ]
 53  unbound1.13                     available    [ =stable ]
  _ †mariadb10.5                     available    [ =stable ]
 55  kernel-5.10=latest              enabled      [ =stable ]
 56  redis6                          available    [ =stable ]
 57 †ruby3.0                         available    [ =stable ]
 58 †postgresql12                    available    [ =stable ]
 59 †postgresql13                    available    [ =stable ]
 60  mock2                           available    [ =stable ]
 61  dnsmasq2.85                     available    [ =stable ]
 62  kernel-5.15                     available    [ =stable ]
 63 †postgresql14                    available    [ =stable ]
 64  firefox                         available    [ =stable ]
 65  lustre                          available    [ =stable ]
  _ †php8.1                          available    [ =stable ]
 67  awscli1                         available    [ =stable ]
  _ †php8.2                          available    [ =stable ]
 69  dnsmasq                         available    [ =stable ]
 70  unbound1.17                     available    [ =stable ]
  _  collectd-python3                available    [ =stable ]
* Extra topic has reached end of support.
† Note on end-of-support. Use 'info' subcommand.
```

## CloudWatch Agentの実行
それではCloudWatch Agentを実行します。

先ほど作成したCloudWatch Agent設定ファイルのあるディレクトリに移動し、設定ファイル```config.json```を指定します。
```
cd /opt/aws/amazon-cloudwatch-agent/bin/
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:config.json

```

以下実行例です。
```Active: active (running)```と表示されれば、正常に起動されています。
```
{{user_name}}:/opt/aws/amazon-cloudwatch-agent/bin $ systemctl status amazon-cloudwatch-agent
● amazon-cloudwatch-agent.service - Amazon CloudWatch Agent
   Loaded: loaded (/etc/systemd/system/amazon-cloudwatch-agent.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2024-03-20 02:23:14 UTC; 1min 41s ago
 Main PID: 20588 (amazon-cloudwat)
    Tasks: 8
   Memory: 175.2M
   CGroup: /system.slice/amazon-cloudwatch-agent.service
           └─20588 /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent -config /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml -envconfig /opt/aws/amazon-cloudwatch-agent/etc/env-config.json -otelconfig...

Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: 2024/03/20 02:23:16 Reading json config file path: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/fi...g.json ...
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: 2024/03/20 02:23:16 I! Valid Json input schema.
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: I! Detecting run_as_user...
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: I! Trying to detect region from ec2
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: 2024/03/20 02:23:16 D! ec2tagger processor required because append_dimensions is set
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: 2024/03/20 02:23:16 D! delta processor required because metrics with diskio or net are set
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: 2024/03/20 02:23:16 D! ec2tagger processor required because append_dimensions is set
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: 2024/03/20 02:23:16 Configuration validation first phase succeeded
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json does not exist or cannot read. Skipping it.
Mar 20 02:23:16 ip-xxx-xxx-xxx-xxx.ap-northeast-1.compute.internal start-amazon-cloudwatch-agent[20588]: I! Detecting run_as_user...
Hint: Some lines were ellipsized, use -l to show in full.
```

起動状態は以下コマンドで確認できます。
```
systemctl status amazon-cloudwatch-agent
```

Cloud9を頻繁に起動/停止する場合は、CloudWatch Agentを自動起動設定しておきましょう。
自動起動設定は以下の設定で問題なさそうです。
```
sudo systemctl enable amazon-cloudwatch-agent
```


# CloudWatchでCloud9のメモリ使用率を確認する
CloudWatch Agentを起動してしばらく経過したら、メトリクスをCloudWatchで確認しましょう。

```CloudWatch```→```すべてのメトリクス```にて、```カスタム名前空間```に**CWAgent**があることを確認します。
![cloudwatch_metrics.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3706974/02ff0452-efcf-51a7-20e9-807ad89d9cd5.png)

メモリ使用量は```InstanceId```→```mem_used_percent```をチェックすると、メモリ使用率を確認できます。

例えば、CloudWatch Agentで収集されたディスク使用率やスワップ使用率、EC2インスタンスの標準メトリクスであるCPU使用率を組み合わせたダッシュボードを作っておくことができます。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3706974/f3a23ceb-0673-05d2-976b-e6b5d7a465a5.png)


## まとめ
EC2インスタンスにCloudWatch Agentを導入するのとほぼ同じ手順で、Cloud9でもCloudWatch Agentを導入できました。
長時間Cloud9を動作させ続けたい方は、設定しておくと便利かもしれません。