I am using the script provided here with a small difference as quoted below to fetch the CPU usage of a droplet VM.
snd date as current time in seconds start date as current time - 180 seconds
But still I am not able to fetch the utilization properly. Screenshot of shell script output and CPU utilization graph is provided.
Any idea why am I not getting the actual utilization as per the graph?
Update 1:
#!/bin/bash
TOKEN="myToken"
HOST_ID="myId"
while true
do
# Get the current time in seconds since the epoch
end_time=$(date +%s)
echo "Current time: $end_time"
# Calculate 5 minutes before the current time
start_time=($(date +%s) - 180)
API_ENDPOINT="https://api.digitalocean.com/v2/monitoring/metrics/droplet/cpu?host_id=$HOST_ID&start=$start_time&end=$end_time"
# Get the metrics
RESPONSE=$(curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" "$API_ENDPOINT")
# Parse the metrics
IDLE=$(echo "$RESPONSE" | jq -r '[.data.result[] | select(.metric.mode == "idle") | .values[0][1]] | add')
TOTAL=$(echo "$RESPONSE" | jq -r '[.data.result[] | .values[0][1] | tonumber] | add')
echo "IDLE: $IDLE"
echo "TOTAL: $TOTAL"
USED=$(echo "$TOTAL - $IDLE" | bc)
echo "USED: $USED"
ZERO_CHECK=$(echo "$TOTAL == 0" | bc)
if [ $ZERO_CHECK -eq 1 ]; then
echo "No change in TOTAL, can't calculate CPU Usage"
else
CPU_USAGE=$(echo "scale=2; ($USED / $TOTAL) * 100" | bc)
echo "CPU Usage: $CPU_USAGE%"
fi
done
I've just tested this with the following modification:
And it seems to be working as expected.
What is the exact change that you made in the script?