chef/cookbooks/rabbitmq/templates/default/rabbitmq-port-blocker.erb
#!/bin/sh
# calcules the blocking level applying the formula
total_nodes=<%= @total_nodes %>
blocking_level=$(expr $total_nodes / 2)
comment_text="rabbitmq port blocker (no quorum)"
port=<%= @port %>
ssl_port=<%= @ssl_port %>
# get the number of running nodes of rabbitmq in the current cluster
function running_nodes()
{
rabbitmqctl cluster_status 2>/dev/null | tr -d "\n" | sed -e 's/running_nodes,/\nrunning_nodes/g'| grep running_nodes | cut -d "[" -f2 | cut -d "]" -f1 | tr "," "\n" | wc -l
}
# check if exists the blocking rule for rabbitmq clients
function check_rule()
{
iptables -L -n | grep -F "tcp dpt:$1 /* $comment_text */" | grep DROP | wc -l
}
function create_rule(){
if [ $(check_rule $1) -eq 0 ]; then
iptables -A INPUT -p tcp --destination-port $1 -m comment --comment "$comment_text" -j DROP
fi
}
function delete_rule(){
if [[ $(check_rule $1) -gt 0 ]]; then
iptables -D INPUT -p tcp --destination-port $1 -m comment --comment "$comment_text" -j DROP
fi
}
# if the running nodes is les that the blocking level, then...
if [ $(running_nodes) -le $blocking_level ]; then
# if rule not exists the rule will be added to block the clients port
create_rule $port
create_rule $ssl_port
else
# finally if the rule exists it will be deleted. If there are more than one, will remove all
delete_rule $port
delete_rule $ssl_port
fi