2022-10-17 08:40:09 +00:00
|
|
|
#!/bin/bash
|
2022-02-21 10:56:57 +00:00
|
|
|
|
|
|
|
# This becomes the sourcing script name
|
|
|
|
# (example: check-for-changes.sh)
|
2022-05-05 08:28:38 +00:00
|
|
|
SCRIPT_NAME=$(basename "$0")
|
2022-02-21 10:56:57 +00:00
|
|
|
# Used inside of lock files to identify them and
|
|
|
|
# prevent removal by other instances of docker-mailserver
|
2022-05-05 08:28:38 +00:00
|
|
|
LOCK_ID=$(uuid)
|
2022-02-21 10:56:57 +00:00
|
|
|
|
2023-05-25 23:01:41 +00:00
|
|
|
function _create_lock() {
|
2022-02-21 10:56:57 +00:00
|
|
|
LOCK_FILE="/tmp/docker-mailserver/${SCRIPT_NAME}.lock"
|
2023-05-25 23:39:39 +00:00
|
|
|
while [[ -e "${LOCK_FILE}" ]]; do
|
2022-02-21 10:56:57 +00:00
|
|
|
# Handle stale lock files left behind on crashes
|
|
|
|
# or premature/non-graceful exits of containers while they're making changes
|
2023-05-24 07:06:59 +00:00
|
|
|
if [[ -n "$(find "${LOCK_FILE}" -mmin +1 2>/dev/null)" ]]; then
|
2022-03-21 06:07:52 +00:00
|
|
|
_log 'warn' 'Lock file older than 1 minute - removing stale lock file'
|
2022-02-21 10:56:57 +00:00
|
|
|
rm -f "${LOCK_FILE}"
|
2023-01-16 07:39:46 +00:00
|
|
|
else
|
|
|
|
_log 'warn' "Lock file '${LOCK_FILE}' exists - another execution of '${SCRIPT_NAME}' is happening - trying again shortly"
|
|
|
|
sleep 5
|
2022-02-21 10:56:57 +00:00
|
|
|
fi
|
|
|
|
done
|
|
|
|
trap _remove_lock EXIT
|
2022-03-21 06:07:52 +00:00
|
|
|
|
2022-03-26 08:30:09 +00:00
|
|
|
_log 'trace' "Creating lock '${LOCK_FILE}'"
|
2022-03-21 06:07:52 +00:00
|
|
|
echo "${LOCK_ID}" >"${LOCK_FILE}"
|
2022-02-21 10:56:57 +00:00
|
|
|
}
|
|
|
|
|
2023-05-25 23:01:41 +00:00
|
|
|
function _remove_lock() {
|
2022-02-21 10:56:57 +00:00
|
|
|
LOCK_FILE="${LOCK_FILE:-"/tmp/docker-mailserver/${SCRIPT_NAME}.lock"}"
|
2022-03-26 08:30:09 +00:00
|
|
|
[[ -z "${LOCK_ID}" ]] && _exit_with_error "Cannot remove '${LOCK_FILE}' as there is no LOCK_ID set"
|
2023-05-24 07:06:59 +00:00
|
|
|
if [[ -e "${LOCK_FILE}" ]] && grep -q "${LOCK_ID}" "${LOCK_FILE}"; then # Ensure we don't delete a lock that's not ours
|
2022-02-21 10:56:57 +00:00
|
|
|
rm -f "${LOCK_FILE}"
|
2022-03-26 08:30:09 +00:00
|
|
|
_log 'trace' "Removed lock '${LOCK_FILE}'"
|
2022-02-21 10:56:57 +00:00
|
|
|
fi
|
|
|
|
}
|