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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
# File 'lib/cw_ec2_cm.rb', line 22
def push_metrics
metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )
metric_data = []
df_fields = %w(fstype source size used avail pcent target)
metric_time = Time.now
df_data = `df -l -k --output=#{df_fields.join(',')}`.lines.collect do |l|
line_array = l.split
while line_array.size > df_fields.size do
line_array.last << ' ' << line_array.pop
end
{}.tap do |line_data|
df_fields.each_with_index do |fld, idx|
line_data[fld] = line_array[idx]
end
line_data['pcent'].gsub!('%', '')
end
end
df_data.shift df_data.reject!{|fs| /tmpfs/ =~ fs['fstype']}
if worst_fs = df_data.max_by{ |fs| fs['pcent'].to_f }
metric_data << {
"MetricName" => "FSUsagePercent",
"Dimensions" => [{ "Name" => "InstanceId", "Value" => instance_id }],
"Timestamp" => metric_time,
"Value" => worst_fs['pcent'].to_f,
"Unit" => "Percent" }
end
meminfo = {}
metric_time = Time.now
`cat /proc/meminfo`.each_line do |l|
line_array = l.split
line_array[0].gsub!(':', '')
meminfo[line_array[0]] = line_array[1].to_f * 1024
end
mem_total = meminfo['MemTotal']
mem_free = meminfo['MemFree'] + meminfo['Cached'] + meminfo['Buffers']
mem_used = mem_total - mem_free
mem_percent = (mem_used/mem_total*100).ceil
metric_data << {
"MetricName" => "MemUsagePercent",
"Dimensions" => [{ "Name" => "InstanceId", "Value" => instance_id }],
"Timestamp" => metric_time,
"Value" => mem_percent,
"Unit" => "Percent" }
metric_data << {
"MetricName" => "MemFree",
"Dimensions" => [{ "Name" => "InstanceId", "Value" => instance_id }],
"Timestamp" => metric_time,
"Value" => mem_free/1024/1024,
"Unit" => "Megabytes" }
Tempfile.open('cw-ec2-cm-metrics') do |f|
f.write(JSON.dump(metric_data))
f.close
`aws cloudwatch put-metric-data --namespace EC2Custom --metric-data file://#{f.path}`
end
end
|