|
Directory : /scripts2/ |
#!/bin/bash
# Configuration
LOG_FILE="/var/log/system_report.log"
ADMIN_EMAIL="sysadmin@sitioshispanos.com"
LOAD_THRESHOLD=50 # System load threshold
# Check if a command exists before executing it
function check_command {
command -v "$1" >/dev/null 2>&1 || { echo "ā ERROR: Command '$1' is not installed."; exit 1; }
}
# Ensure no other instance of the script is running
function sanity_check {
local running_instances
running_instances=$(ps -ef | grep "$0" | grep -v "grep" | grep -v "$$" | wc -l)
if [[ "$running_instances" -ne 0 ]]; then
echo "Another instance of $0 is already running..."
exit 1
fi
}
# Start the daemon
function start_daemon {
sanity_check
echo "Starting daemon..."
main_loop
}
# Stop the daemon
function shutdown_daemon {
echo "Stopping daemon..."
ps -ef | grep "$0" | grep -v "$$" | grep -v "grep" | awk '{print $2}' | xargs kill
}
# Generate system report
function generate_system_report {
echo "===============================" > "$LOG_FILE"
echo "š SYSTEM REPORT $(date)" >> "$LOG_FILE"
echo "===============================" >> "$LOG_FILE"
# Process report
echo -e "\nš¹ Top CPU/Memory consuming processes:" >> "$LOG_FILE"
ps aux --sort=-%mem,-%cpu | head -20 >> "$LOG_FILE"
# CPU and memory usage report
echo -e "\nš¹ CPU and Memory Usage:" >> "$LOG_FILE"
check_command "sar"
sar -u 5 1 | grep "Average" >> "$LOG_FILE"
free -h >> "$LOG_FILE"
# Disk usage report
echo -e "\nš¹ Disk Usage:" >> "$LOG_FILE"
df -h >> "$LOG_FILE"
# MySQL running queries
echo -e "\nš¹ Active MySQL Queries:" >> "$LOG_FILE"
check_command "mysql"
mysql -e "SHOW FULL PROCESSLIST;" >> "$LOG_FILE"
# Apache active requests
echo -e "\nš¹ Apache Active Requests:" >> "$LOG_FILE"
check_command "apachectl"
apachectl fullstatus 2>/dev/null | grep -E "PID|requests/sec|CPU Usage|Total accesses|request|Waiting for Connection" >> "$LOG_FILE"
# Send report via email
mail -s "ā ļø Alert: High System Load on $(hostname)" "$ADMIN_EMAIL" < "$LOG_FILE"
}
# Main daemon loop
function main_loop {
{
while true; do
# Get system load average
local load_avg
load_avg=$(uptime | awk -F'average:' '{ print $2 }' | sed 's/\...,//g' | awk '{ print $1 }')
# If system load exceeds the threshold, take action
if [[ "$load_avg" -gt $LOAD_THRESHOLD ]]; then
echo "ā ļø High system load detected ($load_avg). Generating report..."
generate_system_report
# Kill problematic processes
killall -9 exim httpd
# Kill active MySQL connections
local process_list
process_list=$(mysql -s -e "SHOW FULL PROCESSLIST" | awk '{print $1}')
for id in $process_list; do
mysql -s -e "KILL $id"
done
# Execute recovery scripts
/scripts2/fix_semaphores.sh
/scripts/restartsrv_apache_php_fpm
service httpd restart
fi
sleep 60
done
} &
}
# Handle script arguments
case "$1" in
"start")
start_daemon
;;
"stop")
shutdown_daemon
;;
*)
echo "Usage: $0 [start|stop]"
exit 1
;;
esac