Skip to content

Instantly share code, notes, and snippets.

@tomislacker
Created August 19, 2016 16:38
Show Gist options
  • Select an option

  • Save tomislacker/f41945a33b52cc23d03dfd952d6a0434 to your computer and use it in GitHub Desktop.

Select an option

Save tomislacker/f41945a33b52cc23d03dfd952d6a0434 to your computer and use it in GitHub Desktop.
php-fpm strace all (or some) instances
#!/bin/bash
# Default number of seconds to strace for
DEFAULT_STRACE_TIMEOUT=$((60*30))
# Job check frequency
DEFAULT_CHECK_INTERVAL=30
# Use timeout?
USE_TIMEOUT_CMD=n
# Set a maximum number of strace jobs to run
# If zero, will do all of them
MAX_WORKERS=0
msg_stamp ()
{
date --iso-8601=seconds
}
msg_out ()
{
echo -e "[$(msg_stamp)] $@"
}
msg_err ()
{
msg_out $@ 1>&2
}
msg_fatal ()
{
local exit_val=$1
shift
msg_err $@
exit $exit_val
}
get_master_pid ()
{
ps aux \
| grep 'php-fpm: master process' \
| grep -v grep \
| awk '{ print $2 }'
}
get_worker_pids ()
{
local master_pid=$(get_master_pid)
msg_err "[DEBUG] master_pid=${master_pid}"
pidof php5-fpm \
| sed -e "s/\(^\|\s\)${master_pid}\(\s\|$\)/\2/g"
}
start_worker_strace ()
{
local worker_pid=$1
local strace_timeout=${2:-${DEFAULT_STRACE_TIMEOUT}}
if [ "$USE_TIMEOUT_CMD" == "y" ]
then
( ( \
timeout ${strace_timeout} \
strace -c -p ${worker_pid} \
) \
2>&1 \
| tee strace_php.${worker_pid} \
) &
else
( ( strace -c -p ${worker_pid} ) \
>> strace_php.${worker_pid} 2>&1 \
) &
fi
msg_out "(${worker_pid}) monitored by ($!)"
}
wait_on_workers ()
{
local check_interval=${1:-${DEFAULT_CHECK_INTERVAL}}
local running_pids=( )
while :
do
# Fetch running jobs
running_pids=( $(jobs -p) )
# If no jobs running, break the loop
[[ ${#running_pids[@]} -eq 0 ]] && break
# Show waiting
msg_out "(${#running_pids[@]}) remaining..."
sleep $check_interval
done
}
# Check that we're root
if [[ $UID != 0 ]]
then
echo "ERROR: This script must be run as root or with sudo" >&2
exit 1
fi
pids=( $(get_worker_pids) )
msg_out "Found ${#pids[@]} PID(s) to monitor..."
for pid in ${pids[@]}
do
start_worker_strace \
$pid \
30
# Should we limit how many strace workerss we're running?
if [[ ${MAX_WORKERS} -gt 0 ]]
then
# Yes, limit them. If at the limit, break this loop
[[ $(jobs -p | wc -l) -ge ${MAX_WORKERS} ]] \
&& break
fi
done
# Wait on all the strace invocations to complete
wait_on_workers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment