Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/bin/bash
mailto=admin@ime.usp.br
replyto=admin@ime.usp.br
limit=1000
waitfor=30 # minutes
# debug
if [ "$1" ] && [ "$1" == -d ]; then
limit=10
waitfor=1 # minute
mailto=leoboiko@ime.usp.br
fi
lastmessage=/tmp/watchfila.lastmessage
spooldir=/var/spool/postfix
m4=/usr/bin/m4
postqueue=/usr/sbin/postqueue
queues="incoming active deferred"
# http://emailregex.com/
# use with grep -E
email_regexp="\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b"
subject_template="AVISO: HOSTNAME: QUEUESIZE mensagens em QUEUENAME"
message_template="A fila 'QUEUENAME' na HOSTNAME passou de QUEUESIZE mensagens.
Remetentes mais frequentes:
TOP10_SENDERS
Destinatários mais frequentes:
TOP10_DESTINATIONS
"
function top10_senders()
{
$postqueue -p|grep '^[*0-9A-F]\+'|awk '{print $7}'|sort |uniq -c|sort -nr|head
}
function top10_destinations()
{
$postqueue -p|grep -v '^[*0-9A-F]\+'|grep -E -o "$email_regexp" |sort|uniq -c|sort -nr|head
}
function already_sent_message()
{
if ! [ -f "$lastmessage" ]; then
echo "No messages sent recently; checking queues..."
return 1
elif [ "$(find "$lastmessage" -mmin +$waitfor)" ]; then
echo "Message sent more than $waitfor minutes ago; checking queues..."
return 2
else
echo "Sent message less than $waitfor minutes ago; not running."
return 0
fi
}
function send_message()
{
local queuename="$1"
local queuesize="$2"
local top10s="$(top10_senders|sed -e 's/^/ /' -e "s/\\n/\\\\n/g")"
local top10d="$(top10_destinations|sed -e 's/^/ /' -e "s/\\n/\\\\n/g")"
expansions="
-D HOSTNAME=$(hostname)
-D QUEUENAME=$queuename
-D QUEUESIZE=$queuesize
"
local subject="$(echo "$subject_template" | $m4 $expansions)"
local message="$(echo "$message_template" | $m4 $expansions \
-D TOP10_SENDERS="$top10s" \
-D TOP10_DESTINATIONS="$top10d"
)"
echo "$message" \
| env \
from="\"$(hostname)\" <root@$(hostname --fqdn)>" \
replyto="admin@ime.usp.br" \
mail \
-s "$subject" \
"$mailto"
touch "$lastmessage"
}
if already_sent_message; then
exit 0
fi
for queuename in $queues; do
count="$(find "$spooldir/$queuename" -type f |wc -l)"
if [ $count -ge $limit ]; then
echo Sending message to $mailto: $queuename $count
send_message $queuename $count
exit $?
fi
done
echo "All ok!"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment