[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"
_lock() { if command -v flock >/dev/null 2>&1
until mkdir "${LOCKDIR:?}" 2>/dev/null then
do # use flock (if available) on FD 9
while test -d "${LOCKDIR}" _lock() {
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
# DEBUG: printf 'Locked by PID: %u\n' "$(cat "${LOCKDIR}/pid")" while test -d "${LOCKFILE}.dir"
sleep 1 do
# DEBUG:
# printf 'Locked by PID: %u\n' "$(cat "${LOCKFILE}.dir/pid")"
sleep 1
done
done done
done echo $$ >"${LOCKFILE:?}.dir/pid"
echo $$ >"${LOCKDIR:?}/pid" }
} _unlock() {
_unlock() { test -d "${LOCKFILE}.dir" || return 0
test -d "${LOCKDIR}" || return 0 if test -s "${LOCKFILE}.dir/pid"
if test -s "${LOCKDIR}/pid" then
then test "$(cat "${LOCKFILE}.dir/pid")" = $$ || return 1
test "$(cat "${LOCKDIR}/pid")" = $$ || return 1 rm "${LOCKFILE:?}.dir/pid"
rm "${LOCKDIR:?}/pid" fi
fi rmdir "${LOCKFILE:?}.dir"
rmdir "${LOCKDIR:?}" }
} fi
if test -f "${__object}/parameter/name" if test -f "${__object}/parameter/name"