tmux-continuum/scripts/continuum_save.sh
v9v 721890d22f Fix race condition in autosave
Fixes the case where multiple tmux sessions call auto-save at the same time, which occasionally results in multiple instances of save_all() running in parallel and causing issues like #3 and tmux-plugins/tmux-resurrect#294.

The sequence in main() is:
1. Check enough_time_since_last_run_passed
2. Save
3. Update last_save_timestamp.

The race here is:
* process A finishes step 1 and is busy with step 2. The timestamp is not updated yet.
* process B comes to step 1, sees the old timestamp and proceeds to step 2, too.
2019-07-04 20:21:02 +02:00

46 lines
1.3 KiB
Bash
Executable File

#!/usr/bin/env bash
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "$CURRENT_DIR/helpers.sh"
source "$CURRENT_DIR/variables.sh"
source "$CURRENT_DIR/shared.sh"
supported_tmux_version_ok() {
"$CURRENT_DIR/check_tmux_version.sh" "$SUPPORTED_VERSION"
}
get_interval() {
get_tmux_option "$auto_save_interval_option" "$auto_save_interval_default"
}
auto_save_not_disabled() {
[ "$(get_interval)" -gt 0 ]
}
enough_time_since_last_run_passed() {
local last_saved_timestamp="$(get_tmux_option "$last_auto_save_option" "0")"
local interval_minutes="$(get_interval)"
local interval_seconds="$((interval_minutes * 60))"
local next_run="$((last_saved_timestamp + $interval_seconds))"
[ "$(current_timestamp)" -ge "$next_run" ]
}
fetch_and_run_tmux_resurrect_save_script() {
local resurrect_save_script_path="$(get_tmux_option "$resurrect_save_path_option" "")"
if [ -n "$resurrect_save_script_path" ]; then
"$resurrect_save_script_path" "quiet" >/dev/null 2>&1 &
set_last_save_timestamp
fi
}
main() {
(
flock -n 101 || return # The code below is not thread-safe.
if supported_tmux_version_ok && auto_save_not_disabled && enough_time_since_last_run_passed; then
fetch_and_run_tmux_resurrect_save_script
fi
) 101>/tmp/tmux-continuum-autosave.lockfile
}
main