Ruby server monitoring script

I wrote this script as a basic fix to monitor if certain sites are up. The script needs to be on a different server than where the sites exist for the best results and obviously with a cron job running every 5-10 minutes or more often if needed.

The ruby server monitoring script could also be expanded to ssh into another box and run the command needed to boot the server back up.

First let’s go over what the db looks like…
Sites

  • id
  • domain (url to curl)
  • active (turn monitoring on/off for sites)

Reports

  • id
  • sent_at (time when report was sent)
  • down (count of how many sites were down)
  • fixed (report has been marked as fixed)

Ruby monitoring script

#!/usr/bin/ruby
#change line above to reference your ruby location
 
require 'rubygems'
require 'net/smtp'
require 'mysql'
require 'time'
require 'curb'
 
def check
     @time = nil
 
 
    # Connect to db that stores all of our sites to monitor
     db = Mysql::new("localhost","user","pass","database")
 
	# Make sure we are only looking at sites that are active 
    sites = db.query("SELECT * FROM sites WHERE active = 1")
	# Getting the most recent report since we only want to run the script to send a report every 2 hours
    last_report = db.query("SELECT * FROM reports WHERE fixed = 0 ORDER BY sent_at DESC Limit 0,1")
    last_report.each {|r| @time = r[1]}
		# If there isn't a report in the database yet it sets the time to greater than 2 hours so the script will run and report if needed.
        if @time.nil?
         @diff = 7201
        else
		# Calculating the difference in time 
         @report = Time.parse(@time)
         @now = Time.now
         @diff = @now - @report
        end
			# Change this number to whatever you woudl prefer in seconds. Currently it is 2 hours
        unless @diff.to_i < 7200
            body = ""
            sites_down = 0
 
            sites.each do |s|
				# Prints the site name to the user
                print s[1]
				# need a begin/rescue in case the domain can't be curled
                begin
				# Uses curb to curl the domain
                 c = Curl::Easy.perform(s[1])
                puts " - #{c.response_code}"
 
			   # check http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for examples of response codes
                unless c.response_code < 399
					# reports to the screen when manually ran that the site is down
                      puts "--DOWN--"
					  #increments the number of sites down and writes to the body of the email
                      sites_down = sites_down + 1
                      body = body + "DOWN - #{s[1]}\n"
               end
 
                rescue
				# if the script is unable to curl the site we still mark it as down since we want to make sure we are in good shape
                    sites_down = sites_down + 1
                    body = body + s[1] + " unable to curl, check record in db and ensure that it is being pointed\n"       
                        puts "--DOWN--"
                end
 
 
                #only send if sites are down
 
            end
 
            if sites_down > 0
                #send text and email
                record_report = db.query("INSERT INTO reports(down) VALUES(#{sites_down})")
				# I use this one for a text message. 
                send_email("A server needs help! #{sites_down} down!","destination_address")
				# this is for an inbox since it provides more details to aid in troubleshooting later
                send_email(body,"myemail@blah.com")
            end
         else
			# Since there is still a report that is in the db that was recorded less than 2 hours ago we just want to notify the user if running it from shell.
            puts "Please run 'up.rb' first and then 'mon.rb' again to curl all sites."
            puts "You are seeing this message because there is a report that hasn't been marked as fixed within the past 2 hours." 
         end
end
 
 
def send_email(body,to)
    msg = <<END_OF_MESSAGE
From: Monitoring tool <info@mysite.com>
To: Admin <admin@mysite.com>
Subject: Some sites are down
#{body}
END_OF_MESSAGE
 
    Net::SMTP.start('localhost') do |smtp|
        smtp.send_message msg, "from_address", to
    end
end
#need to run the function
check

Script to update reports table so regular monitoring can continue (up.rb)

#!/usr/bin/ruby
 
require 'mysql'
 
db = Mysql::new("localhost","user","pass","database")
up = db.query("UPDATE reports SET fixed = 1 WHERE fixed = 0")
 
puts "Reports marked as fixed, resuming normal monitoring."

You should also set up a crontab such as….

This one runs every 5 minutes.

MAILTO=”"
*/5 * * * * sh -c $’/usr/bin/ruby /home/username/mon.rb’

Uncategorized

Comments (0)

Permalink

Code Smith Tools Review | What a joke

Go check out the code smith tools website first.

Ok, your back…

Can someone please explain to me how this is beneficial in any way shape or form better than how a developer currently makes templates? Maybe it’s just for those who are unfortunate enough to have to program in .net haha. oh and here’s an amazing video on how simple it is to use…. not. While watching the video pay attention around 6:30 where they show the bagillion files that were generated. Good luck finding the specific function you would like to modify or fine tune your application.

Also, who wants mooooooore lines of code and moooore files than you would ever need, write efficient code and make your code reusable. As they say in the video it generates 1000’s and 1000’s of lines of code that would take developers forever to write.

I must admit I am a big fan of rails but PHP also has some great frameworks such as cake php and .net does have master pages but not much beyond that.

If you really don’t know how to include a file in php (include ‘header.php’) or deal with templates in a framework maybe you should probably read the infinite amount of tutorials online or buy some books from fry’s electronics.

Any current users that love this application?

Uncategorized

Comments (2)

Permalink

Problogger “Secrets for blogging your way to a six-figure income book review chapter 1″

I just recently purchased some books from amazon that are all web related and thought I would write a summary/review of one of them that I purchased which is the problogger book.

Introduction
The book is by 2 different bloggers: Darren Rowse and Chris Garrett. This section talks about how they got into blogging and how it is usually never an overnight success in the blogging world.

Darren: Worked multiple jobs while he started blogging until he could finally become a full time blogger. Had multiple blogs running and his most successful project would be problogger.net , he also co-founded the b5media network which is a network of bloggers.

Chris: Mainly an IT guy that ran a science fiction web site, personal web site and various other sites. Played around with building affiliate marketing websites, freelance writing and programmer training. Most popular blog would be performancing.com and he has a personal web site at chrig.com.

Chapter 1 - blogging for money
General overview of what a blog is and how it is different from a regular web site. Things such as it is updated more often and typically encourages user interaction in the form of users commenting. Various benefits from blogging such as fame, networking, making money and traffic. Different monetization methods for blogs such as affiliate marketing, adsense, paid reviews, sponsorships, and advertising. Indirect monetization methods such as your own freelance work, advertising yourself to be a speaker, consulting opportunities and various other services that you can advertise on your site. Breaks down the different reasons people blog and which advertising method will work best for your particular blog. Measuring a blog’s success using various methods and metrics such as unique visitors, trackbacks, feed readers through feedburner, search engines and technorati.

How to make a blog appealing by taking a look at blogs you like and answering the following questions:

What does and doesn’t appeal to you?

What content does the blog provide?

How often is the site updated?

What reaction is the blog looking for from readers? Shock, amusement, happiness..

Blog Tools mentioned: http://technorati.com/ | http://tools.seobook.com/ | http://www.seomoz.org/tools | http://www.alexa.com/ | http://www.text-link-ads.com/blog_juice/

Chapter 2 - niche blogging
How to define your niche in the blog world and make sure that you will be interested in the long haul with your specific subject. It is important to define your niche because from a reader’s perspective they are probably not interested in the exact same subjects as you. They may be interested in xbox 360 pages and first person shooters or sweet games like GTA IV! but that same reader may not be interested in hiking or parenting. This way if you are able to make your audience more specific then it helps when the reader is going through your articles. Other benefits to having a niche blog are having a community that is already devoted to your subject to connect through your site, specialized authors, more specific advertising, direct ad sales since you have a general idea of the audience, easier to rank higher in search engines since it is a more defined subject, can always expand into a closely related niche if you find there is enough to write about. Things you have to keep in mind though when coming up with your niche are

How interested are you in the topic?
How long will the topic be popular or is it at the moment?
Is it’s popularity growing or shrinking?
Is there someone else already blogging about this or what other similar competition are you up against?
Will you have enough content to write for at least 6 months?
Is there a way to make money out of the niche?

Tools mentioned: AdWords | Google Trends | Technorati | Google Blog Search | Wordtracker | Yahoo Buzz

Cool tip that isn’t in the book or so far at least. Go to google alerts and setup an alert with your domain name in the alert or your name or any other piece of information you want to track. Pick a type and then have it emailed to you however often you want. This helps in monitoring activity and buzz around your blog and specific topics.

So far I like the read and I’ll post more when I have time.


Uncategorized

Comments (0)

Permalink

Drivers for Gateway P-6832

Drivers for the Gateway p-6832 can be found there…

These include the video drivers for the gateway p-6832, media card reader driver, lan driver, and more.

Uncategorized

Comments (0)

Permalink

igoogle rss feed update delay

When first posting your feed to igoogle it takes a little while for it to pull in new posts that you write. Unless you are digg, engadget, or some other already well known and highly visited site. When you first put your site feed on igoogle it can take anywhere from 4-72 hours and then as time progresses you should see faster updates to your igoogle rss widget for your feed. Just make sure that the url you are using for your feed is getting updated when you have new posts to your blog/cms/application.

Uncategorized

Comments (0)

Permalink

Joomla sitemap component Xmap

Xmap is a very useful sitemap component for joomla which basically lets you generate a sitemap out of your menus. You can choose to use all of the menus or just your main menu, whichever works best. You can then link to the sitemap component from a menu item and see a sitemap in a human friendly form on your site. Xmap also generates the xml version for search engines such as google and yahoo. It isn’t extremely obvious where that is located at since it isn’t sitemap.xml so I thought I’d post it to save someone the hassle of looking for it. It should be here…

http://mysite.com/index.php?option=com_xmap&sitemap=1&view=xml&no_html=1

Uncategorized

Comments (0)

Permalink

Facebook Chat on Digsby Released Today

Digsby just released a new version today that adds facebook chat to the program and it is amazing. It’s nice to be able to chat on facebook without a browser and it is much more robust than the online facebook version. Digsby is also nice because it puts all of my chat networks and social updates feeds into one slick program. Download the new Digsby with Facebook chat today.

Uncategorized

Comments (0)

Permalink

Joomla Jobline Component Strip Slashes

If you have magic_quotes_gpc set to on in php and would like to keep it on but jobline is not removing the slashes on display or edit in the backend then edit the following files to fix it.

Continue Reading »

Uncategorized

Comments (0)

Permalink

Best ways to twitter

Besides the obvious web, email, and text ways to twitter there are a couple other really convenient ways as well.

Firefox add-on “twitterbar”
This add-on allows you to type your twitter update in the address bar of firefox and then click update within the address bar and it updates your status. You can use this add-on in secure and safe mode to connect to twitter. The add-on also displays how many characters out of 140 you have left to type and then gives you a confirmation message upon saving the twitter status.

Digsby (see my digsby post for more detailed information)
Digsby is a multi-client chat program and social site status update program. The program enables you to talk on all of your favorite instant message networks as well as update your twitter (also facebook and myspace) status directly from the program. Digsby also shows you your twitter updates from the people you are following.

Uncategorized

Comments (0)

Permalink

Social Bookmarking Widget Customization and modifications (addthis.com)

addthis.com has an amazing social bookmarking widget that integrates every possible social bookmarking site such as digg, stumbleupon, browser bookmarks, reddit, and sooo many more. While they offer some documentation on their widget there are additional features which you can tweak with the widget besides what is mentioned. Basically they are settings within the javascript file.

social bookmarking widget addthis.com specify url
By default the widget uses the current browser url, but if you are on the the main page of your blog and want the widget to specify the actual article the widget is next to you can specify the variable ‘addthis_url’ just like you do the other variables.

specify default title
‘addthis_title’ - Swaps out what’s in the title tag with a title that you specify.

specify caption share
addthis_caption_share - specify a different title besides the default “Bookmark and Share” on the dropdown.

specify custom css file
addthis_css - takes a reference to a css file.

Uncategorized

Comments (1)

Permalink