Files
semaphore/system_cleanup.sh
2025-07-28 18:37:53 +02:00

103 lines
2.7 KiB
Bash
Executable File

#!/bin/bash
# Log file path
LOG_FILE="/opt/phx/log/system_cleanup.log"
EMAIL="y.m.lima19@gmail.com"
# Function to send email notifications
send_email() {
SUBJECT="$1"
MESSAGE="$2"
echo "$MESSAGE" | mail -s "$SUBJECT" "$EMAIL"
}
# Function to log informational messages
log_info() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] $1" | tee -a "$LOG_FILE"
}
# Function to log errors and send email notifications
log_error() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" | tee -a "$LOG_FILE" >&2
send_email "⚠️ System Cleanup Error" "$1"
}
# Start Cleanup
log_info "========== System Cleanup Started =========="
# Clear system cache
log_info "Clearing system cache..."
if sync && echo 3 > /proc/sys/vm/drop_caches; then
log_info "System cache cleared successfully."
else
log_error "Failed to clear system cache."
fi
# Clean up packages
log_info "Cleaning up unused packages..."
if apt-get autoremove -y >> "$LOG_FILE" 2>&1; then
log_info "Unused packages removed."
else
log_error "Failed to remove unused packages."
fi
log_info "Running apt autoclean..."
if apt-get autoclean -y >> "$LOG_FILE" 2>&1; then
log_info "Autoclean completed."
else
log_error "Autoclean failed."
fi
log_info "Running apt clean..."
if apt-get clean >> "$LOG_FILE" 2>&1; then
log_info "Clean completed."
else
log_error "Clean failed."
fi
# Clean up system logs
log_info "Cleaning system logs older than 7 days..."
if journalctl --vacuum-time=7d >> "$LOG_FILE" 2>&1; then
log_info "Old logs cleaned."
else
log_error "Failed to clean old logs."
fi
# Restart services
log_info "Restarting Docker service..."
if systemctl restart docker; then
log_info "Docker restarted successfully."
else
log_error "Failed to restart Docker."
fi
# Kill zombie processes
log_info "Checking for zombie processes..."
ZOMBIES=$(ps aux | grep 'defunct' | grep -v grep)
if [[ -n "$ZOMBIES" ]]; then
log_info "Found zombie processes. Attempting to kill..."
if pkill -9 -f 'defunct'; then
log_info "Zombie processes killed."
else
log_error "Failed to kill zombie processes."
fi
else
log_info "No zombie processes found."
fi
# Swap check and creation
log_info "Checking swap space..."
if swapon --show | grep -q '/swapfile'; then
log_info "Swap space is active."
else
log_info "No swap detected. Creating 2GB swap file..."
if fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile; then
log_info "Swap file created and activated."
else
log_error "Failed to create swap file."
fi
fi
# Cleanup completed
log_info "========== System Cleanup Completed =========="
send_email "✅ System Cleanup Successful" "The system cleanup script has completed successfully."