Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
57 lines (45 sloc) 1.82 KB
require 'fog'
require 'tempfile' # to enable use of Dir.tmpdir
fail "you need to set AWS_ACCESS_KEY_ID" unless access_key = ENV['AWS_ACCESS_KEY_ID']
fail "you need to set AWS_SECRET_KEY" unless secret_key = ENV['AWS_SECRET_KEY']
# This file is touched to record a timestamp for the last successful send
last_sent_time_file_path = File.join(Dir.tmpdir, 'cloud-watch-sent-time')
instance_id = `wget -q -O - http://169.254.169.254/2011-01-01/meta-data/instance-id`
inactive_mem = `vmstat -s -S M | grep 'inactive mem' | awk '{print $1}'`.to_i
free_mem = `vmstat -s -S M | grep 'free mem' | awk '{print $1}'`.to_i
swap_used = `vmstat -s -S M | grep 'used swap' | awk '{print $1}'`.to_i
disk_avail = `df | grep '\/$' | awk '{print $4}'`.to_f
metric_data = []
metric_data.push({
'MetricName' => 'FreeableMemory',
'Unit' => 'Megabytes',
'Value' => inactive_mem + free_mem,
'Dimensions' => [{'Name' => 'InstanceId', 'Value' => instance_id}]
})
metric_data.push({
'MetricName' => 'SwapUsage',
'Unit' => 'Megabytes',
'Value' => swap_used,
'Dimensions' => [{'Name' => 'InstanceId', 'Value' => instance_id}]
})
metric_data.push({
'MetricName' => 'FreeDiskSpace',
'Unit' => 'Gigabytes',
'Value' => disk_avail / 1048576,
'Dimensions' => [{'Name' => 'InstanceId', 'Value' => instance_id}]
})
begin
Fog::AWS::CloudWatch.new(
:aws_secret_access_key => secret_key,
:aws_access_key_id => access_key
).put_metric_data('Custom/EC2', metric_data)
# record successful send
FileUtils.touch last_sent_time_file_path
rescue Exception => e
# Only raise the exception if we haven't successfully sent any data in the
# last 10 minutes
if !File.exist?(last_sent_time_file_path) ||
File.mtime(last_sent_time_file_path) < Time.now - 600
raise e
end
end