Skip to content

Instantly share code, notes, and snippets.

@jpauli
Created July 1, 2014 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpauli/69ff64a8425e8fd2e24b to your computer and use it in GitHub Desktop.
Save jpauli/69ff64a8425e8fd2e24b to your computer and use it in GitHub Desktop.
PHP fast-cgi pool balancer management script
#!/bin/bash
pool1=pool_1
pool2=pool_2
port1=8031
port2=8032
nbport1=0
nbport2=0
getPoolFromPort() {
case "$1" in
"$port1")
echo $pool1
;;
"$port2")
echo $pool2
;;
*)
echo fucked
return 1
;;
esac
return 0
}
getOldestPHP() {
pids=$( lsof -b -F p -n -P -sTCP:LISTEN -i :$port1 ; lsof -b -F p -n -P -sTCP:LISTEN -i :$port2 )
arg=
for pid in $pids; do
arg="$arg -p ${pid//p/} "
done
ps $arg -o pid,lstart k lstart | tail -n +2 | head -n 1 | awk '{ print $1 }'
}
getPortFromPid() {
lsof -n -P -b -F n -p $1 -a -i TCP -s TCP:LISTEN 2>/dev/null | grep ^n | cut -d ':' -f 2
}
# count unique ports from different php-cgi instances
nbport1=$( lsof -b -F p -n -P -sTCP:LISTEN -i :$port1 | wc -l )
nbport2=$( lsof -b -F p -n -P -sTCP:LISTEN -i :$port2 | wc -l )
if [ $nbport1 -gt 0 -a $nbport2 -gt 0 ]; then
# blocked situation : both ports port1 and port2 are in LISTEN status
oldest=$( getOldestPHP )
oport=$( getPortFromPid $oldest )
# kill every process listening on $port
for opid in $( lsof -b -F p -n -P -i :$oport -sTCP:LISTEN ); do
pid=${opid//p/}
echo "killing old php process $pid"
kill -9 $pid
done
fi
# count again to see if we unlocked the situation
nbport1=$( lsof -b -F p -n -P -sTCP:LISTEN -i :$port1 | wc -l )
nbport2=$( lsof -b -F p -n -P -sTCP:LISTEN -i :$port2 | wc -l )
if [ $nbport1 -gt 0 -a $nbport2 -gt 0 ]; then
echo "previous unlock was unsuccessfull !"
exit
fi
if [ $nbport1 -eq 0 -a $nbport2 -eq 0 ]; then
# no more PHP running, shit happenned
# let's start pool number 1
echo "no php running, starting first pool $pool1"
/etc/init.d/spawn-fcgi start $pool1
elif [ $nbport1 -eq 0 -a $nbport2 -gt 0 ]; then
/etc/init.d/spawn-fcgi start $pool1
sleep 1
/etc/init.d/spawn-fcgi stop $pool2
elif [ $nbport2 -eq 0 -a $nbport1 -gt 0 ]; then
/etc/init.d/spawn-fcgi start $pool2
sleep 1
/etc/init.d/spawn-fcgi stop $pool1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment