04 April 2010

Setup email notifications for mdadm (with a splash of Ruby)

The instructions here are adapted from this post.

Mdadm expects a local mail server (e.g. postfix) to be configured to send emails. My preference, however, was to use GMail's SMTP server, as I didn't want to figure out how to configure postfix.

I wrote a simple Ruby script to send out emails:


#!/usr/bin/ruby
require 'net/smtp'

to = "******@gmail.com"
from = '******@gmail.com'
password = '******'
msg = "Net/SMTP email from Ruby"

smtp = Net::SMTP.new "smtp.gmail.com", 587
smtp.enable_starttls
smtp.start(Socket.gethostname, from, password, 'plain' ) { |smtp|
smtp.open_message_stream(from, [to]) do |f|
f.puts "From: #{from}"
f.puts "To: #{to}"
f.puts "Subject: #{ARGV[1]}"
f.puts
f.puts ARGV[0]
end
}


It accepts the text of the message and the subject as command line arguments.

Here is how I configured mdadm to use it:
  • put the script into /usr/sbin/email.rb and make sure it's executable
  • add this line to /etc/mdadm/mdadm.conf:
    PROGRAM /usr/sbin/email.rb

This will send you a message with the RAID device name in the subject.

To test that it's working:
  • edit /etc/default/mdadm and add --test to the end of the DAEMON_OPTIONS string
  • restart mdadm with sudo service mdadm restart and you should receive an email
  • remove --test from /etc/default/mdadm and restart mdadm again.

One more thing to note that the first real notification you are likely to receive will be about a rebuild, which can be confusing. This is caused by a monthly (read-only) redundancy check of the array. More details here.

Works with: Ubuntu 9.10, mdadm 2.6.7.1