blob: 9d0d956ff80d455ad8fb113c0dc5fba3f572dd21 [file] [log] [blame]
Dmitry Burmistrov7939e7f2016-06-06 12:20:17 +03001#!/bin/bash
2
3cleanup_and_exit()
4{
5 trap EXIT
6 exit ${1:-0}
7}
8
9fail_exit()
10{
11 echo "$@"
12 cleanup_and_exit 1
13}
14
15job_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
40trap fail_exit EXIT