# Plex Management Script Documentation **Author:** Peter Wood 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 The enhanced `plex.sh` script is a modern Plex service management tool that performs the following advanced tasks: 1. **Smart Service Management**: Intelligent start/stop/restart operations with dependency checking 2. **Enhanced Status Display**: Detailed service status with health indicators and port monitoring 3. **Safety Validation**: Pre-operation checks and post-operation verification 4. **Progress Indicators**: Visual feedback for all operations with timing information 5. **Comprehensive Logging**: Detailed logging with color-coded output and timestamps 6. **Configuration Validation**: Checks for common configuration issues 7. **Network Monitoring**: Port availability and network configuration validation 8. **Process Management**: Advanced process monitoring and cleanup capabilities 9. **Recovery Operations**: Automatic recovery from common service issues 10. **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 control - **`backup-plex.sh`** - Database backup with integrity checking and auto-repair - **`restore-plex.sh`** - Safe database restoration with validation ### Recovery and Maintenance Scripts - **`recover-plex-database.sh`** - Advanced database recovery operations - **`icu-aware-recovery.sh`** - ICU-aware database recovery for Unicode issues - **`nuclear-plex-recovery.sh`** - Last-resort database replacement and recovery - **`validate-plex-recovery.sh`** - Recovery operation validation and verification ### Monitoring and Testing Scripts - **`monitor-plex-backup.sh`** - Real-time backup monitoring dashboard - **`validate-plex-backups.sh`** - Backup validation and health monitoring - **`test-plex-backup.sh`** - Comprehensive backup testing suite - **`integration-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: ```bash ./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 ```bash # 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 ```bash # 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: ```bash # 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 1. **Pre-start Validation** - Check if service is already running - Validate system dependencies - Check port availability (32400/tcp) - Verify configuration files 2. **Service Start** - Execute systemctl start command - Monitor startup progress - Display progress indicators 3. **Post-start Verification** - Confirm service is active - Verify network port is accessible - Check process health - Display success confirmation ### Stop Operation Process 1. **Pre-stop Checks** - Verify service is currently running - Check for active connections - Prepare for graceful shutdown 2. **Graceful Shutdown** - Send stop signal to service - Allow proper shutdown time - Monitor shutdown progress 3. **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.sh` for 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 1. **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 2. **Service Won't Stop** - Check for active media streaming sessions - Verify no stuck processes are preventing shutdown - Use `--force` option for forced termination if necessary - Review process tree for dependent processes 3. **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: ```bash # 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: ```bash # Enable automatic startup sudo systemctl enable plexmediaserver # Check service dependencies systemctl list-dependencies plexmediaserver ``` ### Cron Integration For scheduled operations: ```bash # 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: ```bash chmod +x plex.sh ``` - The script uses `systemctl` to manage the Plex Media Server service. Ensure that `systemctl` is available on your system. - The script requires `sudo` privileges 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.