Skip to content

Instantly share code, notes, and snippets.

@kmarsh
Created April 15, 2010 15:37
Show Gist options
  • Save kmarsh/367242 to your computer and use it in GitHub Desktop.
Save kmarsh/367242 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rubygems'
require 'right_aws'
require 'optparse'
#
# check_s3_backups
# Nagios script to check S3 for backups
begin
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options]"
opts.on("-i", "--id ID", String, "Amazon Access Key ID") do |i|
options[:amazon_access_key_id] = i
end
opts.on("-s", "--secret SECRET", String, "Amazon Secret Access Key") do |s|
options[:amazon_secret_access_key] = s
end
opts.on("-b", "--bucket BUCKET", String, "S3 Bucket") do |b|
options[:s3_bucket] = b
end
opts.on("-p", "--prefix [PREFIX]", "S3 Prefix") do |p|
options[:s3_prefix] = p || ""
end
opts.on("-r", "--regex REGEX", Regexp, "File regular expression") do |r|
options[:file_regex] = r
end
opts.on("-m", "--minimum-size [BYTES]", Integer, "Minimum file size of backup") do |s|
options[:minimum_size] = (s || 0).to_i
end
opts.on("-w", "--warning [DAYS]", Integer, "Warning threshold in days of last backup") do |w|
options[:warning] = (w || 2).to_i
end
opts.on("-c", "--critical [DAYS]", Integer, "Critical threshold in days of last backup") do |c|
options[:critical] = (c || 5).to_i
end
end.parse!
AMAZON_ACCESS_KEY_ID = ENV['AMAZON_ACCESS_KEY_ID'] || options[:amazon_access_key_id]
AMAZON_SECRET_ACCESS_KEY = ENV['AMAZON_SECRET_ACCESS_KEY'] || options[:amazon_secret_access_key]
S3_BUCKET = options[:s3_bucket]
S3_PREFIX = options[:s3_prefix]
FILE_REGEX = options[:file_regex]
MINIMUM_SIZE = options[:minimum_size]
WARNING = options[:warning] * 24
CRITICAL = options[:critical] * 24
s3 = RightAws::S3.new(AMAZON_ACCESS_KEY_ID, AMAZON_SECRET_ACCESS_KEY, {:port => 80, :protocol => 'http', :logger => Logger.new("/dev/null")})
bucket = s3.bucket(S3_BUCKET)
keys = bucket.keys('prefix' => S3_PREFIX)
filtered = keys.select {|k| k.name.match(FILE_REGEX) && k.size > options[:minimum_size].to_i }
if filtered == []
puts "S3 Backup CRITICAL - No matching files found"
exit 2
else
sorted = filtered.sort_by {|k| k.last_modified }
newest = filtered.last
hours_old = (Time.now - newest.last_modified).to_f / 60.0 / 60.0
if hours_old < WARNING
puts "S3 Backup OK - %s (%d)" % [newest.name, newest.size]
exit 0
elsif hours_old > WARNING && hours_old < CRITICAL
puts "S3 Backup WARNING - %s (%d) %d days old" % [newest.name, newest.size, (Time.now - newest.last_modified).to_f / 60.0 / 60.0 / 24.0]
exit 1
elsif hours_old > CRITICAL
puts "S3 Backup CRITICAL - %s (%d) %d days old" % [newest.name, newest.size, (Time.now - newest.last_modified).to_f / 60.0 / 60.0 / 24.0]
exit 2
end
end
rescue => e
puts "S3 Backup CRITICAL - #{e.inspect} #{e.backtrace}"
exit 2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment