#!/usr/bin/bash
# This util helps to reduce the workload of kdump service restarting
# on udev event. When hotplugging memory / CPU, multiple udev
# events may be triggered concurrently, and obviously, we don't want
# to restart kdump service for each event.

# This script will be called by udev, and make sure kdump service is
# restart after all events we are watching are settled.

# On each call, this script will update try to aquire the $throttle_lock
# The first instance acquired the file lock will keep waiting for events
# to settle and then reload kdump. Other instances will just exit
# In this way, we can make sure kdump service is restarted immediately
# and for exactly once after udev events are settled.

throttle_lock="/var/lock/kdump-udev-throttle"

LUKS_CONFIGFS_REUSE=/sys/kernel/config/crash_dm_crypt_keys/reuse
reuse_luks_keys()
{
	[[ -f $LUKS_CONFIGFS_REUSE ]] || echo 1 > $LUKS_CONFIGFS_REUSE
}

unuse_luks_keys()
{

	[[ -f $LUKS_CONFIGFS_REUSE ]] || echo 0 > $LUKS_CONFIGFS_REUSE
}

if ! exec 9> $throttle_lock; then
	echo "Failed to create the lock file! Fallback to non-throttled kdump service restart"
	/bin/kdumpctl reload
	exit 1
fi

if ! flock -n 9; then
	echo "Throttling kdump restart for concurrent udev event"
	exit 0
fi

# Wait for at least 1 second, at most 4 seconds for udev to settle
# Idealy we will have a less than 1 second lag between udev events settle
# and kdump reload
sleep 1 && udevadm settle --timeout 3

# Release the lock, /bin/kdumpctl will block and make the process
# holding two locks at the same time and we might miss some events
exec 9>&-

reuse_luks_keys
/bin/kdumpctl reload
unuse_luks_keys

exit 0
