Pop3 Ruby calls cause loss of MySQL connection

Any help is very much appreciated.

MySQL 5.0 and Rails 1.2.6

I have a Deamon process that looks for incoming mail using pop3. It
all works smashing, except after a day or so, the process starts
throwing this error every time it tries to talk to my database.

Mysql::Error: Lost connection to MySQL server during query: SELECT *
FROM incoming_email_messages WHERE (incoming_email_messages.name =
‘UID26-1219353451’) LIMIT 1

I have 4 rails instances running in a mongrel pack as well as 5 other
daemon processes all talking to the same database. They never
experience this loss of connectivity. The issue seems to be around my
repeated calls to the Ruby pop3 library. I suspect that this is some
kind of memory or garbage collection issue, but I don’t know for
sure. Right now, I have to bounce my thread once a day to snap it out
of it. I tried moving the Net::POP3.new call outside the loop and
just calling start/finish on the same object but that just make it
stop working altogether.

Here is the thread

#!/usr/bin/env ruby

require ‘net/pop’
require ‘rubygems’ # if you use RubyGems
require ‘daemons’

Daemons.run_proc(“incoming_email_thread”, {:dir_mode => :normal, :dir
=> ‘tmp/pids’}) do
require “/home/xxxxx/user/xxxxxx/config/environment.rb”
loop {
logger.info('incoming_email_thread: polling for email messages at
’ + Time.now.to_s)
begin
pop = Net::POP3.new(‘mail.myserver.com’)
pop.start(‘[email protected]’, ‘password’)
if pop.mails.empty?
logger.info('incoming_email_thread: no mail at ’ +
Time.now.to_s)
else
i = 0
pop.each_mail do |m|
logger.info('incoming_email_thread: message with id ’ +
m.unique_id)
filename = File.expand_path(“#{RAILS_ROOT}/public/models/
emails/#{m.unique_id}”)
dbrec = IncomingEmailMessage.new(:name =>
m.unique_id, :header => m.header, :status => ‘writing’)
# This is where I see the error. The model has a
validate_uniqueness :name
if dbrec.save
if !File.exists?(filename)
File.open(filename, ‘w’) do |f|
m.pop do |chunk| # get a message little by little.
f.write chunk
end
end
end
dbrec.update_attribute(:status, ‘ready’)
else
logger.info(‘incoming_email_thread: message with id ’ +
m.unique_id + ’ has already been fetched’)
end
m.delete
end
logger.info(“incoming_email_thread: #{pop.mails.size} mails
popped.”)
end
pop.finish
rescue Exception => exc
logger.error(“incoming_email_thread: receiving email…” +
exc.message)
logger.error(exc.backtrace.join(“\n”))
end
sleep 60
}
end