File: //scripts/checkLoadnAlert.sh
#!/bin/bash
# Set the maximum load threshold
MAX_LOAD=13
# Define the SAR log file (you can modify this to dynamically pick the latest file)
SAR_FILE="/var/log/sa/sa$(date +%d)" # Uses current day's log file (e.g., sa07 for the 7th)
# State file to track the last processed log entry
STATE_FILE="/tmp/last_processed_log_entry.txt"
# Check if the SAR log file exists
if [[ -f "$SAR_FILE" ]]; then
echo "Checking $SAR_FILE..."
# Get the last log entry (second-to-last line, excluding the "Average:" line)
LAST_LOG_ENTRY=$(sar -q -f "$SAR_FILE" | grep -E '^[0-9][0-9]:[0-9][0-9]:[0-9][0-9] (AM|PM)' | tail -n 1)
# Check if the last log entry is already processed
if [[ -f "$STATE_FILE" ]]; then
LAST_PROCESSED_ENTRY=$(cat "$STATE_FILE")
if [[ "$LAST_LOG_ENTRY" == "$LAST_PROCESSED_ENTRY" ]]; then
echo "This log entry has already been processed. Exiting."
exit 0
fi
fi
# Extract load averages from the last log entry
TIMESTAMP=$(echo "$LAST_LOG_ENTRY" | awk '{print $1 " " $2}')
LDAVG1=$(echo "$LAST_LOG_ENTRY" | awk '{print $5 + 0}') # ldavg-1 (5th column)
LDAVG5=$(echo "$LAST_LOG_ENTRY" | awk '{print $6 + 0}') # ldavg-5 (6th column)
LDAVG15=$(echo "$LAST_LOG_ENTRY" | awk '{print $7 + 0}') # ldavg-15 (7th column)
# Debug: Print the extracted values
echo "Timestamp: $TIMESTAMP"
echo "ldavg-1: $LDAVG1"
echo "ldavg-5: $LDAVG5"
echo "ldavg-15: $LDAVG15"
# Check if any of the load averages exceed the threshold
if (( $(echo "$LDAVG1 > $MAX_LOAD" | bc -l) )) || \
(( $(echo "$LDAVG5 > $MAX_LOAD" | bc -l) )) || \
(( $(echo "$LDAVG15 > $MAX_LOAD" | bc -l) )); then
echo "Load exceeded $MAX_LOAD at: $TIMESTAMP"
echo "Load averages: $LDAVG1 (1-min), $LDAVG5 (5-min), $LDAVG15 (15-min)"
# Execute curl request (replace with your actual curl command)
curl --location --request POST 'https://marketing.wp.karmanye.in/api/Karmanye/send-message' --header 'Content-Type: application/json; charset=utf-8' --header 'Accept: application/json' --header 'Authorization: Bearer $2b$10$f7yAQHm3Y1eOxs92aiEJ9eohJ0AdUQ2YwXxUARzk3sVLgKIVw0k2q' --data '{ "phone": "919033595842", "message": "🚨 *Server Load Alert* 🚨\n\n📌 *Timestamp:* '"$TIMESTAMP"'\n⚠️ *High Load Detected*\n🔹 *1 min Load Avg:* '"$LDAVG1"'\n🔹 *5 min Load Avg:* '"$LDAVG5"'\n🔹 *15 min Load Avg:* '"$LDAVG15"'\n\n🛠️ *Action Required: Investigate Server Performance on 5.9.111.147*"}'
# Save the last processed log entry to the state file
echo "$LAST_LOG_ENTRY" > "$STATE_FILE"
else
echo "Load is within the threshold. No action taken."
fi
else
echo "File $SAR_FILE does not exist."
fi