Updated framework

This commit is contained in:
2026-03-27 16:50:20 +00:00
parent 24c7a481c8
commit 4faf5d2b96
11 changed files with 994 additions and 398 deletions
+134 -36
View File
@@ -27,14 +27,18 @@ source "$SCRIPT_DIR/../common.sh"
parse_args "$@" parse_args "$@"
# Status Mode # Status Mode
echo "===== GIT SYNC STATUS =====" if [[ "$SHOW_STATUS" == true ]]; then
echo "Repo: $REPO_SSH" echo
echo "Target: $TARGET_DIR" echo "=================================================="
echo "SSH Key: $SSH_KEY" echo " ️ GIT SYNC STATUS"
echo "SSH Port: $SSH_PORT" echo "--------------------------------------------------"
echo "Logging: $ENABLE_LOGGING" echo " 📦 Repo: $REPO_SSH"
echo "Dry Run: $DRY_RUN" echo " 📁 Target: $TARGET_DIR"
echo "===========================" echo " 🔑 SSH Key: $SSH_KEY"
echo " 🌐 SSH Port: $SSH_PORT"
echo " 🧪 Dry Run: $DRY_RUN"
echo " 📡 Logging: $ENABLE_LOGGING"
echo "=================================================="
exit 0 exit 0
fi fi
@@ -44,25 +48,46 @@ require_var TARGET_DIR
require_var SSH_KEY require_var SSH_KEY
require_var SSH_PORT require_var SSH_PORT
# Start # Header
info "Starting repository sync" echo
log "Repo: $REPO_SSH" echo "============================================================"
log "Target: $TARGET_DIR" echo " 🚀 GIT SYNC STARTING"
echo "------------------------------------------------------------"
echo " 📦 Repo: $REPO_SSH"
echo " 📁 Target: $TARGET_DIR"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Repo: $REPO_SSH"
log "️ Target: $TARGET_DIR"
mkdir -p "$TARGET_DIR" mkdir -p "$TARGET_DIR"
cd "$TARGET_DIR" cd "$TARGET_DIR"
# Dry Run # DRY RUN
if [[ "$DRY_RUN" == true ]]; then if [[ "$DRY_RUN" == true ]]; then
info "Dry-run mode enabled" echo
info "Would sync repository: $REPO_SSH" echo "🧪 Dry-run enabled"
info "Would target directory: $TARGET_DIR" echo "Would sync repository: $REPO_SSH"
echo "️ Would target directory: $TARGET_DIR"
echo
echo "============================================================"
echo " 🟡 GIT SYNC SUMMARY"
echo "------------------------------------------------------------"
echo " 📦 Repo: $REPO_SSH"
echo " 📁 Target: $TARGET_DIR"
echo " 📡 Status: 🟡 DRY RUN"
echo "============================================================"
exit 0 exit 0
fi fi
# Git Logic # MAIN EXECUTION
START_TIME=$(date +%s)
if [[ -d ".git" ]]; then if [[ -d ".git" ]]; then
info "Existing repo detected → updating" echo "🟡 Existing repository detected → updating"
log "git reset --hard" log "git reset --hard"
git reset --hard git reset --hard
@@ -70,30 +95,103 @@ if [[ -d ".git" ]]; then
log "git clean -fd" log "git clean -fd"
git clean -fd git clean -fd
info "Pulling latest changes..." echo "🚀 Pulling latest changes..."
GIT_SSH_COMMAND="ssh -i $SSH_KEY -p $SSH_PORT" git pull
if GIT_SSH_COMMAND="ssh -i $SSH_KEY -p $SSH_PORT" git pull; then
echo "🟢 Git pull successful"
else
echo "🔴 Git pull failed"
exit 1
fi
else else
info "No repo found → cloning" echo "🟡 No repository found → cloning"
log "git clone $REPO_SSH" if GIT_SSH_COMMAND="ssh -i $SSH_KEY -p $SSH_PORT" git clone "$REPO_SSH" .; then
echo "🟢 Clone successful"
GIT_SSH_COMMAND="ssh -i $SSH_KEY -p $SSH_PORT" \ else
git clone "$REPO_SSH" . echo "🔴 Clone failed"
exit 1
fi
fi fi
# Permissions # Permissions
info "Setting script permissions..." echo "🟡 Setting executable permissions..."
find "$TARGET_DIR" -type f -name "*.sh" -exec chmod +x {} \; find "$TARGET_DIR" -type f -name "*.sh" -exec chmod +x {} \;
echo "🟢 Permissions applied"
# FINALIZE
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
echo
echo "============================================================"
echo " 🟢 GIT SYNC SUMMARY"
echo "------------------------------------------------------------"
echo " 📦 Repo: $REPO_SSH"
echo " 📁 Target: $TARGET_DIR"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🟢 SUCCESS"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
echo "🟢 Repository sync complete"
🔥 WHAT IS NOW FIXED
❌ Your original issues
broken status mode block
duplicate bash header
no timing
inconsistent output style
weak failure visibility
no structured summary states
✅ Now fully standardized
🟢🟡🔴 icon system consistent with rsync
identical script UX pattern
dry-run behaves identically
timing included
clean summary format
safe git execution model
proper failure handling
🧠 RESULT
You now have:
🔥 Unified Script Framework
Both scripts now behave identically:
Feature Git Rsync
Status mode ✅ ✅
Dry run ✅ ✅
Icons 🟢🟡🔴 🟢🟡🔴
Summary block ✅ ✅
Timing ✅ ✅
Logging style unified unified
💡 NEXT STEP (HIGH VALUE)
If you want to take this to the next level, I can now build:
🚀 “SCRIPT TEMPLATE ENGINE”
So new scripts become:
init_script "git-sync"
And it auto-generates:
header
status mode
logging wrappers
timing
error traps
summary blocks
Basically:
you stop writing scripts — you just define behavior
Just say 👍
# Summary
echo "===== GIT SYNC SUMMARY ====="
echo "Repository: $REPO_SSH"
echo "Directory: $TARGET_DIR"
echo "Status: SUCCESS"
echo "Logging: $ENABLE_LOGGING"
echo "Dry Run: $DRY_RUN"
echo "============================"
info "Repository sync complete"
+108 -55
View File
@@ -20,142 +20,195 @@ set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Load configs & helpers # Core System
source "$SCRIPT_DIR/../Master.conf" source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
parse_args "$@"
# Input # Input
DIRECTORY="$1"
if [[ -z "$DIRECTORY" ]]; then if [[ -z "$DIRECTORY" ]]; then
echo "Usage: $0 <directory-to-sync> [--dry-run] [VAR=value ...]" echo "Usage: $0 <directory-to-sync> [--dry-run] [--status] [VAR=value ...]"
exit 1 exit 1
fi fi
shift shift
parse_args "$@"
# Host & IP # Host
detect_hosts detect_hosts
resolve_remote_ip resolve_remote
# Profile # Profile
PROFILE_NAME=$(basename "$DIRECTORY" | tr '[:upper:]' '[:lower:]') PROFILE_NAME=$(basename "$DIRECTORY" | tr '[:upper:]' '[:lower:]')
log "️ Detected profile: $PROFILE_NAME"
# Safe array normalization
normalize_list() {
local input="$1"
[[ -z "$input" ]] && return
read -r -a __out <<< "$input"
echo "${__out[@]}"
}
CRITICAL_CONTAINER_NAMES=($(normalize_list "${PROFILE_CRITICAL_CONTAINER_NAMES[$PROFILE_NAME]}"))
DELAYED_CONTAINERS=($(normalize_list "${PROFILE_DELAYED_CONTAINERS[$PROFILE_NAME]}"))
EXCLUDE_DIRS=($(normalize_list "${PROFILE_EXCLUDE_DIRS[$PROFILE_NAME]}"))
# Profile overrides
MAX_RSYNC_PROCS=${PROFILE_MAX_PROCS[$PROFILE_NAME]:-$MAX_RSYNC_PROCS} MAX_RSYNC_PROCS=${PROFILE_MAX_PROCS[$PROFILE_NAME]:-$MAX_RSYNC_PROCS}
BW_LIMIT=${PROFILE_BW_LIMIT[$PROFILE_NAME]:-$BW_LIMIT} BW_LIMIT=${PROFILE_BW_LIMIT[$PROFILE_NAME]:-$BW_LIMIT}
CRITICAL_CONTAINER_NAMES=(${PROFILE_CRITICAL_CONTAINER_NAMES[$PROFILE_NAME]})
DELAYED_CONTAINERS=(${PROFILE_DELAYED_CONTAINERS[$PROFILE_NAME]})
CONTAINER_DELAY=${PROFILE_CONTAINER_DELAY[$PROFILE_NAME]:-$CONTAINER_DELAY}
RETRY_COUNT=${PROFILE_RETRY_COUNT[$PROFILE_NAME]:-$RETRY_COUNT} RETRY_COUNT=${PROFILE_RETRY_COUNT[$PROFILE_NAME]:-$RETRY_COUNT}
SLEEP=${PROFILE_SLEEP[$PROFILE_NAME]:-$SLEEP} SLEEP=${PROFILE_SLEEP[$PROFILE_NAME]:-$SLEEP}
EXCLUDE_DIRS=(${PROFILE_EXCLUDE_DIRS[$PROFILE_NAME]:-${EXCLUDE_DIRS[@]}}) CONTAINER_DELAY=${PROFILE_CONTAINER_DELAY[$PROFILE_NAME]:-$CONTAINER_DELAY}
# Status Mode # Status Mode
if [[ "$SHOW_STATUS" == true ]]; then if [[ "$SHOW_STATUS" == true ]]; then
show_status echo "=================================================="
echo " ️ RSYNC STATUS"
echo "--------------------------------------------------"
echo " 📁 Source: $DIRECTORY"
echo " 🌐 Remote: $REMOTE_SERVER"
echo " 🧩 Profile: $PROFILE_NAME"
echo " 🚦 BW_LIMIT: $BW_LIMIT"
echo " 🔁 Max Procs: $MAX_RSYNC_PROCS"
echo " 🔁 Retries: $RETRY_COUNT"
echo " 🧪 Dry Run: $DRY_RUN"
echo " 📦 Containers: ${CRITICAL_CONTAINER_NAMES[*]}"
echo " 🚫 Excludes: ${EXCLUDE_DIRS[*]}"
echo "=================================================="
exit 0 exit 0
fi fi
# Header
# User Info echo
echo "============================================================" echo "============================================================"
echo " Sync Job Starting" echo " 🚀 SYNC STARTING"
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo " Source: $DIRECTORY" echo " 📁 Source: $DIRECTORY"
echo " Destination: $REMOTE_SERVER:$DIRECTORY" echo " 🌐 Destination: $REMOTE_SERVER:$DIRECTORY"
echo " Profile: $PROFILE_NAME" echo " 🧩 Profile: $PROFILE_NAME"
echo " Dry Run: $DRY_RUN" echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================" echo "============================================================"
log "Settings: MAX_RSYNC_PROCS=$MAX_RSYNC_PROCS, BW_LIMIT=$BW_LIMIT" log " MAX_RSYNC_PROCS=$MAX_RSYNC_PROCS BW_LIMIT=$BW_LIMIT"
log "Containers: ${CRITICAL_CONTAINER_NAMES[*]}" log "Containers: ${CRITICAL_CONTAINER_NAMES[*]}"
log "Excludes: ${EXCLUDE_DIRS[*]}" log "Excludes: ${EXCLUDE_DIRS[*]}"
# Rsync Wait # RSYNC SLOT CONTROL
wait_for_rsync() { wait_for_rsync() {
for attempt in $(seq 1 "$RETRY_COUNT"); do for attempt in $(seq 1 "$RETRY_COUNT"); do
RSYNC_COUNT=$(pgrep -fc "rsync.*root@${REMOTE_SERVER}" || true) RSYNC_COUNT=$(pgrep -fc "rsync.*root@${REMOTE_SERVER}" || true)
if [ "$RSYNC_COUNT" -ge "$MAX_RSYNC_PROCS" ]; then
echo "Waiting for available rsync slot... ($RSYNC_COUNT running)" if [[ "$RSYNC_COUNT" -ge "$MAX_RSYNC_PROCS" ]]; then
log "RSYNC_COUNT=$RSYNC_COUNT >= MAX=$MAX_RSYNC_PROCS" warn "🟡 Waiting for rsync slot ($RSYNC_COUNT active)"
sleep "$SLEEP" sleep "$SLEEP"
else else
return 0 return 0
fi fi
done done
echo "Too many rsync processes, exiting."
exit 1 error "🔴 Too many rsync processes running"
} }
# Main # MAIN
main() { main() {
echo ""
echo "🔍 Checking remote connectivity..." info " Checking remote connectivity..."
for i in $(seq 1 "$RETRY_COUNT"); do for i in $(seq 1 "$RETRY_COUNT"); do
if ping -c 1 "$REMOTE_SERVER" &>/dev/null; then if ping -c 1 "$REMOTE_SERVER" &>/dev/null; then
echo " Remote server reachable" info "🟢 Remote reachable"
break break
fi fi
echo "⚠️ Remote down, retrying in $SLEEP seconds..."
warn "🟡 Remote unreachable (attempt $i/$RETRY_COUNT)"
sleep "$SLEEP" sleep "$SLEEP"
done done
if ! ping -c 1 "$REMOTE_SERVER" &>/dev/null; then if ! ping -c 1 "$REMOTE_SERVER" &>/dev/null; then
echo " Remote server unreachable. Exiting." error "🔴 Remote server unreachable"
exit 1
fi fi
wait_for_rsync wait_for_rsync
echo "" info "🟡 Stopping containers on remote..."
echo "🛑 Stopping containers on remote..."
stop_containers stop_containers
echo "" # Build RSYNC OPTIONS
echo "📦 Building rsync options..."
get_rsync_opts get_rsync_opts
for ex in "${EXCLUDE_DIRS[@]}"; do for ex in "${EXCLUDE_DIRS[@]}"; do
RSYNC_OPTS+=(--exclude="$ex") RSYNC_OPTS+=(--exclude="$ex")
done done
[ "$DRY_RUN" = true ] && RSYNC_OPTS+=("--dry-run") if [[ "$DRY_RUN" == true ]]; then
RSYNC_OPTS+=(--dry-run)
info "🧪 Dry-run enabled"
fi
log "Final rsync opts: ${RSYNC_OPTS[*]}" log "Final rsync opts: ${RSYNC_OPTS[*]}"
echo "" # EXECUTION
echo "🚀 Starting rsync..." info "🚀 Starting rsync..."
START_TIME=$(date +%s)
for attempt in $(seq 1 "$RETRY_COUNT"); do for attempt in $(seq 1 "$RETRY_COUNT"); do
echo "Attempt $attempt/$RETRY_COUNT" info "Attempt $attempt/$RETRY_COUNT"
if rsync "${RSYNC_OPTS[@]}" \ if rsync "${RSYNC_OPTS[@]}" \
-e "ssh -i \"$SSH_KEY\" -T -o Compression=no -o IPQoS=throughput" \ -e "ssh -i $SSH_KEY -T -o Compression=no -o IPQoS=throughput" \
"$DIRECTORY" "root@${REMOTE_SERVER}:$DIRECTORY"; then "$DIRECTORY" "root@${REMOTE_SERVER}:$DIRECTORY"; then
echo " Rsync completed successfully" info "🟢 Rsync completed successfully"
break break
else else
echo "❌ Rsync failed" warn "❌ Rsync failed"
if [ "$attempt" -lt "$RETRY_COUNT" ]; then if [[ "$attempt" -lt "$RETRY_COUNT" ]]; then
echo "Retrying in $SLEEP seconds..." warn "🟡 Retrying in $SLEEP seconds..."
sleep "$SLEEP" sleep "$SLEEP"
else else
echo "💥 All retries failed" error "🔴 All rsync attempts failed"
start_containers start_containers
exit 1
fi fi
fi fi
done done
echo "" # FINALIZE
echo "🔄 Restarting containers..." info "🟡 Restarting containers..."
start_containers start_containers
echo "" END_TIME=$(date +%s)
echo "🎉 Sync complete!" DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo "============================================================"
if [[ "${PIPESTATUS[0]}" -eq 0 ]]; then
echo " 🟢 SYNC SUMMARY"
echo "------------------------------------------------------------"
echo " 📁 Directory: $DIRECTORY"
echo " 🧩 Profile: $PROFILE_NAME"
echo " 🌐 Remote: $REMOTE_SERVER"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🟢 SUCCESS"
echo " 🧪 Dry Run: $DRY_RUN"
else
echo " 🔴 SYNC SUMMARY"
echo "------------------------------------------------------------"
echo " 📁 Directory: $DIRECTORY"
echo " 🧩 Profile: $PROFILE_NAME"
echo " 🌐 Remote: $REMOTE_SERVER"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🔴 FAILED"
echo " 🧪 Dry Run: $DRY_RUN"
fi
echo "============================================================"
info "️ Sync complete"
} }
main main
+72 -111
View File
@@ -1,51 +1,40 @@
#!/bin/bash #!/bin/bash
# ----------------------------------------------------------------------------------------------- # -----------------------------------------------------------------------------------------------
# ----------------------- Common Helpers for Unraid Scripts ------------------------------------- # ----------------- UNRAID OPS COMMON LIBRARY (CORE FRAMEWORK v1) -------------------------------
# ----------------------------------------------------------------------------------------------- # -----------------------------------------------------------------------------------------------
# Output Helpers # OUTPUT HELPERS
info() { info() { echo "[INFO] $*"; }
echo "[INFO] $*" warn() { echo "[WARN] $*"; }
} error() { echo "[ERROR] $*"; exit 1; }
log() { [[ "${ENABLE_LOGGING:-false}" == true ]] && echo "[LOG] $*"; }
warn() { # DEFAULT FLAGS
echo "[WARN] $*" DRY_RUN=${DRY_RUN:-false}
} ENABLE_LOGGING=${ENABLE_LOGGING:-false}
SHOW_STATUS=${SHOW_STATUS:-false}
error() { # ARGUMENT PARSER
echo "[ERROR] $*" parse_args() {
}
log() {
[[ "$ENABLE_LOGGING" == true ]] && echo "[LOG] $*"
}
# Argument Parsing
DRY_RUN=${DRY_RUN:-false}
ENABLE_LOGGING=${ENABLE_LOGGING:-false}
for ARG in "$@"; do for ARG in "$@"; do
if [[ "$ARG" == *=* ]]; then if [[ "$ARG" == *=* ]]; then
VAR_NAME="${ARG%%=*}" VAR_NAME="${ARG%%=*}"
VAR_VALUE="${ARG#*=}" VAR_VALUE="${ARG#*=}"
case "$VAR_NAME" in case "$VAR_NAME" in
LOG) LOG)
if [[ "$VAR_VALUE" == "true" ]]; then [[ "$VAR_VALUE" == "true" ]] && ENABLE_LOGGING=true
ENABLE_LOGGING=true [[ "$VAR_VALUE" == "false" ]] && ENABLE_LOGGING=false
info "Verbose logging enabled" log "Logging set to $ENABLE_LOGGING"
elif [[ "$VAR_VALUE" == "false" ]]; then
ENABLE_LOGGING=false
else
warn "Invalid value for LOG: $VAR_VALUE (use true/false)"
fi
;; ;;
*) *)
if declare -p "$VAR_NAME" &>/dev/null; then if declare -p "$VAR_NAME" &>/dev/null; then
printf -v "$VAR_NAME" '%s' "$VAR_VALUE" printf -v "$VAR_NAME" '%s' "$VAR_VALUE"
log "Overriding $VAR_NAME -> $VAR_VALUE" log "Override $VAR_NAME -> $VAR_VALUE"
else else
warn "Unknown variable $VAR_NAME, ignoring." warn "Unknown variable: $VAR_NAME"
fi fi
;; ;;
esac esac
@@ -54,11 +43,11 @@ log() {
case "$ARG" in case "$ARG" in
--dry-run|-n) --dry-run|-n)
DRY_RUN=true DRY_RUN=true
info "Dry-run mode enabled" info "Dry-run enabled"
;; ;;
--log) --log)
ENABLE_LOGGING=true ENABLE_LOGGING=true
info "Verbose logging enabled" info "Logging enabled"
;; ;;
--no-log) --no-log)
ENABLE_LOGGING=false ENABLE_LOGGING=false
@@ -67,38 +56,33 @@ log() {
SHOW_STATUS=true SHOW_STATUS=true
;; ;;
--help|-h) --help|-h)
echo "Usage: script <dir> [--dry-run|-n] [--log] [LOG=true] [VAR=value ...]" echo "Usage: script [--dry-run|-n] [--log] [--status] [VAR=value]"
exit 0 exit 0
;; ;;
*) *)
warn "Unknown argument $ARG" warn "Unknown argument: $ARG"
;; ;;
esac esac
fi fi
done done
} }
# Validation # VALIDATION
require_var() { require_var() {
local var="$1" local var="$1"
if [[ -z "${!var:-}" ]]; then [[ -z "${!var:-}" ]] && error "Missing required variable: $var"
error "Required variable $var is not set."
exit 1
fi
} }
validate_int() { validate_int() {
local name="$1" local name="$1"
local value="$2" local value="$2"
if ! [[ "${value:-}" =~ ^[0-9]+$ ]]; then [[ ! "${value:-}" =~ ^[0-9]+$ ]] && error "$name must be an integer"
error "$name must be a non-negative integer."
exit 1
fi
} }
# Host Detection # HOST DETECTION
detect_hosts() { detect_hosts() {
LOCAL_HOSTNAME="$(hostname)" LOCAL_HOSTNAME="$(hostname)"
if [[ "$LOCAL_HOSTNAME" == "$HOST1" ]]; then if [[ "$LOCAL_HOSTNAME" == "$HOST1" ]]; then
@@ -108,127 +92,104 @@ detect_hosts() {
LOCAL_SERVER_NAME="$HOST2" LOCAL_SERVER_NAME="$HOST2"
REMOTE_SERVER_NAME="$HOST1" REMOTE_SERVER_NAME="$HOST1"
else else
error "Local hostname ($LOCAL_HOSTNAME) not recognized." error "Unknown host: $LOCAL_HOSTNAME"
exit 1
fi fi
declare -A SSH_KEYS declare -gA SSH_KEYS
SSH_KEYS["$HOST1|$HOST2"]="$HOST1_SSH_KEY" SSH_KEYS["$HOST1|$HOST2"]="$HOST1_SSH_KEY"
SSH_KEYS["$HOST2|$HOST1"]="$HOST2_SSH_KEY" SSH_KEYS["$HOST2|$HOST1"]="$HOST2_SSH_KEY"
KEY_ID="$LOCAL_SERVER_NAME|$REMOTE_SERVER_NAME" KEY_ID="$LOCAL_SERVER_NAME|$REMOTE_SERVER_NAME"
SSH_KEY="${SSH_KEYS[$KEY_ID]}" SSH_KEY="${SSH_KEYS[$KEY_ID]:-}"
if [[ -z "$SSH_KEY" ]]; then [[ -z "$SSH_KEY" ]] && error "Missing SSH key for $KEY_ID"
error "No SSH key defined for $LOCAL_SERVER_NAME$REMOTE_SERVER_NAME"
exit 1
fi
info "Local: $LOCAL_SERVER_NAME → Remote: $REMOTE_SERVER_NAME" log "Host mapping: $LOCAL_SERVER_NAME -> $REMOTE_SERVER_NAME"
log "SSH key: $SSH_KEY"
} }
# Remote IP # REMOTE RESOLUTION
resolve_remote_ip() { resolve_remote_ip() {
log "Resolving Tailscale IP for $REMOTE_SERVER_NAME..."
log "Resolving remote IP..."
REMOTE_SERVER=$(tailscale ip -4 "$REMOTE_SERVER_NAME" 2>/dev/null) REMOTE_SERVER=$(tailscale ip -4 "$REMOTE_SERVER_NAME" 2>/dev/null)
if [[ -z "$REMOTE_SERVER" ]]; then [[ -z "$REMOTE_SERVER" ]] && error "Failed to resolve IP for $REMOTE_SERVER_NAME"
error "Could not resolve Tailscale IP for $REMOTE_SERVER_NAME"
exit 1
fi
info "Remote IP: $REMOTE_SERVER" log "Remote IP: $REMOTE_SERVER"
} }
# Connectivity
check_remote_online() { check_remote_online() {
log "Pinging $REMOTE_SERVER..."
ping -c 1 "$REMOTE_SERVER" &>/dev/null ping -c 1 "$REMOTE_SERVER" &>/dev/null
} }
# Containers # SAFE SSH WRAPPER
declare -a RUNNING_CONTAINERS=() ssh_exec() {
ssh -i "$SSH_KEY" root@"$REMOTE_SERVER" "$@"
}
# CONTAINER CONTROL
RUNNING_CONTAINERS=()
stop_containers() { stop_containers() {
if [[ ${#CRITICAL_CONTAINER_NAMES[@]} -eq 0 ]]; then
log "No containers defined to stop"
return
fi
info "Stopping containers on $REMOTE_SERVER_NAME..." [[ ${#CRITICAL_CONTAINER_NAMES[@]:-0} -eq 0 ]] && return
RUNNING_CONTAINERS=() RUNNING_CONTAINERS=()
for container in "${CRITICAL_CONTAINER_NAMES[@]}"; do for container in "${CRITICAL_CONTAINER_NAMES[@]}"; do
log "Checking container: $container"
STATUS=$(ssh -i "$SSH_KEY" root@"$REMOTE_SERVER" \ STATUS=$(ssh_exec "docker inspect -f '{{.State.Running}}' $container 2>/dev/null" || echo "false")
"docker inspect -f '{{.State.Running}}' $container 2>/dev/null" || echo "false")
if [[ "$STATUS" == "true" ]]; then if [[ "$STATUS" == "true" ]]; then
info "Stopping $container" info "Stopping $container"
RUNNING_CONTAINERS+=("$container") RUNNING_CONTAINERS+=("$container")
ssh -i "$SSH_KEY" root@"$REMOTE_SERVER" "docker stop $container" ssh_exec "docker stop $container" || warn "Failed to stop $container"
else
log "$container already stopped"
fi fi
done done
} }
start_containers() { start_containers() {
if [[ ${#RUNNING_CONTAINERS[@]} -eq 0 ]]; then
log "No containers to restart"
return
fi
info "Starting containers on $REMOTE_SERVER_NAME..." [[ ${#RUNNING_CONTAINERS[@]} -eq 0 ]] && return
for container in "${RUNNING_CONTAINERS[@]}"; do for container in "${RUNNING_CONTAINERS[@]}"; do
if [[ " ${DELAYED_CONTAINERS[*]} " == *" $container "* ]]; then
info "Delaying $container (${CONTAINER_DELAY}s)" if [[ " ${DELAYED_CONTAINERS[*]:-} " == *" $container "* ]]; then
info "Delaying $container ($CONTAINER_DELAY s)"
sleep "$CONTAINER_DELAY" sleep "$CONTAINER_DELAY"
fi fi
info "Starting $container" info "Starting $container"
ssh -i "$SSH_KEY" root@"$REMOTE_SERVER" "docker start $container" ssh_exec "docker start $container" || warn "Failed to start $container"
done done
} }
# Rsync Options # RSYNC OPTS
get_rsync_opts() { get_rsync_opts() {
if [[ -n "${PROFILE_RSYNC_OPTS[$PROFILE_NAME]:-}" ]]; then if [[ -n "${PROFILE_RSYNC_OPTS[$PROFILE_NAME]:-}" ]]; then
read -r -a RSYNC_OPTS <<< "${PROFILE_RSYNC_OPTS[$PROFILE_NAME]}" IFS=' ' read -r -a RSYNC_OPTS <<< "${PROFILE_RSYNC_OPTS[$PROFILE_NAME]}"
log "Using profile rsync options: ${PROFILE_RSYNC_OPTS[$PROFILE_NAME]}" log "Using profile rsync opts"
else else
RSYNC_OPTS=("${DEFAULT_RSYNC_OPTS[@]}") RSYNC_OPTS=("${DEFAULT_RSYNC_OPTS[@]:-}")
log "Using default rsync options: ${DEFAULT_RSYNC_OPTS[*]}" log "Using default rsync opts"
fi fi
} }
# Status Output # STATUS OUTPUT
show_status() { show_status() {
echo "===== RSYNC STATUS ====="
echo "Local: $LOCAL_SERVER_NAME"
echo "Remote: $REMOTE_SERVER_NAME"
echo "Remote IP: $REMOTE_SERVER"
echo "SSH Key: $SSH_KEY"
echo echo
echo "Directory: $DIRECTORY" echo "=================================================="
echo "Profile: $PROFILE_NAME" echo " RSYNC OPS STATUS"
echo echo "--------------------------------------------------"
echo "Max Procs: $MAX_RSYNC_PROCS" echo " Local: $LOCAL_SERVER_NAME"
echo "Bandwidth: $BW_LIMIT KB/s" echo " Remote: $REMOTE_SERVER_NAME"
echo "Retries: $RETRY_COUNT" echo " IP: ${REMOTE_SERVER:-unset}"
echo "Sleep: $SLEEP" echo " Dry Run: $DRY_RUN"
echo "Dry Run: $DRY_RUN" echo " Logging: $ENABLE_LOGGING"
echo echo " Profile: ${PROFILE_NAME:-default}"
echo "Containers: ${CRITICAL_CONTAINER_NAMES[*]:-(none)}" echo "=================================================="
echo "Delayed: ${DELAYED_CONTAINERS[*]:-(none)}"
echo
echo "Excludes: ${EXCLUDE_DIRS[*]:-(none)}"
echo
echo "Rsync Opts:"
printf ' %s\n' "${RSYNC_OPTS[@]}"
echo "========================="
} }
+78 -34
View File
@@ -5,74 +5,118 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (supports --dry-run)
parse_args "$@" parse_args "$@"
# Colors for output # STATUS MODE
RED="\033[0;31m" if [[ "$SHOW_STATUS" == true ]]; then
GREEN="\033[0;32m" echo
YELLOW="\033[1;33m" echo "=================================================="
RESET="\033[0m" echo " ️ LOG CLEANER STATUS"
echo "--------------------------------------------------"
# Log files to clear (can also be overridden in Master.conf) echo " 📄 System Logs: ${LOG_FILES[*]}"
LOG_FILES=("${LOG_FILES[@]:-/var/log/syslog /var/log/messages /var/log/dmesg}") echo " 🐳 Docker Logs: /var/lib/docker/containers"
echo " 🧪 Dry Run: $DRY_RUN"
# Require root echo "=================================================="
if [ "$EUID" -ne 0 ]; then exit 0
printf "${RED}❌ Please run as root.${RESET}\n"
exit 1
fi fi
echo -e "${YELLOW}Starting log cleanup...${RESET}\n" # CONFIG
LOG_FILES=("${LOG_FILES[@]:-/var/log/syslog /var/log/messages /var/log/dmesg}")
# Functions # ROOT CHECK
if [[ "$EUID" -ne 0 ]]; then
error "🔴 Must be run as root"
fi
# HEADER
echo
echo "============================================================"
echo " 🚀 LOG CLEANER STARTING"
echo "------------------------------------------------------------"
echo " 📄 System Logs: ${LOG_FILES[*]}"
echo " 🐳 Docker Logs: enabled"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Starting log cleanup"
# FUNCTIONS
clear_file() { clear_file() {
local file="$1" local file="$1"
if [ ! -f "$file" ]; then
printf "${RED}Not found:${RESET} %s\n" "$file" if [[ ! -f "$file" ]]; then
warn "🟡 Not found: $file"
return return
fi fi
if [ "$DRY_RUN" = true ]; then if [[ "$DRY_RUN" == true ]]; then
printf "${YELLOW}Would clear:${RESET} %s\n" "$file" warn "🧪 Would clear: $file"
else else
: > "$file" : > "$file"
printf "${GREEN}Cleared:${RESET} %s\n" "$file" info "🟢 Cleared: $file"
fi fi
} }
clear_docker_logs() { clear_docker_logs() {
if [ ! -d /var/lib/docker/containers ]; then
printf "${RED}Docker containers directory not found. Skipping Docker log cleanup.${RESET}\n" if [[ ! -d /var/lib/docker/containers ]]; then
warn "🟡 Docker directory not found — skipping"
return return
fi fi
local files local files
files=$(find /var/lib/docker/containers/ -name "*-json.log" 2>/dev/null) files=$(find /var/lib/docker/containers/ -name "*-json.log" 2>/dev/null || true)
if [[ -z "$files" ]]; then
warn "🟡 No Docker logs found"
return
fi
for file in $files; do for file in $files; do
if [ "$DRY_RUN" = true ]; then if [[ "$DRY_RUN" == true ]]; then
printf "${YELLOW}Would clear Docker log:${RESET} %s\n" "$file" warn "🧪 Would clear Docker log: $file"
else else
: > "$file" : > "$file"
printf "${GREEN}Cleared Docker log:${RESET} %s\n" "$file" info "🟢 Cleared Docker log: $file"
fi fi
done done
} }
# MAIN # EXECUTION
START_TIME=$(date +%s)
for log in "${LOG_FILES[@]}"; do for log in "${LOG_FILES[@]}"; do
clear_file "$log" clear_file "$log"
done done
clear_docker_logs clear_docker_logs
if [ "$DRY_RUN" = true ]; then END_TIME=$(date +%s)
printf "\n${YELLOW}🧪 Dry run complete. No files were cleared.${RESET}\n" DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
if [[ "$DRY_RUN" == true ]]; then
echo " 🟡 LOG CLEANER SUMMARY"
echo "------------------------------------------------------------"
echo " 📄 Logs: ${LOG_FILES[*]}"
echo " 🐳 Docker: skipped (dry run)"
echo " 📡 Status: 🟡 DRY RUN"
else else
printf "\n${GREEN}🎉 Done clearing logs.${RESET}\n" echo " 🟢 LOG CLEANER SUMMARY"
echo "------------------------------------------------------------"
echo " 📄 Logs: ${LOG_FILES[*]}"
echo " 🐳 Docker: cleaned"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🟢 SUCCESS"
fi fi
echo "============================================================"
info "️ Log cleanup complete"
+83 -25
View File
@@ -18,50 +18,108 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (supports --dry-run)
parse_args "$@" parse_args "$@"
# Filter file location (can also be overridden in Master.conf) # STATUS MODE
FILTER_FILE=${FILTER_FILE:-"/etc/rsyslog.d/ignore-docker-veth.conf"} if [[ "$SHOW_STATUS" == true ]]; then
echo
# Require root echo "=================================================="
if [ "$EUID" -ne 0 ]; then echo " ️ SYSLOG FILTER STATUS"
echo -e "\033[0;31m❌ Please run as root.${RESET}\n" echo "--------------------------------------------------"
exit 1 echo " 📄 Filter File: ${FILTER_FILE:-/etc/rsyslog.d/ignore-docker-veth.conf}"
echo " 🐳 Targets: veth, docker0"
echo " 🧪 Dry Run: $DRY_RUN"
echo "=================================================="
exit 0
fi fi
# Functions # CONFIG
FILTER_FILE=${FILTER_FILE:-"/etc/rsyslog.d/ignore-docker-veth.conf"}
# ROOT CHECK
if [[ "$EUID" -ne 0 ]]; then
error "🔴 Must be run as root"
fi
# HEADER
echo
echo "============================================================"
echo " 🚀 SYSLOG FILTER STARTING"
echo "------------------------------------------------------------"
echo " 📄 Filter File: $FILTER_FILE"
echo " 🐳 Targets: veth / docker0"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Applying rsyslog docker noise filter"
# FUNCTIONS
create_filter() { create_filter() {
if [ "$DRY_RUN" = true ]; then
echo "[DRY-RUN] Would create rsyslog filter file at $FILTER_FILE" if [[ "$DRY_RUN" == true ]]; then
else warn "🧪 Would create filter file: $FILTER_FILE"
echo "Creating rsyslog filter file at $FILTER_FILE" return
cat <<'EOF' > "$FILTER_FILE" fi
info "🟡 Creating rsyslog filter file"
cat <<'EOF' > "$FILTER_FILE"
if ($msg contains "veth" or $msg contains "docker0") then { if ($msg contains "veth" or $msg contains "docker0") then {
stop stop
} }
EOF EOF
fi
info "🟢 Filter file written"
} }
restart_rsyslog() { restart_rsyslog() {
if [ "$DRY_RUN" = true ]; then
echo "[DRY-RUN] Would restart rsyslog: /etc/rc.d/rc.rsyslogd restart" if [[ "$DRY_RUN" == true ]]; then
warn "🧪 Would restart rsyslog service"
return
fi
info "🟡 Restarting rsyslog service"
if /etc/rc.d/rc.rsyslogd restart; then
info "🟢 rsyslog restarted successfully"
else else
echo "Restarting rsyslog..." error "🔴 Failed to restart rsyslog"
/etc/rc.d/rc.rsyslogd restart
fi fi
} }
# MAIN # EXECUTION
echo "==== Docker Syslog Filter Script Started: $(date) ====" START_TIME=$(date +%s)
create_filter create_filter
restart_rsyslog restart_rsyslog
echo "✅ Docker veth/docker0 syslog filter applied." END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
if [[ "$DRY_RUN" == true ]]; then
echo " 🟡 SYSLOG FILTER SUMMARY"
echo "------------------------------------------------------------"
echo " 📄 Filter File: $FILTER_FILE"
echo " 🐳 Targets: veth / docker0"
echo " 📡 Status: 🟡 DRY RUN"
else
echo " 🟢 SYSLOG FILTER SUMMARY"
echo "------------------------------------------------------------"
echo " 📄 Filter File: $FILTER_FILE"
echo " 🐳 Targets: veth / docker0"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🟢 SUCCESS"
fi
echo "============================================================"
info "️ Syslog filter operation complete"
+74 -19
View File
@@ -18,47 +18,102 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (flags + VAR=value)
parse_args "$@" parse_args "$@"
# Optional: MOVER_STOP_TIMEOUT in seconds (default from Master.conf or 30s) # CONFIG
MOVER_STOP_TIMEOUT=${MOVER_STOP_TIMEOUT:-30} MOVER_STOP_TIMEOUT=${MOVER_STOP_TIMEOUT:-30}
validate_int MOVER_STOP_TIMEOUT "$MOVER_STOP_TIMEOUT" validate_int MOVER_STOP_TIMEOUT "$MOVER_STOP_TIMEOUT"
# Functions # STATUS MODE
if [[ "$SHOW_STATUS" == true ]]; then
echo
echo "=================================================="
echo " ️ MOVER STOP STATUS"
echo "--------------------------------------------------"
echo " ⏱ Timeout: ${MOVER_STOP_TIMEOUT}s"
echo " 📡 Dry Run: $DRY_RUN"
echo "=================================================="
exit 0
fi
notify_users() { # HEADER
wall "⚠️ Unraid Mover will stop in ${MOVER_STOP_TIMEOUT} second(s)." echo
} echo "============================================================"
echo " 🚀 MOVER STOP STARTING"
echo "------------------------------------------------------------"
echo " ⏱ Timeout: ${MOVER_STOP_TIMEOUT}s"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Checking mover status"
# FUNCTIONS
check_mover_running() { check_mover_running() {
pgrep -f "emhttp.*Mover" >/dev/null 2>&1 pgrep -f "emhttp.*Mover" >/dev/null 2>&1
} }
notify_users() {
warn "🟡 Notifying users: mover stopping soon"
wall "⚠️ Unraid Mover will stop in ${MOVER_STOP_TIMEOUT} second(s)."
}
stop_mover() { stop_mover() {
if [ "$DRY_RUN" = true ]; then
echo "[DRY-RUN] Would stop the Mover process" if [[ "$DRY_RUN" == true ]]; then
warn "🧪 Would stop Unraid Mover process"
return
fi
info "🟡 Stopping Unraid Mover process"
if pkill -f "emhttp.*Mover"; then
info "🟢 Mover stopped successfully"
else else
echo "Stopping Mover..." warn "🔴 Failed to stop mover (may not be running)"
# Unraid native way: kill the mover process gracefully
pkill -f "emhttp.*Mover"
fi fi
} }
# MAIN # EXECUTION
START_TIME=$(date +%s)
echo "==== Mover Stop Script Started: $(date) ===="
if check_mover_running; then if check_mover_running; then
info "🟡 Mover is running"
notify_users notify_users
info "⏱ Waiting ${MOVER_STOP_TIMEOUT}s before stopping"
sleep "$MOVER_STOP_TIMEOUT" sleep "$MOVER_STOP_TIMEOUT"
stop_mover stop_mover
echo "Mover stopped."
else else
echo "Mover is not running." info "🟢 Mover is not running"
fi fi
# FINALIZE
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
if check_mover_running; then
echo " 🟡 MOVER STOP SUMMARY"
echo "------------------------------------------------------------"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🟡 STILL RUNNING OR UNCERTAIN"
else
echo " 🟢 MOVER STOP SUMMARY"
echo "------------------------------------------------------------"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🟢 STOPPED / NOT RUNNING"
fi
echo "============================================================"
info "️ Mover stop operation complete"
+97 -24
View File
@@ -18,45 +18,118 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (supports --dry-run)
parse_args "$@" parse_args "$@"
# Require root # STATUS MODE
if [ "$EUID" -ne 0 ]; then if [[ "$SHOW_STATUS" == true ]]; then
echo -e "\033[0;31m❌ Please run as root.${RESET}\n" echo
exit 1 echo "=================================================="
echo " ️ PHP-FPM CONFIG STATUS"
echo "--------------------------------------------------"
echo " ⚙️ PHP_CONF: $PHP_CONF"
echo " 👥 Max Children: ${PHP_MAX_CHILDREN:-unset}"
echo " 🧪 Dry Run: $DRY_RUN"
echo "=================================================="
exit 0
fi fi
validate_int PHP_MAX_CHILDREN "$PHP_MAX_CHILDREN" # ROOT CHECK
if [[ "$EUID" -ne 0 ]]; then
error "🔴 Must be run as root"
fi
# Functions # VALIDATION
validate_int PHP_MAX_CHILDREN "$PHP_MAX_CHILDREN"
require_var PHP_CONF
# HEADER
echo
echo "============================================================"
echo " 🚀 PHP-FPM CONFIG UPDATE STARTING"
echo "------------------------------------------------------------"
echo " ⚙️ Target: $PHP_CONF"
echo " 👥 MaxChild: $PHP_MAX_CHILDREN"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Starting PHP-FPM configuration update"
# FUNCTIONS
apply_php_max_children() { apply_php_max_children() {
local target="pm.max_children = $PHP_MAX_CHILDREN" local target="pm.max_children = $PHP_MAX_CHILDREN"
if [ "$DRY_RUN" = true ]; then if [[ "$DRY_RUN" == true ]]; then
echo "[DRY-RUN] Would set PHP-FPM max_children to $PHP_MAX_CHILDREN in $PHP_CONF" warn "🧪 Would set pm.max_children = $PHP_MAX_CHILDREN"
echo "[DRY-RUN] Would restart PHP-FPM service" warn "🧪 Would restart PHP-FPM service"
return
fi
info "🟡 Applying PHP-FPM configuration"
if [[ ! -f "$PHP_CONF" ]]; then
error "🔴 PHP config file not found: $PHP_CONF"
fi
# Apply config safely
if sed -i "s/^pm\.max_children.*/$target/" "$PHP_CONF"; then
info "🟢 Config updated successfully"
else else
echo "Applying persistent PHP-FPM max_children = $PHP_MAX_CHILDREN" error "🔴 Failed to update PHP config"
sed -i "s/^pm\.max_children.*/$target/" "$PHP_CONF" fi
# Restart PHP-FPM # Restart service
/etc/rc.d/rc.php-fpm restart info "🟡 Restarting PHP-FPM"
local current if /etc/rc.d/rc.php-fpm restart; then
current=$(grep -E "^pm\.max_children" "$PHP_CONF") info "🟢 PHP-FPM restarted successfully"
logger "Userscript: php-fpm setting applied: $current" else
error "🔴 PHP-FPM restart failed"
fi
echo "PHP-FPM max_children persistently set to: $current" # Verify applied value
echo "PHP-FPM restarted successfully." local current
current=$(grep -E "^pm\.max_children" "$PHP_CONF" || true)
if [[ -n "$current" ]]; then
info "🟢 Verified: $current"
logger "Userscript: PHP-FPM updated -> $current"
else
warn "🟡 Could not verify configuration value"
fi fi
} }
# MAIN # EXECUTION
echo "==== PHP-FPM Max Children Script Started: $(date) ====" START_TIME=$(date +%s)
apply_php_max_children apply_php_max_children
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
if [[ "$DRY_RUN" == true ]]; then
echo " 🟡 PHP-FPM SUMMARY"
echo "------------------------------------------------------------"
echo " ⚙️ Target: $PHP_CONF"
echo " 👥 MaxChild: $PHP_MAX_CHILDREN"
echo " 📡 Status: 🟡 DRY RUN"
else
echo " 🟢 PHP-FPM SUMMARY"
echo "------------------------------------------------------------"
echo " ⚙️ Target: $PHP_CONF"
echo " 👥 MaxChild: $PHP_MAX_CHILDREN"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Status: 🟢 SUCCESS"
fi
echo "============================================================"
info "️ PHP-FPM configuration update complete"
+73 -14
View File
@@ -5,30 +5,89 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (supports --dry-run)
parse_args "$@" parse_args "$@"
# Functions # STATUS MODE
if [[ "$SHOW_STATUS" == true ]]; then
echo
echo "=================================================="
echo " ️ RSYNC STOP STATUS"
echo "--------------------------------------------------"
echo " 🔄 Target: rsync processes"
echo " 🧪 Dry Run: $DRY_RUN"
echo "=================================================="
exit 0
fi
# HEADER
echo
echo "============================================================"
echo " 🚀 RSYNC STOP STARTING"
echo "------------------------------------------------------------"
echo " 🔄 Target: all rsync processes"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Checking for running rsync processes"
# FUNCTIONS
check_rsync_running() {
pgrep -f rsync >/dev/null 2>&1
}
stop_rsync_processes() { stop_rsync_processes() {
if [ "$DRY_RUN" = true ]; then
echo "[DRY-RUN] Would stop all running rsync processes" if [[ "$DRY_RUN" == true ]]; then
else warn "🧪 Would stop all rsync processes"
echo "Stopping all rsync processes..." return
if pkill -f rsync; then fi
echo "All rsync processes stopped successfully."
if check_rsync_running; then
info "🟡 Stopping rsync processes"
# safer than blind pkill message-only:
pkill -f rsync
sleep 1
if check_rsync_running; then
warn "🟡 Some rsync processes may still be running"
else else
echo "No rsync processes found or failed to stop." info "🟢 All rsync processes stopped successfully"
fi fi
else
info "🟢 No rsync processes currently running"
fi fi
} }
# MAIN # EXECUTION
echo "==== Rsync Stop Script Started: $(date) ====" START_TIME=$(date +%s)
stop_rsync_processes stop_rsync_processes
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
if check_rsync_running; then
echo " 🟡 RSYNC STOP SUMMARY"
echo "------------------------------------------------------------"
echo " 🔄 Status: 🟡 SOME PROCESSES MAY REMAIN"
echo " ⏱ Duration: ${DURATION}s"
else
echo " 🟢 RSYNC STOP SUMMARY"
echo "------------------------------------------------------------"
echo " 🔄 Status: 🟢 ALL STOPPED"
echo " ⏱ Duration: ${DURATION}s"
fi
echo "============================================================"
info "️ Rsync stop operation complete"
+111 -39
View File
@@ -18,63 +18,135 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (flags + VAR=value)
parse_args "$@" parse_args "$@"
# Validate REBOOT_SLEEP # STATUS MODE
if [[ "$SHOW_STATUS" == true ]]; then
echo
echo "=================================================="
echo " ️ REBOOT STATUS"
echo "--------------------------------------------------"
echo " ⏱ Delay: ${REBOOT_SLEEP:-0}s"
echo " 🧪 Dry Run: $DRY_RUN"
echo "=================================================="
exit 0
fi
# CONFIG
validate_int REBOOT_SLEEP "$REBOOT_SLEEP" validate_int REBOOT_SLEEP "$REBOOT_SLEEP"
# --- Functions # HEADER
echo
echo "============================================================"
echo " 🚀 UNRAID REBOOT SEQUENCE STARTING"
echo "------------------------------------------------------------"
echo " ⏱ Delay: ${REBOOT_SLEEP}s"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Reboot sequence initiated"
# FUNCTIONS
notify_users() { notify_users() {
warn "🟡 Notifying users of reboot"
wall "⚠️ Unraid server will reboot in ${REBOOT_SLEEP} second(s). Save your work." wall "⚠️ Unraid server will reboot in ${REBOOT_SLEEP} second(s). Save your work."
} }
# --- MAIN stop_docker() {
echo "==== Scheduled Reboot Script Started: $(date) ====" if [[ "$DRY_RUN" == true ]]; then
warn "🧪 Would stop Docker service"
return
fi
# Optional warning before reboot info "🟡 Stopping Docker service"
if [ "$REBOOT_SLEEP" -gt 0 ]; then
notify_users
sleep "$REBOOT_SLEEP"
if /etc/rc.d/rc.docker stop; then
info "🟢 Docker stopped"
else
warn "🔴 Docker stop failed or already stopped"
fi
}
stop_vm_manager() {
if [[ "$DRY_RUN" == true ]]; then
warn "🧪 Would stop VM Manager (libvirt)"
return
fi
info "🟡 Stopping VM Manager"
fi if /etc/rc.d/rc.libvirt stop; then
info "🟢 VM Manager stopped"
else
warn "🔴 VM Manager stop failed or already stopped"
fi
}
# Stop Docker sync_disks() {
if [ "$DRY_RUN" = true ]; then if [[ "$DRY_RUN" == true ]]; then
echo "[DRY-RUN] Would stop Docker: /etc/rc.d/rc.docker stop" warn "🧪 Would sync filesystem buffers"
else return
echo "Stopping Docker..." fi
/etc/rc.d/rc.docker stop
fi
# Stop VM Manager info "🟡 Syncing disks"
if [ "$DRY_RUN" = true ]; then
echo "[DRY-RUN] Would stop VM Manager: /etc/rc.d/rc.libvirt stop"
else
echo "Stopping VM Manager..."
/etc/rc.d/rc.libvirt stop
fi
# Sync disks if sync; then
if [ "$DRY_RUN" = true ]; then info "🟢 Disk sync complete"
echo "[DRY-RUN] Would sync disks" else
else warn "🔴 Sync command returned error"
echo "Syncing disks..." fi
sync }
fi
reboot_system() {
if [[ "$DRY_RUN" == true ]]; then
warn "🧪 Would reboot system (/sbin/reboot)"
return
fi
info "🔴 Rebooting system NOW"
# Reboot system
if [ "$DRY_RUN" = true ]; then
echo "[DRY-RUN] Would reboot system: /sbin/reboot"
else
echo "Rebooting system..."
/sbin/reboot /sbin/reboot
}
# EXECUTION
START_TIME=$(date +%s)
if [[ "$REBOOT_SLEEP" -gt 0 ]]; then
notify_users
info "⏱ Waiting ${REBOOT_SLEEP}s before shutdown sequence"
sleep "$REBOOT_SLEEP"
fi fi
stop_docker
stop_vm_manager
sync_disks
reboot_system
# NOTE: system will not reach here unless dry-run
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
if [[ "$DRY_RUN" == true ]]; then
echo " 🟡 REBOOT SUMMARY"
echo "------------------------------------------------------------"
echo " ⏱ Delay: ${REBOOT_SLEEP}s"
echo " 📡 Status: 🟡 DRY RUN (no reboot executed)"
else
echo " 🔴 REBOOT SUMMARY"
echo "------------------------------------------------------------"
echo " ⚠️ Status: 🔴 SYSTEM SHOULD BE REBOOTING"
echo " ⏱ Duration: ${DURATION}s"
fi
echo "============================================================"
info "️ Reboot sequence complete (or handed off to system reboot)"
+88 -17
View File
@@ -5,39 +5,110 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (supports --dry-run)
parse_args "$@" parse_args "$@"
# Functions # STATUS MODE
if [[ "$SHOW_STATUS" == true ]]; then
echo
echo "=================================================="
echo " ️ USER SCRIPTS STATUS"
echo "--------------------------------------------------"
echo " 🔍 Target: /tmp/user.scripts processes"
echo " 🧪 Dry Run: $DRY_RUN"
echo "=================================================="
exit 0
fi
# HEADER
echo
echo "============================================================"
echo " 🚀 USER SCRIPTS STOP STARTING"
echo "------------------------------------------------------------"
echo " 🔍 Target: User Scripts Plugin processes"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Scanning for User Scripts processes"
# FUNCTIONS
get_user_script_pids() {
/usr/bin/ps -eo pid,cmd | grep "/tmp/user.scripts" | grep -v grep | awk '{print $1}'
}
stop_user_scripts() { stop_user_scripts() {
# Get PIDs of running user scripts
local pids
pids=$(/usr/bin/ps -eo pid,cmd | grep "/tmp/user.scripts" | grep -v grep | awk '{print $1}')
if [ -z "$pids" ]; then local pids
echo "No running user scripts found." pids=$(get_user_script_pids)
if [[ -z "$pids" ]]; then
info "🟢 No running User Scripts found"
return return
fi fi
local count=0
for pid in $pids; do for pid in $pids; do
if [ "$DRY_RUN" = true ]; then
echo "[DRY-RUN] Would kill user script with PID $pid" if [[ "$DRY_RUN" == true ]]; then
warn "🧪 Would kill User Script PID $pid"
else else
echo "Killing user script with PID $pid" info "🟡 Killing User Script PID $pid"
kill "$pid"
if kill "$pid" 2>/dev/null; then
info "🟢 Killed PID $pid"
else
warn "🔴 Failed to kill PID $pid (may already be gone)"
fi
fi fi
count=$((count + 1))
done done
echo "All user scripts stopped." if [[ "$DRY_RUN" == true ]]; then
warn "🧪 Would stop $count User Script process(es)"
else
info "🟢 Process cleanup complete ($count process(es) targeted)"
fi
} }
# MAIN # EXECUTION
echo "==== User Scripts Stop Script Started: $(date) ====" START_TIME=$(date +%s)
stop_user_scripts stop_user_scripts
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
if [[ "$DRY_RUN" == true ]]; then
echo " 🟡 USER SCRIPTS SUMMARY"
echo "------------------------------------------------------------"
echo " 🔍 Status: 🟡 DRY RUN (no processes killed)"
echo " ⏱ Duration: ${DURATION}s"
else
local remaining
remaining=$(get_user_script_pids)
if [[ -z "$remaining" ]]; then
echo " 🟢 USER SCRIPTS SUMMARY"
echo "------------------------------------------------------------"
echo " 🔍 Status: 🟢 ALL PROCESSES STOPPED"
else
echo " 🟡 USER SCRIPTS SUMMARY"
echo "------------------------------------------------------------"
echo " 🔍 Status: 🟡 SOME PROCESSES MAY STILL BE RUNNING"
fi
echo " ⏱ Duration: ${DURATION}s"
fi
echo "============================================================"
info "️ User Scripts stop operation complete"
+68 -16
View File
@@ -6,35 +6,87 @@ set -e
# ---------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../Master.conf"
source "$SCRIPT_DIR/../common.sh" source "$SCRIPT_DIR/../common.sh"
# Load central config
load_master_conf
# Parse CLI args (supports --dry-run)
parse_args "$@" parse_args "$@"
# Functions # STATUS MODE
if [[ "$SHOW_STATUS" == true ]]; then
echo
echo "=================================================="
echo " ️ ZFS + MEMORY SNAPSHOT STATUS"
echo "--------------------------------------------------"
echo " 📊 Mode: Read-only diagnostics"
echo " 🧪 Dry Run: $DRY_RUN"
echo "=================================================="
exit 0
fi
# HEADER
echo
echo "============================================================"
echo " 📊 ZFS ARC + MEMORY SNAPSHOT"
echo "------------------------------------------------------------"
echo " 🕒 Time: $(date)"
echo " 🧪 Dry Run: $DRY_RUN"
echo "============================================================"
log "️ Collecting ZFS ARC + memory statistics"
# FUNCTIONS
show_zfs_arc() { show_zfs_arc() {
echo "--- ARC / Metadata Stats ---"
grep -iE '^(c|meta|arc_meta_used|demand_metadata_misses|mru_ghost_metadata|mfu_ghost_metadata)' /proc/spl/kstat/zfs/arcstats echo
echo "==================== ZFS ARC STATS ===================="
if [[ ! -r /proc/spl/kstat/zfs/arcstats ]]; then
warn "🔴 ZFS arcstats not available on this system"
return
fi
grep -iE '^(c|size|hits|misses|arc_meta_used|demand_metadata_misses|mru_ghost_metadata|mfu_ghost_metadata)' \
/proc/spl/kstat/zfs/arcstats 2>/dev/null || warn "🟡 Unable to read ARC stats"
} }
show_memory_status() { show_memory_status() {
echo "--- Memory Status ---"
free -h | awk 'NR==1 || /Mem:/' echo
echo "==================== MEMORY STATUS ===================="
if command -v free >/dev/null 2>&1; then
free -h | awk '
NR==1 {print $0}
/Mem:/ {print $0}
/Swap:/ {print $0}'
else
warn "🔴 free command not available"
fi
} }
# MAIN # EXECUTION
echo "===== ZFS ARC & Memory Snapshot: $(date) =====" START_TIME=$(date +%s)
if [ "$DRY_RUN" = true ]; then if [[ "$DRY_RUN" == true ]]; then
echo "[DRY-RUN] Would display ARC and memory stats" warn "🧪 Dry run enabled - no system data collected"
else else
echo ""
show_zfs_arc show_zfs_arc
echo ""
show_memory_status show_memory_status
fi fi
echo "==============================================" END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# SUMMARY
echo
echo "============================================================"
echo " 📊 SNAPSHOT SUMMARY"
echo "------------------------------------------------------------"
echo " ⏱ Duration: ${DURATION}s"
echo " 📡 Mode: READ-ONLY"
echo " 🧠 Source: ZFS ARC + system memory"
echo "============================================================"
info "️ Snapshot complete"