Skip to content

Instantly share code, notes, and snippets.

@efim-a-efim
Created April 2, 2014 09:56
Show Gist options
  • Save efim-a-efim/9931244 to your computer and use it in GitHub Desktop.
Save efim-a-efim/9931244 to your computer and use it in GitHub Desktop.
Complex lock management with one command.
#!/bin/bash
########################################################
# Locking library
########################################################
__LOCK_DIR="${_LOCK_DIR:-/var/lock/backup}"
__clear_locks() {
local _lock_dir="${1:-${__LOCK_DIR}}"
find "${_lock_dir}" -name '*.lock' | \
while read _lf; do
cat "${_lf}" | read _pid _resource
kill -0 "${_pid}" || rm -f "${_lf}"
done
}
lock() {
local _action="$1"
local _resource="${2:-main}"
local _lock_dir="${3:-${__LOCK_DIR}}"
[[ -z "${_action}" ]] && return 255
[[ -z "${_resource}" ]] && return 255
[[ -d "${_lock_dir}" ]] || mkdir -p "${_lock_dir}"
# Clear unneeded locks
clear_locks "${_lock_dir}"
case "${_action}" in
acquire|lock)
local _lf="`mktemp --tmpdir="${_lock_dir}" 'XXXXXXXX.lock'`"
echo "$$ ${_resource}" > "${_lf}" || return 1
return 0
;;
release|free)
# find all locks for current PID and release (remove) first one
local _lf="`grep "$$ ${_resource}" "${_lock_dir}/*.lock" | cut -d ':' -f 1 | uniq | head -n 1`"
[[ -f "${_lf}" ]] && rm -f "${_lf}"
return $?
;;
status|list)
# list all locker PIDs
grep "[0-9]\+ ${_resource}" "${_lock_dir}/*.lock" | cut -d ':' -f 2 | cut -d ' ' -f 1 | uniq
return 0
;;
check)
# return 0 if resource is not locked by any PID
local _lf="`grep "[0-9]\+ ${_resource}" "${_lock_dir}/*.lock" | cut -d ':' -f 1 | uniq | head -n 1`"
[[ -f "${_lf}" ]] && return 1
return 0
;;
*)
return 255
;;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment