mirror of
https://github.com/acedanger/shell.git
synced 2025-12-06 03:20:12 -08:00
Add advanced Plex database recovery and restoration scripts
- Introduced `recover-plex-database.sh` for comprehensive database recovery with multiple strategies, logging, and rollback capabilities. - Added `restore-plex.sh` for safe restoration of Plex backups, including validation and dry-run options. - Created `plex-db-manager.sh` to consolidate database management functionalities, including integrity checks and service management. - Enhanced logging and error handling across all scripts for better user feedback and troubleshooting. - Implemented safety measures to prevent running scripts as root and ensure proper service management during operations.
This commit is contained in:
42
plex/deprecated/README.md
Normal file
42
plex/deprecated/README.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# Deprecated Scripts
|
||||
|
||||
These scripts have been moved to this folder because their functionality has been consolidated into the main Plex management tools.
|
||||
|
||||
## Scripts Moved (June 21, 2025)
|
||||
|
||||
### `plex-database-repair.sh`
|
||||
- **Reason**: Functionality consolidated into `plex-db-manager.sh`
|
||||
- **Replacement**: Use `plex-db-manager.sh check` and `plex-db-manager.sh repair`
|
||||
|
||||
### `recover-plex-database.sh`
|
||||
- **Reason**: Advanced recovery methods rarely worked effectively
|
||||
- **Replacement**: Use `nuclear-plex-recovery.sh` for emergency situations
|
||||
|
||||
### `restore-plex.sh`
|
||||
- **Reason**: Basic restoration functionality covered by other scripts
|
||||
- **Replacement**: Use `nuclear-plex-recovery.sh` for backup restoration
|
||||
|
||||
### `icu-aware-recovery.sh`
|
||||
- **Reason**: ICU collation issues addressed in main repair logic
|
||||
- **Replacement**: Built into `plex-db-manager.sh` and `nuclear-plex-recovery.sh`
|
||||
|
||||
## Why These Were Retired
|
||||
|
||||
The original issue causing database corruption was identified as the **aggressive 30-minute auto-repair cron schedule**. With this fixed:
|
||||
|
||||
1. **Repair operations are now rarely needed**
|
||||
2. **Simpler tools are more reliable** than complex multi-strategy repair scripts
|
||||
3. **Manual intervention is preferred** over automated repair attempts
|
||||
4. **Nuclear recovery** provides a clean last-resort option
|
||||
|
||||
## Access If Needed
|
||||
|
||||
These scripts are preserved for emergency use but are no longer maintained. If you need emergency access to advanced repair functionality:
|
||||
|
||||
```bash
|
||||
# Emergency use only
|
||||
./deprecated/plex-database-repair.sh repair /path/to/database.db
|
||||
./deprecated/recover-plex-database.sh --auto
|
||||
```
|
||||
|
||||
⚠️ **Note**: These scripts are no longer tested or supported. Use at your own risk.
|
||||
351
plex/deprecated/icu-aware-recovery.sh
Executable file
351
plex/deprecated/icu-aware-recovery.sh
Executable file
@@ -0,0 +1,351 @@
|
||||
#!/bin/bash
|
||||
|
||||
################################################################################
|
||||
# ICU-Aware Plex Database Recovery Script
|
||||
################################################################################
|
||||
#
|
||||
# Author: Peter Wood <peter@peterwood.dev>
|
||||
# Description: Specialized recovery script for Plex databases that require
|
||||
# ICU (International Components for Unicode) collation sequences.
|
||||
# Handles complex database corruption scenarios involving Unicode
|
||||
# sorting and collation issues.
|
||||
#
|
||||
# Features:
|
||||
# - ICU collation sequence detection and repair
|
||||
# - Unicode-aware database reconstruction
|
||||
# - Advanced SQLite recovery techniques
|
||||
# - Backup creation before recovery attempts
|
||||
# - Comprehensive logging and error tracking
|
||||
# - Plex service management during recovery
|
||||
#
|
||||
# Related Scripts:
|
||||
# - backup-plex.sh: Creates backups used for recovery scenarios
|
||||
# - restore-plex.sh: Standard restoration procedures
|
||||
# - nuclear-plex-recovery.sh: Last-resort recovery methods
|
||||
# - validate-plex-recovery.sh: Validates recovery results
|
||||
# - plex.sh: General Plex service management
|
||||
#
|
||||
# Usage:
|
||||
# ./icu-aware-recovery.sh # Interactive recovery
|
||||
# ./icu-aware-recovery.sh --auto # Automated recovery
|
||||
# ./icu-aware-recovery.sh --check-only # Check ICU status only
|
||||
# ./icu-aware-recovery.sh --backup-first # Force backup before recovery
|
||||
#
|
||||
# Dependencies:
|
||||
# - sqlite3 with ICU support
|
||||
# - Plex Media Server
|
||||
# - libicu-dev (ICU libraries)
|
||||
# - systemctl (for service management)
|
||||
#
|
||||
# Exit Codes:
|
||||
# 0 - Recovery successful
|
||||
# 1 - General error
|
||||
# 2 - ICU-related issues
|
||||
# 3 - Database corruption beyond repair
|
||||
# 4 - Service management failure
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# ICU-Aware Plex Database Recovery Script
|
||||
# Handles databases that require ICU collation sequences
|
||||
|
||||
set -e
|
||||
|
||||
# Colors for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Configuration
|
||||
PLEX_DB_DIR="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases"
|
||||
BACKUP_TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
|
||||
RECOVERY_LOG="/home/acedanger/shell/plex/logs/icu-recovery-${BACKUP_TIMESTAMP}.log"
|
||||
|
||||
# Ensure log directory exists
|
||||
mkdir -p "$(dirname "$RECOVERY_LOG")"
|
||||
|
||||
# Function to log messages
|
||||
log_message() {
|
||||
local level="$1"
|
||||
local message="$2"
|
||||
local timestamp
|
||||
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo "[$timestamp] [$level] $message" | tee -a "$RECOVERY_LOG"
|
||||
}
|
||||
|
||||
# Function to print colored output
|
||||
print_status() {
|
||||
local color="$1"
|
||||
local message="$2"
|
||||
echo -e "${color}${message}${NC}"
|
||||
log_message "INFO" "$message"
|
||||
}
|
||||
|
||||
# Function to check SQLite ICU support
|
||||
check_sqlite_icu() {
|
||||
print_status "$YELLOW" "Checking SQLite ICU collation support..."
|
||||
|
||||
# Try to create a test database with ICU collation
|
||||
local test_db="/tmp/test_icu_$$"
|
||||
|
||||
if sqlite3 "$test_db" "CREATE TABLE test (id TEXT COLLATE icu_root); DROP TABLE test;" 2>/dev/null; then
|
||||
print_status "$GREEN" "SQLite has ICU collation support"
|
||||
rm -f "$test_db"
|
||||
return 0
|
||||
else
|
||||
print_status "$YELLOW" "SQLite lacks ICU collation support - will use alternative verification"
|
||||
rm -f "$test_db"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to verify database without ICU-dependent checks
|
||||
verify_database_basic() {
|
||||
local db_file="$1"
|
||||
local db_name="$2"
|
||||
|
||||
print_status "$YELLOW" "Performing basic verification of $db_name..."
|
||||
|
||||
# Check if file exists and is not empty
|
||||
if [[ ! -f "$db_file" ]]; then
|
||||
print_status "$RED" "$db_name: File does not exist"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local file_size
|
||||
file_size=$(stat -c%s "$db_file" 2>/dev/null || stat -f%z "$db_file" 2>/dev/null)
|
||||
if [[ $file_size -lt 1024 ]]; then
|
||||
print_status "$RED" "$db_name: File is too small ($file_size bytes)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check if it's a valid SQLite file
|
||||
if ! file "$db_file" | grep -q "SQLite"; then
|
||||
print_status "$RED" "$db_name: Not a valid SQLite database"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Try basic SQLite operations that don't require ICU
|
||||
if sqlite3 "$db_file" "SELECT name FROM sqlite_master WHERE type='table' LIMIT 1;" >/dev/null 2>&1; then
|
||||
print_status "$GREEN" "$db_name: Basic SQLite operations successful"
|
||||
|
||||
# Count tables
|
||||
local table_count
|
||||
table_count=$(sqlite3 "$db_file" "SELECT COUNT(*) FROM sqlite_master WHERE type='table';" 2>/dev/null || echo "0")
|
||||
print_status "$GREEN" "$db_name: Contains $table_count tables"
|
||||
|
||||
return 0
|
||||
else
|
||||
print_status "$RED" "$db_name: Failed basic SQLite operations"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to attempt ICU-safe integrity check
|
||||
verify_database_integrity() {
|
||||
local db_file="$1"
|
||||
local db_name="$2"
|
||||
|
||||
print_status "$YELLOW" "Attempting integrity check for $db_name..."
|
||||
|
||||
# First try the basic verification
|
||||
if ! verify_database_basic "$db_file" "$db_name"; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Try integrity check with ICU fallback handling
|
||||
local integrity_result
|
||||
integrity_result=$(sqlite3 "$db_file" "PRAGMA integrity_check;" 2>&1)
|
||||
local sqlite_exit_code=$?
|
||||
|
||||
if [[ $sqlite_exit_code -eq 0 ]] && echo "$integrity_result" | grep -q "ok"; then
|
||||
print_status "$GREEN" "$db_name: Full integrity check PASSED"
|
||||
return 0
|
||||
elif echo "$integrity_result" | grep -q "no such collation sequence: icu"; then
|
||||
print_status "$YELLOW" "$db_name: ICU collation issue detected, but database structure appears valid"
|
||||
print_status "$YELLOW" "This is normal for restored databases and should resolve when Plex starts"
|
||||
return 0
|
||||
else
|
||||
print_status "$RED" "$db_name: Integrity check failed with: $integrity_result"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to stop Plex service
|
||||
stop_plex() {
|
||||
print_status "$YELLOW" "Stopping Plex Media Server..."
|
||||
|
||||
if systemctl is-active --quiet plexmediaserver; then
|
||||
systemctl stop plexmediaserver
|
||||
sleep 5
|
||||
|
||||
# Verify it's stopped
|
||||
if systemctl is-active --quiet plexmediaserver; then
|
||||
print_status "$RED" "Failed to stop Plex service"
|
||||
exit 1
|
||||
fi
|
||||
print_status "$GREEN" "Plex service stopped successfully"
|
||||
else
|
||||
print_status "$YELLOW" "Plex service was already stopped"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to start Plex service
|
||||
start_plex() {
|
||||
print_status "$YELLOW" "Starting Plex Media Server..."
|
||||
|
||||
systemctl start plexmediaserver
|
||||
sleep 10
|
||||
|
||||
# Verify it's running
|
||||
if systemctl is-active --quiet plexmediaserver; then
|
||||
print_status "$GREEN" "Plex service started successfully"
|
||||
|
||||
# Check if it's actually responding
|
||||
local max_attempts=30
|
||||
local attempt=1
|
||||
|
||||
while [[ $attempt -le $max_attempts ]]; do
|
||||
if curl -s -f "http://localhost:32400/web/index.html" > /dev/null 2>&1; then
|
||||
print_status "$GREEN" "Plex web interface is responding"
|
||||
return 0
|
||||
fi
|
||||
|
||||
print_status "$YELLOW" "Waiting for Plex to fully start... (attempt $attempt/$max_attempts)"
|
||||
sleep 5
|
||||
((attempt++))
|
||||
done
|
||||
|
||||
print_status "$YELLOW" "Plex service is running but web interface may still be starting"
|
||||
else
|
||||
print_status "$RED" "Failed to start Plex service"
|
||||
systemctl status plexmediaserver --no-pager
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to validate current database state
|
||||
validate_current_state() {
|
||||
print_status "$YELLOW" "Validating current database state..."
|
||||
|
||||
local main_db="${PLEX_DB_DIR}/com.plexapp.plugins.library.db"
|
||||
local blobs_db="${PLEX_DB_DIR}/com.plexapp.plugins.library.blobs.db"
|
||||
|
||||
local validation_passed=true
|
||||
|
||||
# Check main database
|
||||
if ! verify_database_integrity "$main_db" "Main database"; then
|
||||
validation_passed=false
|
||||
fi
|
||||
|
||||
# Check blobs database
|
||||
if ! verify_database_integrity "$blobs_db" "Blobs database"; then
|
||||
validation_passed=false
|
||||
fi
|
||||
|
||||
if [[ "$validation_passed" == "true" ]]; then
|
||||
print_status "$GREEN" "Database validation completed successfully"
|
||||
return 0
|
||||
else
|
||||
print_status "$YELLOW" "Database validation completed with warnings"
|
||||
print_status "$YELLOW" "ICU collation issues are normal for restored databases"
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to check database sizes
|
||||
check_database_sizes() {
|
||||
print_status "$YELLOW" "Checking database file sizes..."
|
||||
|
||||
local main_db="${PLEX_DB_DIR}/com.plexapp.plugins.library.db"
|
||||
local blobs_db="${PLEX_DB_DIR}/com.plexapp.plugins.library.blobs.db"
|
||||
|
||||
if [[ -f "$main_db" ]]; then
|
||||
local main_size
|
||||
main_size=$(du -h "$main_db" | cut -f1)
|
||||
print_status "$GREEN" "Main database size: $main_size"
|
||||
fi
|
||||
|
||||
if [[ -f "$blobs_db" ]]; then
|
||||
local blobs_size
|
||||
blobs_size=$(du -h "$blobs_db" | cut -f1)
|
||||
print_status "$GREEN" "Blobs database size: $blobs_size"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to test Plex functionality
|
||||
test_plex_functionality() {
|
||||
print_status "$YELLOW" "Testing Plex functionality..."
|
||||
|
||||
# Wait a bit longer for Plex to fully initialize
|
||||
sleep 15
|
||||
|
||||
# Test basic API endpoints
|
||||
local max_attempts=10
|
||||
local attempt=1
|
||||
|
||||
while [[ $attempt -le $max_attempts ]]; do
|
||||
# Test the main API endpoint
|
||||
if curl -s -f "http://localhost:32400/" > /dev/null 2>&1; then
|
||||
print_status "$GREEN" "Plex API is responding"
|
||||
|
||||
# Try to get server info
|
||||
local server_info=$(curl -s "http://localhost:32400/" 2>/dev/null)
|
||||
if echo "$server_info" | grep -q "MediaContainer"; then
|
||||
print_status "$GREEN" "Plex server is fully functional"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
print_status "$YELLOW" "Waiting for Plex API... (attempt $attempt/$max_attempts)"
|
||||
sleep 10
|
||||
((attempt++))
|
||||
done
|
||||
|
||||
print_status "$YELLOW" "Plex may still be initializing - check manually at http://localhost:32400"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Main function
|
||||
main() {
|
||||
print_status "$BLUE" "=== ICU-AWARE PLEX DATABASE RECOVERY ==="
|
||||
print_status "$BLUE" "Timestamp: $(date)"
|
||||
print_status "$BLUE" "Log file: $RECOVERY_LOG"
|
||||
|
||||
# Check SQLite ICU support
|
||||
check_sqlite_icu
|
||||
|
||||
# Validate current database state
|
||||
validate_current_state
|
||||
|
||||
# Check database sizes
|
||||
check_database_sizes
|
||||
|
||||
# Stop Plex (if running)
|
||||
stop_plex
|
||||
|
||||
# Start Plex service
|
||||
if start_plex; then
|
||||
print_status "$GREEN" "Plex service started successfully"
|
||||
|
||||
# Test functionality
|
||||
test_plex_functionality
|
||||
|
||||
print_status "$GREEN" "=== RECOVERY COMPLETED SUCCESSFULLY ==="
|
||||
print_status "$GREEN" "Your Plex Media Server should now be functional."
|
||||
print_status "$GREEN" "Check the web interface at: http://localhost:32400"
|
||||
print_status "$YELLOW" "Note: ICU collation warnings are normal for restored databases"
|
||||
print_status "$BLUE" "Recovery log saved to: $RECOVERY_LOG"
|
||||
else
|
||||
print_status "$RED" "Failed to start Plex service - check logs for details"
|
||||
print_status "$BLUE" "Recovery log saved to: $RECOVERY_LOG"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Script usage
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
||||
649
plex/deprecated/plex-database-repair.sh
Executable file
649
plex/deprecated/plex-database-repair.sh
Executable file
@@ -0,0 +1,649 @@
|
||||
#!/bin/bash
|
||||
|
||||
################################################################################
|
||||
# Plex Database Repair Utility
|
||||
################################################################################
|
||||
#
|
||||
# Author: Peter Wood <peter@peterwood.dev>
|
||||
# Description: Shared database repair functionality for Plex Media Server
|
||||
# Extracted from backup-plex.sh to be reusable across scripts
|
||||
#
|
||||
# Features:
|
||||
# - Database integrity verification with automatic repair
|
||||
# - WAL (Write-Ahead Logging) file handling
|
||||
# - Multiple repair strategies (dump/restore, schema recreation, backup recovery)
|
||||
# - Comprehensive error handling and recovery
|
||||
#
|
||||
# Usage:
|
||||
# ./plex-database-repair.sh check <database_file> # Check integrity only
|
||||
# ./plex-database-repair.sh repair <database_file> # Attempt repair
|
||||
# ./plex-database-repair.sh force-repair <database_file> # Force repair without prompts
|
||||
#
|
||||
# Exit Codes:
|
||||
# 0 - Success (database is healthy or successfully repaired)
|
||||
# 1 - Database has issues but repair failed
|
||||
# 2 - Critical error (cannot access database or repair tools)
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# Color codes for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Configuration
|
||||
PLEX_SQLITE="/usr/lib/plexmediaserver/Plex SQLite"
|
||||
BACKUP_ROOT="/mnt/share/media/backups/plex"
|
||||
|
||||
# Logging functions
|
||||
log_message() {
|
||||
local message="$1"
|
||||
local timestamp
|
||||
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo -e "${CYAN}[${timestamp}]${NC} ${message}"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
local message="$1"
|
||||
local timestamp
|
||||
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo -e "${RED}[${timestamp}] ERROR:${NC} ${message}" >&2
|
||||
}
|
||||
|
||||
log_success() {
|
||||
local message="$1"
|
||||
local timestamp
|
||||
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo -e "${GREEN}[${timestamp}] SUCCESS:${NC} ${message}"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
local message="$1"
|
||||
local timestamp
|
||||
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo -e "${YELLOW}[${timestamp}] WARNING:${NC} ${message}"
|
||||
}
|
||||
|
||||
log_info() {
|
||||
local message="$1"
|
||||
local timestamp
|
||||
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo -e "${BLUE}[${timestamp}] INFO:${NC} ${message}"
|
||||
}
|
||||
|
||||
# Check if Plex SQLite binary exists and is executable
|
||||
check_plex_sqlite() {
|
||||
if [[ ! -f "$PLEX_SQLITE" ]]; then
|
||||
log_error "Plex SQLite binary not found at: $PLEX_SQLITE"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! sudo chmod +x "$PLEX_SQLITE" 2>/dev/null; then
|
||||
log_warning "Could not make Plex SQLite executable, but will try to use it"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# Enhanced WAL file management for repair operations
|
||||
handle_wal_files_for_repair() {
|
||||
local db_file="$1"
|
||||
local operation="${2:-prepare}" # prepare, cleanup, or restore
|
||||
|
||||
local db_dir
|
||||
db_dir=$(dirname "$db_file")
|
||||
local db_base
|
||||
db_base=$(basename "$db_file" .db)
|
||||
local wal_file="${db_dir}/${db_base}.db-wal"
|
||||
local shm_file="${db_dir}/${db_base}.db-shm"
|
||||
|
||||
case "$operation" in
|
||||
"prepare")
|
||||
log_message "Preparing WAL files for repair of $(basename "$db_file")"
|
||||
|
||||
# Force WAL checkpoint to consolidate all changes
|
||||
if [[ -f "$wal_file" ]]; then
|
||||
log_info "Found WAL file, performing checkpoint..."
|
||||
if sudo "$PLEX_SQLITE" "$db_file" "PRAGMA wal_checkpoint(TRUNCATE);" 2>/dev/null; then
|
||||
log_success "WAL checkpoint completed"
|
||||
else
|
||||
log_warning "WAL checkpoint failed, but continuing"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Create backup copies of WAL/SHM files if they exist
|
||||
for file in "$wal_file" "$shm_file"; do
|
||||
if [[ -f "$file" ]]; then
|
||||
local backup_file="${file}.repair-backup"
|
||||
if sudo cp "$file" "$backup_file" 2>/dev/null; then
|
||||
log_info "Backed up $(basename "$file")"
|
||||
else
|
||||
log_warning "Failed to backup $(basename "$file")"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
;;
|
||||
|
||||
"cleanup")
|
||||
log_message "Cleaning up WAL files after repair"
|
||||
|
||||
# Remove any remaining WAL/SHM files to force clean state
|
||||
for file in "$wal_file" "$shm_file"; do
|
||||
if [[ -f "$file" ]]; then
|
||||
if sudo rm -f "$file" 2>/dev/null; then
|
||||
log_info "Removed $(basename "$file")"
|
||||
else
|
||||
log_warning "Failed to remove $(basename "$file")"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
# Force WAL mode back on for consistency
|
||||
if sudo "$PLEX_SQLITE" "$db_file" "PRAGMA journal_mode=WAL;" 2>/dev/null | grep -q "wal"; then
|
||||
log_success "WAL mode restored for $(basename "$db_file")"
|
||||
else
|
||||
log_warning "Failed to restore WAL mode for $(basename "$db_file")"
|
||||
fi
|
||||
;;
|
||||
|
||||
"restore")
|
||||
log_message "Restoring WAL files after failed repair"
|
||||
|
||||
# Restore WAL/SHM backup files if they exist
|
||||
for file in "$wal_file" "$shm_file"; do
|
||||
local backup_file="${file}.repair-backup"
|
||||
if [[ -f "$backup_file" ]]; then
|
||||
if sudo mv "$backup_file" "$file" 2>/dev/null; then
|
||||
log_info "Restored $(basename "$file")"
|
||||
else
|
||||
log_warning "Failed to restore $(basename "$file")"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Check database integrity using Plex SQLite
|
||||
check_database_integrity() {
|
||||
local db_file="$1"
|
||||
local db_name
|
||||
db_name=$(basename "$db_file")
|
||||
|
||||
log_message "Checking database integrity: $db_name"
|
||||
|
||||
if ! check_plex_sqlite; then
|
||||
return 2
|
||||
fi
|
||||
|
||||
# Check if WAL file exists and handle it
|
||||
local wal_file="${db_file}-wal"
|
||||
if [[ -f "$wal_file" ]]; then
|
||||
log_info "WAL file found for $db_name, performing checkpoint..."
|
||||
if sudo "$PLEX_SQLITE" "$db_file" "PRAGMA wal_checkpoint(FULL);" 2>/dev/null; then
|
||||
log_success "WAL checkpoint completed for $db_name"
|
||||
else
|
||||
log_warning "WAL checkpoint failed for $db_name, proceeding with integrity check"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Run integrity check
|
||||
local integrity_result
|
||||
integrity_result=$(sudo "$PLEX_SQLITE" "$db_file" "PRAGMA integrity_check;" 2>&1)
|
||||
local check_exit_code=$?
|
||||
|
||||
if [[ $check_exit_code -ne 0 ]]; then
|
||||
log_error "Failed to run integrity check on $db_name: $integrity_result"
|
||||
return 2
|
||||
fi
|
||||
|
||||
if echo "$integrity_result" | grep -q "^ok$"; then
|
||||
log_success "Database integrity check passed: $db_name"
|
||||
return 0
|
||||
else
|
||||
log_warning "Database integrity issues detected in $db_name:"
|
||||
echo "$integrity_result" | while read -r line; do
|
||||
log_warning " $line"
|
||||
done
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Strategy 1: Dump and restore approach with enhanced validation
|
||||
attempt_dump_restore() {
|
||||
local working_copy="$1"
|
||||
local original_db="$2"
|
||||
local timestamp="$3"
|
||||
local dump_file="${original_db}.dump-${timestamp}.sql"
|
||||
local new_db="${original_db}.repaired-${timestamp}"
|
||||
|
||||
log_message "Attempting repair via SQL dump/restore..."
|
||||
|
||||
# Try to dump the database with error checking
|
||||
log_info "Creating database dump..."
|
||||
if sudo "$PLEX_SQLITE" "$working_copy" ".dump" 2>/dev/null | sudo tee "$dump_file" >/dev/null; then
|
||||
# Validate the dump file exists and has substantial content
|
||||
if [[ ! -f "$dump_file" ]]; then
|
||||
log_warning "Dump file was not created"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local dump_size
|
||||
dump_size=$(stat -c%s "$dump_file" 2>/dev/null || echo "0")
|
||||
if [[ "$dump_size" -lt 1024 ]]; then
|
||||
log_warning "Dump file is too small ($dump_size bytes) - likely incomplete"
|
||||
sudo rm -f "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check for essential database structures in dump
|
||||
if ! grep -q "CREATE TABLE" "$dump_file" 2>/dev/null; then
|
||||
log_warning "Dump file contains no CREATE TABLE statements - dump is incomplete"
|
||||
sudo rm -f "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check for critical Plex tables
|
||||
local critical_tables=("schema_migrations" "accounts" "library_sections")
|
||||
local missing_tables=()
|
||||
for table in "${critical_tables[@]}"; do
|
||||
if ! grep -q "CREATE TABLE.*$table" "$dump_file" 2>/dev/null; then
|
||||
missing_tables+=("$table")
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ ${#missing_tables[@]} -gt 0 ]]; then
|
||||
log_warning "Dump is missing critical tables: ${missing_tables[*]}"
|
||||
log_warning "This would result in an incomplete database - aborting dump/restore"
|
||||
sudo rm -f "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "Database dumped successfully (${dump_size} bytes)"
|
||||
log_info "Dump contains all critical tables: ${critical_tables[*]}"
|
||||
|
||||
# Create new database from dump
|
||||
log_info "Creating new database from validated dump..."
|
||||
if sudo cat "$dump_file" | sudo "$PLEX_SQLITE" "$new_db" 2>/dev/null; then
|
||||
# Verify the new database was created and has content
|
||||
if [[ ! -f "$new_db" ]]; then
|
||||
log_warning "New database file was not created"
|
||||
sudo rm -f "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local new_db_size
|
||||
new_db_size=$(stat -c%s "$new_db" 2>/dev/null || echo "0")
|
||||
if [[ "$new_db_size" -lt 1048576 ]]; then # Less than 1MB
|
||||
log_warning "New database is too small ($new_db_size bytes) - likely empty or incomplete"
|
||||
sudo rm -f "$new_db" "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Verify critical tables exist in new database
|
||||
local table_count
|
||||
table_count=$(sudo "$PLEX_SQLITE" "$new_db" "SELECT COUNT(*) FROM sqlite_master WHERE type='table';" 2>/dev/null || echo "0")
|
||||
if [[ "$table_count" -lt 50 ]]; then # Plex should have way more than 50 tables
|
||||
log_warning "New database has too few tables ($table_count) - likely incomplete"
|
||||
sudo rm -f "$new_db" "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Verify schema_migrations table specifically (this was the root cause)
|
||||
if ! sudo "$PLEX_SQLITE" "$new_db" "SELECT COUNT(*) FROM schema_migrations;" >/dev/null 2>&1; then
|
||||
log_warning "New database missing schema_migrations table - Plex will not start"
|
||||
sudo rm -f "$new_db" "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "New database created from dump ($new_db_size bytes, $table_count tables)"
|
||||
|
||||
# Verify the new database passes integrity check
|
||||
log_info "Performing integrity check on repaired database..."
|
||||
if sudo "$PLEX_SQLITE" "$new_db" "PRAGMA integrity_check;" 2>/dev/null | grep -q "ok"; then
|
||||
log_success "New database passes integrity check"
|
||||
|
||||
# Replace original with repaired version
|
||||
log_info "Replacing original database with repaired version..."
|
||||
if sudo mv "$new_db" "$original_db"; then
|
||||
# Force filesystem sync to prevent corruption
|
||||
sync
|
||||
# Fix ownership to plex user
|
||||
sudo chown plex:plex "$original_db"
|
||||
sudo rm -f "$dump_file"
|
||||
return 0
|
||||
else
|
||||
sudo rm -f "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
log_warning "Repaired database failed integrity check"
|
||||
sudo rm -f "$new_db" "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
log_warning "Failed to create database from dump - SQL import failed"
|
||||
sudo rm -f "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
log_warning "Failed to dump corrupted database - dump command failed"
|
||||
# Clean up any potentially created but empty dump file
|
||||
sudo rm -f "$dump_file"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Strategy 2: Schema recreation with data recovery
|
||||
attempt_schema_recreation() {
|
||||
local working_copy="$1"
|
||||
local original_db="$2"
|
||||
local timestamp="$3"
|
||||
local schema_file="${original_db}.schema-${timestamp}.sql"
|
||||
local new_db="${original_db}.rebuilt-${timestamp}"
|
||||
|
||||
log_message "Attempting repair via schema recreation..."
|
||||
|
||||
# Extract schema
|
||||
if sudo "$PLEX_SQLITE" "$working_copy" ".schema" 2>/dev/null | sudo tee "$schema_file" >/dev/null; then
|
||||
log_success "Schema extracted"
|
||||
|
||||
# Create new database with schema
|
||||
if sudo cat "$schema_file" | sudo "$PLEX_SQLITE" "$new_db" 2>/dev/null; then
|
||||
log_success "New database created with schema"
|
||||
|
||||
# Try to recover data table by table
|
||||
if recover_table_data "$working_copy" "$new_db"; then
|
||||
log_success "Data recovery completed"
|
||||
|
||||
# Verify the rebuilt database
|
||||
if sudo "$PLEX_SQLITE" "$new_db" "PRAGMA integrity_check;" 2>/dev/null | grep -q "ok"; then
|
||||
if sudo mv "$new_db" "$original_db"; then
|
||||
sync
|
||||
# Fix ownership to plex user
|
||||
sudo chown plex:plex "$original_db"
|
||||
sudo rm -f "$schema_file"
|
||||
return 0
|
||||
fi
|
||||
else
|
||||
log_warning "Rebuilt database failed integrity check"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
sudo rm -f "$new_db" "$schema_file"
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Strategy 3: Recovery from previous backup
|
||||
attempt_backup_recovery() {
|
||||
local original_db="$1"
|
||||
local backup_dir="$2"
|
||||
local current_backup="$3"
|
||||
|
||||
log_message "Attempting recovery from previous backup..."
|
||||
|
||||
# Find the most recent backup that's not the current corrupted one
|
||||
local latest_backup
|
||||
if [[ -n "$current_backup" ]]; then
|
||||
# Exclude the current backup from consideration
|
||||
latest_backup=$(find "$backup_dir" -name "plex-backup-*.tar.gz" -type f ! -samefile "$current_backup" -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2-)
|
||||
else
|
||||
latest_backup=$(find "$backup_dir" -name "plex-backup-*.tar.gz" -type f -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2-)
|
||||
fi
|
||||
|
||||
if [[ -n "$latest_backup" && -f "$latest_backup" ]]; then
|
||||
log_message "Found recent backup: $(basename "$latest_backup")"
|
||||
|
||||
local temp_restore_dir="/tmp/plex-restore-$$"
|
||||
mkdir -p "$temp_restore_dir"
|
||||
|
||||
# Extract the backup
|
||||
if tar -xzf "$latest_backup" -C "$temp_restore_dir" 2>/dev/null; then
|
||||
local restored_db
|
||||
restored_db="${temp_restore_dir}/$(basename "$original_db")"
|
||||
|
||||
if [[ -f "$restored_db" ]]; then
|
||||
# Verify the restored database
|
||||
if sudo "$PLEX_SQLITE" "$restored_db" "PRAGMA integrity_check;" 2>/dev/null | grep -q "ok"; then
|
||||
if sudo cp "$restored_db" "$original_db"; then
|
||||
sync
|
||||
# Fix ownership to plex user
|
||||
sudo chown plex:plex "$original_db"
|
||||
rm -rf "$temp_restore_dir"
|
||||
return 0
|
||||
fi
|
||||
else
|
||||
log_warning "Backup database also corrupted"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
rm -rf "$temp_restore_dir"
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Recovery helper for table data
|
||||
recover_table_data() {
|
||||
local source_db="$1"
|
||||
local target_db="$2"
|
||||
|
||||
# Get list of tables
|
||||
local tables
|
||||
tables=$(sudo "$PLEX_SQLITE" "$source_db" ".tables" 2>/dev/null)
|
||||
|
||||
if [[ -z "$tables" ]]; then
|
||||
log_warning "No tables found in source database"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local recovered_count=0
|
||||
local total_tables=0
|
||||
|
||||
for table in $tables; do
|
||||
((total_tables++))
|
||||
|
||||
# Try to copy data from each table
|
||||
if sudo "$PLEX_SQLITE" "$source_db" ".mode insert $table" ".output | sudo tee /tmp/table_data_$$.sql > /dev/null" "SELECT * FROM $table;" ".output stdout" 2>/dev/null && \
|
||||
sudo cat "/tmp/table_data_$$.sql" | sudo "$PLEX_SQLITE" "$target_db" 2>/dev/null; then
|
||||
((recovered_count++))
|
||||
sudo rm -f "/tmp/table_data_$$.sql" 2>/dev/null || true
|
||||
else
|
||||
log_warning "Failed to recover data from table: $table"
|
||||
sudo rm -f "/tmp/table_data_$$.sql" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
log_message "Recovered $recovered_count/$total_tables tables"
|
||||
|
||||
# Consider successful if we recovered at least 80% of tables
|
||||
if [[ "$total_tables" -eq 0 ]]; then
|
||||
log_warning "No tables found for recovery"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if (( recovered_count * 100 / total_tables >= 80 )); then
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Cleanup helper function
|
||||
cleanup_repair_files() {
|
||||
local pre_repair_backup="$1"
|
||||
local working_copy="$2"
|
||||
|
||||
if [[ -n "$pre_repair_backup" && -f "$pre_repair_backup" ]]; then
|
||||
sudo rm -f "$pre_repair_backup" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [[ -n "$working_copy" && -f "$working_copy" ]]; then
|
||||
sudo rm -f "$working_copy" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
# Enhanced database repair with multiple recovery strategies
|
||||
repair_database() {
|
||||
local db_file="$1"
|
||||
local force_repair="${2:-false}"
|
||||
local db_name
|
||||
db_name=$(basename "$db_file")
|
||||
local timestamp
|
||||
timestamp=$(date "+%Y-%m-%d_%H.%M.%S")
|
||||
|
||||
if ! check_plex_sqlite; then
|
||||
return 2
|
||||
fi
|
||||
|
||||
log_message "Attempting to repair corrupted database: $db_name"
|
||||
|
||||
# Enhanced WAL file handling for repair
|
||||
handle_wal_files_for_repair "$db_file" "prepare"
|
||||
|
||||
# Create multiple backup copies before attempting repair
|
||||
local pre_repair_backup="${db_file}.pre-repair-backup"
|
||||
local working_copy="${db_file}.working-${timestamp}"
|
||||
|
||||
if ! sudo cp "$db_file" "$pre_repair_backup"; then
|
||||
log_error "Failed to create pre-repair backup"
|
||||
handle_wal_files_for_repair "$db_file" "restore"
|
||||
return 2
|
||||
fi
|
||||
# Force filesystem sync to prevent corruption
|
||||
sync
|
||||
|
||||
if ! sudo cp "$db_file" "$working_copy"; then
|
||||
log_error "Failed to create working copy"
|
||||
handle_wal_files_for_repair "$db_file" "restore"
|
||||
return 2
|
||||
fi
|
||||
# Force filesystem sync to prevent corruption
|
||||
sync
|
||||
|
||||
log_success "Created pre-repair backup: $(basename "$pre_repair_backup")"
|
||||
|
||||
# Strategy 1: Try dump and restore approach
|
||||
log_message "Step 1: Database cleanup and optimization..."
|
||||
if attempt_dump_restore "$working_copy" "$db_file" "$timestamp"; then
|
||||
log_success "Database repaired using dump/restore method"
|
||||
handle_wal_files_for_repair "$db_file" "cleanup"
|
||||
cleanup_repair_files "$pre_repair_backup" "$working_copy"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Strategy 2: Try schema recreation
|
||||
if attempt_schema_recreation "$working_copy" "$db_file" "$timestamp"; then
|
||||
log_success "Database repaired using schema recreation"
|
||||
handle_wal_files_for_repair "$db_file" "cleanup"
|
||||
cleanup_repair_files "$pre_repair_backup" "$working_copy"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Strategy 3: Try recovery from previous backup
|
||||
if attempt_backup_recovery "$db_file" "$BACKUP_ROOT" "$pre_repair_backup"; then
|
||||
log_success "Database recovered from previous backup"
|
||||
handle_wal_files_for_repair "$db_file" "cleanup"
|
||||
cleanup_repair_files "$pre_repair_backup" "$working_copy"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# All strategies failed - restore original and flag for manual intervention
|
||||
log_error "Database repair failed. Restoring original..."
|
||||
if sudo cp "$pre_repair_backup" "$db_file"; then
|
||||
# Force filesystem sync to prevent corruption
|
||||
sync
|
||||
log_success "Original database restored"
|
||||
handle_wal_files_for_repair "$db_file" "restore"
|
||||
else
|
||||
log_error "Failed to restore original database!"
|
||||
handle_wal_files_for_repair "$db_file" "restore"
|
||||
cleanup_repair_files "$pre_repair_backup" "$working_copy"
|
||||
return 2
|
||||
fi
|
||||
|
||||
log_error "Database repair failed for $db_name"
|
||||
log_warning "Will backup corrupted database - manual intervention may be needed"
|
||||
cleanup_repair_files "$pre_repair_backup" "$working_copy"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Main function
|
||||
main() {
|
||||
local action="$1"
|
||||
local db_file="$2"
|
||||
local force_repair=false
|
||||
|
||||
# Parse arguments
|
||||
case "$action" in
|
||||
"check")
|
||||
if [[ -z "$db_file" ]]; then
|
||||
log_error "Usage: $0 check <database_file>"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ ! -f "$db_file" ]]; then
|
||||
log_error "Database file not found: $db_file"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
check_database_integrity "$db_file"
|
||||
exit $?
|
||||
;;
|
||||
"repair")
|
||||
if [[ -z "$db_file" ]]; then
|
||||
log_error "Usage: $0 repair <database_file>"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ ! -f "$db_file" ]]; then
|
||||
log_error "Database file not found: $db_file"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
repair_database "$db_file" "$force_repair"
|
||||
exit $?
|
||||
;;
|
||||
"force-repair")
|
||||
force_repair=true
|
||||
if [[ -z "$db_file" ]]; then
|
||||
log_error "Usage: $0 force-repair <database_file>"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ ! -f "$db_file" ]]; then
|
||||
log_error "Database file not found: $db_file"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
repair_database "$db_file" "$force_repair"
|
||||
exit $?
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {check|repair|force-repair} <database_file>"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " check <db_file> Check database integrity only"
|
||||
echo " repair <db_file> Attempt to repair corrupted database"
|
||||
echo " force-repair <db_file> Force repair without prompts"
|
||||
echo ""
|
||||
echo "Exit codes:"
|
||||
echo " 0 - Success (database is healthy or successfully repaired)"
|
||||
echo " 1 - Database has issues but repair failed"
|
||||
echo " 2 - Critical error (cannot access database or repair tools)"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Run main function if script is executed directly
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
||||
706
plex/deprecated/recover-plex-database.sh
Executable file
706
plex/deprecated/recover-plex-database.sh
Executable file
@@ -0,0 +1,706 @@
|
||||
#!/bin/bash
|
||||
|
||||
################################################################################
|
||||
# Advanced Plex Database Recovery Script
|
||||
################################################################################
|
||||
#
|
||||
# Author: Peter Wood <peter@peterwood.dev>
|
||||
# Description: Advanced database recovery script with multiple repair strategies
|
||||
# for corrupted Plex databases. Implements progressive recovery
|
||||
# techniques from gentle repairs to aggressive reconstruction
|
||||
# methods, with comprehensive logging and rollback capabilities.
|
||||
#
|
||||
# Features:
|
||||
# - Progressive recovery strategy (gentle to aggressive)
|
||||
# - Multiple repair techniques (VACUUM, dump/restore, rebuild)
|
||||
# - Automatic backup before any recovery attempts
|
||||
# - Database integrity verification at each step
|
||||
# - Rollback capability if recovery fails
|
||||
# - Dry-run mode for safe testing
|
||||
# - Comprehensive logging and reporting
|
||||
#
|
||||
# Related Scripts:
|
||||
# - backup-plex.sh: Creates backups for recovery scenarios
|
||||
# - icu-aware-recovery.sh: ICU-specific recovery methods
|
||||
# - nuclear-plex-recovery.sh: Last-resort complete replacement
|
||||
# - validate-plex-recovery.sh: Validates recovery results
|
||||
# - restore-plex.sh: Standard restoration from backups
|
||||
# - plex.sh: General Plex service management
|
||||
#
|
||||
# Usage:
|
||||
# ./recover-plex-database.sh # Interactive recovery
|
||||
# ./recover-plex-database.sh --auto # Automated recovery
|
||||
# ./recover-plex-database.sh --dry-run # Show recovery plan
|
||||
# ./recover-plex-database.sh --gentle # Gentle repair only
|
||||
# ./recover-plex-database.sh --aggressive # Aggressive repair methods
|
||||
#
|
||||
# Dependencies:
|
||||
# - sqlite3 or Plex SQLite binary
|
||||
# - systemctl (for service management)
|
||||
# - Sufficient disk space for backups and temp files
|
||||
#
|
||||
# Exit Codes:
|
||||
# 0 - Recovery successful
|
||||
# 1 - General error
|
||||
# 2 - Database corruption beyond repair
|
||||
# 3 - Service management failure
|
||||
# 4 - Insufficient disk space
|
||||
# 5 - Recovery partially successful (manual intervention needed)
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# Advanced Plex Database Recovery Script
|
||||
# Usage: ./recover-plex-database.sh [--auto] [--dry-run]
|
||||
|
||||
set -e
|
||||
|
||||
# Color codes for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Configuration
|
||||
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
|
||||
PLEX_DB_DIR="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases"
|
||||
MAIN_DB="com.plexapp.plugins.library.db"
|
||||
PLEX_SQLITE="/usr/lib/plexmediaserver/Plex SQLite"
|
||||
BACKUP_SUFFIX="recovery-$(date +%Y%m%d_%H%M%S)"
|
||||
RECOVERY_LOG="$SCRIPT_DIR/logs/database-recovery-$(date +%Y%m%d_%H%M%S).log"
|
||||
|
||||
# Script options
|
||||
AUTO_MODE=false
|
||||
DRY_RUN=false
|
||||
|
||||
# Ensure logs directory exists
|
||||
mkdir -p "$SCRIPT_DIR/logs"
|
||||
|
||||
# Logging function
|
||||
log_message() {
|
||||
local message
|
||||
message="[$(date '+%Y-%m-%d %H:%M:%S')] $1"
|
||||
echo -e "$message"
|
||||
echo "$message" >> "$RECOVERY_LOG"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
log_message "${GREEN}SUCCESS: $1${NC}"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
log_message "${RED}ERROR: $1${NC}"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
log_message "${YELLOW}WARNING: $1${NC}"
|
||||
}
|
||||
|
||||
log_info() {
|
||||
log_message "${BLUE}INFO: $1${NC}"
|
||||
}
|
||||
|
||||
# Parse command line arguments
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--auto)
|
||||
AUTO_MODE=true
|
||||
shift
|
||||
;;
|
||||
--dry-run)
|
||||
DRY_RUN=true
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [--auto] [--dry-run] [--help]"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " --auto Automatically attempt all recovery methods without prompts"
|
||||
echo " --dry-run Show what would be done without making changes"
|
||||
echo " --help Show this help message"
|
||||
echo ""
|
||||
echo "Recovery Methods (in order):"
|
||||
echo " 1. SQLite .recover command (modern SQLite recovery)"
|
||||
echo " 2. Partial table extraction with LIMIT"
|
||||
echo " 3. Emergency data extraction"
|
||||
echo " 4. Backup restoration from most recent good backup"
|
||||
echo ""
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
log_error "Unknown option: $1"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Check dependencies
|
||||
check_dependencies() {
|
||||
log_info "Checking dependencies..."
|
||||
|
||||
if [ ! -f "$PLEX_SQLITE" ]; then
|
||||
log_error "Plex SQLite binary not found at: $PLEX_SQLITE"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! command -v sqlite3 >/dev/null 2>&1; then
|
||||
log_error "Standard sqlite3 command not found"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Make Plex SQLite executable
|
||||
sudo chmod +x "$PLEX_SQLITE" 2>/dev/null || true
|
||||
|
||||
log_success "Dependencies check passed"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Stop Plex service safely
|
||||
stop_plex_service() {
|
||||
log_info "Stopping Plex Media Server..."
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
log_info "DRY RUN: Would stop Plex service"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if sudo systemctl is-active --quiet plexmediaserver; then
|
||||
sudo systemctl stop plexmediaserver
|
||||
|
||||
# Wait for service to fully stop
|
||||
local timeout=30
|
||||
while sudo systemctl is-active --quiet plexmediaserver && [ $timeout -gt 0 ]; do
|
||||
sleep 1
|
||||
timeout=$((timeout - 1))
|
||||
done
|
||||
|
||||
if sudo systemctl is-active --quiet plexmediaserver; then
|
||||
log_error "Failed to stop Plex service within timeout"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "Plex service stopped successfully"
|
||||
else
|
||||
log_info "Plex service was already stopped"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# Start Plex service
|
||||
start_plex_service() {
|
||||
log_info "Starting Plex Media Server..."
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
log_info "DRY RUN: Would start Plex service"
|
||||
return 0
|
||||
fi
|
||||
|
||||
sudo systemctl start plexmediaserver
|
||||
|
||||
# Wait for service to start
|
||||
local timeout=30
|
||||
while ! sudo systemctl is-active --quiet plexmediaserver && [ $timeout -gt 0 ]; do
|
||||
sleep 1
|
||||
timeout=$((timeout - 1))
|
||||
done
|
||||
|
||||
if sudo systemctl is-active --quiet plexmediaserver; then
|
||||
log_success "Plex service started successfully"
|
||||
else
|
||||
log_warning "Plex service may not have started properly"
|
||||
fi
|
||||
}
|
||||
|
||||
# Check database integrity
|
||||
check_database_integrity() {
|
||||
local db_file="$1"
|
||||
local db_name
|
||||
db_name=$(basename "$db_file")
|
||||
|
||||
log_info "Checking integrity of $db_name..."
|
||||
|
||||
if [ ! -f "$db_file" ]; then
|
||||
log_error "Database file not found: $db_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local integrity_result
|
||||
integrity_result=$(sudo "$PLEX_SQLITE" "$db_file" "PRAGMA integrity_check;" 2>&1)
|
||||
local check_exit_code=$?
|
||||
|
||||
if [ $check_exit_code -ne 0 ]; then
|
||||
log_error "Failed to run integrity check on $db_name"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if echo "$integrity_result" | grep -q "^ok$"; then
|
||||
log_success "Database integrity check passed: $db_name"
|
||||
return 0
|
||||
else
|
||||
log_warning "Database integrity issues detected in $db_name:"
|
||||
echo "$integrity_result" | while IFS= read -r line; do
|
||||
log_warning " $line"
|
||||
done
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Recovery Method 1: SQLite .recover command
|
||||
recovery_method_sqlite_recover() {
|
||||
local db_file="$1"
|
||||
local db_name
|
||||
db_name=$(basename "$db_file")
|
||||
local recovered_sql="${db_file}.recovered.sql"
|
||||
local new_db="${db_file}.recovered"
|
||||
|
||||
log_info "Recovery Method 1: SQLite .recover command for $db_name"
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
log_info "DRY RUN: Would attempt SQLite .recover method"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check if .recover is available (SQLite 3.37.0+)
|
||||
if ! echo ".help" | sqlite3 2>/dev/null | grep -q "\.recover"; then
|
||||
log_warning "SQLite .recover command not available in this version"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "Attempting SQLite .recover method..."
|
||||
|
||||
# Use standard sqlite3 for .recover as it's more reliable
|
||||
if sqlite3 "$db_file" ".recover" > "$recovered_sql" 2>/dev/null; then
|
||||
log_success "Recovery SQL generated successfully"
|
||||
|
||||
# Create new database from recovered data
|
||||
if [ -f "$recovered_sql" ] && [ -s "$recovered_sql" ]; then
|
||||
if sqlite3 "$new_db" < "$recovered_sql" 2>/dev/null; then
|
||||
log_success "New database created from recovered data"
|
||||
|
||||
# Verify new database integrity
|
||||
if sqlite3 "$new_db" "PRAGMA integrity_check;" | grep -q "ok"; then
|
||||
log_success "Recovered database integrity verified"
|
||||
|
||||
# Replace original with recovered database
|
||||
if sudo mv "$db_file" "${db_file}.corrupted" && sudo mv "$new_db" "$db_file"; then
|
||||
sudo chown plex:plex "$db_file"
|
||||
sudo chmod 644 "$db_file"
|
||||
log_success "Database successfully recovered using .recover method"
|
||||
|
||||
# Clean up
|
||||
rm -f "$recovered_sql"
|
||||
|
||||
return 0
|
||||
else
|
||||
log_error "Failed to replace original database"
|
||||
fi
|
||||
else
|
||||
log_error "Recovered database failed integrity check"
|
||||
fi
|
||||
else
|
||||
log_error "Failed to create database from recovered SQL"
|
||||
fi
|
||||
else
|
||||
log_error "Recovery SQL file is empty or not generated"
|
||||
fi
|
||||
else
|
||||
log_error "SQLite .recover command failed"
|
||||
fi
|
||||
|
||||
# Clean up on failure
|
||||
rm -f "$recovered_sql" "$new_db"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Recovery Method 2: Partial table extraction
|
||||
recovery_method_partial_extraction() {
|
||||
local db_file="$1"
|
||||
local db_name
|
||||
db_name=$(basename "$db_file")
|
||||
local partial_sql="${db_file}.partial.sql"
|
||||
local new_db="${db_file}.partial"
|
||||
|
||||
log_info "Recovery Method 2: Partial table extraction for $db_name"
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
log_info "DRY RUN: Would attempt partial extraction method"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "Extracting schema and partial data..."
|
||||
|
||||
# Start the SQL file with schema
|
||||
{
|
||||
echo "-- Partial recovery of $db_name"
|
||||
echo "-- Generated on $(date)"
|
||||
echo ""
|
||||
} > "$partial_sql"
|
||||
|
||||
# Extract schema
|
||||
if sudo "$PLEX_SQLITE" "$db_file" ".schema" | sudo tee -a "$partial_sql" >/dev/null 2>&1; then
|
||||
log_success "Schema extracted successfully"
|
||||
else
|
||||
log_warning "Schema extraction failed, trying alternative method"
|
||||
# Try with standard sqlite3
|
||||
if sqlite3 "$db_file" ".schema" >> "$partial_sql" 2>/dev/null; then
|
||||
log_success "Schema extracted with standard sqlite3"
|
||||
else
|
||||
log_error "Schema extraction failed completely"
|
||||
rm -f "$partial_sql"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Critical tables to extract (in order of importance)
|
||||
local critical_tables=(
|
||||
"accounts"
|
||||
"library_sections"
|
||||
"directories"
|
||||
"metadata_items"
|
||||
"media_items"
|
||||
"media_parts"
|
||||
"media_streams"
|
||||
"taggings"
|
||||
"tags"
|
||||
)
|
||||
|
||||
log_info "Attempting to extract critical tables..."
|
||||
|
||||
for table in "${critical_tables[@]}"; do
|
||||
log_info "Extracting table: $table"
|
||||
|
||||
# Try to extract with LIMIT to avoid hitting corrupted data
|
||||
local extract_success=false
|
||||
local limit=10000
|
||||
|
||||
while [ "$limit" -le 100000 ] && [ "$extract_success" = false ]; do
|
||||
if sudo "$PLEX_SQLITE" "$db_file" "SELECT COUNT(*) FROM $table;" >/dev/null 2>&1; then
|
||||
# Table exists and is readable
|
||||
{
|
||||
echo ""
|
||||
echo "-- Data for table $table (limited to $limit rows)"
|
||||
echo "DELETE FROM $table;"
|
||||
} >> "$partial_sql"
|
||||
|
||||
if sudo "$PLEX_SQLITE" "$db_file" ".mode insert $table" >>/dev/null 2>&1 && \
|
||||
sudo "$PLEX_SQLITE" "$db_file" "SELECT * FROM $table LIMIT $limit;" | sudo tee -a "$partial_sql" >/dev/null 2>&1; then
|
||||
local row_count
|
||||
row_count=$(tail -n +3 "$partial_sql" | grep -c "INSERT INTO $table")
|
||||
log_success "Extracted $row_count rows from $table"
|
||||
extract_success=true
|
||||
else
|
||||
log_warning "Failed to extract $table with limit $limit, trying smaller limit"
|
||||
limit=$((limit / 2))
|
||||
fi
|
||||
else
|
||||
log_warning "Table $table is not accessible or doesn't exist"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$extract_success" = false ]; then
|
||||
log_warning "Could not extract any data from table $table"
|
||||
fi
|
||||
done
|
||||
|
||||
# Create new database from partial data
|
||||
if [ -f "$partial_sql" ] && [ -s "$partial_sql" ]; then
|
||||
log_info "Creating database from partial extraction..."
|
||||
|
||||
if sqlite3 "$new_db" < "$partial_sql" 2>/dev/null; then
|
||||
log_success "Partial database created successfully"
|
||||
|
||||
# Verify basic functionality
|
||||
if sqlite3 "$new_db" "PRAGMA integrity_check;" | grep -q "ok"; then
|
||||
log_success "Partial database integrity verified"
|
||||
|
||||
# Replace original with partial database
|
||||
if sudo mv "$db_file" "${db_file}.corrupted" && sudo mv "$new_db" "$db_file"; then
|
||||
sudo chown plex:plex "$db_file"
|
||||
sudo chmod 644 "$db_file"
|
||||
log_success "Database partially recovered - some data may be lost"
|
||||
log_warning "Please verify your Plex library after recovery"
|
||||
|
||||
# Clean up
|
||||
rm -f "$partial_sql"
|
||||
|
||||
return 0
|
||||
else
|
||||
log_error "Failed to replace original database"
|
||||
fi
|
||||
else
|
||||
log_error "Partial database failed integrity check"
|
||||
fi
|
||||
else
|
||||
log_error "Failed to create database from partial extraction"
|
||||
fi
|
||||
else
|
||||
log_error "Partial extraction SQL file is empty"
|
||||
fi
|
||||
|
||||
# Clean up on failure
|
||||
rm -f "$partial_sql" "$new_db"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Recovery Method 3: Emergency data extraction
|
||||
recovery_method_emergency_extraction() {
|
||||
local db_file="$1"
|
||||
local db_name
|
||||
db_name=$(basename "$db_file")
|
||||
|
||||
log_info "Recovery Method 3: Emergency data extraction for $db_name"
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
log_info "DRY RUN: Would attempt emergency extraction method"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_warning "This method will create a minimal database with basic library structure"
|
||||
log_warning "You will likely need to re-scan your media libraries"
|
||||
|
||||
if [ "$AUTO_MODE" = false ]; then
|
||||
read -p "Continue with emergency extraction? This will lose most metadata [y/N]: " -n 1 -r
|
||||
echo
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
log_info "Emergency extraction cancelled by user"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
local emergency_db="${db_file}.emergency"
|
||||
|
||||
# Create a minimal database with essential tables
|
||||
log_info "Creating minimal emergency database..."
|
||||
|
||||
cat > "/tmp/emergency_schema.sql" << 'EOF'
|
||||
-- Emergency Plex database schema (minimal)
|
||||
CREATE TABLE accounts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT,
|
||||
hashed_password TEXT,
|
||||
salt TEXT,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME
|
||||
);
|
||||
|
||||
CREATE TABLE library_sections (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT,
|
||||
section_type INTEGER,
|
||||
agent TEXT,
|
||||
scanner TEXT,
|
||||
language TEXT,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME
|
||||
);
|
||||
|
||||
CREATE TABLE directories (
|
||||
id INTEGER PRIMARY KEY,
|
||||
library_section_id INTEGER,
|
||||
path TEXT,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME
|
||||
);
|
||||
|
||||
-- Insert default admin account
|
||||
INSERT INTO accounts (id, name, created_at, updated_at)
|
||||
VALUES (1, 'plex', datetime('now'), datetime('now'));
|
||||
EOF
|
||||
|
||||
if sqlite3 "$emergency_db" < "/tmp/emergency_schema.sql" 2>/dev/null; then
|
||||
log_success "Emergency database created"
|
||||
|
||||
# Replace original with emergency database
|
||||
if sudo mv "$db_file" "${db_file}.corrupted" && sudo mv "$emergency_db" "$db_file"; then
|
||||
sudo chown plex:plex "$db_file"
|
||||
sudo chmod 644 "$db_file"
|
||||
log_success "Emergency database installed"
|
||||
log_warning "You will need to re-add library sections and re-scan media"
|
||||
|
||||
# Clean up
|
||||
rm -f "/tmp/emergency_schema.sql"
|
||||
|
||||
return 0
|
||||
else
|
||||
log_error "Failed to install emergency database"
|
||||
fi
|
||||
else
|
||||
log_error "Failed to create emergency database"
|
||||
fi
|
||||
|
||||
# Clean up on failure
|
||||
rm -f "/tmp/emergency_schema.sql" "$emergency_db"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Recovery Method 4: Restore from backup
|
||||
recovery_method_backup_restore() {
|
||||
local db_file="$1"
|
||||
local backup_dir="/mnt/share/media/backups/plex"
|
||||
|
||||
log_info "Recovery Method 4: Restore from most recent backup"
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
log_info "DRY RUN: Would attempt backup restoration"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Find most recent backup
|
||||
local latest_backup
|
||||
latest_backup=$(find "$backup_dir" -maxdepth 1 -name "plex-backup-*.tar.gz" -type f 2>/dev/null | sort -r | head -1)
|
||||
|
||||
if [ -z "$latest_backup" ]; then
|
||||
log_error "No backup files found in $backup_dir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "Found latest backup: $(basename "$latest_backup")"
|
||||
|
||||
if [ "$AUTO_MODE" = false ]; then
|
||||
read -p "Restore from backup $(basename "$latest_backup")? [y/N]: " -n 1 -r
|
||||
echo
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
log_info "Backup restoration cancelled by user"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Extract and restore database from backup
|
||||
local temp_extract="/tmp/plex-recovery-extract-$(date +%Y%m%d_%H%M%S)"
|
||||
mkdir -p "$temp_extract"
|
||||
|
||||
log_info "Extracting backup..."
|
||||
if tar -xzf "$latest_backup" -C "$temp_extract" 2>/dev/null; then
|
||||
local backup_db_file="$temp_extract/$(basename "$db_file")"
|
||||
|
||||
if [ -f "$backup_db_file" ]; then
|
||||
# Verify backup database integrity
|
||||
if sqlite3 "$backup_db_file" "PRAGMA integrity_check;" | grep -q "ok"; then
|
||||
log_success "Backup database integrity verified"
|
||||
|
||||
# Replace corrupted database with backup
|
||||
if sudo mv "$db_file" "${db_file}.corrupted" && sudo cp "$backup_db_file" "$db_file"; then
|
||||
sudo chown plex:plex "$db_file"
|
||||
sudo chmod 644 "$db_file"
|
||||
log_success "Database restored from backup"
|
||||
|
||||
# Clean up
|
||||
rm -rf "$temp_extract"
|
||||
|
||||
return 0
|
||||
else
|
||||
log_error "Failed to replace database with backup"
|
||||
fi
|
||||
else
|
||||
log_error "Backup database also has integrity issues"
|
||||
fi
|
||||
else
|
||||
log_error "Database file not found in backup"
|
||||
fi
|
||||
else
|
||||
log_error "Failed to extract backup"
|
||||
fi
|
||||
|
||||
# Clean up on failure
|
||||
rm -rf "$temp_extract"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Main recovery function
|
||||
main_recovery() {
|
||||
local db_file="$PLEX_DB_DIR/$MAIN_DB"
|
||||
|
||||
log_info "Starting Plex database recovery process"
|
||||
log_info "Recovery log: $RECOVERY_LOG"
|
||||
|
||||
# Check dependencies
|
||||
if ! check_dependencies; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Stop Plex service
|
||||
if ! stop_plex_service; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Change to database directory
|
||||
cd "$PLEX_DB_DIR" || {
|
||||
log_error "Failed to change to database directory"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Check if database exists
|
||||
if [ ! -f "$MAIN_DB" ]; then
|
||||
log_error "Main database file not found: $MAIN_DB"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create backup of current corrupted state
|
||||
log_info "Creating backup of current corrupted database..."
|
||||
if [ "$DRY_RUN" = false ]; then
|
||||
sudo cp "$MAIN_DB" "${MAIN_DB}.${BACKUP_SUFFIX}"
|
||||
log_success "Corrupted database backed up as: ${MAIN_DB}.${BACKUP_SUFFIX}"
|
||||
fi
|
||||
|
||||
# Check current integrity
|
||||
log_info "Verifying database corruption..."
|
||||
if check_database_integrity "$MAIN_DB"; then
|
||||
log_success "Database integrity check passed - no recovery needed!"
|
||||
start_plex_service
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log_warning "Database corruption confirmed, attempting recovery..."
|
||||
|
||||
# Try recovery methods in order
|
||||
local recovery_methods=(
|
||||
"recovery_method_sqlite_recover"
|
||||
"recovery_method_partial_extraction"
|
||||
"recovery_method_emergency_extraction"
|
||||
"recovery_method_backup_restore"
|
||||
)
|
||||
|
||||
for method in "${recovery_methods[@]}"; do
|
||||
log_info "Attempting: $method"
|
||||
|
||||
if $method "$MAIN_DB"; then
|
||||
log_success "Recovery successful using: $method"
|
||||
|
||||
# Verify the recovered database
|
||||
if check_database_integrity "$MAIN_DB"; then
|
||||
log_success "Recovered database integrity verified"
|
||||
start_plex_service
|
||||
log_success "Database recovery completed successfully!"
|
||||
log_info "Please check your Plex server and verify your libraries"
|
||||
exit 0
|
||||
else
|
||||
log_error "Recovered database still has integrity issues"
|
||||
# Restore backup for next attempt
|
||||
if [ "$DRY_RUN" = false ]; then
|
||||
sudo cp "${MAIN_DB}.${BACKUP_SUFFIX}" "$MAIN_DB"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
log_warning "Recovery method failed: $method"
|
||||
fi
|
||||
done
|
||||
|
||||
log_error "All recovery methods failed"
|
||||
log_error "Manual intervention required"
|
||||
|
||||
# Restore original corrupted database
|
||||
if [ "$DRY_RUN" = false ]; then
|
||||
sudo cp "${MAIN_DB}.${BACKUP_SUFFIX}" "$MAIN_DB"
|
||||
fi
|
||||
|
||||
start_plex_service
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Trap to ensure Plex service is restarted
|
||||
trap 'start_plex_service' EXIT
|
||||
|
||||
# Run main recovery
|
||||
main_recovery "$@"
|
||||
313
plex/deprecated/restore-plex.sh
Executable file
313
plex/deprecated/restore-plex.sh
Executable file
@@ -0,0 +1,313 @@
|
||||
#!/bin/bash
|
||||
|
||||
################################################################################
|
||||
# Plex Media Server Backup Restoration Script
|
||||
################################################################################
|
||||
#
|
||||
# Author: Peter Wood <peter@peterwood.dev>
|
||||
# Description: Safe and reliable restoration script for Plex Media Server
|
||||
# backups with validation, dry-run capability, and automatic
|
||||
# backup of current data before restoration.
|
||||
#
|
||||
# Features:
|
||||
# - Interactive backup selection from available archives
|
||||
# - Backup validation before restoration
|
||||
# - Dry-run mode for testing restoration process
|
||||
# - Automatic backup of current data before restoration
|
||||
# - Service management (stop/start Plex during restoration)
|
||||
# - Comprehensive logging and error handling
|
||||
# - File ownership and permission restoration
|
||||
#
|
||||
# Related Scripts:
|
||||
# - backup-plex.sh: Creates backups that this script restores
|
||||
# - validate-plex-backups.sh: Validates backup integrity
|
||||
# - monitor-plex-backup.sh: Monitors backup system health
|
||||
# - test-plex-backup.sh: Tests backup/restore operations
|
||||
# - plex.sh: General Plex service management
|
||||
#
|
||||
# Usage:
|
||||
# ./restore-plex.sh # List available backups
|
||||
# ./restore-plex.sh plex-backup-20250125_143022.tar.gz # Restore specific backup
|
||||
# ./restore-plex.sh --dry-run backup-file.tar.gz # Test restoration process
|
||||
# ./restore-plex.sh --list # List all available backups
|
||||
#
|
||||
# Dependencies:
|
||||
# - tar (for archive extraction)
|
||||
# - Plex Media Server
|
||||
# - systemctl (for service management)
|
||||
# - Access to backup directory
|
||||
#
|
||||
# Exit Codes:
|
||||
# 0 - Success
|
||||
# 1 - General error
|
||||
# 2 - Backup file not found or invalid
|
||||
# 3 - Service management failure
|
||||
# 4 - Restoration failure
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# Plex Backup Restoration Script
|
||||
# Usage: ./restore-plex.sh [backup_date] [--dry-run]
|
||||
|
||||
set -e
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m'
|
||||
|
||||
# Configuration
|
||||
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
|
||||
BACKUP_ROOT="/mnt/share/media/backups/plex"
|
||||
PLEX_DATA_DIR="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server"
|
||||
|
||||
# Plex file locations
|
||||
declare -A RESTORE_LOCATIONS=(
|
||||
["com.plexapp.plugins.library.db"]="$PLEX_DATA_DIR/Plug-in Support/Databases/"
|
||||
["com.plexapp.plugins.library.blobs.db"]="$PLEX_DATA_DIR/Plug-in Support/Databases/"
|
||||
["Preferences.xml"]="$PLEX_DATA_DIR/"
|
||||
)
|
||||
|
||||
log_message() {
|
||||
echo -e "$(date '+%H:%M:%S') $1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
log_message "${RED}ERROR: $1${NC}"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
log_message "${GREEN}SUCCESS: $1${NC}"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
log_message "${YELLOW}WARNING: $1${NC}"
|
||||
}
|
||||
|
||||
# List available backups
|
||||
list_backups() {
|
||||
log_message "Available backups:"
|
||||
find "$BACKUP_ROOT" -maxdepth 1 -type f -name "plex-backup-*.tar.gz" | sort -r | while read -r backup_file; do
|
||||
local backup_name
|
||||
backup_name=$(basename "$backup_file")
|
||||
local backup_date
|
||||
backup_date=${backup_name#plex-backup-}
|
||||
backup_date=${backup_date%_*.tar.gz}
|
||||
if [[ "$backup_date" =~ ^[0-9]{8}$ ]]; then
|
||||
local readable_date
|
||||
readable_date=$(date -d "${backup_date:0:4}-${backup_date:4:2}-${backup_date:6:2}" '+%B %d, %Y' 2>/dev/null || echo "Unknown date")
|
||||
local file_size
|
||||
file_size=$(du -h "$backup_file" 2>/dev/null | cut -f1)
|
||||
echo " $backup_name ($readable_date) - $file_size"
|
||||
else
|
||||
echo " $backup_name - $(du -h "$backup_file" 2>/dev/null | cut -f1)"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Validate backup integrity
|
||||
validate_backup() {
|
||||
local backup_file="$1"
|
||||
|
||||
if [ ! -f "$backup_file" ]; then
|
||||
log_error "Backup file not found: $backup_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_message "Validating backup integrity for $(basename "$backup_file")..."
|
||||
|
||||
# Test archive integrity
|
||||
if tar -tzf "$backup_file" >/dev/null 2>&1; then
|
||||
log_success "Archive integrity check passed"
|
||||
|
||||
# List contents to verify expected files are present
|
||||
log_message "Archive contents:"
|
||||
tar -tzf "$backup_file" | while read -r file; do
|
||||
log_success " Found: $file"
|
||||
done
|
||||
return 0
|
||||
else
|
||||
log_error "Archive integrity check failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Create backup of current Plex data
|
||||
backup_current_data() {
|
||||
local backup_suffix
|
||||
backup_suffix=$(date '+%Y%m%d_%H%M%S')
|
||||
local current_backup_dir="$SCRIPT_DIR/plex_current_backup_$backup_suffix"
|
||||
|
||||
log_message "Creating backup of current Plex data..."
|
||||
mkdir -p "$current_backup_dir"
|
||||
|
||||
for file in "${!RESTORE_LOCATIONS[@]}"; do
|
||||
local src="${RESTORE_LOCATIONS[$file]}$file"
|
||||
if [ -f "$src" ]; then
|
||||
if sudo cp "$src" "$current_backup_dir/"; then
|
||||
log_success "Backed up current: $file"
|
||||
else
|
||||
log_error "Failed to backup current: $file"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
log_success "Current data backed up to: $current_backup_dir"
|
||||
echo "$current_backup_dir"
|
||||
}
|
||||
|
||||
# Restore files from backup
|
||||
restore_files() {
|
||||
local backup_file="$1"
|
||||
local dry_run="$2"
|
||||
|
||||
if [ ! -f "$backup_file" ]; then
|
||||
log_error "Backup file not found: $backup_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Create temporary extraction directory
|
||||
local temp_dir
|
||||
temp_dir="/tmp/plex-restore-$(date +%Y%m%d_%H%M%S)"
|
||||
mkdir -p "$temp_dir"
|
||||
|
||||
log_message "Extracting backup archive..."
|
||||
if ! tar -xzf "$backup_file" -C "$temp_dir"; then
|
||||
log_error "Failed to extract backup archive"
|
||||
rm -rf "$temp_dir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_message "Restoring files..."
|
||||
local restore_errors=0
|
||||
|
||||
for file in "${!RESTORE_LOCATIONS[@]}"; do
|
||||
local src_file="$temp_dir/$file"
|
||||
local dest_path="${RESTORE_LOCATIONS[$file]}"
|
||||
local dest_file="$dest_path$file"
|
||||
|
||||
if [ -f "$src_file" ]; then
|
||||
if [ "$dry_run" == "true" ]; then
|
||||
log_message "Would restore: $file to $dest_file"
|
||||
else
|
||||
log_message "Restoring: $file"
|
||||
if sudo cp "$src_file" "$dest_file"; then
|
||||
sudo chown plex:plex "$dest_file"
|
||||
log_success "Restored: $file"
|
||||
else
|
||||
log_error "Failed to restore: $file"
|
||||
restore_errors=$((restore_errors + 1))
|
||||
fi
|
||||
fi
|
||||
else
|
||||
log_warning "File not found in backup: $file"
|
||||
restore_errors=$((restore_errors + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
# Clean up temporary directory
|
||||
rm -rf "$temp_dir"
|
||||
|
||||
return $restore_errors
|
||||
}
|
||||
|
||||
# Manage Plex service
|
||||
manage_plex_service() {
|
||||
local action="$1"
|
||||
log_message "$action Plex Media Server..."
|
||||
|
||||
case "$action" in
|
||||
"stop")
|
||||
sudo systemctl stop plexmediaserver.service
|
||||
sleep 3
|
||||
log_success "Plex stopped"
|
||||
;;
|
||||
"start")
|
||||
sudo systemctl start plexmediaserver.service
|
||||
sleep 3
|
||||
log_success "Plex started"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Main function
|
||||
main() {
|
||||
local backup_file="$1"
|
||||
local dry_run=false
|
||||
|
||||
# Check for dry-run flag
|
||||
if [ "$2" = "--dry-run" ] || [ "$1" = "--dry-run" ]; then
|
||||
dry_run=true
|
||||
fi
|
||||
|
||||
# If no backup file provided, list available backups
|
||||
if [ -z "$backup_file" ] || [ "$backup_file" = "--dry-run" ]; then
|
||||
list_backups
|
||||
echo
|
||||
echo "Usage: $0 <backup_file> [--dry-run]"
|
||||
echo "Example: $0 plex-backup-20250125_143022.tar.gz"
|
||||
echo " $0 /mnt/share/media/backups/plex/plex-backup-20250125_143022.tar.gz"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# If relative path, prepend BACKUP_ROOT
|
||||
if [[ "$backup_file" != /* ]]; then
|
||||
backup_file="$BACKUP_ROOT/$backup_file"
|
||||
fi
|
||||
|
||||
# Validate backup exists and is complete
|
||||
if ! validate_backup "$backup_file"; then
|
||||
log_error "Backup validation failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$dry_run" = "true" ]; then
|
||||
restore_files "$backup_file" true
|
||||
log_message "Dry run completed. No changes were made."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Confirm restoration
|
||||
echo
|
||||
log_warning "This will restore Plex data from backup $(basename "$backup_file")"
|
||||
log_warning "Current Plex data will be backed up before restoration"
|
||||
read -p "Continue? (y/N): " -n 1 -r
|
||||
echo
|
||||
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
log_message "Restoration cancelled"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Stop Plex service
|
||||
manage_plex_service stop
|
||||
|
||||
# Backup current data
|
||||
local current_backup
|
||||
if ! current_backup=$(backup_current_data); then
|
||||
log_error "Failed to backup current data"
|
||||
manage_plex_service start
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Restore files
|
||||
if restore_files "$backup_file" false; then
|
||||
log_success "Restoration completed successfully"
|
||||
log_message "Current data backup saved at: $current_backup"
|
||||
else
|
||||
log_error "Restoration failed"
|
||||
manage_plex_service start
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Start Plex service
|
||||
manage_plex_service start
|
||||
|
||||
log_success "Plex restoration completed. Please verify your server is working correctly."
|
||||
}
|
||||
|
||||
# Trap to ensure Plex is restarted on script exit
|
||||
trap 'manage_plex_service start' EXIT
|
||||
|
||||
main "$@"
|
||||
Reference in New Issue
Block a user