blob: 29b3285babe28e73295b8337886e4794d4119b59 [file] [log] [blame]
Dmitry Burmistrov7939e7f2016-06-06 12:20:17 +03001#!/bin/bash
2
3cleanup_and_exit()
4{
5 trap EXIT
Dmitry Burmistrov81860c12016-06-06 16:03:12 +03006 exit "${1:-0}"
Dmitry Burmistrov7939e7f2016-06-06 12:20:17 +03007}
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")
Dmitry Burmistrov81860c12016-06-06 16:03:12 +030023 flock -x -n "$fd" \
Dmitry Burmistrov7939e7f2016-06-06 12:20:17 +030024 || fail_exit "Process already running. Lockfile: $LOCKFILE"
25 ;;
26 "unset")
Dmitry Burmistrov81860c12016-06-06 16:03:12 +030027 flock -u "$fd"
28 [ -f "$LOCKFILE" ] && rm -f "$LOCKFILE"
Dmitry Burmistrov7939e7f2016-06-06 12:20:17 +030029 ;;
30 "wait")
31 local TIMEOUT=${2:-3600}
Dmitry Burmistrov81860c12016-06-06 16:03:12 +030032 [ "$IS_VERBOSE" == "true" ] \
33 && echo "[INFO] Waiting of concurrent process (lockfile: $LOCKFILE, timeout = $TIMEOUT seconds) ..."
34 flock -x -w "$TIMEOUT" "$fd" \
Dmitry Burmistrov7939e7f2016-06-06 12:20:17 +030035 || fail_exit "Timeout error (lockfile: $LOCKFILE)"
Dmitry Burmistrov81860c12016-06-06 16:03:12 +030036 [ "${IS_VERBOSE}" == "true" ] && echo "[INFO] Done"
Dmitry Burmistrov7939e7f2016-06-06 12:20:17 +030037 ;;
38 esac
39}
40
41trap fail_exit EXIT