Dmitry Burmistrov | 7939e7f | 2016-06-06 12:20:17 +0300 | [diff] [blame^] | 1 | #!/bin/bash |
| 2 | |
| 3 | cleanup_and_exit() |
| 4 | { |
| 5 | trap EXIT |
| 6 | exit ${1:-0} |
| 7 | } |
| 8 | |
| 9 | fail_exit() |
| 10 | { |
| 11 | echo "$@" |
| 12 | cleanup_and_exit 1 |
| 13 | } |
| 14 | |
| 15 | job_lock() { |
| 16 | [ -z "$1" ] && fail_exit "Lock file is not specified" |
| 17 | local LOCKFILE=$1 |
| 18 | shift |
| 19 | local fd=1000 |
| 20 | eval "exec $fd>>$LOCKFILE" |
| 21 | case $1 in |
| 22 | "set") |
| 23 | flock -x -n $fd \ |
| 24 | || fail_exit "Process already running. Lockfile: $LOCKFILE" |
| 25 | ;; |
| 26 | "unset") |
| 27 | flock -u $fd |
| 28 | rm -f $LOCKFILE |
| 29 | ;; |
| 30 | "wait") |
| 31 | local TIMEOUT=${2:-3600} |
| 32 | [ "${VERBOSE}" == "true" ] \ |
| 33 | && echo "Waiting of concurrent process (lockfile: $LOCKFILE, timeout = $TIMEOUT seconds) ..." |
| 34 | flock -x -w $TIMEOUT $fd \ |
| 35 | || fail_exit "Timeout error (lockfile: $LOCKFILE)" |
| 36 | ;; |
| 37 | esac |
| 38 | } |
| 39 | |
| 40 | trap fail_exit EXIT |