Bash script to kill Magento 2 indexing process after 2.5 hours

Recently, I needed to create a script that would kill a process that would overrun the server CPU and memory.

Magento 2 is prone to having issues with Elasticsearch and indexing. If indexing fails somewhere down the line, it does not stop the process and keeps running the server into the ground.

Here is a bash script that kills the process after 2.5 hours (9000 seconds):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash
# This script will kill Indexing process which is running for more than 2.5 hours

(PIDS="`ps aux | grep "group=index" | awk '{print $2}'`"

for i in ${PIDS};
do
{
    time="`ps -p $i -o etimes= | awk '{print $1}'`";

    now=$(date +"%T");

    echo "trying to kill $i";

    if [[ $time -gt 9000 ]] ; then
        echo "---------------------------";
        echo "Killing $i";
        echo "Process running for $time";
        echo "Current time : $now";
        kill -9 $i;
    fi
}
done;)|tee -a "/var/www/php/var/log/indexkiller.log"

When deploying it, you will need to run it in cron of www-data user, with user www-data owning the file and having execute permissions on the file.

I would suggest commenting this line for testing before full deployment:

1
#kill -9 $i;

Then you can take a look at the logs and see if the bash script actually worked.

Leave a Reply