4
0

check_update_lock.sh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/bin/bash
  2. # LinuxGSM check_update_lock.sh module
  3. # Author: Daniel Gibbs
  4. # Contributors: https://linuxgsm.com/contrib
  5. # Website: https://linuxgsm.com
  6. # Description: Stops an update or validate from running while another one is running.
  7. moduleselfname="$(basename "$(readlink -f "${BASH_SOURCE[0]}")")"
  8. updatinglock="${lockdir}/updating.lock"
  9. fn_update_lock_create() {
  10. (
  11. set -o noclobber
  12. echo "$$" > "${updatinglock}"
  13. ) 2> /dev/null
  14. }
  15. # Checks the PID in the lockfile is running and started before the lockfile was written.
  16. fn_update_lock_running() {
  17. local lockpid="${1}"
  18. local lockage processage
  19. if [ -z "${lockpid}" ] || ! kill -0 "${lockpid}" 2> /dev/null; then
  20. return 1
  21. fi
  22. lockage="$(($(date '+%s') - $(stat -c %Y "${updatinglock}" 2> /dev/null || echo 0)))"
  23. processage="$(ps -o etimes= -p "${lockpid}" 2> /dev/null | tr -d ' ')"
  24. [ -n "${processage}" ] && [ "$((processage + 2))" -ge "${lockage}" ]
  25. }
  26. if ! fn_update_lock_create; then
  27. updatelockpid="$(cat "${updatinglock}" 2> /dev/null)"
  28. if [ -z "${updatelockpid}" ]; then
  29. sleep 1
  30. updatelockpid="$(cat "${updatinglock}" 2> /dev/null)"
  31. fi
  32. if [ "${updatelockpid}" == "$$" ] && [ -n "${updatelocklevel}" ]; then
  33. return
  34. fi
  35. if [ "${updatelockpid}" == "$$" ] || ! fn_update_lock_running "${updatelockpid}"; then
  36. fn_script_log_warn "Checking update: Removing stale lockfile from PID ${updatelockpid:-unknown}"
  37. rm -f "${updatinglock:?}"
  38. fn_update_lock_create
  39. fi
  40. fi
  41. updatelockpid="$(cat "${updatinglock}" 2> /dev/null)"
  42. if [ "${updatelockpid}" != "$$" ]; then
  43. fn_print_dots "Checking update"
  44. fn_print_checking_eol
  45. fn_print_info "Checking update: Update is already running (PID ${updatelockpid})"
  46. fn_print_info_eol_nl
  47. fn_script_log_info "Checking update: Update is already running (PID ${updatelockpid})"
  48. # shellcheck disable=SC2034 # Used by core_exit.sh.
  49. exitcode=0
  50. unset exitbypass
  51. core_exit.sh
  52. fi
  53. updatelocklevel="${BASH_SUBSHELL}"