From 0d5b114617f7ad4c79ced72b04351c518491b396 Mon Sep 17 00:00:00 2001 From: Anthony Date: Tue, 29 Jul 2025 00:51:33 +0800 Subject: [PATCH] Test object cache connection --- mbadmin.jps | 117 ++++++ .../configure_litespeed_redis_object_cache.sh | 340 ++++++++++++++++++ scripts/install-wordpress.sh | 71 +++- scripts/manage_litespeed_objcache.php | 187 ++++++++++ 4 files changed, 713 insertions(+), 2 deletions(-) create mode 100644 scripts/configure_litespeed_redis_object_cache.sh create mode 100644 scripts/manage_litespeed_objcache.php diff --git a/mbadmin.jps b/mbadmin.jps index 0c877b8..88b65cf 100644 --- a/mbadmin.jps +++ b/mbadmin.jps @@ -160,6 +160,21 @@ menu: caption: Get Redis Metrics action: redis_metrics successText: "${response.out}" + - confirmText: Enable LiteSpeed Object Cache with Redis (Socket)? + loadingText: Enabling LiteSpeed Object Cache... + caption: Enable LiteSpeed Object Cache (Socket) + action: litespeed_objcache_enable + successText: "${response.out}" + - confirmText: Disable LiteSpeed Object Cache? + loadingText: Disabling LiteSpeed Object Cache... + caption: Disable LiteSpeed Object Cache + action: litespeed_objcache_disable + successText: "${response.out}" + - confirmText: Check LiteSpeed Object Cache status? + loadingText: Checking Object Cache status... + caption: Check LiteSpeed Object Cache Status + action: litespeed_objcache_status + successText: "${response.out}" - confirmText: Check OPcache status? loadingText: Checking OPcache status... caption: Check OPcache Status @@ -423,6 +438,40 @@ settings: type: text caption: Email Address (Optional) default: "${EMAIL}" + redisObjectCacheConfig: + submitUnchanged: true + fields: + - name: redis_host + type: text + caption: Redis Host (for TCP connection) + default: "127.0.0.1" + - name: redis_port + type: text + caption: Redis Port (for TCP connection) + default: "6379" + wpInstallWithObjCacheConfig: + submitUnchanged: true + fields: + - name: wp_username + type: text + caption: WordPress Admin Username + required: true + - name: wp_password + type: text + caption: WordPress Admin Password + required: true + - name: wp_email + type: text + caption: WordPress Admin Email + required: true + - name: db_root_pass + type: text + caption: Database Root Password + required: true + - name: domain + type: text + caption: Domain Name (optional) + default: "" cleanCertConfig: submitUnchanged: true fields: @@ -751,6 +800,62 @@ actions: - return: type: info message: "${response.out}" + + # LiteSpeed Object Cache with Redis actions + litespeed_objcache_enable: + - cmd[cp]: + user: root + commands: + - bash /home/litespeed/mbmanager/scripts/configure_litespeed_redis_object_cache.sh --enable + - return: + type: success + message: "${response.out}" + + litespeed_objcache_disable: + - cmd[cp]: + user: root + commands: + - bash /home/litespeed/mbmanager/scripts/configure_litespeed_redis_object_cache.sh --disable + - return: + type: success + message: "${response.out}" + + litespeed_objcache_status: + - cmd[cp]: + user: root + commands: + - bash /home/litespeed/mbmanager/scripts/configure_litespeed_redis_object_cache.sh --status + - return: + type: info + message: "${response.out}" + + litespeed_objcache_enable_tcp: + - cmd[cp]: + user: root + commands: + - bash /home/litespeed/mbmanager/scripts/configure_litespeed_redis_object_cache.sh --enable --connection-type=tcp --redis-host="${settings.redis_host}" --redis-port="${settings.redis_port}" + - return: + type: success + message: "${response.out}" + + # WordPress installation with automatic Object Cache + install_wordpress_with_objcache: + - cmd[cp]: + user: root + commands: + - bash /home/litespeed/mbmanager/scripts/install-wordpress.sh --wpusername="${settings.wp_username}" --wppassword="${settings.wp_password}" --wpemail="${settings.wp_email}" --dbrootpass="${settings.db_root_pass}" --domain="${settings.domain}" + - return: + type: success + message: "${response.out}" + + install_wordpress_skip_objcache: + - cmd[cp]: + user: root + commands: + - bash /home/litespeed/mbmanager/scripts/install-wordpress.sh --wpusername="${settings.wp_username}" --wppassword="${settings.wp_password}" --wpemail="${settings.wp_email}" --dbrootpass="${settings.db_root_pass}" --domain="${settings.domain}" --skip-objcache + - return: + type: success + message: "${response.out}" litespeed_metrics: - cmd[cp]: user: litespeed @@ -848,6 +953,18 @@ buttons: action: remove_ssl_cert caption: Remove SSL Certificates submitButtonText: Remove Certificates + - settings: redisObjectCacheConfig + action: litespeed_objcache_enable_tcp + caption: Enable LiteSpeed Object Cache (TCP) + submitButtonText: Enable Object Cache with TCP + - settings: wpInstallWithObjCacheConfig + action: install_wordpress_with_objcache + caption: Install WordPress with Object Cache + submitButtonText: Install WordPress + Object Cache + - settings: wpInstallWithObjCacheConfig + action: install_wordpress_skip_objcache + caption: Install WordPress (Skip Object Cache) + submitButtonText: Install WordPress Only onUninstall: - cmd[cp]: diff --git a/scripts/configure_litespeed_redis_object_cache.sh b/scripts/configure_litespeed_redis_object_cache.sh new file mode 100644 index 0000000..d7eb5b8 --- /dev/null +++ b/scripts/configure_litespeed_redis_object_cache.sh @@ -0,0 +1,340 @@ +#!/bin/bash +# +# Configure LiteSpeed Object Cache with Redis +# This script configures LiteSpeed's built-in Object Cache to use Redis +# For MightyBox.io CloudScripting addon +# + +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 + +# Helper Functions +info() { + printf "${BLUE}[INFO] %s${NC}\n" "$@" +} + +success() { + printf "${GREEN}[SUCCESS] %s${NC}\n" "$@" +} + +warning() { + printf "${YELLOW}[WARNING] %s${NC}\n" "$@" +} + +error_exit() { + printf "${RED}[ERROR] %s${NC}\n" "$@" >&2 + exit 1 +} + +# Configuration variables +LSWS_CONF_DIR="/usr/local/lsws/conf" +HTTPD_CONF="$LSWS_CONF_DIR/httpd_config.conf" +REDIS_SOCKET="/var/run/redis/redis.sock" +REDIS_HOST="127.0.0.1" +REDIS_PORT="6379" +CONNECTION_TYPE="socket" # Default to socket for better performance + +usage() { + printf "Usage: %s [OPTIONS]\n" "$0" + printf "\n" + printf "Configure LiteSpeed Object Cache with Redis\n" + printf "\n" + printf "Options:\n" + printf " --connection-type=TYPE Connection type: 'socket' or 'tcp' (default: socket)\n" + printf " --redis-host=HOST Redis host (default: 127.0.0.1, used with tcp)\n" + printf " --redis-port=PORT Redis port (default: 6379, used with tcp)\n" + printf " --redis-socket=PATH Redis socket path (default: /var/run/redis/redis.sock)\n" + printf " --enable Enable Object Cache\n" + printf " --disable Disable Object Cache\n" + printf " --status Show current Object Cache status\n" + printf " -h, --help Display this help message\n" + printf "\n" + printf "Examples:\n" + printf " %s --enable # Enable with socket connection\n" "$0" + printf " %s --enable --connection-type=tcp # Enable with TCP connection\n" "$0" + printf " %s --enable --redis-host=192.168.1.100 # Enable with remote Redis\n" "$0" + printf " %s --disable # Disable Object Cache\n" "$0" + printf " %s --status # Show current status\n" "$0" + exit 1 +} + +# Parse command line arguments +ACTION="" +while [[ $# -gt 0 ]]; do + case $1 in + --connection-type=*) + CONNECTION_TYPE="${1#*=}" + shift + ;; + --redis-host=*) + REDIS_HOST="${1#*=}" + shift + ;; + --redis-port=*) + REDIS_PORT="${1#*=}" + shift + ;; + --redis-socket=*) + REDIS_SOCKET="${1#*=}" + shift + ;; + --enable) + ACTION="enable" + shift + ;; + --disable) + ACTION="disable" + shift + ;; + --status) + ACTION="status" + shift + ;; + -h|--help) + usage + ;; + *) + error_exit "Unknown option: $1" + ;; + esac +done + +# Validate connection type +if [[ "$CONNECTION_TYPE" != "socket" && "$CONNECTION_TYPE" != "tcp" ]]; then + error_exit "Invalid connection type: $CONNECTION_TYPE. Must be 'socket' or 'tcp'" +fi + +# Function to check if Redis is running +check_redis_connection() { + local test_result + + if [[ "$CONNECTION_TYPE" == "socket" ]]; then + if [[ ! -S "$REDIS_SOCKET" ]]; then + error_exit "Redis socket not found at: $REDIS_SOCKET" + fi + test_result=$(redis-cli -s "$REDIS_SOCKET" ping 2>/dev/null || echo "FAILED") + else + test_result=$(redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" ping 2>/dev/null || echo "FAILED") + fi + + if [[ "$test_result" != "PONG" ]]; then + error_exit "Cannot connect to Redis. Please ensure Redis is running and accessible." + fi + + success "Redis connection test successful" +} + +# Function to backup LiteSpeed configuration +backup_config() { + local backup_file="$HTTPD_CONF.backup.$(date +%Y%m%d_%H%M%S)" + if [[ -f "$HTTPD_CONF" ]]; then + cp "$HTTPD_CONF" "$backup_file" + info "Configuration backed up to: $backup_file" + fi +} + +# Function to configure LiteSpeed Object Cache +configure_object_cache() { + local enable_cache="$1" + + info "Configuring LiteSpeed Object Cache..." + + # Check if LiteSpeed config exists + if [[ ! -f "$HTTPD_CONF" ]]; then + error_exit "LiteSpeed configuration file not found: $HTTPD_CONF" + fi + + # Backup configuration + backup_config + + # Create temporary configuration + local temp_config=$(mktemp) + local cache_config="" + + if [[ "$enable_cache" == "true" ]]; then + if [[ "$CONNECTION_TYPE" == "socket" ]]; then + cache_config=" +cache { + enableCache 1 + qsCache 1 + reqCookieCache 1 + respCookieCache 1 + ignoreReqCacheCtrl 1 + ignoreRespCacheCtrl 0 + enablePrivateCache 0 + privateExpireInSeconds 3600 + + storage { + cacheStorePath /tmp/lshttpd/cache/ + + # Redis Object Cache Configuration + objCache { + type redis + addr $(if [[ "$CONNECTION_TYPE" == "socket" ]]; then echo "unix:$REDIS_SOCKET"; else echo "$REDIS_HOST:$REDIS_PORT"; fi) + defaultTTL 60 + } + } +} +" + else + cache_config=" +cache { + enableCache 1 + qsCache 1 + reqCookieCache 1 + respCookieCache 1 + ignoreReqCacheCtrl 1 + ignoreRespCacheCtrl 0 + enablePrivateCache 0 + privateExpireInSeconds 3600 + + storage { + cacheStorePath /tmp/lshttpd/cache/ + + # Redis Object Cache Configuration + objCache { + type redis + addr $REDIS_HOST:$REDIS_PORT + defaultTTL 60 + } + } +} +" + fi + else + cache_config=" +cache { + enableCache 0 + + storage { + cacheStorePath /tmp/lshttpd/cache/ + } +} +" + fi + + # Remove existing cache configuration and add new one + awk ' + BEGIN { in_cache_block = 0; brace_count = 0 } + /^cache\s*{/ { in_cache_block = 1; brace_count = 1; next } + in_cache_block == 1 { + for (i = 1; i <= length($0); i++) { + char = substr($0, i, 1) + if (char == "{") brace_count++ + if (char == "}") brace_count-- + } + if (brace_count == 0) { + in_cache_block = 0 + } + next + } + { print } + ' "$HTTPD_CONF" > "$temp_config" + + # Add new cache configuration + echo "$cache_config" >> "$temp_config" + + # Replace original configuration + mv "$temp_config" "$HTTPD_CONF" + + # Set proper permissions + chown lsadm:lsadm "$HTTPD_CONF" + chmod 644 "$HTTPD_CONF" + + success "LiteSpeed Object Cache configuration updated" +} + +# Function to restart LiteSpeed +restart_litespeed() { + info "Restarting LiteSpeed Web Server..." + if systemctl restart lsws; then + success "LiteSpeed Web Server restarted successfully" + sleep 3 # Give LiteSpeed time to initialize + else + error_exit "Failed to restart LiteSpeed Web Server" + fi +} + +# Function to show Object Cache status +show_status() { + info "Checking LiteSpeed Object Cache status..." + + # Check if cache configuration exists in httpd_config.conf + if grep -q "objCache" "$HTTPD_CONF" 2>/dev/null; then + local cache_enabled=$(grep -A 20 "^cache" "$HTTPD_CONF" | grep "enableCache" | awk '{print $2}' | head -1) + local cache_type=$(grep -A 50 "objCache" "$HTTPD_CONF" | grep "type" | awk '{print $2}' | head -1) + local cache_addr=$(grep -A 50 "objCache" "$HTTPD_CONF" | grep "addr" | awk '{print $2}' | head -1) + + printf "\n${YELLOW}LiteSpeed Object Cache Status:${NC}\n" + printf "Cache Enabled: %s\n" "${cache_enabled:-"Not configured"}" + printf "Cache Type: %s\n" "${cache_type:-"Not configured"}" + printf "Redis Address: %s\n" "${cache_addr:-"Not configured"}" + + # Test Redis connection if configured + if [[ "$cache_type" == "redis" && -n "$cache_addr" ]]; then + printf "Redis Connection: " + if [[ "$cache_addr" == unix:* ]]; then + local socket_path="${cache_addr#unix:}" + if redis-cli -s "$socket_path" ping >/dev/null 2>&1; then + printf "${GREEN}Connected${NC}\n" + else + printf "${RED}Failed${NC}\n" + fi + else + local host_port=(${cache_addr//:/ }) + if redis-cli -h "${host_port[0]}" -p "${host_port[1]}" ping >/dev/null 2>&1; then + printf "${GREEN}Connected${NC}\n" + else + printf "${RED}Failed${NC}\n" + fi + fi + fi + else + printf "\n${YELLOW}LiteSpeed Object Cache Status:${NC}\n" + printf "Status: ${RED}Not configured${NC}\n" + fi + + # Check LiteSpeed service status + printf "\nLiteSpeed Service: " + if systemctl is-active lsws >/dev/null 2>&1; then + printf "${GREEN}Running${NC}\n" + else + printf "${RED}Not running${NC}\n" + fi +} + +# Main execution +case "$ACTION" in + "enable") + info "Enabling LiteSpeed Object Cache with Redis..." + check_redis_connection + configure_object_cache "true" + restart_litespeed + show_status + success "LiteSpeed Object Cache with Redis enabled successfully!" + ;; + "disable") + info "Disabling LiteSpeed Object Cache..." + configure_object_cache "false" + restart_litespeed + show_status + success "LiteSpeed Object Cache disabled successfully!" + ;; + "status") + show_status + ;; + "") + error_exit "No action specified. Use --enable, --disable, or --status" + ;; + *) + error_exit "Invalid action: $ACTION" + ;; +esac + +exit 0 \ No newline at end of file diff --git a/scripts/install-wordpress.sh b/scripts/install-wordpress.sh index b557836..b6f2439 100644 --- a/scripts/install-wordpress.sh +++ b/scripts/install-wordpress.sh @@ -36,6 +36,7 @@ WEB_USER="litespeed" # Web server user WEB_GROUP="litespeed" # Web server group WP_CLI_PATH="/usr/local/bin/wp" # Path to WP-CLI executable NEEDS_OWNERSHIP_CORRECTION="false" # Flag to track if ownership correction is needed +SKIP_OBJCACHE="false" # Flag to skip automatic Object Cache configuration # --- Helper Functions --- @@ -82,11 +83,13 @@ usage() { printf " --webgroup=GROUP Web server group (default: %s)\n" "$WEB_GROUP" printf " --dbhost=HOST Database host (default: %s)\n" "$DB_HOST" printf " --reset-db-root-pass Perform the risky root password reset (requires script runner with root privileges)\n" + printf " --skip-objcache Skip automatic LiteSpeed Object Cache with Redis configuration\n" printf " -h, --help Display this help message\n" printf "\n" - printf "Example:\n" + printf "Examples:\n" printf " %s --wpusername=myuser --wppassword='securePass' --wpemail=me@example.com --dbrootpass='currentRootPass'\n" "$0" printf " %s --wpusername=myuser --wppassword='securePass' --wpemail=me@example.com --reset-db-root-pass --domain=example.com\n" "$0" + printf " %s --wpusername=myuser --wppassword='securePass' --wpemail=me@example.com --dbrootpass='currentRootPass' --skip-objcache\n" "$0" exit 1 } @@ -122,7 +125,7 @@ cleanup() { } # --- Argument Parsing --- -TEMP=$(getopt -o h --longoptions help,wpusername:,wppassword:,wpemail:,wproot:,domain:,dbhost:,dbrootpass:,reset-db-root-pass,webuser:,webgroup: -n "$0" -- "$@") +TEMP=$(getopt -o h --longoptions help,wpusername:,wppassword:,wpemail:,wproot:,domain:,dbhost:,dbrootpass:,reset-db-root-pass,webuser:,webgroup:,skip-objcache -n "$0" -- "$@") if [ $? != 0 ]; then error_exit "Terminating... Invalid arguments provided." fi @@ -144,6 +147,7 @@ while true; do --reset-db-root-pass) PERFORM_DB_ROOT_RESET="true"; shift 1 ;; --webuser) WEB_USER="$2"; shift 2 ;; --webgroup) WEB_GROUP="$2"; shift 2 ;; + --skip-objcache) SKIP_OBJCACHE="true"; shift 1 ;; -h|--help) usage ;; --) shift ; break ;; *) error_exit "Internal error parsing options! Unexpected option: $1";; @@ -680,6 +684,45 @@ if ! $SUDO_CMD $WP_EXECUTABLE core is-installed "${WP_RUN_ARGS[@]}"; then $SUDO_CMD $WP_EXECUTABLE option update litespeed.conf.cache-browser 1 "${WP_RUN_ARGS[@]}" || warning "Could not enable browser cache" success "LiteSpeed Cache basic configuration completed." + + # Configure LiteSpeed Object Cache with Redis (unless skipped) + if [[ "$SKIP_OBJCACHE" == "false" ]]; then + info "Configuring LiteSpeed Object Cache with Redis (Single Node/Standalone)..." + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + OBJCACHE_SCRIPT="$SCRIPT_DIR/configure_litespeed_redis_object_cache.sh" + + if [[ -f "$OBJCACHE_SCRIPT" ]]; then + # Simple Redis detection for single node/standalone setup + REDIS_SOCKET="/var/run/redis/redis.sock" + + # Priority: Socket first (best performance), then TCP fallback + if [[ -S "$REDIS_SOCKET" ]] && redis-cli -s "$REDIS_SOCKET" ping >/dev/null 2>&1; then + info "Redis socket available. Configuring with socket connection (optimal for single node)..." + if bash "$OBJCACHE_SCRIPT" --enable --connection-type=socket; then + success "LiteSpeed Object Cache configured with Redis socket successfully." + else + warning "Failed to configure LiteSpeed Object Cache with Redis socket. You can configure it manually later." + fi + elif redis-cli -h 127.0.0.1 -p 6379 ping >/dev/null 2>&1; then + info "Redis TCP available. Configuring with TCP connection..." + if bash "$OBJCACHE_SCRIPT" --enable --connection-type=tcp --redis-host=127.0.0.1 --redis-port=6379; then + success "LiteSpeed Object Cache configured with Redis TCP successfully." + else + warning "Failed to configure LiteSpeed Object Cache with Redis TCP. You can configure it manually later." + fi + else + warning "Redis is not available. LiteSpeed Object Cache not configured." + warning "To configure later: bash $OBJCACHE_SCRIPT --enable" + fi + else + warning "LiteSpeed Object Cache configuration script not found at: $OBJCACHE_SCRIPT" + warning "You can configure Object Cache manually through the LiteSpeed admin panel." + fi + else + info "Skipping automatic LiteSpeed Object Cache configuration (--skip-objcache specified)." + info "You can configure Object Cache later using:" + info "bash $(dirname "${BASH_SOURCE[0]}")/configure_litespeed_redis_object_cache.sh --enable" + fi else warning "Failed to install LiteSpeed Cache plugin. You can install it manually from the WordPress admin." fi @@ -1060,6 +1103,30 @@ printf " Cache Enabled: ${GREEN}Yes${NC}\n" printf " Cache TTL: ${GREEN}1 week (604800 seconds)${NC}\n" printf " Optimizations: ${GREEN}CSS/JS minification, WebP, Lazy loading${NC}\n" printf " Admin Panel: ${GREEN}https://%s/wp-admin/admin.php?page=litespeed${NC}\n" "$DOMAIN" +printf "\n" +printf "${YELLOW}LiteSpeed Object Cache (Single Node):${NC}\n" +if [[ "$SKIP_OBJCACHE" == "true" ]]; then + printf " Status: ${YELLOW}Skipped (--skip-objcache used)${NC}\n" + printf " Manual Setup: ${BLUE}bash scripts/configure_litespeed_redis_object_cache.sh --enable${NC}\n" +else + # Simple Redis detection for summary + REDIS_SOCKET="/var/run/redis/redis.sock" + if [[ -S "$REDIS_SOCKET" ]] && redis-cli -s "$REDIS_SOCKET" ping >/dev/null 2>&1; then + printf " Status: ${GREEN}Configured (Socket Connection)${NC}\n" + printf " Method: ${BLUE}Redis${NC}\n" + printf " Host: ${GREEN}%s${NC}\n" "$REDIS_SOCKET" + printf " Port: ${GREEN}0${NC}\n" + elif redis-cli -h 127.0.0.1 -p 6379 ping >/dev/null 2>&1; then + printf " Status: ${GREEN}Configured (TCP Connection)${NC}\n" + printf " Method: ${BLUE}Redis${NC}\n" + printf " Host: ${GREEN}127.0.0.1${NC}\n" + printf " Port: ${GREEN}6379${NC}\n" + else + printf " Status: ${RED}Not Configured (Redis unavailable)${NC}\n" + printf " Next Steps: ${YELLOW}1. Install and start Redis${NC}\n" + printf " ${YELLOW}2. Run: bash scripts/configure_litespeed_redis_object_cache.sh --enable${NC}\n" + fi +fi if [[ "$PERFORM_DB_ROOT_RESET" == "true" ]]; then printf "\n${RED}IMPORTANT: The MySQL/MariaDB root password was reset during this process.${NC}\n" printf " New Root Pass: ${YELLOW}%s${NC} (Keep this safe!)\n" "$DB_ROOT_PASS" diff --git a/scripts/manage_litespeed_objcache.php b/scripts/manage_litespeed_objcache.php new file mode 100644 index 0000000..8e4a674 --- /dev/null +++ b/scripts/manage_litespeed_objcache.php @@ -0,0 +1,187 @@ +&1', $output, $return_var); + return ['output' => $output, 'return_var' => $return_var]; +} + +function test_redis_connection($connection_type, $host = '127.0.0.1', $port = '6379') { + if ($connection_type === 'socket') { + if (!file_exists(REDIS_SOCKET)) { + return ['success' => false, 'message' => 'Redis socket not found: ' . REDIS_SOCKET]; + } + $result = run_command('redis-cli -s ' . REDIS_SOCKET . ' ping'); + } else { + $result = run_command("redis-cli -h $host -p $port ping"); + } + + $success = ($result['return_var'] === 0 && isset($result['output'][0]) && trim($result['output'][0]) === 'PONG'); + + return [ + 'success' => $success, + 'message' => $success ? 'Redis connection successful' : 'Redis connection failed', + 'output' => $result['output'] + ]; +} + +function get_object_cache_status() { + if (!file_exists(HTTPD_CONF)) { + return [ + 'enabled' => false, + 'configured' => false, + 'message' => 'LiteSpeed configuration file not found' + ]; + } + + $config_content = file_get_contents(HTTPD_CONF); + $has_objcache = strpos($config_content, 'objCache') !== false; + $cache_enabled = false; + + // Check if cache is enabled + if (preg_match('/enableCache\s+(\d+)/', $config_content, $matches)) { + $cache_enabled = (int)$matches[1] === 1; + } + + $redis_config = []; + if ($has_objcache) { + // Extract Redis configuration + if (preg_match('/type\s+redis/', $config_content)) { + $redis_config['type'] = 'redis'; + } + if (preg_match('/addr\s+([^\s\n]+)/', $config_content, $matches)) { + $redis_config['addr'] = $matches[1]; + } + if (preg_match('/defaultTTL\s+(\d+)/', $config_content, $matches)) { + $redis_config['ttl'] = $matches[1]; + } + } + + return [ + 'enabled' => $cache_enabled, + 'configured' => $has_objcache, + 'redis_config' => $redis_config, + 'message' => $has_objcache ? 'Object Cache is configured' : 'Object Cache not configured' + ]; +} + +function generate_cache_config($enable = true, $connection_type = 'socket', $host = '127.0.0.1', $port = '6379') { + if (!$enable) { + return " +cache { + enableCache 0 + + storage { + cacheStorePath /tmp/lshttpd/cache/ + } +} +"; + } + + $redis_addr = ($connection_type === 'socket') ? 'unix:' . REDIS_SOCKET : "$host:$port"; + + return " +cache { + enableCache 1 + qsCache 1 + reqCookieCache 1 + respCookieCache 1 + ignoreReqCacheCtrl 1 + ignoreRespCacheCtrl 0 + enablePrivateCache 0 + privateExpireInSeconds 3600 + + storage { + cacheStorePath /tmp/lshttpd/cache/ + + # Redis Object Cache Configuration + objCache { + type redis + addr $redis_addr + defaultTTL 60 + } + } +} +"; +} + +switch ($action) { + case 'status': + $status = get_object_cache_status(); + + echo json_encode([ + 'status' => 'success', + 'data' => $status, + 'message' => $status['message'] + ], JSON_PRETTY_PRINT); + break; + + case 'test-redis': + $test = test_redis_connection($connection_type, $redis_host, $redis_port); + + echo json_encode([ + 'status' => $test['success'] ? 'success' : 'error', + 'message' => $test['message'], + 'connection_type' => $connection_type, + 'redis_host' => $connection_type === 'tcp' ? $redis_host : 'socket', + 'redis_port' => $connection_type === 'tcp' ? $redis_port : 'N/A' + ], JSON_PRETTY_PRINT); + break; + + case 'enable': + // Test Redis connection first + $test = test_redis_connection($connection_type, $redis_host, $redis_port); + if (!$test['success']) { + echo json_encode([ + 'status' => 'error', + 'message' => 'Cannot enable Object Cache: ' . $test['message'] + ]); + exit(1); + } + + // Generate configuration + $config = generate_cache_config(true, $connection_type, $redis_host, $redis_port); + + echo json_encode([ + 'status' => 'success', + 'message' => 'Object Cache configuration generated successfully', + 'config_preview' => $config, + 'next_step' => 'Run the bash script to apply configuration' + ], JSON_PRETTY_PRINT); + break; + + case 'disable': + $config = generate_cache_config(false); + + echo json_encode([ + 'status' => 'success', + 'message' => 'Object Cache disable configuration generated', + 'config_preview' => $config, + 'next_step' => 'Run the bash script to apply configuration' + ], JSON_PRETTY_PRINT); + break; + + default: + echo json_encode([ + 'status' => 'error', + 'message' => 'Invalid action. Available actions: status, test-redis, enable, disable', + 'usage' => 'php manage_litespeed_objcache.php [action] [connection_type] [redis_host] [redis_port]' + ]); + exit(1); +} +?> \ No newline at end of file