今回は CloudWatch の Alarm を CLI 経由で設定します。


・負荷をかける対象のEC2インスタンスを作成する
GUIでCloudWatchのAlarmを設定した記事でやったように、sysbench というコマンドで負荷をかけてみます。
AmazonLinux では sysbench が yum でインストールできるパッケージに含まれていないので、負荷対象として 新規に Ubuntu を OS とする EC2を起動します。
$ ec2-run-instances  \
     ami-20ad1221 \
     --group web  \
     --key innerkey  \
     --instance-count 1  \
     --instance-type t1.micro  \
     --instance-initiated-shutdown-behavior stop

RESERVATION     r-15841f16      488224276535    web
INSTANCE        i-55b38d56      ami-20ad1221                    pending innerkey        0             t1.micro        2013-02-25T07:43:21+0000        ap-northeast-1a aki-ec5df7ed                  monitoring-disabled                                     ebs                                   paravirtual     xen             sg-33bace32     default false
セキュリティグループや鍵ペアについては適切なものを指定ください。

次に、作成した 負荷対象となるEC2インスタンスにsshログインして、負荷試験ツール(sysbench)をインストールします。まずは ssh ログイン。
$ ec2-describe-instances i-55b38d56 \
     | grep '^INSTANCE'  \
     | cut --fields=5

ip-10-132-166-244.ap-northeast-1.compute.internal

$ ssh \
     -i ~/.ssh/innerkey.pem \
     -l ubuntu \
     ip-10-132-166-244.ap-northeast-1.compute.internal

続いて、EC2インスタンス上での設定。
まずは前準備の呪文として、以下の二つを実行しておきます(後者は、まぁ、無くてもOKかも)。
$ sudo apt-get update
$ sudo apt-get upgrade
次は、sysbench をインストールします。
$ sudo apt-cache search sysbench
sysbench - Cross-platform and multi-threaded benchmark tool

$ sudo apt-get install sysbench

Ubuntu 側の設定はコレで終わりなので、一旦ログアウトしておきます。
$ exit



・S
NSの設定

Alarmを利用するには通知先となるSNSが必要になります。
そのため、先に server-alarm という名前のSNSトピックを作成し、メールアドレスを登録しておきます。
手順は以前の記事を参考にしてください。
$ sns-create-topic server-alarm
arn:aws:sns:ap-northeast-1:488224276535:server-alarm

$ sns-subscribe \
     arn:aws:sns:ap-northeast-1:488224276535:server-alarm \
     --protocol email  \
     --endpoint  exploreaws@example.com

Subscription request received.

※ここでメール受信

$ sns-confirm-subscription \
     arn:aws:sns:ap-northeast-1:488224276535:server-alarm \
     --token ~メールで送られてきたTOEKN識別子~

arn:aws:sns:ap-northeast-1:488224276535:server-alarm:59bb374a-186b-40e9-8d6c-09d43d716058
念のため、sns-publish コマンドで通知が届くことを確認しておいてください。
⇒ Alarm設定後に通知が届かない場合、SNS側の設定ミスなのか、Alarm側の設定ミスなのか判断できなくなるので。
$ sns-publish \
     arn:aws:sns:ap-northeast-1:488224276535:server-alarm \
     --message 'This is sample publishing.'

13dc2c0b-069c-5820-8e6e-65965c13ae80



・Alarmの設定
(AmazonLinuxの場合) /opt/aws/bin/ にインストールされている alarm に関連しそうな mon-* 系コマンドは以下の通り。
$ ls -1 /opt/aws/bin/mon* \
     | grep -i alarm

/opt/aws/bin/mon-delete-alarms
/opt/aws/bin/mon-describe-alarm-history
/opt/aws/bin/mon-describe-alarms
/opt/aws/bin/mon-describe-alarms-for-metric
/opt/aws/bin/mon-disable-alarm-actions
/opt/aws/bin/mon-enable-alarm-actions
/opt/aws/bin/mon-put-metric-alarm
/opt/aws/bin/mon-set-alarm-state
Alarmの作成と削除は、それぞれ mon-put-metric-alarm と mon-delete-alarms が対応するようです。

まずはAlarmの作成から。

mon-put-metric-alarm で、良く使いそうなパラメータを並べてみます。
mon-put-metric-alarm

  ALARM_NAME
  --alarm-description 'COMMENT'
  --alarm-actions SNS_TOPIC_NAME,...

  --namespace  CLOUDWATCH_NAMESPACE
  --metric-name  CLOUDWATCH_METRIC
  --statistic  CLOUDWATCH_STATISTIC
  --dimensions CLOUDWATCH_DIMENSION
  --period  CLOUDWATCH_PERIOD_IN_SECOND
  --unit CLOUDWATCH_UNIT

  --threshold  VALUE_TO_COMPARE
  --evaluation-periods  NUMBER_OF_PERIODS
  --comparison-operator  (
         GreaterThanOrEqualToThreshold
       | GreaterThanThreshold,
       | LessThanThreshold
       | LessThanOrEqualToThreshold
       )
ものすごく大量にあってゲンナリしますが…。2つにグループ分けすると、以下のような感じになります。
  • 上段 - Alarmに関する名前、通知先SNSトピックの指定
  • 中段 - 監視対象となる CloudWatch の指定
  • 下段 - 条件と閾値(この値になったらAlarm作動するぜ…というモノ)

Alarm に関する名前は、EC2インスタンス自身の CPU負荷に対するAlarmを作成するので、それらしいモノにしておきます。


  cpu-overload
  --alarm-description 'CPU utlization overload'
  --alarm-actions server-alarm


CloudWatch の設定は、前回の記事で試したので特に困ることは無いですね…。以下のような感じになります。


  --namespace  AWS/EC2
  --metric-name  CPUUtilization
  --statistic  Average
  --period  300

  --unit Percent


EC2インスタンス、300秒(5分)間、CPU使用率…の平均値を監視対象とします。

どのEC2インスタンスで負荷が発生してもAlarmを出したいので、dimensions は指定しません。

period を指定させる意味が良く分かりませんが、とりあえず(CloudWatchデフォルトの)300としておきます。


最後の条件と閾値は…


  --threshold  50
  --evaluation-periods  2
  --comparison-operator  GreaterThanOrEqualToThreshold


…という設定で、「監視対象の値が 50%以上の2回以上続いたら」という条件設定にします。

ではコマンドを実行してみましょう。
$ mon-put-metric-alarm  \
     cpu-overload  \
     --alarm-description 'CPU utlization overload'  \
     --alarm-actions arn:aws:sns:ap-northeast-1:488224276535:server-alarm  \
     --namespace  AWS/EC2  \
     --metric-name  CPUUtilization  \
     --statistic  Average  \
     --period  300  \
     --unit Percent  \
     --threshold  50  \
     --evaluation-periods  2  \
     --comparison-operator  GreaterThanOrEqualToThreshold
OK-Created Alarm
先ほどのコマンド一覧にあった mon-describe-alarms で結果を確認してみます。
$ mon-describe-alarms
cpu-overload  INSUFFICIENT_DATA  arn:aws:sns:ap-nor...276535:server-alarm  AWS/EC2  CPUUtilization  300  Average  2  GreaterThanOrEqualToThreshold  50.0
それらしいものが設定されているように見えますね…。
しかし、状態(?)が INSUFFICIENT_DATA になっています。これって異常???
https://forums.aws.amazon.com/message.jspa?messageID=253009

Ensure any dimensions you specify are applicable to the metric (e.g. CPUUtilization for EC2 instances is measured against the InstanceId and AutoscalingGroup dimensions for the AWS/EC2 namespace, whereas CPUUtilization for RDS is measured against the dimensions DatabaseClass, DBInstanceIdentifier and EngineName for the AWS/RDS namespace).
上記の公式フォーラムの回答によると、CPUUtilization は Instance-ID か AutoScalingGroup を dimension として必要とするみたいですね…。どのインスタンスのCPU 負荷でも良いからアラーム対象とする…という設定にはできないみたいです…(x_x;

Alarm を再設定します。再設定(update)も 同じ mon-put-metric-alarm コマンドを使用するようです。
$ mon-put-metric-alarm  \
     cpu-overload  \
     --alarm-description 'CPU utlization overload'  \
     --alarm-actions arn:aws:sns:ap-northeast-1:488224276535:server-alarm  \
     --namespace  AWS/EC2  \
     --metric-name  CPUUtilization  \
     --dimensions 'InstanceId=i-55b38d56' \
     --statistic  Average  \
     --period  300  \
     --unit Percent  \
     --threshold  50  \
     --evaluation-periods  2  \
     --comparison-operator  GreaterThanOrEqualToThreshold

OK-Created Alarm

$ mon-describe-alarms
cpu-overload  OK  arn:aws:sns:ap-nor...276535:server-alarm  AWS/EC2  CPUUtilization  300  Average  2  GreaterThanOrEqualToThreshold  50.0
今度はバッチリ設定されているようですね。




・負荷試験の実行

負荷試験は、Ubuntu側で直接実行します。sshでログインして、そこから作業しましょう。
先に設定した mon-put-metric-alarm では「5分単位の計測で2回の高負荷」時に警告が飛ぶようにしたので、比較的な長い時間負荷試験を実行する必要があります。
ここでは、900秒(15分)実行しておくことにします。

$ ssh \
     -i ~/.ssh/innerkey.pem \
     -l ubuntu \
     ip-10-132-166-244.ap-northeast-1.compute.internal



$ sysbench \
     --max-requests=9999999 \
     --max-time=900 \
     --test=cpu run


sysbench 0.4.12:  multi-threaded system evaluation benchmark

Running the test with following options:
Number of threads: 1

Doing CPU performance benchmark

Threads started!

Time limit exceeded, exiting...
Done.

Maximum prime number checked in CPU test: 10000


Test execution summary:
    total time:                          900.0490s
    total number of events:              203125
    total time taken by event execution: 899.3371
    per-request statistics:
         min:                                  1.78ms
         avg:                                  4.43ms
         max:                                229.57ms
         approx.  95 percentile:               2.11ms

Threads fairness:
    events (avg/stddev):           203125.0000/0.00
    execution time (avg/stddev):   899.3371/0.00



負荷試験対象である Ubuntu にはEC2コマンドをインストールしていないので、AmazonLinuxなインスタンスから CPUUtlization (CPU負荷)を確認してみます。
$ mon-get-stats  \
     CPUUtilization \
     --namespace AWS/EC2 \
     --statistics Maximum \
     --dimensions 'InstanceId=i-55b38d56'
2013-02-25 09:40:00  1.67   Percent
2013-02-25 09:45:00  1.67   Percent
2013-02-25 09:50:00  1.69   Percent
2013-02-25 09:55:00  1.64   Percent
2013-02-25 10:00:00  1.67   Percent
2013-02-25 10:05:00  1.75   Percent
2013-02-25 10:10:00  100.0  Percent
2013-02-25 10:15:00  100.0  Percent
2013-02-25 10:20:00  100.0  Percent
2013-02-25 10:25:00  100.0  Percent
2013-02-25 10:30:00  100.0  Percent

$ mon-describe-alarms
cpu-overload  OK  arn:aws:sns:ap-nor...276535:server-alarm  AWS/EC2  CPUUtilization  300  Average  2  GreaterThanOrEqualToThreshold  50.0

$ mon-describe-alarm-history cpuoverload
cpu-overload  2013-02-25T10:35:36.223Z  StateUpdate          Alarm updated from ALARM to OK
cpu-overload  2013-02-25T10:25:36.253Z  Action               Successfully executed action arn:aws:sns:ap-northeast-1:488224276535:server-alarm
cpu-overload  2013-02-25T10:25:36.230Z  StateUpdate          Alarm updated from OK to ALARM
cpu-overload  2013-02-25T09:46:47.720Z  StateUpdate          Alarm updated from INSUFFICIENT_DATA to OK
cpu-overload  2013-02-25T09:46:47.136Z  ConfigurationUpdate  Alarm "cpu-overload" updated
cpu-overload  2013-02-25T09:33:04.279Z  ConfigurationUpdate  Alarm "cpu-overload" created

Alarmに設定されたアクションが実行されたことになっています。

exploreaws@example.com にも、「ALARM: "cpu-overload" in APAC - Tokyo」という件名のメールが届いていました。

You are receiving this email because your Amazon CloudWatch Alarm "cpu-overload" in the APAC - Tokyo region has entered the ALARM state, because "Threshold Crossed: 2 datapoints were greater than or equal to the threshold (50.0). The most recent datapoints: [100.0, 100.0]." at "Monday 25 February, 2013 10:25:36 UTC".

View this alarm in the AWS Management Console:
https://console.aws.amazon.com/cloudwatch/home?region=ap-northeast-1#s=Alarms&alarm=cpu-overload

Alarm Details:
- Name:                       cpu-overload
- Description:                CPU utlization overload
- State Change:               OK -> ALARM
- Reason for State Change:    Threshold Crossed: 2 datapoints were greater than or equal to the threshold (50.0). The most recent datapoints: [100.0, 100.0].
- Timestamp:                  Monday 25 February, 2013 10:25:36 UTC
- AWS Account:                488224276535

Threshold:
- The alarm is in the ALARM state when the metric is GreaterThanOrEqualToThreshold 50.0 for 300 seconds. 

Monitored Metric:
- MetricNamespace:            AWS/EC2
- MetricName:                 CPUUtilization
- Dimensions:                 [InstanceId = i-55b38d56]
- Period:                     300 seconds
- Statistic:                  Average
- Unit:                       Percent

State Change Actions:
- OK: 
- ALARM: [arn:aws:sns:ap-northeast-1:488224276535:server-alarm]
- INSUFFICIENT_DATA: 

これでAlarmの設定が正しく機能していることが確認できました。

ちなみに、今回は「ALARMになった時」のActionだけ設定しましたが、実運用では「OKになった時」も設定しておくのが良いでしょう。負荷状態から自動的に復帰した場合、それも知りたいでしょうから…。

しかしAlarmの文面が変更できないのは、微妙に使いにくいですね…。



・後始末
mon-delete-alarm でAlarm設定を削除します。
$ mon-delete-alarms cpu-overload
    Are you sure you want to delete these Alarms? [Ny]y
OK-Deleted alarms
プロンプトがメンドくさければ、--force オプションで抑制できます。

Alarm の通知先であった、SNS も削除します。
$ sns-list-topics
arn:aws:sns:ap-northeast-1:488224276535:server-alarm

$ sns-delete-topic \
     arn:aws:sns:ap-northeast-1:488224276535:server-alarm
    Are you sure you want to delete this topic? [Ny]y
Topic deleted.
要らなくなった EC2 インスタンス (Ubuntu)も削除しておいてください。
$ ec2-stop-instances i-55b38d56
INSTANCE        i-55b38d56      running stopping

$ ec2-terminate-instances i-55b38d56
INSTANCE        i-55b38d56      stopped terminated

これで後始末も終了。




今回はここまで。