Skip to content

Commit

Permalink
first version that just does disk space
Browse files Browse the repository at this point in the history
  • Loading branch information
Stuart Eccles committed Aug 10, 2012
0 parents commit c869dec
Show file tree
Hide file tree
Showing 14 changed files with 334 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .gitignore
@@ -0,0 +1,17 @@
*.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
4 changes: 4 additions & 0 deletions Gemfile
@@ -0,0 +1,4 @@
source 'https://rubygems.org'

# Specify your gem's dependencies in nephelae.gemspec
gemspec
22 changes: 22 additions & 0 deletions LICENSE
@@ -0,0 +1,22 @@
Copyright (c) 2012 Stuart Eccles

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 changes: 29 additions & 0 deletions README.md
@@ -0,0 +1,29 @@
# Nephelae

TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

gem 'nephelae'

And then execute:

$ bundle

Or install it yourself as:

$ gem install nephelae

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
2 changes: 2 additions & 0 deletions Rakefile
@@ -0,0 +1,2 @@
#!/usr/bin/env rake
require "bundler/gem_tasks"
26 changes: 26 additions & 0 deletions bin/nephelae
@@ -0,0 +1,26 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
require 'nephelae'
require 'optparse'

settings = {}

opts = ARGV.options{ |o|
o.banner << " command"
o.on("-k", "--aws-access-key", "AWS Access Key to use for cloudwatch" do |v|
settings[:aws_access_key] = v
end
o.on("-s", "--aws-secret-access-key", "AWS Secret Access Key to use for cloudwatch" do |v|
settings[:aws_secret_access_key] = v
end

}

opts.parse!

new_argv = [ARGV.first]
Daemons.run_proc('nephelae', {ARGV: new_argv}) do
r = Nephelae::Runner.new(settings)
r.run
end
12 changes: 12 additions & 0 deletions lib/nephelae.rb
@@ -0,0 +1,12 @@
require "nephelae/version"
require "nephelae/cloud_watch/simple_aws"
require "nephelae/cloud_watch/cloud_watch"
require "nephelae/cloud_watch/metrics"

require "nephelae/plugins/disk_space"

require "nephelae/runner"

module Nephelae
# Your code goes here...
end
49 changes: 49 additions & 0 deletions lib/nephelae/cloud_watch/cloud_watch.rb
@@ -0,0 +1,49 @@
module Nephelae
class CloudWatch

attr_accessor :aws_access_key_id, :aws_secret_access_key, :aws_session_token, :aws_credentials_expire_at, :url

def initialize(options={})
options[:region] ||= 'us-east-1'
@host = options[:host] || "monitoring.#{options[:region]}.amazonaws.com"
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@aws_session_token = options[:aws_session_token]
@aws_credentials_expire_at = options[:aws_credentials_expire_at]

@url = "#{@scheme}://#{@host}:#{@port}#{@path}"

end

def request(params)
body = AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,
:aws_session_token => @aws_session_token,
:aws_secret_access_key => @aws_secret_access_key,
:host => @host,
:path => @path,
:port => @port,
:version => '2010-08-01'
}
)

AWS.request(@url, {
:body => body,
:expects => 200,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:host => @host,
:method => 'POST'
})
end

def put_metric(metric)
request(metric.params)
end

end
end
32 changes: 32 additions & 0 deletions lib/nephelae/cloud_watch/metrics.rb
@@ -0,0 +1,32 @@
module Nephelae
class Metrics
attr_accessor :params, :namespace, :instance_id

attr_reader :mcount

def initialize(namespace, options = {})
#code to get the instance id from ec2 metadata
@instance_id = options[:instance_id] || AWS.get_instance_id
@params = {}
@params['Action'] = 'PutMetricData'
@params['Namespace'] = namespace
@mcount = 0
end

def append_metric(name, value, options)
dim_count = 1
@mcount = @mcount + 1
params["MetricData.member.#{@mcount}.MetricName"] = name
params["MetricData.member.#{@mcount}.Value"] = value
params["MetricData.member.#{@mcount}.Unit"] = options[:unit] || 'None'
params["MetricData.member.#{@mcount}.Timestamp"] = options[:timestamp] if options[:timestamp]

if @instance_id
params["MetricData.member.#{@mcount}.Dimensions.member.#{dim_count}.Name"] = 'InstanceId'
params["MetricData.member.#{@mcount}.Dimensions.member.#{dim_count}.Value"] = @instance_id
end

end

end
end
56 changes: 56 additions & 0 deletions lib/nephelae/cloud_watch/simple_aws.rb
@@ -0,0 +1,56 @@
require 'base64'
require 'excon'
require 'openssl'

module Nephelae
module AWS

def self.escape(string)
string.gsub(/([^a-zA-Z0-9_.\-~]+)/) {
"%" + $1.unpack("H2" * $1.bytesize).join("%").upcase
}
end

def self.hmac_sign(string_to_sign, key)
digest = OpenSSL::Digest::Digest.new('sha256')
OpenSSL::HMAC.digest(digest, key, string_to_sign)
end

def self.signed_params(params, options = {})
params.merge!({
'AWSAccessKeyId' => options[:aws_access_key_id],
'SignatureMethod' => 'HmacSHA256',
'SignatureVersion' => '2',
'Timestamp' => Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
'Version' => options[:version]
})

params.merge!({
'SecurityToken' => options[:aws_session_token]
}) if options[:aws_session_token]

body = ''
for key in params.keys.sort
unless (value = params[key]).nil?
body << "#{key}=#{escape(value.to_s)}&"
end
end
string_to_sign = "POST\n#{options[:host]}:#{options[:port]}\n#{options[:path]}\n" << body.chop
signed_string = hmac_sign(string_to_sign, options[:aws_secret_access_key])
body << "Signature=#{escape(Base64.encode64(signed_string).chomp!)}"

body
end

def self.request(url, params, &block)
excon = Excon.new(url, params)
excon.request(params, &block)
end

def self.get_instance_id
#Excon.get('http://169.254.169.254/latest/meta-data/instance-id').body
'i-016c576f'
end

end
end
30 changes: 30 additions & 0 deletions lib/nephelae/plugins/disk_space.rb
@@ -0,0 +1,30 @@
module Nephelae

class DiskSpace
attr_accessor :path

def initialize(params = {})
@path = params[:path] || '/'
end

def command
"/bin/df -k -l -P #{@path}"
end

def get_metrics
metrics = Metrics.new('System/Linux')
output = `#{command}`
stats = output.split(/\n/).last.split(/\s+/)

percent = stats[4].chomp('%')
metrics.append_metric('DiskSpaceUtilization', percent, {unit: 'Percent'})
metrics.append_metric('DiskSpaceUsed', stats[2], {unit: 'Kilobytes'})
metrics.append_metric('DiskSpaceAvailable', stats[1], {unit: 'Kilobytes'})

return metrics

end

end

end
27 changes: 27 additions & 0 deletions lib/nephelae/runner.rb
@@ -0,0 +1,27 @@
require 'eventmachine'
require 'rufus/scheduler'
module Nephelae
class Runner

attr_accessor :aws_access_key_id, :aws_secret_access_key

def initialize(config = {})
@aws_access_key_id = config[:aws_access_key_id]
@aws_secret_access_key = config[:aws_secret_access_key]
end

def run

EM.run {
cloud = CloudWatch.new({aws_access_key_id: @aws_access_key_id, aws_secret_access_key:, @aws_secret_access_key})
ds = DiskSpace.new
scheduler = Rufus::Scheduler::EmScheduler.start_new

scheduler.every '5m' do
cloud.put_metric(ds.get_metrics)
end
}
end

end
end
3 changes: 3 additions & 0 deletions lib/nephelae/version.rb
@@ -0,0 +1,3 @@
module Nephelae
VERSION = "0.0.1"
end
25 changes: 25 additions & 0 deletions nephelae.gemspec
@@ -0,0 +1,25 @@
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/nephelae/version', __FILE__)

Gem::Specification.new do |gem|
gem.authors = ["Stuart Eccles"]
gem.email = ["stuart@madebymany.co.uk"]
gem.description = %q{Nephelae is a daemon process that will upload custom cloud watch metrics in AWS}
gem.summary = %q{Poll for server metrics and post them to AWS as custom CloudWatch metrics}
gem.homepage = ""

gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "nephelae"
gem.require_paths = ["lib"]
gem.version = Nephelae::VERSION

gem.add_dependency('excon', '~>0.14')
gem.add_dependency('nokogiri', '~>1.5.0')
gem.add_dependency('eventmachine')
gem.add_dependency('rufus-scheduler')
gem.add_dependency('daemons')
gem.add_dependency('ruby-hmac')

end

0 comments on commit c869dec

Please sign in to comment.