Skip to content

Instantly share code, notes, and snippets.

@b0noI
Created July 20, 2019 21:07
Show Gist options
  • Save b0noI/4f7fc3d1a4a7bb0f75a6b9230d8540fa to your computer and use it in GitHub Desktop.
Save b0noI/4f7fc3d1a4a7bb0f75a6b9230d8540fa to your computer and use it in GitHub Desktop.
#!/bin/bash
# Number of sequential checks when the instance had utilization below the threshold.
COUNTER=0
# If actual CPU utilization is below this threshold script will increase the counter.
THRESHOLD_PERCENT=2
# Interval between checks of the CPU utilizations.
SLEEP_INTERVAL_SECONDS=5
# How big COUNTER need to be for the script to shutdown the instance. For example,
# if we want an instance to be stopped after 20min of idle. Each utilization probe
# happens every 5sec (SLEEP_INTERVAL_SECONDS), therefore since there are 1200 seconds
# in 20 min (20 * 60 = 1200) we need counter threshold to be 240 (1200 / 5).
HALT_THRESHOLD=240
while true; do
CPU_PERCENT=$(mpstat -P ALL 1 1 | awk '/Average:/ && $2 ~ /[0–9]/ {print $3}')
if (( $(echo "${CPU_PERCENT} < ${THRESHOLD_PERCENT}" | bc -l) )); then
COUNTER=$((COUNTER + 1))
if (( $(echo "${COUNTER} > ${HALT_THRESHOLD}" | bc -l) )); then
shutdown now
fi
else
COUNTER=0
fi
sleep "${SLEEP_INTERVAL_SECONDS}"
done
@IlyaKochnev
Copy link

IlyaKochnev commented Jun 17, 2020

Hi @b0nol
I believe the command mpstat -P ALL 1 1 | awk '/Average:/ && $2 ~ /[0–9]/ {print $3}' is not correct enoght to assess the overall utilization of an instance. awk '/Average:/ && $2 ~ /[0–9]/ {print $3}' catches only the processor 0 activity and provides multiple output in case instance has more than 8 CPU, what is not expected in the script.
I suggest the following command instaead mpstat -u 1 1 | awk '/Average:/ {print $3}'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment