[type/__package_opkg] Implement flock locking if available

This commit is contained in:
Dennis Camera 2020-06-24 20:49:48 +02:00
parent a9778965be
commit 5364d3bc90

View file

@ -25,28 +25,45 @@
readonly __type_path=${__object%%${__object_id}*} readonly __type_path=${__object%%${__object_id}*}
test -d "${__type_path}" || { echo 'Cannot determine __type_path' >&2; exit 1; } test -d "${__type_path}" || { echo 'Cannot determine __type_path' >&2; exit 1; }
readonly LOCKDIR="${__type_path:?}/.cdist_opkg.lock.dir" readonly LOCKFILE="${__type_path:?}/.cdist_opkg.lock"
if command -v flock >/dev/null 2>&1
then
# use flock (if available) on FD 9
_lock() { _lock() {
until mkdir "${LOCKDIR:?}" 2>/dev/null exec 9<>"${LOCKFILE:?}"
flock -x 9
echo $$>&9
}
_unlock() {
:>"${LOCKFILE:?}"
flock -u 9
exec 9<&-
}
else
# fallback to mkdir if flock is missing
_lock() {
until mkdir "${LOCKFILE:?}.dir" 2>/dev/null
do do
while test -d "${LOCKDIR}" while test -d "${LOCKFILE}.dir"
do do
# DEBUG: printf 'Locked by PID: %u\n' "$(cat "${LOCKDIR}/pid")" # DEBUG:
# printf 'Locked by PID: %u\n' "$(cat "${LOCKFILE}.dir/pid")"
sleep 1 sleep 1
done done
done done
echo $$ >"${LOCKDIR:?}/pid" echo $$ >"${LOCKFILE:?}.dir/pid"
} }
_unlock() { _unlock() {
test -d "${LOCKDIR}" || return 0 test -d "${LOCKFILE}.dir" || return 0
if test -s "${LOCKDIR}/pid" if test -s "${LOCKFILE}.dir/pid"
then then
test "$(cat "${LOCKDIR}/pid")" = $$ || return 1 test "$(cat "${LOCKFILE}.dir/pid")" = $$ || return 1
rm "${LOCKDIR:?}/pid" rm "${LOCKFILE:?}.dir/pid"
fi fi
rmdir "${LOCKDIR:?}" rmdir "${LOCKFILE:?}.dir"
} }
fi
if test -f "${__object}/parameter/name" if test -f "${__object}/parameter/name"