Friday, November 25, 2011

Bash, PID and queues

Something useful for a change.

I run some synchronisation between servers using unison

I won't go into the details of setting it up, but it's pretty easy.

I had a couple of issues to resolve. First was that this was running every 20 minutes, which was fine for a few small changes, but if you had a large change/s then it would trigger itself again, and again, and again....

To cure this I added a check to see if the job was already running, and if so, too bail out.

I knicked a bit of code from a script called pid_queue.sh here and hacked it about slightly.

#!/bin/bash

if [ ! -z "`ps -C unison --no-headers -o "pid,ppid,sid,comm"|grep -v "$$ "|grep -v ""`" ]; then
#script is already running  so abort
exit 1
fi

So that will stop the script running if the process is already on the go.

Some of the syncs only run daily. In that case I don't want it to exit til the following day, but want it to sleep until the current process has stopped.

#!/bin/bash

while [ ! -z "`ps -C unison --no-headers -o "pid,ppid,sid,comm"|grep -v "$$ "|grep -v ""`" ]
do
# echo "sleeping"
 sleep 1
done


Then I realised that some things were probably hanging around if they couldn't find the server. My servers are on a DMZ on their routers. The problem was that I couldn't work out if the server was up with a ping because the router answered. Checking something with telnet or ssh took a while so I thought about nmap and came up with the following :

X=`/usr/bin/nmap -PN -p53 myserver.somedomain.org |grep open`
    
if [ ! "$X" = "" ]; then
    # do whatever
fi


This very quickly checks whether the DNS port is open - it could be any port really. If the server is up, it shows as open, but if it is not it is shown as filtered.

Job done.....

No comments:

Post a Comment