Skip to content

Instantly share code, notes, and snippets.

@LeoniePhiline
Last active March 24, 2024 12:41
Show Gist options
  • Save LeoniePhiline/c2e209c958050df98fc97c5bb0048146 to your computer and use it in GitHub Desktop.
Save LeoniePhiline/c2e209c958050df98fc97c5bb0048146 to your computer and use it in GitHub Desktop.
Auto-determine plesk php-fpm version for a given site in order to invoke the correct plesk php CLI binary in crontab. Requires PHP FPM setting "pm" to be set to "dynamic" with at least 1 process running at all times. Will not work with default "pm=ondemand"!
#!/bin/zsh
# USAGE in crontab:
# =================
#
# */15 * * * * (date -Is; /path/to/auto-php.sh 'subdomain.example.com' -f '/path/to/php/script' -- '<php script argument...>') >> /var/www/vhosts/example.com/logs/subdomain.example.com/cron_log 2>&1
# First argument, e.g. "subdomain.example.com"
SITE_HOSTNAME="$1"
# Move up all remaining arguments, so we can use "$@" starting at what used to be "$2".
shift
# Get the first (any, we don't care which) of multiple process IDs
# of the php-fpm pool running for the site hostname.
# NOTE: PHP-FPM must be configured with `pm=dynamic` and `pm.min_spare_servers` >= 1.
PHP_FPM_POOL_PID="$(pgrep -f "php-fpm: pool ${SITE_HOSTNAME}" | head -n 1)"
# Get the service name which started the pool process.
PHP_FPM_SERVICE_NAME="$(systemctl status -n0 "${PHP_FPM_POOL_PID}" 2>/dev/null | head -n1 | awk '{print $2}')"
# Extract the systemd service's `ExecStart` property.
# e.g. "{ path=/opt/plesk/php/8.3/sbin/php-fpm ; argv[]=/opt/plesk/php/8.3/sbin/php-fpm --nodaemonize ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }"
PHP_FPM_SERVICE_EXEC_START="$(systemctl show "${PHP_FPM_SERVICE_NAME}" -P ExecStart)"
# Extract only the `path=(\S*?)` part.
# e.g. "/opt/plesk/php/8.3/sbin/php-fpm"
PHP_FPM_BIN_PATH="$(echo "$PHP_FPM_SERVICE_EXEC_START" | awk '{match($0,/path=[^ ]*/,a);print a[0]}' | cut -d'=' -f2)"
# Construct the path to the php CLI binary in `../bin`.
# e.g. "/opt/plesk/php/8.3/sbin/php-fpm" -> "/opt/plesk/php/8.3/bin/php"
PHP_CLI_BIN_PATH="$(realpath "$(dirname "${PHP_FPM_BIN_PATH}")/../bin/php")"
# Execute the PHP CLI with the rest of the arguments.
"${PHP_CLI_BIN_PATH}" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment