Created
April 14, 2010 18:13
-
-
Save house9/366133 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# call from a rake or cron task make sure your site is still alive | |
# Usage | |
# ======== | |
# ping = Pingy.new('https://www.example.com/login', "/login?operations=pingy", 3, 2) | |
# ping.perform | |
# puts ping.message | |
# ======== | |
# Not Included code to send the email | |
# see 'Notifier.deliver_ping_failure(@to, @message)' below | |
# ALSO: hard wired for https urls, needs a few tweaks to work with either http or https | |
class Pingy | |
require 'uri' | |
require 'net/http' | |
require 'net/https' | |
def initialize(url, path, try_count, delay) | |
raise "try_count must be greater than 0" if try_count <= 0 | |
raise "delay must be greater than 0" if delay <= 0 | |
@url = URI.parse(url) | |
@path = path | |
@try_count = try_count | |
@tries = 0 | |
@delay = delay | |
@message = "Checking site at #{Time.now.strftime("%Y-%m-%d %H:%M:%S %Z")}\n" | |
@message += "Automated check from: " + `hostname` | |
@message += " Checking: https://#{@url.host}#{@path}\n" | |
@user_agent = "Pingy" | |
@to = '[email protected]' | |
end | |
attr_reader :message | |
attr_accessor :user_agent | |
def perform | |
while @tries < @try_count do | |
result = perform_call | |
break if result | |
# else | |
@tries = @tries + 1 | |
sleep @delay | |
if @tries == @try_count then | |
@message += "... All tries failed sending email alert to #{@to}\n" | |
# Notifier.deliver_ping_failure(@to, @message) | |
else | |
@message += "Try #{@tries + 1}\n" | |
end | |
end | |
end | |
def perform_call | |
begin | |
response = make_call | |
@message += " HTTP Status: #{response.code} \n" #for https://#{@url.host}#{@path}\n" | |
unless response.body.nil? then | |
@message += " Response: #{response.body.split("\n")[0][0,70]}...\n" | |
end | |
if response.code != "200" then | |
raise "NOT 200 was #{response.code}\n" | |
end | |
# else | |
return true | |
rescue Exception => ex | |
full_message = "#{ex.class}: #{ex.message}\n\n" | |
@message += " Failure: " + full_message | |
return false | |
end | |
end | |
def make_call | |
http = Net::HTTP.new(@url.host, 443) | |
http.use_ssl = (@url.port == 443) ? true : false | |
headers = { 'User-Agent' => @user_agent} | |
return http.get(@path, headers) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment