BGUL Ruby in Linux example source code

This might be useful for these present at today’s BGUL meeting, but not only. Basically, I have demonstrated how to develop simple script useful for sysadmins, that checks if web pages are up and running, and stores results in MySQL database.

Additional cleanup, error handling and comments added (in Polish, sorry).

Full code is here

main.rb

#!/usr/bin/ruby
#
# Główny plik programu
# utuchamianie:
# $ ruby main.rb
# lub
# $ ./main.rb

# Dołączamy nasze biblioteki
require 'config'
require 'site_test'

# i bibliotekę do obsługi MySQL
require 'mysql'

begin
  # Najpierw łączymy się z bazą danych
  connection = Mysql::init()
  # wpiszcie swoje dane poniżej (hasło tu jest puste, ale jak trzeba to nie zapomnijcie)
  connection.connect("localhost", "root", "", "tester")

  for url in Config.instance.urls # w pętli sprawdź wszystkie strony
    # przetestuj URL
    puts "Testuje... " +url
    test = SiteTest.new(url)
    puts Time.new.strftime('%Y-%m-%d %H:%M:%S')
    connection.query("INSERT into site_tests VALUES ('', '#{Time.new.strftime('%Y%m%d%H%M%S')}', '#{url}', '#{test.code}', '#{test.message}')")
  end

rescue Mysql::Error => e # odpowiednik sekcji "catch" z Javy/C++
  puts "Oops, mamy error bazy danych: "+e
ensure # wykonaj zawsze -> patrz "finally" w javie
  connection.close()
end

config.rb

require "yaml"
require "singleton"

# Daje dostęp do danych zapianych w pliku konfiguracyjnym
class Config
  include Singleton

  attr_reader :urls, :timeout

  def initialize
    # Pliki YAML przegląda się podobnie do plików XML przy pomocy XPath
    options = YAML::parse( File.open( "configuration.yml" ) )
    @urls = options.select("/urls/*").collect { |el| el.value }
    @timeout = options.select("/timeout")[0].value.to_i # konwersja stringa do integera
  end
end

site_test.rb

require 'net/http'
require 'uri'
require 'config'

# Klasa ta przy inicjalizacji testuje dostępność strony, zapisując we właściwościach "code" i "message" status
class SiteTest

  attr_accessor :code, :message

  def initialize(url) # konstruktor z parametrem
    begin
      adres = URI.parse(url)
      path = "/"
      path = adres.path if adres.path != ""
      req = Net::HTTP::Get.new(path)
      res = Net::HTTP.start(adres.host, adres.port) {|http|
        http.read_timeout = http.open_timeout = Config.instance.timeout
        http.request(req)
      }

      @code = res.code
      @message = res.message
    rescue Timeout::Error => e
      @code = 0
      @message = "Timeout of #{Config.instance.timeout} seconds exceeded"
    rescue SocketError =>e
      @code = -1 # tak oznaczmy sobie "inny błąd", np. nie ma takiego hosta
      @message = e.to_s
    end

  end
end
# To jest zwykły plik YAML
urls:
    - http://www.wp.pl
    - http://slashdot.org
    - http://gazeta.pl
    - http://bgul.org
    - http://microsoftruby.com

timeout: 10

Posted by Hubert Łępicki Wed, 29 Oct 2008 22:53:00 GMT