Last active
March 5, 2024 17:32
-
-
Save vadimstasiev/90de58126911ac5afd67d2977be3c406 to your computer and use it in GitHub Desktop.
Turn off TrueNAS when system is idle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
INACTIVE_THRESHOLD=1800 # 30 minutes in seconds | |
CHECK_INTERVAL=1 # How often to check disk activity, in seconds | |
SAMPLE_DURATION=1 # Duration for iostat to collect data, in seconds | |
DEBUG=1 # Set to 1 to enable debug mode, 0 to disable | |
LOW_ACTIVITY_THRESHOLD_READ=5000 # Threshold for read activity in kB/s, adjust as needed | |
LOW_ACTIVITY_THRESHOLD_WRITE=5000 # Threshold for write activity in kB/s, adjust as needed | |
last_activity_time=$(date +%s) | |
if [ "$DEBUG" -eq 1 ]; then | |
echo "Starting disk activity monitoring in debug mode..." | |
else | |
echo "Starting disk activity monitoring..." | |
fi | |
# List all disks excluding specific patterns (e.g., loop devices) and get only the name column | |
DISKS=$(lsblk -nd -o name | grep -v '^loop') | |
while true; do | |
current_time=$(date +%s) | |
low_activity_disks=0 | |
total_disks=0 | |
for DISK in $DISKS; do | |
iostat_output=$(iostat -x ${DISK} ${SAMPLE_DURATION} 2) | |
read_activity=$(echo "$iostat_output" | awk -v disk="$DISK" '$0 ~ disk {getline; print $3}') | |
write_activity=$(echo "$iostat_output" | awk -v disk="$DISK" '$0 ~ disk {getline; print $9}') | |
if [ "$DEBUG" -eq 1 ]; then | |
echo "Disk: $DISK, Current Read activity: $read_activity kB/s, Current Write activity: $write_activity kB/s" | |
fi | |
read_active=$(awk -v ra="$read_activity" -v threshold="$LOW_ACTIVITY_THRESHOLD_READ" 'BEGIN {print (ra < threshold) ? "1" : "0"}') | |
write_active=$(awk -v wa="$write_activity" -v threshold="$LOW_ACTIVITY_THRESHOLD_WRITE" 'BEGIN {print (wa < threshold) ? "1" : "0"}') | |
if [ "$read_active" -eq 1 ] && [ "$write_active" -eq 1 ]; then | |
low_activity_disks=$((low_activity_disks + 1)) | |
fi | |
total_disks=$((total_disks + 1)) | |
done | |
if [ "$DEBUG" -eq 1 ]; then | |
echo "Low activity disks: $low_activity_disks out of $total_disks" | |
fi | |
# If all disks are under low activity, consider shutting down | |
if [ "$low_activity_disks" -eq "$total_disks" ]; then | |
if [ $((current_time - last_activity_time)) -ge ${INACTIVE_THRESHOLD} ]; then | |
echo "All disks have been under low activity for 30 minutes. Shutting down." | |
sudo shutdown -h now | |
exit | |
fi | |
else | |
last_activity_time=$(date +%s) | |
fi | |
sleep ${CHECK_INTERVAL} | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment