月曜日, 9月 06, 2010

RubyでWebサイトのレスポンス監視

2008/02/25perlfreak.vox.comより転載)

RubyGemsでtmailとmechanizeをインストールしてある前提。
これをcronで5分おきに実行。

=== ( response_check.rb ここから ) ===
#!/usr/bin/env ruby

require 'rubygems'
require 'tmail'
require 'iconv'
require 'net/smtp'
require 'mechanize'

# アラートフラグ用ディレクトリ
alert_dir_path = '/var/run/response_check/'

# アラートまでのチェック回数
alert_check_count = 2

# チェック対象
target_hash = {
'www_hoge_jp' => {
'url' => 'https://www.hoge.jp/',
'user_id' => 'foo',
'password' => 'bar',
'mailto' => [ 'list@hoge.com' ],
'alert_time' => 3
},
'www2_hoge_jp' => {
'url' => 'https://www2.hoge.jp/',
'user_id' => 'foo',
'password' => 'bar',
'mailto' => [ 'list@hoge.com' ],
'alert_time' => 3
},
'www3_hoge_jp' => {
'url' => 'https://www3.hoge.jp/',
'user_id' => 'foo',
'password' => 'bar',
'mailto' => [ 'list@hoge.com' ],
'alert_time' => 3
}
}

## ログインしてから管理画面が表示されるまでの時間を返すメソッド
def response_time( user_agent, url, user_id, password )
agent = user_agent
page = agent.get( url )
form = page.forms.with.name( 'login' ).first
form.userid = user_id
form.password = password
start_time = Time.now.to_f
results = agent.submit( form )
body = results.body
end_time = Time.now.to_f

return end_time - start_time
end

## メール送信メソッド
def mail_send( target, url, mailto, response, alt )
subject = ""
if alt == "alert"
subject = "応答時間アラート (" + target + ")"
else
subject = "応答時間リカバリ (" + target + ")"
end

mesg = target + "\n\n" + "応答時間:" + "#{response}"

mail = TMail::Mail.new
mail.to = mailto
mail.cc = ['']
mail.bcc = ['']
mail.from = 'system@hoge.jp'
mail.subject = Iconv.conv( 'ISO-2022-JP', 'EUC-JP', subject )
mail.date = Time.now
mail.mime_version = '1.0'
mail.set_content_type( 'text', 'plain', {'charset' => 'iso-2022-jp'} )
mail.encoding = '7bit'
mail.body = Iconv.conv( 'ISO-2022-JP', 'EUC-JP', mesg )

Net::SMTP.start( 'localhost', 25 ) do |smtp|
str = mail.encoded
smtp.send_mail( str, mail.from, mail.destinations )
end
end

# アラートメール、リカバリメール
agent = WWW::Mechanize.new
target_hash.each do | key, value |
flag_file_ary = Dir.glob( alert_dir_path + "#{key}_[1-9]*" )
url = value['url']
user_id = value['user_id']
password = value['password']
mailto = value['mailto']
alert_time = value['alert_time']
response = response_time( agent, url, user_id, password )

if flag_file_ary.size == 0
if response > alert_time
system( '/bin/touch', alert_dir_path + key + "_1" )
if alert_check_count == 1
send_mail( key, mailto, response, "alert" )
end
end
elsif flag_file_ary.size == 1
flag_file = flag_file_ary[0]
/^#{key}_([\d]+)$/ =~ File.split( flag_file )[1]
flag_count = $1.to_i
if response > alert_time
if flag_count < flag_file_2 =" alert_dir_path" flag_count ="="" flag_count ="="" end ="="="">

0 件のコメント: