Last active
October 7, 2015 15:28
-
-
Save n-shinya/3186790 to your computer and use it in GitHub Desktop.
Sonar Alert Mail
This file contains 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
require 'net/http' | |
require 'net/smtp' | |
require 'nkf' | |
require 'rubygems' | |
require 'json/pure' | |
require 'pp' | |
def sendmail(name, key, alert_text) | |
from = 'xxx@xxx.com' | |
to = 'yyy@yyy.com' | |
subject = NKF.nkf('-WMm0', '[SONAR]' + '[' + name + ']' + 'アラートが検出されました') | |
if key == 'violations_density' | |
message = 'ルール順守率が90%を下回っています。' | |
elsif key == 'critical_violations' | |
message = 'CRITICALな違反が検出されています。' | |
end | |
body = <<EOT | |
From: #{from} | |
To: #{to} | |
Subject: #{subject} | |
Date: #{Time::now.strftime("%a, %d %b %Y %X %z")} | |
Mime-Version: 1.0 | |
Content-Type: text/plain; charset=ISO-2022-JP | |
Content-Transfer-Encoding: 7bit | |
(このメールはSonarから送信されています) | |
#{message} | |
http://xx.xx.xx.xxx/sonar/ | |
EOT | |
Net::SMTP.start('localhost', 25) {|smtp| | |
smtp.send_mail body, from, to | |
} | |
end | |
url = { | |
:host => 'xx.xx.xx.xxx', | |
:port => '80', | |
:path => '/sonar/api/resources', | |
:params => '?metrics=violations_density,critical_violations&includealerts=true' | |
} | |
res = Net::HTTP.start(url[:host], url[:port]) {|http| | |
res = http.get(url[:path] + url[:params]) | |
} | |
json = JSON.parse(res.body) | |
json.each{|project| | |
project['msr'].each{|msr| | |
if msr.has_key?('alert') | |
if msr['alert'] == 'ERROR' | |
sendmail(project['name'], msr['key'], msr['alert_text']) | |
end | |
end | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment