Reapply "Merge branch 'development-SDXPINN' into SDXPINN"

This reverts commit 738567acd7.
This commit is contained in:
Cameron Thompson
2025-08-28 17:42:45 -04:00
parent 738567acd7
commit e125cc1461
130 changed files with 927 additions and 568 deletions

View File

@@ -1,195 +0,0 @@
#!/bin/sh
# Configuration
CONFIG_FILE="/etc/keep_alive_schedule.conf"
STATUS_FILE="/tmp/keep_alive_status"
SPEEDTEST_SCRIPT="/www/cgi-bin/home/speedtest/speedtest.sh"
# Function to convert HH:MM to minutes since midnight
time_to_minutes() {
echo "$1" | awk -F: '{print $1 * 60 + $2}'
}
# Function to validate time interval
validate_interval() {
START_TIME=$1
END_TIME=$2
INTERVAL_MINUTES=$3
# Convert times to minutes
START_MINUTES=$(time_to_minutes "$START_TIME")
END_MINUTES=$(time_to_minutes "$END_TIME")
# Calculate duration between start and end time
if [ $END_MINUTES -lt $START_MINUTES ]; then
# Handle case where end time is on the next day
DURATION=$((1440 - START_MINUTES + END_MINUTES))
else
DURATION=$((END_MINUTES - START_MINUTES))
fi
# Check if interval is longer than duration
if [ $INTERVAL_MINUTES -gt $DURATION ]; then
return 1
fi
return 0
}
# Function to generate cron time expression
generate_cron_time() {
START_TIME=$1
END_TIME=$2
INTERVAL=$3
START_HOUR=$(echo "$START_TIME" | cut -d: -f1 | sed 's/^0//')
START_MIN=$(echo "$START_TIME" | cut -d: -f2)
END_HOUR=$(echo "$END_TIME" | cut -d: -f1 | sed 's/^0//')
END_MIN=$(echo "$END_TIME" | cut -d: -f2)
# If end time is less than start time, it means we cross midnight
if [ $(time_to_minutes "$END_TIME") -lt $(time_to_minutes "$START_TIME") ]; then
# Create two cron entries for before and after midnight
echo "*/$INTERVAL $START_HOUR-23 * * * $SPEEDTEST_SCRIPT"
echo "*/$INTERVAL 0-$((END_HOUR - 1)) * * * $SPEEDTEST_SCRIPT"
else
echo "*/$INTERVAL $START_HOUR-$((END_HOUR - 1)) * * * $SPEEDTEST_SCRIPT"
fi
}
# Function to urldecode
urldecode() {
echo -e "$(echo "$1" | sed 's/+/ /g;s/%\([0-9A-F][0-9A-F]\)/\\x\1/g')"
}
# Function to save configuration
save_config() {
echo "START_TIME=$1" >"$CONFIG_FILE"
echo "END_TIME=$2" >>"$CONFIG_FILE"
echo "INTERVAL=$3" >>"$CONFIG_FILE"
echo "ENABLED=1" >>"$CONFIG_FILE"
}
# Function to disable scheduling
disable_scheduling() {
if [ -f "$CONFIG_FILE" ]; then
sed -i 's/ENABLED=1/ENABLED=0/' "$CONFIG_FILE"
fi
# Remove any existing cron jobs
crontab -l | grep -v "$SPEEDTEST_SCRIPT" | crontab -
}
# Function to get current status
get_status() {
if [ -f "$CONFIG_FILE" ]; then
ENABLED=$(grep "ENABLED=" "$CONFIG_FILE" | cut -d'=' -f2)
START_TIME=$(grep "START_TIME=" "$CONFIG_FILE" | cut -d'=' -f2)
END_TIME=$(grep "END_TIME=" "$CONFIG_FILE" | cut -d'=' -f2)
INTERVAL=$(grep "INTERVAL=" "$CONFIG_FILE" | cut -d'=' -f2)
echo "Status: 200 OK"
echo "Content-Type: application/json"
echo ""
echo "{\"enabled\":$ENABLED,\"start_time\":\"$START_TIME\",\"end_time\":\"$END_TIME\",\"interval\":$INTERVAL}"
else
echo "Status: 200 OK"
echo "Content-Type: application/json"
echo ""
echo "{\"enabled\":0,\"start_time\":\"\",\"end_time\":\"\",\"interval\":0}"
fi
}
# Handle POST requests
if [ "$REQUEST_METHOD" = "POST" ]; then
# Read POST data
read -r POST_DATA
# Check if disabling is requested
echo "$POST_DATA" | grep -q "disable=true"
if [ $? -eq 0 ]; then
disable_scheduling
echo "Status: 200 OK"
echo "Content-Type: application/json"
echo ""
echo "{\"status\":\"success\",\"message\":\"Scheduling disabled\"}"
exit 0
fi
# Extract times and interval
START_TIME=$(echo "$POST_DATA" | grep -o 'start_time=[^&]*' | cut -d'=' -f2)
END_TIME=$(echo "$POST_DATA" | grep -o 'end_time=[^&]*' | cut -d'=' -f2)
INTERVAL=$(echo "$POST_DATA" | grep -o 'interval=[^&]*' | cut -d'=' -f2)
# Decode times
START_TIME=$(urldecode "$START_TIME")
END_TIME=$(urldecode "$END_TIME")
INTERVAL=$(urldecode "$INTERVAL")
# Validate times
if [ -z "$START_TIME" ] || [ -z "$END_TIME" ] || [ -z "$INTERVAL" ]; then
echo "Status: 400 Bad Request"
echo "Content-Type: application/json"
echo ""
echo "{\"error\":\"Missing start time, end time, or interval\"}"
exit 1
fi
# Validate interval is a number
if ! echo "$INTERVAL" | grep -q '^[0-9]\+$'; then
echo "Status: 400 Bad Request"
echo "Content-Type: application/json"
echo ""
echo "{\"error\":\"Interval must be a number in minutes\"}"
exit 1
fi
# Validate interval
if ! validate_interval "$START_TIME" "$END_TIME" "$INTERVAL"; then
echo "Status: 400 Bad Request"
echo "Content-Type: application/json"
echo ""
echo "{\"error\":\"Interval is longer than the time between start and end time\"}"
exit 1
fi
# Create temporary file for new crontab
TEMP_CRON=$(mktemp)
# Get existing crontab entries (excluding our script)
crontab -l 2>/dev/null | grep -v "$SPEEDTEST_SCRIPT" >"$TEMP_CRON"
# Generate and add cron entries
generate_cron_time "$START_TIME" "$END_TIME" "$INTERVAL" >>"$TEMP_CRON"
# Install new crontab
crontab "$TEMP_CRON"
rm "$TEMP_CRON"
# Save configuration
save_config "$START_TIME" "$END_TIME" "$INTERVAL"
echo "Status: 200 OK"
echo "Content-Type: application/json"
echo ""
echo "{\"status\":\"success\",\"message\":\"Keep-alive scheduling enabled\"}"
exit 0
fi
# Parse query string for GET requests
if [ "$REQUEST_METHOD" = "GET" ]; then
QUERY_STRING=$(echo "$QUERY_STRING" | sed 's/&/\n/g')
for param in $QUERY_STRING; do
case "$param" in
status=*)
get_status
exit 0
;;
esac
done
fi
# If no valid request is made
echo "Status: 400 Bad Request"
echo "Content-Type: application/json"
echo ""
echo "{\"error\":\"Invalid request\"}"
exit 1

