Skip to content

Instantly share code, notes, and snippets.

@joshelson
Last active April 15, 2024 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshelson/1bfdda99d700e8a69a2271cf3d19fdf9 to your computer and use it in GitHub Desktop.
Save joshelson/1bfdda99d700e8a69a2271cf3d19fdf9 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Configuration
LOG_DIR="/apps/asterisk/logs" # Asterisk log directory
CRASH_DIR="/apps/asterisk/logs/crash_debug" # Crash debug directory
WATCHER_LOG="/var/log/asterisk_crash_watcher.log" # Path to the watcher log file
LOG_FILES=("messages" "full" "debug") # Array of log files to monitor and copy
MIN_UPTIME_SECONDS=300 # Consider it a restart if the uptime is less than this, 300 seconds = 5 minutes
DOCKER_CONTAINER_NAME="asterisk" # Name or ID of the Docker container running Asterisk
# Standard logging function
log_message() {
local message="$1"
echo "$(date +"%Y-%m-%d %H:%M:%S") - $message" | tee -a "$WATCHER_LOG"
}
# Check for required commands
check_dependencies() {
local missing_deps=0
for cmd in docker awk; do
if ! command -v $cmd &> /dev/null; then
log_message "Error: Required command '$cmd' is not available."
missing_deps=$((missing_deps+1))
fi
done
if [ $missing_deps -ne 0 ]; then
exit 1
fi
}
# Function to get Asterisk uptime in seconds using Docker
get_asterisk_uptime_seconds() {
local uptime_seconds=$(docker exec $DOCKER_CONTAINER_NAME asterisk -rx 'core show uptime seconds' | grep "System uptime" | awk '{print $3}')
echo $uptime_seconds
}
# Function to copy logs for crash debugging
copy_logs_for_debugging() {
[ ! -d "$CRASH_DIR" ] && mkdir -p "$CRASH_DIR"
local timestamp=$(date +%Y%m%d-%H%M%S)
for log_file in "${LOG_FILES[@]}"; do
if [ -f "$LOG_DIR/$log_file" ]; then
cp "$LOG_DIR/$log_file" "$CRASH_DIR/${log_file}_$timestamp"
fi
done
log_message "Copied log files to crash debug directory."
}
# Function to empty logs if disk space is low
empty_logs_if_needed() {
local disk_usage=$(df "$LOG_DIR" | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$disk_usage" -ge 90 ]; then
for log_file in "${LOG_FILES[@]}"; do
> "$LOG_DIR/$log_file"
done
log_message "Emptied log files due to disk space constraints."
fi
}
# Main execution
check_dependencies
asterisk_uptime_seconds=$(get_asterisk_uptime_seconds)
if [[ -z "$asterisk_uptime_seconds" || ! "$asterisk_uptime_seconds" =~ ^[0-9]+$ ]]; then
log_message "Error: Unable to determine Asterisk uptime."
exit 1
fi
if [ "$asterisk_uptime_seconds" -le "$MIN_UPTIME_SECONDS" ]; then
log_message "Asterisk recent restart detected (uptime: $asterisk_uptime_seconds seconds), copying logs for debugging..."
copy_logs_for_debugging
else
log_message "No recent Asterisk restart detected (uptime: $asterisk_uptime_seconds seconds)."
empty_logs_if_needed
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment