Tuesday, January 8, 2013

Use lockf to prevent running multiple rsync processes

Use lockf to ensure only one instance of rsync is running at a time.

#!/bin/sh
runRsync () {
  mode=${1}
  lockFile=/tmp/test.lock
  runCount=0
  runMax=5

  date "+rsync update starts at %Y-%m-%d %H:%M:%S"

  while [ $runCount -lt $runMax ]; do
    ### program to execute.
    if [ $mode = "PULLING" ]; then
      lockf -t 0 ${lockFile} /usr/local/bin/rsync -avu --ipv4 --stats --safe-links --password-file=/usr/local/etc/rsyncd.passwd_rsyncbot rsyncbot@1.2.3.4::mybackup /home/srv/mybackup/
    elif [ $mode = "PUSHING" ]; then
      lockf -t 0 ${lockFile} /usr/local/bin/rsync -avu --ipv4 --stats --safe-links --password-file=/usr/local/etc/rsyncd.passwd_rsyncbot /home/srv/mybackup/ rsyncbot@1.2.3.4::mybackup
    fi

    ### checking the exit status of the previous command.
    if [ $? -eq 0 ]; then
      break
    fi

    runCount=`expr $runCount + 1`

    if [ $runCount -eq $runMax ]; then
      break
    fi

    ### retry after ten seconds.
    sleep 10
  done;

  date "+rsync update ends at %Y-%m-%d %H:%M:%S"
}

#umask 27

### pulling from remote files to local
runRsync "PULLING"

### pushing from local files to remote
runRsync "PUSHING"

echo '[DONE]'

Reference:
http://blog.ijun.org/2010/02/rsync-synchronizing-two-file-trees_19.html

No comments: