- Introduced `validate-plex-recovery.sh` for validating Plex database recovery. - Implemented checks for service status, database integrity, web interface accessibility, API functionality, and recent logs. - Added detailed recovery summary and next steps for users. fix: Improve Debian patching script for compatibility - Enhanced `debian-patches.sh` to securely download and execute bootstrap scripts. - Updated package mapping logic and ensured proper permissions for patched files. fix: Update Docker test scripts for better permission handling - Modified `run-docker-tests.sh` to set appropriate permissions on logs directory. - Ensured log files have correct permissions after test runs. fix: Enhance setup scripts for secure installations - Updated `setup.sh` to securely download and execute installation scripts for zoxide and nvm. - Improved error handling for failed downloads. fix: Refine startup script for log directory permissions - Adjusted `startup.sh` to set proper permissions for log directories and files. chore: Revamp update-containers.sh for better error handling and logging - Rewrote `update-containers.sh` to include detailed logging and error handling. - Added validation for Docker image names and improved overall script robustness.
12 KiB
Plex Management Script Documentation
Author: Peter Wood peter@peterwood.dev
This document provides comprehensive documentation for the modern plex.sh script, featuring enhanced service management with progress indicators, dependency validation, safety checks, and comprehensive error handling.
Script Overview
Author: Peter Wood peter@peterwood.dev
The enhanced plex.sh script is a modern Plex service management tool that performs the following advanced tasks:
- Smart Service Management: Intelligent start/stop/restart operations with dependency checking
- Enhanced Status Display: Detailed service status with health indicators and port monitoring
- Safety Validation: Pre-operation checks and post-operation verification
- Progress Indicators: Visual feedback for all operations with timing information
- Comprehensive Logging: Detailed logging with color-coded output and timestamps
- Configuration Validation: Checks for common configuration issues
- Network Monitoring: Port availability and network configuration validation
- Process Management: Advanced process monitoring and cleanup capabilities
- Recovery Operations: Automatic recovery from common service issues
- Performance Monitoring: Service health and resource usage tracking
Related Scripts in the Plex Ecosystem
This script is part of a comprehensive Plex management suite:
Core Management Scripts
plex.sh(this script) - Service management and controlbackup-plex.sh- Database backup with integrity checking and auto-repairrestore-plex.sh- Safe database restoration with validation
Recovery and Maintenance Scripts
recover-plex-database.sh- Advanced database recovery operationsicu-aware-recovery.sh- ICU-aware database recovery for Unicode issuesnuclear-plex-recovery.sh- Last-resort database replacement and recoveryvalidate-plex-recovery.sh- Recovery operation validation and verification
Monitoring and Testing Scripts
monitor-plex-backup.sh- Real-time backup monitoring dashboardvalidate-plex-backups.sh- Backup validation and health monitoringtest-plex-backup.sh- Comprehensive backup testing suiteintegration-test-plex.sh- End-to-end integration testing
Utility Scripts
plex-recent-additions.sh- Recent media additions reporting and statistics
Enhanced Features
Smart Service Management
The enhanced script includes intelligent service operations:
- Dependency Validation: Checks for required services and dependencies before operations
- Safe Stop Operations: Graceful shutdown with proper wait times and verification
- Intelligent Restart: Combines stop and start operations with validation between steps
- Service Health Checks: Comprehensive status validation beyond simple systemctl status
Progress Indicators and User Experience
- Visual Progress: Real-time progress indicators for all operations
- Timing Information: Displays operation duration and timestamps
- Color-coded Output: Success (green), error (red), warning (yellow), info (blue)
- Clear Status Messages: Descriptive messages for all operations and their outcomes
Advanced Status Display
The status command provides comprehensive information:
./plex.sh status
Shows:
- Service status and health
- Process information and resource usage
- Network port availability (32400/tcp)
- Configuration file validation
- Recent log entries and error conditions
- Performance metrics and uptime information
Safety and Validation Features
- Pre-operation Checks: Validates system state before making changes
- Post-operation Verification: Confirms operations completed successfully
- Configuration Validation: Checks for common configuration issues
- Network Validation: Verifies port availability and network configuration
- Recovery Capabilities: Automatic recovery from common service issues
Command Line Usage
Basic Operations
# Start Plex Media Server
./plex.sh start
# Stop Plex Media Server
./plex.sh stop
# Restart Plex Media Server
./plex.sh restart
# Display comprehensive status
./plex.sh status
Advanced Options
# Enhanced status with detailed information
./plex.sh status --verbose
# Force restart (ignores current state)
./plex.sh restart --force
# Safe stop with extended wait time
./plex.sh stop --safe
# Start with configuration validation
./plex.sh start --validate
Integration with Other Scripts
The plex.sh script is designed to work seamlessly with other Plex management scripts:
# Used by backup script for safe service management
./backup-plex.sh # Automatically calls plex.sh stop/start
# Used by recovery scripts for service control
./recover-plex-database.sh # Uses plex.sh for service management
# Used by testing scripts for service validation
./integration-test-plex.sh # Validates service operations
Detailed Operation Steps
Start Operation Process
-
Pre-start Validation
- Check if service is already running
- Validate system dependencies
- Check port availability (32400/tcp)
- Verify configuration files
-
Service Start
- Execute systemctl start command
- Monitor startup progress
- Display progress indicators
-
Post-start Verification
- Confirm service is active
- Verify network port is accessible
- Check process health
- Display success confirmation
Stop Operation Process
-
Pre-stop Checks
- Verify service is currently running
- Check for active connections
- Prepare for graceful shutdown
-
Graceful Shutdown
- Send stop signal to service
- Allow proper shutdown time
- Monitor shutdown progress
-
Verification and Cleanup
- Confirm service has stopped
- Verify process termination
- Clean up any remaining resources
Status Operation Details
The status command provides comprehensive system information:
- Service Status: Active/inactive state and health
- Process Information: PID, memory usage, CPU utilization
- Network Status: Port availability and connection status
- Configuration: Validation of key configuration files
- Recent Activity: Latest log entries and system events
- Performance Metrics: Uptime, resource usage, response times
Configuration and Dependencies
System Requirements
- Operating System: systemd-based Linux distribution
- Permissions: sudo access for systemctl operations
- Network: Port 32400/tcp available for Plex communications
- Dependencies: systemctl, curl (for network validation), ps (for process monitoring)
Configuration Validation
The script validates key configuration elements:
- Service Definition: Ensures plexmediaserver.service is properly configured
- Network Configuration: Validates port availability and network bindings
- File Permissions: Checks critical file and directory permissions
- Process Limits: Verifies system resource limits are appropriate
Integration Points
The script integrates with the broader Plex management ecosystem:
- Backup Operations: Called by
backup-plex.shfor safe service management - Recovery Procedures: Used by recovery scripts for controlled service restart
- Testing Framework: Utilized by integration tests for service validation
- Monitoring Systems: Provides status information for monitoring dashboards
Error Handling and Troubleshooting
Common Issues and Solutions
-
Service Won't Start
- Check configuration files for syntax errors
- Verify port 32400 is not in use by another process
- Confirm Plex user has necessary permissions
- Review system logs for specific error messages
-
Service Won't Stop
- Check for active media streaming sessions
- Verify no stuck processes are preventing shutdown
- Use
--forceoption for forced termination if necessary - Review process tree for dependent processes
-
Network Issues
- Confirm firewall settings allow port 32400
- Check network interface configuration
- Verify DNS resolution if using remote access
- Test local network connectivity
Debug Mode
Enable verbose logging for troubleshooting:
# Run with enhanced debugging
./plex.sh status --debug
# Check system integration
./plex.sh start --validate --debug
Security Considerations
Access Control
- Script requires sudo privileges for systemctl operations
- Service runs under dedicated plex user account
- Network access restricted to required ports only
- Configuration files protected with appropriate permissions
Best Practices
- Regularly update Plex Media Server software
- Monitor service logs for security events
- Restrict network access to trusted networks
- Use strong authentication for remote access
- Regularly backup configuration and databases
Performance Optimization
Service Tuning
The script supports performance optimization through:
- Process Priority: Adjusts service priority for optimal performance
- Resource Limits: Configures appropriate memory and CPU limits
- Network Tuning: Optimizes network buffer sizes and timeouts
- Disk I/O: Configures efficient disk access patterns
Monitoring Integration
Integrates with monitoring systems:
- Prometheus Metrics: Exports service metrics for monitoring
- Log Aggregation: Structured logging for centralized analysis
- Health Checks: Regular health validation for proactive monitoring
- Performance Tracking: Resource usage tracking and alerting
Automation and Scheduling
Systemd Integration
The script works seamlessly with systemd:
# Enable automatic startup
sudo systemctl enable plexmediaserver
# Check service dependencies
systemctl list-dependencies plexmediaserver
Cron Integration
For scheduled operations:
# Weekly service restart for maintenance
0 3 * * 0 /home/acedanger/shell/plex/plex.sh restart --safe
# Daily health check
0 6 * * * /home/acedanger/shell/plex/plex.sh status --validate
Exit Codes and Return Values
The script uses standard exit codes for automation:
- 0: Operation completed successfully
- 1: General error or operation failed
- 2: Invalid command line arguments
- 3: Service operation timeout
- 4: Permission denied or insufficient privileges
- 5: Network or connectivity issues
- 6: Configuration validation failed
- 7: Dependency check failed
These exit codes enable reliable automation and error handling in larger scripts and systems.
Important Information
Prerequisites
-
Ensure that the script is executable:
chmod +x plex.sh -
The script uses
systemctlto manage the Plex Media Server service. Ensure thatsystemctlis available on your system. -
The script requires
sudoprivileges to manage the Plex Media Server service. Ensure that you have the necessary permissions.
Script Integration
This script is designed to work as part of the broader Plex management ecosystem:
- Backup Integration: Automatically called by backup scripts for safe service management
- Recovery Integration: Used by recovery scripts for controlled service operations
- Testing Integration: Utilized by testing frameworks for service validation
- Monitoring Integration: Provides status information for monitoring systems
Compatibility
- Operating Systems: Tested on Ubuntu 20.04+, Debian 10+, CentOS 8+
- Plex Versions: Compatible with Plex Media Server 1.25.0 and later
- Dependencies: Minimal external dependencies for maximum compatibility
- Architecture: Supports both x86_64 and ARM64 architectures
By following this documentation, you should be able to effectively use the enhanced plex.sh script as part of your comprehensive Plex media server management strategy.