Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: f3ba4f3de8
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 73 lines (58 sloc) 2.615 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
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']

server_name = ARGV[0] || fail("Please provide a server name as the first argument, e.g. #{$0} econsultancy.com")

# 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

# Count of the number of 5xx pages served by Apache in the previous minute as
# found by grepping the access logs
http_log_location = "/var/log/apache2/#{server_name}.access.log"
error_pages_served = `if [ -e #{http_log_location} ];
then grep -E '\\[#{(Time.now - 60).strftime '%d\/%b\/%Y:%H:%M'}.*\\] "[^"]+" 5[0-9]{2}' #{http_log_location} | wc -l;
fi;`.to_i

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}]
})

metric_data.push({
  'MetricName' => 'ServerErrorPages',
  'Unit' => 'Count',
  'Value' => error_pages_served,
  '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

Something went wrong with that request. Please try again.