View File

@@ -0,0 +1,220 @@
#!/bin/sh
# QuecManager Log Viewer API
# Provides centralized log access for the web interface
. /www/cgi-bin/services/quecmanager_logger.sh
# CGI Headers
printf "Content-Type: application/json\r\n"
printf "Access-Control-Allow-Origin: *\r\n"
printf "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n"
printf "Access-Control-Allow-Headers: Content-Type\r\n"
printf "\r\n"
# Initialize logs if needed
qm_init_logs
# Parse query parameters
QUERY_STRING="${QUERY_STRING:-}"
CATEGORY=""
SCRIPT=""
LEVEL=""
LINES="50"
SINCE=""
# Simple parameter parsing
if [ -n "$QUERY_STRING" ]; then
for param in $(echo "$QUERY_STRING" | tr '&' ' '); do
case "$param" in
category=*)
CATEGORY=$(echo "$param" | cut -d'=' -f2 | sed 's/%20/ /g' | tr -d '"')
;;
script=*)
SCRIPT=$(echo "$param" | cut -d'=' -f2 | sed 's/%20/ /g' | tr -d '"')
;;
level=*)
LEVEL=$(echo "$param" | cut -d'=' -f2 | sed 's/%20/ /g' | tr -d '"')
;;
lines=*)
LINES=$(echo "$param" | cut -d'=' -f2 | tr -d '"')
;;
since=*)
SINCE=$(echo "$param" | cut -d'=' -f2 | sed 's/%20/ /g' | tr -d '"')
;;
esac
done
fi
# Validate lines parameter
if ! echo "$LINES" | grep -qE '^[0-9]+$' || [ "$LINES" -gt 1000 ]; then
LINES="50"
fi
# Function to get available categories
get_categories() {
printf '{\n'
printf ' "categories": [\n'
if [ -d "$QM_LOG_DAEMONS" ]; then
printf ' "daemons"'
[ -d "$QM_LOG_SERVICES" ] || [ -d "$QM_LOG_SETTINGS" ] || [ -d "$QM_LOG_SYSTEM" ] && printf ','
printf '\n'
fi
if [ -d "$QM_LOG_SERVICES" ]; then
printf ' "services"'
[ -d "$QM_LOG_SETTINGS" ] || [ -d "$QM_LOG_SYSTEM" ] && printf ','
printf '\n'
fi
if [ -d "$QM_LOG_SETTINGS" ]; then
printf ' "settings"'
[ -d "$QM_LOG_SYSTEM" ] && printf ','
printf '\n'
fi
if [ -d "$QM_LOG_SYSTEM" ]; then
printf ' "system"\n'
fi
printf ' ]\n'
printf '}\n'
}
# Function to get available scripts for a category
get_scripts() {
local cat_dir=""
case "$CATEGORY" in
"daemons") cat_dir="$QM_LOG_DAEMONS" ;;
"services") cat_dir="$QM_LOG_SERVICES" ;;
"settings") cat_dir="$QM_LOG_SETTINGS" ;;
"system") cat_dir="$QM_LOG_SYSTEM" ;;
*)
printf '{"error": "Invalid category"}\n'
return 1
;;
esac
if [ ! -d "$cat_dir" ]; then
printf '{"scripts": []}\n'
return 0
fi
printf '{\n'
printf ' "scripts": [\n'
first=true
for logfile in "$cat_dir"/*.log; do
if [ -f "$logfile" ]; then
if [ "$first" = "false" ]; then
printf ',\n'
fi
script_name=$(basename "$logfile" .log)
printf ' "%s"' "$script_name"
first=false
fi
done
printf '\n ]\n'
printf '}\n'
}
# Function to get log entries
get_logs() {
local logfile=""
if [ -n "$CATEGORY" ] && [ -n "$SCRIPT" ]; then
logfile=$(qm_get_logfile "$CATEGORY" "$SCRIPT")
else
printf '{"error": "Category and script parameters required"}\n'
return 1
fi
if [ ! -f "$logfile" ]; then
printf '{"entries": [], "total": 0}\n'
return 0
fi
# Get log entries with optional filtering
local temp_file="/tmp/quecmanager_log_view.$$"
# Start with all entries
cat "$logfile" > "$temp_file" 2>/dev/null
# Filter by level if specified
if [ -n "$LEVEL" ]; then
grep "\[$LEVEL\]" "$temp_file" > "${temp_file}.filtered" 2>/dev/null || touch "${temp_file}.filtered"
mv "${temp_file}.filtered" "$temp_file"
fi
# Filter by time if specified (simple grep for now)
if [ -n "$SINCE" ]; then
grep "$SINCE" "$temp_file" > "${temp_file}.filtered" 2>/dev/null || touch "${temp_file}.filtered"
mv "${temp_file}.filtered" "$temp_file"
fi
# Get total count
local total_count=$(wc -l < "$temp_file" 2>/dev/null || echo "0")
# Get last N lines
tail -n "$LINES" "$temp_file" > "${temp_file}.final" 2>/dev/null || touch "${temp_file}.final"
printf '{\n'
printf ' "entries": [\n'
first=true
while IFS= read -r line; do
if [ -n "$line" ]; then
if [ "$first" = "false" ]; then
printf ',\n'
fi
# Parse log line (format: [timestamp] [level] [script] [pid] message)
timestamp=$(echo "$line" | sed -n 's/^\[\([^]]*\)\].*/\1/p')
level=$(echo "$line" | sed -n 's/^[^]]*\] \[\([^]]*\)\].*/\1/p')
script=$(echo "$line" | sed -n 's/^[^]]*\] [^]]*\] \[\([^]]*\)\].*/\1/p')
pid=$(echo "$line" | sed -n 's/^[^]]*\] [^]]*\] [^]]*\] \[PID:\([^]]*\)\].*/\1/p')
message=$(echo "$line" | sed 's/^[^]]*\] [^]]*\] [^]]*\] [^]]*\] //')
# Escape quotes in message
message=$(echo "$message" | sed 's/"/\\"/g')
printf ' {\n'
printf ' "timestamp": "%s",\n' "$timestamp"
printf ' "level": "%s",\n' "$level"
printf ' "script": "%s",\n' "$script"
printf ' "pid": "%s",\n' "$pid"
printf ' "message": "%s"\n' "$message"
printf ' }'
first=false
fi
done < "${temp_file}.final"
printf '\n ],\n'
printf ' "total": %s,\n' "$total_count"
printf ' "showing": %s\n' "$LINES"
printf '}\n'
# Cleanup temp files
rm -f "$temp_file" "${temp_file}.filtered" "${temp_file}.final" 2>/dev/null || true
}
# Main logic
case "$REQUEST_METHOD" in
"GET")
if [ -z "$CATEGORY" ]; then
# Return available categories
get_categories
elif [ -z "$SCRIPT" ]; then
# Return available scripts for category
get_scripts
else
# Return log entries
get_logs
fi
;;
"OPTIONS")
# Handle CORS preflight
exit 0
;;
*)
printf '{"error": "Method not allowed"}\n'
;;
esac

View File

@@ -1,50 +0,0 @@
#!/bin/sh
# Ping Latency Script with Enable/Disable Configuration
# Author: dr-dolomite
# Date: 2025-08-04
# Set the content type to JSON
echo "Content-Type: application/json"
echo ""
# Configuration
CONFIG_DIR="/etc/quecmanager/settings"
CONFIG_FILE="$CONFIG_DIR/ping_settings.conf"
# Check if ping is enabled (default: enabled if no config exists)
is_ping_enabled() {
# If config file exists, read the setting
if [ -f "$CONFIG_FILE" ]; then
ping_enabled=$(grep "^PING_ENABLED=" "$CONFIG_FILE" | cut -d'=' -f2)
if [ "$ping_enabled" = "false" ] || [ "$ping_enabled" = "0" ] || [ "$ping_enabled" = "off" ]; then
return 1 # Disabled
fi
fi
return 0 # Enabled (default)
}
# Check if ping is enabled before proceeding
if ! is_ping_enabled; then
echo '{"connection": "DISABLED", "latency": 0}'
exit 0
fi
# Ping 8.8.8.8 with 5 packets and capture the full output
ping_result=$(ping -c 5 8.8.8.8)
# Check if ping was successful
if [ $? -eq 0 ]; then
# Extract the average latency using awk
avg_latency=$(echo "$ping_result" | awk '/avg/ {split($4, a, "/"); print int(a[2])}')
# If average latency was extracted, return it
if [ ! -z "$avg_latency" ]; then
echo "{\"connection\": \"ACTIVE\", \"latency\": $avg_latency}"
else
echo '{"connection": "ACTIVE", "latency": 0}'
fi
else
# Ping failed
echo '{"connection": "INACTIVE", "latency": 0}'
fi

View File

@@ -2,6 +2,9 @@
# AT Queue Manager for OpenWRT with Preemption Support and Token System
# Located in /www/cgi-bin/services/at_queue_manager
# Load centralized logging
. /www/cgi-bin/services/quecmanager_logger.sh
# Constants
QUEUE_DIR="/tmp/at_queue"
QUEUE_FILE="$QUEUE_DIR/queue"
@@ -15,6 +18,32 @@ RESULTS_MAX_AGE=3600 # 1 hour in seconds
POLL_INTERVAL=0.01
PREEMPTION_THRESHOLD=2 # 3 seconds threshold for preemption
TOKEN_TIMEOUT=30 # seconds before token expires
SCRIPT_NAME="at_queue_manager"
# Logging function - uses both centralized and system logging
log_at_queue() {
local level="$1"
local message="$2"
# Use centralized logging
case "$level" in
"error")
qm_log_error "service" "$SCRIPT_NAME" "$message"
;;
"warn")
qm_log_warn "service" "$SCRIPT_NAME" "$message"
;;
"debug")
qm_log_debug "service" "$SCRIPT_NAME" "$message"
;;
*)
qm_log_info "service" "$SCRIPT_NAME" "$message"
;;
esac
# Also maintain system logging for compatibility
logger -t at_queue -p "daemon.$level" "$message"
}
# Utility function for JSON escaping
escape_json() {
@@ -39,7 +68,7 @@ acquire_lock() {
while [ $attempt -lt $timeout ]; do
if mkdir "$LOCK_DIR" 2>/dev/null; then
logger -t at_queue -p daemon.debug "Lock acquired"
log_at_queue "debug" "Lock acquired"
return 0
fi
@@ -47,42 +76,36 @@ acquire_lock() {
attempt=$((attempt + 1))
done
logger -t at_queue -p daemon.error "Failed to acquire lock after $timeout attempts"
log_at_queue "error" "Failed to acquire lock after $timeout attempts"
return 1
}
release_lock() {
if [ -d "$LOCK_DIR" ]; then
rmdir "$LOCK_DIR" 2>/dev/null
logger -t at_queue -p daemon.debug "Lock released"
if rmdir "$LOCK_DIR" 2>/dev/null; then
log_at_queue "debug" "Lock released"
return 0
else
log_at_queue "error" "Lock directory doesn't exist"
return 1
fi
logger -t at_queue -p daemon.error "Lock directory doesn't exist"
return 1
}
# Ensure required directories exist
init_queue_system() {
initialize_queue() {
mkdir -p "$QUEUE_DIR" "$RESULTS_DIR"
touch "$QUEUE_FILE"
chmod 755 "$QUEUE_DIR"
chmod 644 "$QUEUE_FILE"
chmod 755 "$RESULTS_DIR"
logger -t at_queue -p daemon.info "Queue system initialized"
touch "$QUEUE_FILE" "$ACTIVE_FILE"
chmod 666 "$QUEUE_FILE" "$ACTIVE_FILE"
log_at_queue "info" "Queue system initialized"
}
# Cleanup old results and tracking files
cleanup_old_results() {
local current_time=$(date +%s)
# Clean up old execution tracking files
find "$QUEUE_DIR" -name "pid.*" -type f -mmin +60 -delete 2>/dev/null
find "$QUEUE_DIR" -name "*.exit" -type f -mmin +60 -delete 2>/dev/null
find "$QUEUE_DIR" -name "start_time.*" -type f -mmin +60 -delete 2>/dev/null
logger -t at_queue -p daemon.debug "Cleaned up old tracking files"
# Remove old tracking files
find "$QUEUE_DIR" -name "start_time.*" -o -name "pid.*" -type f -mmin +60 -delete 2>/dev/null
# Use find with -delete and basic timestamp check for OpenWRT
log_at_queue "debug" "Cleaned up old tracking files" # Use find with -delete and basic timestamp check for OpenWRT
find "$RESULTS_DIR" -name "*.json" -type f -mmin +60 -delete 2>/dev/null || {
# Fallback method if find fails
for file in "$RESULTS_DIR"/*.json; do
@@ -99,12 +122,12 @@ cleanup_old_results() {
local token_time=$(cat "$TOKEN_FILE" | jsonfilter -e '@.timestamp')
if [ $((current_time - token_time)) -gt $TOKEN_TIMEOUT ]; then
local token_holder=$(cat "$TOKEN_FILE" | jsonfilter -e '@.id')
logger -t at_queue -p daemon.warn "Removing expired token from $token_holder"
log_at_queue "warn" "Removing expired token from $token_holder"
rm -f "$TOKEN_FILE"
fi
fi
logger -t at_queue -p daemon.info "Cleanup: Removed files older than 1 hour"
log_at_queue "info" "Cleanup: Removed files older than 1 hour"
}
# Generate unique command ID
@@ -122,7 +145,7 @@ start_execution_tracking() {
echo "$pid" > "$QUEUE_DIR/pid.$cmd_id"
chmod 644 "$QUEUE_DIR/start_time.$cmd_id"
chmod 644 "$QUEUE_DIR/pid.$cmd_id"
logger -t at_queue -p daemon.debug "Started tracking command $cmd_id (PID: $pid)"
log_at_queue "debug" "Started tracking command $cmd_id (PID: $pid)"
}
# Check if running command should be preempted
@@ -131,7 +154,7 @@ should_preempt() {
local new_priority="$2"
if [ ! -f "$QUEUE_DIR/start_time.$current_cmd_id" ]; then
logger -t at_queue -p daemon.debug "No start time found for $current_cmd_id"
log_at_queue "debug" "No start time found for $current_cmd_id"
return 1
fi
@@ -144,16 +167,16 @@ should_preempt() {
if [ -f "$ACTIVE_FILE" ]; then
current_priority=$(cat "$ACTIVE_FILE" | jsonfilter -e '@.priority')
else
logger -t at_queue -p daemon.debug "No active command found"
log_at_queue "debug" "No active command found"
return 1
fi
if [ $execution_time -gt $PREEMPTION_THRESHOLD ] && [ $new_priority -lt $current_priority ]; then
logger -t at_queue -p daemon.info "Command $current_cmd_id (priority $current_priority) running for ${execution_time}s is eligible for preemption by priority $new_priority"
log_at_queue "info" "Command $current_cmd_id (priority $current_priority) running for ${execution_time}s is eligible for preemption by priority $new_priority"
return 0
fi
logger -t at_queue -p daemon.debug "Command $current_cmd_id not eligible for preemption (time: ${execution_time}s, current priority: $current_priority, new priority: $new_priority)"
log_at_queue "debug" "Command $current_cmd_id not eligible for preemption (time: ${execution_time}s, current priority: $current_priority, new priority: $new_priority)"
return 1
}
@@ -164,7 +187,7 @@ preempt_command() {
if [ -f "$pid_file" ]; then
local pid=$(cat "$pid_file")
logger -t at_queue -p daemon.info "Preempting command $cmd_id (PID: $pid)"
log_at_queue "info" "Preempting command $cmd_id (PID: $pid)"
# Send SIGTERM first
kill -TERM $pid 2>/dev/null
@@ -175,7 +198,7 @@ preempt_command() {
# Force kill if still running
if kill -0 $pid 2>/dev/null; then
kill -KILL $pid 2>/dev/null
logger -t at_queue -p daemon.warn "Forced termination of command $cmd_id"
log_at_queue "warn" "Forced termination of command $cmd_id"
fi
# Record preemption result
@@ -185,11 +208,11 @@ preempt_command() {
rm -f "$pid_file" "$QUEUE_DIR/start_time.$cmd_id" "$QUEUE_DIR/$cmd_id.exit"
[ -f "$ACTIVE_FILE" ] && rm -f "$ACTIVE_FILE"
logger -t at_queue -p daemon.info "Command $cmd_id preemption complete"
log_at_queue "info" "Command $cmd_id preemption complete"
return 0
fi
logger -t at_queue -p daemon.warn "No PID file found for command $cmd_id"
log_at_queue "warn" "No PID file found for command $cmd_id"
return 1
}
@@ -227,7 +250,7 @@ EOF
printf "%s" "$response" > "$RESULTS_DIR/$cmd_id.json"
chmod 644 "$RESULTS_DIR/$cmd_id.json"
logger -t at_queue -p daemon.info "Recorded preemption result for command $cmd_id (duration: ${duration}ms)"
log_at_queue "info" "Recorded preemption result for command $cmd_id (duration: ${duration}ms)"
}
# Request a token for direct sms_tool execution
@@ -238,7 +261,7 @@ request_token() {
# Acquire lock first
if ! acquire_lock; then
logger -t at_queue -p daemon.error "Failed to acquire lock for token request"
log_at_queue "error" "Failed to acquire lock for token request"
echo "{\"error\":\"Could not acquire lock\",\"status\":\"denied\"}"
return 1
fi
@@ -252,11 +275,11 @@ request_token() {
# Check for expired token (> TOKEN_TIMEOUT seconds old)
if [ $((current_time - timestamp)) -gt $TOKEN_TIMEOUT ]; then
logger -t at_queue -p daemon.warn "Found expired token from $current_holder, releasing"
log_at_queue "warn" "Found expired token from $current_holder, releasing"
rm -f "$TOKEN_FILE"
# Check for priority preemption
elif [ $priority -lt $current_priority ]; then
logger -t at_queue -p daemon.info "Preempting token from $current_holder (priority: $current_priority) for $requestor_id (priority: $priority)"
log_at_queue "info" "Preempting token from $current_holder (priority: $current_priority) for $requestor_id (priority: $priority)"
rm -f "$TOKEN_FILE"
else
# Token in use and cannot be preempted
@@ -278,7 +301,7 @@ request_token() {
return 1
fi
logger -t at_queue -p daemon.info "Direct execution with higher priority than active queue command"
log_at_queue "info" "Direct execution with higher priority than active queue command"
fi
# Grant token
@@ -296,7 +319,7 @@ release_token() {
local requestor_id="$1"
if ! acquire_lock; then
logger -t at_queue -p daemon.error "Failed to acquire lock for token release"
log_at_queue "error" "Failed to acquire lock for token release"
return 1
fi
@@ -305,15 +328,15 @@ release_token() {
if [ "$current_holder" = "$requestor_id" ]; then
rm -f "$TOKEN_FILE"
logger -t at_queue -p daemon.debug "Token released by $requestor_id"
log_at_queue "debug" "Token released by $requestor_id"
release_lock
echo "{\"status\":\"released\"}"
return 0
else
logger -t at_queue -p daemon.warn "Token release attempted by $requestor_id but held by $current_holder"
log_at_queue "warn" "Token release attempted by $requestor_id but held by $current_holder"
fi
else
logger -t at_queue -p daemon.warn "Token release attempted but no token exists"
log_at_queue "warn" "Token release attempted but no token exists"
fi
release_lock
@@ -331,11 +354,11 @@ enqueue_command() {
# Ensure queue directory exists
[ ! -d "$QUEUE_DIR" ] && init_queue_system
logger -t at_queue -p daemon.info "Enqueuing command: $cmd (priority: $priority, id: $cmd_id)"
log_at_queue "info" "Enqueuing command: $cmd (priority: $priority, id: $cmd_id)"
# Acquire lock for queue modification
if ! acquire_lock; then
logger -t at_queue -p daemon.error "Failed to acquire lock for enqueuing command"
log_at_queue "error" "Failed to acquire lock for enqueuing command"
echo "{\"error\":\"Queue lock acquisition failed\",\"command\":\"$cmd\"}"
return 1
fi
@@ -358,11 +381,11 @@ enqueue_command() {
cat "$QUEUE_FILE" >> "$temp_file"
mv "$temp_file" "$QUEUE_FILE"
chmod 644 "$QUEUE_FILE"
logger -t at_queue -p daemon.info "Added high priority command to front of queue"
log_at_queue "info" "Added high priority command to front of queue"
else
# Normal priority - append to queue
echo "$entry" >> "$QUEUE_FILE"
logger -t at_queue -p daemon.info "Added normal priority command to end of queue"
log_at_queue "info" "Added normal priority command to end of queue"
fi
# Release lock
@@ -379,7 +402,7 @@ dequeue_command() {
# Acquire lock
if ! acquire_lock; then
logger -t at_queue -p daemon.error "Failed to acquire lock for dequeuing command"
log_at_queue "error" "Failed to acquire lock for dequeuing command"
return 1
fi
@@ -395,7 +418,7 @@ dequeue_command() {
# Release lock
release_lock
logger -t at_queue -p daemon.debug "Dequeued command: $(echo "$cmd_entry" | jsonfilter -e '@.command')"
log_at_queue "debug" "Dequeued command: $(echo "$cmd_entry" | jsonfilter -e '@.command')"
echo "$cmd_entry"
}
@@ -433,7 +456,7 @@ execute_with_timeout() {
# Start execution tracking
start_execution_tracking "$cmd_id" "$pid"
logger -t at_queue -p daemon.debug "Started command execution: $command (PID: $pid)"
log_at_queue "debug" "Started command execution: $command (PID: $pid)"
# Wait for completion with shorter polling interval
local start_time=$(date +%s)
@@ -447,7 +470,7 @@ execute_with_timeout() {
# Cleanup
rm -f "$QUEUE_DIR/pid.$cmd_id" "$QUEUE_DIR/$cmd_id.exit" "$output_file" "$QUEUE_DIR/start_time.$cmd_id"
logger -t at_queue -p daemon.debug "Command completed with exit code $exit_code"
log_at_queue "debug" "Command completed with exit code $exit_code"
echo "$output"
return $exit_code
fi
@@ -471,7 +494,7 @@ execute_with_timeout() {
# Cleanup
rm -f "$QUEUE_DIR/pid.$cmd_id" "$QUEUE_DIR/$cmd_id.exit" "$output_file" "$QUEUE_DIR/start_time.$cmd_id"
logger -t at_queue -p daemon.warn "Command timed out after $timeout seconds"
log_at_queue "warn" "Command timed out after $timeout seconds"
echo "${partial_output:-Command timed out after $timeout seconds}"
fi
@@ -487,7 +510,7 @@ execute_command() {
local start_time=$(date +%s%3N)
logger -t at_queue -p daemon.info "Executing command $cmd_id: $cmd_text (priority: $priority)"
log_at_queue "info" "Executing command $cmd_id: $cmd_text (priority: $priority)"
# Execute command with timeout
local result=$(execute_with_timeout "$cmd_text" $MAX_TIMEOUT "$cmd_id")
@@ -501,16 +524,16 @@ execute_command() {
if [ $exit_code -eq 124 ]; then
status="timeout"
logger -t at_queue -p daemon.error "Command $cmd_id timed out after ${duration}ms"
log_at_queue "error" "Command $cmd_id timed out after ${duration}ms"
elif echo "$result" | grep -q "OK"; then
status="success"
log_level="info"
logger -t at_queue -p daemon.info "Command $cmd_id completed successfully in ${duration}ms"
log_at_queue "info" "Command $cmd_id completed successfully in ${duration}ms"
elif echo "$result" | grep -q "CME ERROR"; then
status="cme_error"
logger -t at_queue -p daemon.error "Command $cmd_id failed with CME ERROR in ${duration}ms"
log_at_queue "error" "Command $cmd_id failed with CME ERROR in ${duration}ms"
else
logger -t at_queue -p daemon.error "Command $cmd_id failed with general error in ${duration}ms"
log_at_queue "error" "Command $cmd_id failed with general error in ${duration}ms"
fi
# Clean and escape the output
@@ -536,7 +559,7 @@ EOF
# Acquire lock for writing result
if ! acquire_lock; then
logger -t at_queue -p daemon.error "Failed to acquire lock for writing result"
log_at_queue "error" "Failed to acquire lock for writing result"
else
# Save response
printf "%s" "$response" > "$RESULTS_DIR/$cmd_id.json"
@@ -561,7 +584,7 @@ process_queue() {
# Make sure the lock directory doesn't exist at startup
[ -d "$LOCK_DIR" ] && rmdir "$LOCK_DIR" 2>/dev/null
logger -t at_queue -p daemon.info "Started queue processing daemon"
log_at_queue "info" "Started queue processing daemon"
while true; do
# Quick cleanup check
@@ -579,12 +602,12 @@ process_queue() {
# Check for expired token
if [ $((current_time - token_time)) -gt $TOKEN_TIMEOUT ]; then
logger -t at_queue -p daemon.warn "Removing expired token from $token_holder"
log_at_queue "warn" "Removing expired token from $token_holder"
rm -f "$TOKEN_FILE"
else
# Log pause status only every 5 seconds to reduce log spam
if [ $((current_time - last_log)) -ge 5 ]; then
logger -t at_queue -p daemon.debug "Queue processing paused, token held by $token_holder"
log_at_queue "debug" "Queue processing paused, token held by $token_holder"
last_log=$current_time
fi
sleep $POLL_INTERVAL
@@ -612,49 +635,64 @@ if [ "${SCRIPT_NAME}" != "" ]; then
echo ""
fi
# Log the incoming request for debugging
log_at_queue "debug" "CGI: Incoming request - QUERY_STRING='$QUERY_STRING', REQUEST_METHOD='$REQUEST_METHOD', HTTP_USER_AGENT='$HTTP_USER_AGENT'"
# Parse query string for CGI mode
eval $(echo "$QUERY_STRING" | sed 's/&/;/g')
# Handle empty action parameter specifically
if [ -z "$action" ]; then
if [ -z "$QUERY_STRING" ]; then
log_at_queue "warn" "CGI: No query string provided - possible health check or browser prefetch"
echo "{\"error\":\"No action specified\",\"help\":\"Valid actions: enqueue, status, request_token, release_token\"}"
else
log_at_queue "warn" "CGI: Query string present but no action parameter: '$QUERY_STRING'"
echo "{\"error\":\"Missing action parameter\",\"query_string\":\"$QUERY_STRING\"}"
fi
exit 0
fi
case "$action" in
"enqueue")
if [ -n "$command" ]; then
logger -t at_queue -p daemon.info "CGI: Received enqueue request for command: $command"
log_at_queue "info" "CGI: Received enqueue request for command: $command"
enqueue_command "$command" "$priority"
else
logger -t at_queue -p daemon.error "CGI: Empty command received"
log_at_queue "error" "CGI: Empty command received"
echo "{\"error\":\"No command specified\"}"
fi
;;
"status")
if [ -f "$ACTIVE_FILE" ]; then
logger -t at_queue -p daemon.debug "CGI: Status request - queue active"
log_at_queue "debug" "CGI: Status request - queue active"
cat "$ACTIVE_FILE"
else
logger -t at_queue -p daemon.debug "CGI: Status request - queue idle"
log_at_queue "debug" "CGI: Status request - queue idle"
echo "{\"status\":\"idle\"}"
fi
;;
"request_token")
if [ -n "$id" ]; then
logger -t at_queue -p daemon.info "Token request from $id (priority: ${priority:-10})"
log_at_queue "info" "Token request from $id (priority: ${priority:-10})"
request_token "$id" "${priority:-10}" "${timeout:-10}"
else
logger -t at_queue -p daemon.error "Token request missing ID"
log_at_queue "error" "Token request missing ID"
echo "{\"error\":\"No requestor ID specified\",\"status\":\"denied\"}"
fi
;;
"release_token")
if [ -n "$id" ]; then
logger -t at_queue -p daemon.info "Token release from $id"
log_at_queue "info" "Token release from $id"
release_token "$id"
else
logger -t at_queue -p daemon.error "Token release missing ID"
log_at_queue "error" "Token release missing ID"
echo "{\"error\":\"No requestor ID specified\",\"status\":\"denied\"}"
fi
;;
*)
logger -t at_queue -p daemon.error "CGI: Invalid action received: $action"
echo "{\"error\":\"Invalid action\"}"
log_at_queue "error" "CGI: Invalid action received: '$action' (QUERY_STRING: '$QUERY_STRING')"
echo "{\"error\":\"Invalid action: $action\",\"valid_actions\":[\"enqueue\",\"status\",\"request_token\",\"release_token\"]}"
;;
esac
exit 0
@@ -669,4 +707,4 @@ fi
# If not run as CGI, start queue processing
if [ "${SCRIPT_NAME}" = "" ] && [ -z "$1" ]; then
process_queue
fi
fi

View File

@@ -0,0 +1,110 @@
#!/bin/sh
# QuecManager Log Cleanup Script
# Periodically clean up old log files to prevent /tmp from filling up
. /www/cgi-bin/services/quecmanager_logger.sh
# Configuration
MAX_LOG_AGE_DAYS=7 # Delete logs older than 7 days
MAX_BACKUP_FILES=2 # Keep maximum 2 backup files (.1, .2)
CLEANUP_LOG_SIZE=1000 # Run cleanup if any log exceeds 1MB
# Function to log cleanup activities
log_cleanup() {
qm_log_info "system" "log_cleanup" "$1"
}
# Initialize
qm_init_logs
log_cleanup "Starting log cleanup process"
# Cleanup function
perform_cleanup() {
local files_cleaned=0
local space_freed=0
# Clean up old backup files
if [ -d "$QM_LOG_BASE" ]; then
# Remove backup files older than specified days
old_backups=$(find "$QM_LOG_BASE" -name "*.1" -o -name "*.2" -type f -mtime +$MAX_LOG_AGE_DAYS 2>/dev/null)
for backup_file in $old_backups; do
if [ -f "$backup_file" ]; then
file_size=$(du -k "$backup_file" 2>/dev/null | cut -f1)
rm -f "$backup_file" 2>/dev/null
if [ $? -eq 0 ]; then
files_cleaned=$((files_cleaned + 1))
space_freed=$((space_freed + ${file_size:-0}))
log_cleanup "Removed old backup file: $(basename "$backup_file")"
fi
fi
done
# Force rotation for large log files
for category_dir in "$QM_LOG_DAEMONS" "$QM_LOG_SERVICES" "$QM_LOG_SETTINGS" "$QM_LOG_SYSTEM"; do
if [ -d "$category_dir" ]; then
for logfile in "$category_dir"/*.log; do
if [ -f "$logfile" ]; then
# Check file size in KB
file_size_kb=$(du -k "$logfile" 2>/dev/null | cut -f1)
if [ "${file_size_kb:-0}" -gt $CLEANUP_LOG_SIZE ]; then
log_cleanup "Rotating large log file: $(basename "$logfile") (${file_size_kb}KB)"
qm_rotate_log "$logfile"
files_cleaned=$((files_cleaned + 1))
fi
fi
done
fi
done
# Additional cleanup: remove empty log files
empty_logs=$(find "$QM_LOG_BASE" -name "*.log" -type f -size 0 2>/dev/null)
for empty_log in $empty_logs; do
rm -f "$empty_log" 2>/dev/null
if [ $? -eq 0 ]; then
files_cleaned=$((files_cleaned + 1))
log_cleanup "Removed empty log file: $(basename "$empty_log")"
fi
done
fi
# Log cleanup summary
if [ $files_cleaned -gt 0 ]; then
log_cleanup "Cleanup completed: $files_cleaned files processed, ${space_freed}KB freed"
else
log_cleanup "Cleanup completed: no files needed cleaning"
fi
}
# Check if we should run cleanup based on disk usage
check_disk_usage() {
# Check /tmp usage (OpenWrt compatible)
local tmp_usage=""
# Try df first (most common)
if command -v df >/dev/null 2>&1; then
tmp_usage=$(df /tmp 2>/dev/null | awk 'NR==2 {print $5}' | tr -d '%')
fi
# If we got a valid percentage and it's high, force cleanup
if [ -n "$tmp_usage" ] && [ "$tmp_usage" -gt 80 ]; then
log_cleanup "High /tmp usage detected (${tmp_usage}%), forcing cleanup"
return 0
fi
# Always run periodic cleanup
return 0
}
# Main execution
if check_disk_usage; then
perform_cleanup
else
log_cleanup "Disk usage check passed, skipping cleanup"
fi
# Clean up centralized log helper's old logs too
qm_cleanup_logs
log_cleanup "Log cleanup process completed"

View File

@@ -8,14 +8,17 @@ set -eu
# Ensure PATH for OpenWrt/BusyBox
export PATH="/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
# Load centralized logging
. /www/cgi-bin/services/quecmanager_logger.sh
# Configuration
TMP_DIR="/tmp/quecmanager"
OUT_JSON="$TMP_DIR/memory.json"
PID_FILE="$TMP_DIR/memory_daemon.pid"
LOG_FILE="$TMP_DIR/memory_daemon.log"
CONFIG_FILE="/etc/quecmanager/settings/memory_settings.conf"
[ -f "$CONFIG_FILE" ] || CONFIG_FILE="/tmp/quecmanager/settings/memory_settings.conf"
DEFAULT_INTERVAL=1
SCRIPT_NAME="memory_daemon"
# Ensure temp directory exists
ensure_tmp_dir() {
@@ -24,7 +27,7 @@ ensure_tmp_dir() {
# Logging function
log() {
printf '%s - %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >> "$LOG_FILE" 2>/dev/null || true
qm_log_info "daemon" "$SCRIPT_NAME" "$1"
}
# Check if this daemon instance is already running

View File

@@ -5,19 +5,22 @@ set -eu
# Ensure PATH for OpenWrt/BusyBox
export PATH="/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
# Load centralized logging
. /www/cgi-bin/services/quecmanager_logger.sh
TMP_DIR="/tmp/quecmanager"
OUT_JSON="$TMP_DIR/ping_latency.json"
PID_FILE="$TMP_DIR/ping_daemon.pid"
LOG_FILE="$TMP_DIR/ping_daemon.log"
CONFIG_FILE="/etc/quecmanager/settings/ping_settings.conf"
[ -f "$CONFIG_FILE" ] || CONFIG_FILE="/tmp/quecmanager/settings/ping_settings.conf"
DEFAULT_HOST="8.8.8.8"
DEFAULT_INTERVAL=5
SCRIPT_NAME="ping_daemon"
ensure_tmp_dir() { [ -d "$TMP_DIR" ] || mkdir -p "$TMP_DIR" || exit 1; }
log() {
printf '%s - %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >> "$LOG_FILE" 2>/dev/null || true
qm_log_info "daemon" "$SCRIPT_NAME" "$1"
}
daemon_is_running() {

View File

@@ -0,0 +1,119 @@
#!/bin/sh
# QuecManager Centralized Logging Helper
# OpenWrt/BusyBox compatible logging system
# Usage: source this file and use qm_log function
set -e
# Base log directory
QM_LOG_BASE="/tmp/quecmanager/logs"
# Log categories
QM_LOG_DAEMONS="$QM_LOG_BASE/daemons"
QM_LOG_SERVICES="$QM_LOG_BASE/services"
QM_LOG_SETTINGS="$QM_LOG_BASE/settings"
QM_LOG_SYSTEM="$QM_LOG_BASE/system"
# Log levels
QM_LOG_ERROR="ERROR"
QM_LOG_WARN="WARN"
QM_LOG_INFO="INFO"
QM_LOG_DEBUG="DEBUG"
# Maximum log file size (in KB) - keep small for OpenWrt
QM_LOG_MAX_SIZE=500
# Initialize log directories
qm_init_logs() {
mkdir -p "$QM_LOG_DAEMONS" "$QM_LOG_SERVICES" "$QM_LOG_SETTINGS" "$QM_LOG_SYSTEM" 2>/dev/null || true
}
# Get log file path based on category and script name
qm_get_logfile() {
local category="$1"
local script_name="$2"
case "$category" in
"daemon"|"daemons")
echo "$QM_LOG_DAEMONS/${script_name}.log"
;;
"service"|"services")
echo "$QM_LOG_SERVICES/${script_name}.log"
;;
"setting"|"settings")
echo "$QM_LOG_SETTINGS/${script_name}.log"
;;
"system")
echo "$QM_LOG_SYSTEM/${script_name}.log"
;;
*)
echo "$QM_LOG_SYSTEM/unknown.log"
;;
esac
}
# Simple log rotation - keep it OpenWrt compatible
qm_rotate_log() {
local logfile="$1"
if [ -f "$logfile" ]; then
# Get file size in KB (use du for BusyBox compatibility)
local size_kb=$(du -k "$logfile" 2>/dev/null | cut -f1)
if [ "${size_kb:-0}" -gt "$QM_LOG_MAX_SIZE" ]; then
# Simple rotation: keep last 2 versions
[ -f "${logfile}.1" ] && mv "${logfile}.1" "${logfile}.2" 2>/dev/null || true
mv "$logfile" "${logfile}.1" 2>/dev/null || true
touch "$logfile" 2>/dev/null || true
fi
fi
}
# Main logging function
# Usage: qm_log "category" "script_name" "level" "message"
qm_log() {
local category="$1"
local script_name="$2"
local level="$3"
local message="$4"
# Initialize if needed
qm_init_logs
# Get log file path
local logfile=$(qm_get_logfile "$category" "$script_name")
# Rotate if needed
qm_rotate_log "$logfile"
# Create log entry with OpenWrt compatible date
local timestamp=$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null || date)
local pid="$$"
# Write log entry
printf '[%s] [%s] [%s] [PID:%s] %s\n' "$timestamp" "$level" "$script_name" "$pid" "$message" >> "$logfile" 2>/dev/null || true
}
# Convenience functions for different log levels
qm_log_error() {
qm_log "$1" "$2" "$QM_LOG_ERROR" "$3"
}
qm_log_warn() {
qm_log "$1" "$2" "$QM_LOG_WARN" "$3"
}
qm_log_info() {
qm_log "$1" "$2" "$QM_LOG_INFO" "$3"
}
qm_log_debug() {
qm_log "$1" "$2" "$QM_LOG_DEBUG" "$3"
}
# Cleanup old logs (called periodically)
qm_cleanup_logs() {
# Remove .2 backup files older than 1 day to save space
find "$QM_LOG_BASE" -name "*.2" -type f -mtime +1 -delete 2>/dev/null || true
}

View File

@@ -2,6 +2,9 @@
# Updated QuecProfiles daemon with enhanced SA/NSA NR5G band management and TTL support
# Including profile application functions and fixed comparison logic
# Load centralized logging
. /www/cgi-bin/services/quecmanager_logger.sh
# Configuration
QUEUE_DIR="/tmp/at_queue"
TOKEN_FILE="$QUEUE_DIR/token"
@@ -9,33 +12,39 @@ TRACK_FILE="/tmp/quecprofiles_active"
CHECK_TRIGGER="/tmp/quecprofiles_check"
STATUS_FILE="/tmp/quecprofiles_status.json"
APPLIED_FLAG="/tmp/quecprofiles_applied"
DEBUG_LOG="/tmp/quecprofiles_debug.log"
DETAILED_LOG="/tmp/quecprofiles_detailed.log"
DEFAULT_CHECK_INTERVAL=60 # Default check interval in seconds
COMMAND_TIMEOUT=10 # Default timeout for AT commands in seconds
QUEUE_PRIORITY=3 # Medium-high priority (1 is highest for cell scan)
MAX_TOKEN_WAIT=15 # Maximum seconds to wait for token acquisition
SCRIPT_NAME="quecprofile"
# Initialize log file
echo "$(date) - Starting QuecProfiles daemon with SA/NSA NR5G and TTL support (PID: $$)" >"$DEBUG_LOG"
echo "$(date) - Starting QuecProfiles daemon with SA/NSA NR5G and TTL support (PID: $$)" >"$DETAILED_LOG"
chmod 644 "$DEBUG_LOG" "$DETAILED_LOG"
# Initialize logging
qm_log_info "service" "$SCRIPT_NAME" "Starting QuecProfiles daemon with SA/NSA NR5G and TTL support (PID: $$)"
# Function to log messages
log_message() {
local message="$1"
local level="${2:-info}"
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
# Log to system log
logger -t quecprofiles_daemon -p "daemon.$level" "$message"
# Use centralized logging
case "$level" in
"error")
qm_log_error "service" "$SCRIPT_NAME" "$message"
;;
"warn")
qm_log_warn "service" "$SCRIPT_NAME" "$message"
;;
"debug")
qm_log_debug "service" "$SCRIPT_NAME" "$message"
;;
*)
qm_log_info "service" "$SCRIPT_NAME" "$message"
;;
esac
# Log to debug file
echo "[$timestamp] [$level] $message" >>"$DEBUG_LOG"
# For detailed logs or errors
if [ "$level" = "error" ] || [ "$level" = "debug" ]; then
echo "[$timestamp] [$level] $message" >>"$DETAILED_LOG"
# Also log to system log for important messages
if [ "$level" = "error" ] || [ "$level" = "warn" ] || [ "$level" = "info" ]; then
logger -t quecprofiles_daemon -p "daemon.$level" "$message"
fi
}

View File

@@ -6,20 +6,22 @@
# Load UCI configuration functions
. /lib/functions.sh
# Load centralized logging
. /www/cgi-bin/services/quecmanager_logger.sh
# Configuration
QUEUE_DIR="/tmp/at_queue"
TOKEN_FILE="$QUEUE_DIR/token"
LOG_DIR="/tmp/log/quecwatch"
LOG_FILE="$LOG_DIR/quecwatch.log"
PID_FILE="/var/run/quecwatch.pid"
STATUS_FILE="/tmp/quecwatch_status.json"
RETRY_COUNT_FILE="/tmp/quecwatch_retry_count"
UCI_CONFIG="quecmanager"
MAX_TOKEN_WAIT=10 # Maximum seconds to wait for token acquisition
TOKEN_PRIORITY=15 # Medium priority (between profiles and metrics)
SCRIPT_NAME="quecwatch"
# Ensure directories exist
mkdir -p "$LOG_DIR" "$QUEUE_DIR"
mkdir -p "$QUEUE_DIR"
# Store PID
echo "$$" > "$PID_FILE"
@@ -29,13 +31,27 @@ chmod 644 "$PID_FILE"
log_message() {
local level="${2:-info}"
local message="$1"
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
# Log to file
echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
# Use centralized logging
case "$level" in
"error")
qm_log_error "service" "$SCRIPT_NAME" "$message"
;;
"warn")
qm_log_warn "service" "$SCRIPT_NAME" "$message"
;;
"debug")
qm_log_debug "service" "$SCRIPT_NAME" "$message"
;;
*)
qm_log_info "service" "$SCRIPT_NAME" "$message"
;;
esac
# Log to system log
logger -t quecwatch -p "daemon.$level" "$message"
# Also log to system log for important messages
if [ "$level" = "error" ] || [ "$level" = "warn" ] || [ "$level" = "info" ]; then
logger -t quecwatch -p "daemon.$level" "$message"
fi
}
# Function to update status