17 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 Terminal Detection and Color Output
The script includes intelligent terminal detection and color management:
- Automatic Color Detection: Detects terminal capabilities and adjusts output accordingly
- Environment Variable Support: Respects
NO_COLORenvironment variable for accessibility - Porcelain Mode:
--porcelainor-pprovides machine-readable output for automation - ANSI Escape Handling: Properly handles color codes when called from other scripts
System Integration and Automation
- update.sh Integration: Automatically called during system updates with simple output mode
- Non-Interactive Operation: Designed to work seamlessly when called from other scripts
- Service Presence Detection: Gracefully handles systems without Plex installed
- Root User Prevention: Explicitly prevents running as root for security
Environment Variables
The script supports several environment variables for customization:
# Disable color output entirely
NO_COLOR=1 ./plex.sh status
# Force porcelain mode for machine-readable output
./plex.sh --porcelain start
# Check terminal capabilities
TERM=dumb ./plex.sh status # Forces simple output
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
Available Commands
The script supports the following commands:
# Basic service operations
./plex.sh start # Start Plex Media Server
./plex.sh stop # Stop Plex Media Server
./plex.sh restart # Restart Plex Media Server (also accepts 'reload')
./plex.sh status # Show detailed service status (also accepts 'info')
./plex.sh logs # Display recent Plex Media Server logs
./plex.sh help # Show help message (also accepts '--help' or '-h')
# Logs command with options
./plex.sh logs # Display last 20 lines of Plex logs
./plex.sh logs -n 50 # Display last 50 lines of Plex logs
./plex.sh logs -f # Follow logs in real-time
./plex.sh logs --follow --lines 100 # Follow logs with custom line count
# Porcelain mode for machine-readable output
./plex.sh --porcelain start # Machine-readable service output
./plex.sh --porcelain status # Machine-readable status output
# Environment variable examples
NO_COLOR=1 ./plex.sh status # Disable colors
./plex.sh --porcelain start # Machine-readable output
Note: The script automatically detects when it's being called from other scripts (like update.sh) and adjusts its output accordingly.
Integration with Other Scripts
The plex.sh script is designed to work seamlessly with other Plex management scripts and system automation:
# Used by update.sh during system updates (automatic porcelain output)
./update.sh # Automatically calls plex.sh --porcelain stop/start
# 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
# Manual integration with porcelain output
./plex.sh --porcelain start # For use in scripts/automation
Security and Safety Features
- Root Prevention: Script refuses to run as root user for security
- Safe Defaults: Uses conservative settings for service operations
- Error Handling: Comprehensive error checking and reporting
- Graceful Degradation: Works on systems without Plex installed
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
Logs Operation Details
The logs command provides flexible log viewing capabilities:
# Basic log viewing (last 20 lines)
./plex.sh logs
# Custom line count
./plex.sh logs -n 50
./plex.sh logs --lines 100
# Real-time log following
./plex.sh logs -f
./plex.sh logs --follow
# Combined options
./plex.sh logs --follow --lines 50
Logs Command Features:
- Flexible Line Count: Specify number of log lines to display (default: 20)
- Real-time Following: Use
-for--followto tail logs in real-time - Systemd Integration: Uses
journalctlfor reliable log access - Porcelain Mode Support: Works with
--porcelainfor script automation - Error Handling: Graceful handling when service is not available
Logs Command Options:
-n, --lines NUMBER: Number of log lines to display (default: 20)-f, --follow: Follow logs in real-time (liketail -f)- Can be combined with global
--porcelainoption for clean output
Configuration and Dependencies
Environment Variable Configuration
The script respects several environment variables for customization:
NO_COLOR: Set to1to disable all color output (accessibility compliance)--porcelain: Command-line option to force machine-readable output (for automation)TERM: Automatically detected;dumbterminals get simple output
System Requirements
- Operating System: systemd-based Linux distribution
- Permissions: sudo access for systemctl operations (script prevents running as root)
- Network: Port 32400/tcp available for Plex communications
- Dependencies: systemctl, basic shell utilities
- Service: plexmediaserver.service (gracefully handles absence)
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
System Update Integration
The script is designed to work seamlessly with system update processes:
- Automatic Integration: Called by
update.shduring system updates - Service Management: Safely stops Plex before package updates, restarts after completion
- Porcelain Mode: Uses
--porcelainfor clean, log-friendly output - Graceful Handling: Properly handles systems without Plex installed
- Error Prevention: Prevents interruption of package manager operations
Example system update integration:
# In update.sh - automatically stops Plex before updates
/home/acedanger/shell/plex/plex.sh --porcelain stop
# Package updates occur here...
# In update.sh - automatically starts Plex after updates
/home/acedanger/shell/plex/plex.sh --porcelain start
This integration ensures that Plex databases and processes don't interfere with system package updates while maintaining service availability.
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.