Skip to content

Instantly share code, notes, and snippets.

@s0enke
Last active May 12, 2023 14:21
Show Gist options
  • Save s0enke/68b3288bd1cbec3336ad to your computer and use it in GitHub Desktop.
Save s0enke/68b3288bd1cbec3336ad to your computer and use it in GitHub Desktop.
Dashing Cloudwatch

This is an adjusted version of EC2 CloudWatch stats for Dashing which is not bound to EC2 metrics but a generic widget for cloudwatch graphs. Visualization is done by Rickshawgraph as in the original example.

# lib/cloudwatch.rb
require 'aws-sdk'
require 'time'
class Cloudwatch
def initialize(options)
@access_key_id = options[:access_key_id]
@secret_access_key = options[:secret_access_key]
@region = options[:region]
@clientCache = {}
end
def get_metric_data(namespace, dimensions, metric_name, type=:average, options={})
if type == :average
statName = "Average"
elsif type == :sum
statName = "Sum"
elsif type == :maximum
statName = "Maxmimum"
end
statKey = type
# Get an API client instance
cw = @clientCache[@region]
if not cw
cw = @clientCache[@region] = AWS::CloudWatch::Client.new({
region: @region,
access_key_id: @access_key_id,
secret_access_key: @secret_access_key
})
end
# Build a default set of options to pass to get_metric_statistics
duration = (options[:duration] or (60*60*8))
start_time = (options[:start_time] or (Time.now - duration))
end_time = (options[:end_time] or (Time.now))
get_metric_statistics_options = {
namespace: namespace ,
metric_name: metric_name,
statistics: [statName],
start_time: start_time.utc.iso8601,
end_time: end_time.utc.iso8601,
period: (options[:period] or (60 * 5)), # Default to 5 min stats
dimensions: dimensions
}
# Go get stats
result = cw.get_metric_statistics(get_metric_statistics_options)
if ((not result[:datapoints]) or (result[:datapoints].length == 0))
# TODO: What kind of errors can I get back?
puts "\e[33mWarning: Got back no data for metric #{metric_name}\e[0m"
answer = nil
else
# Turn the result into a Rickshaw-style series
data = []
result[:datapoints].each do |datapoint|
point = {
x: (datapoint[:timestamp].to_i), # time in seconds since epoch
y: datapoint[statKey]
}
data.push point
end
data.sort! { |a,b| a[:x] <=> b[:x] }
answer = {
name: metric_name,
data: data
}
end
return answer
end
end
# jobs/some_job.rb
require './lib/cloudwatch'
cw = Cloudwatch.new({
:access_key_id => "xxx",
:secret_access_key => "xxx",
:region => 'eu-west-1'
})
SCHEDULER.every '1m', :first_in => 0 do |job|
series = []
%w(NumberOfNotificationsDelivered NumberOfNotificationsFailed).each do |metric|
series.push(
cw.get_metric_data(
'AWS/SNS',
[{:name => 'TopicName', :value => 'sometopic'}],
metric,
:sum,
{}
)
)
end
send_event "series", { series: series }
end
@sean-kang
Copy link

In line #27, AWS needs to be replaced with Aws.

@gl-lamhnguyen
Copy link

Can someone help me with the instruction to create BillingAlarm Cloudwatch with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment