Tuesday, March 6, 2012

lock it ,lock it up and lock it

I like to I run backups and other scripts that require exclusive access to directories. For directory mirroring, rsync is a graceful candidate for the job - either locally or over the net to another host. A problem with some scripts that call rsync is that you can get into a race situation if one of your scheduled rsync jobs starts trying to "back up" the same thing that another scheduled rsync process is processing. Bad joss all around. Of course, you could write something that says, if this script is running, please don't run. Or. lockfile can be used in this regard. lockfile is part of the procmail package on various flavors of Ubuntu. To get it issue:
# apt-get install procmail
Easy.

Here's a useful snippet of code using lockfile in a shell script:
#!/bin/sh

LOCKFILE="/tmp/processname.lock"

# Break the lock if locking process has died
RUNNING_PID=`cat $LOCKFILE 2>/dev/null`;
if [ "x"$RUNNING_PID != "x" ] ; then
        RUNNING_NAME=`ps -p $RUNNING_PID -o comm= 2>/dev/null`;
        if [ "x"$RUNNING_NAME != "processname.sh" ] ; then
                rm -f $LOCKFILE
        fi
fi

# Acquire lock
lockfile $LOCKFILE
echo $$ > $LOCKFILE

echo whatever i am doing and plop in a log `date` >> /var/log/processname.log

...snip...

echo whatever i am doing is completed `date` >> /var/log/processname.log

# Release the lock
rm -f $LOCKFILE
If you're doing a scad of stuff, rotate your logs by placing an appropriately named file in logrotate.d:
/var/log/processname.log /var/log/ohlookanotherprocessname.log {
    rotate 7
    daily
    missingok
    notifempty
    compress
    sharedscripts
    endscript
}
Post a Comment