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).
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()
endconfig.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