PhantomJS is fantastic and I use at my SEO Analyzer Site Toolbox hosted with AWS.
Few days after launch, I was going through metrics and noticed CPU utilization is consistently high.
After spending few minutes, I realized it was “phantom/lib/shim.js” process which was eating my CPU. I restarted my node app and CPU was normal.
root 2317 1 5 Oct30 ? 04:40:56 /apps/tools/TWC/1.0/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs /apps/tools/TWC/1.0/node_modules/phantom/lib/shim.js root 2857 1 2 Oct30 ? 01:37:47 /apps/tools/TWC/1.0/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs /apps/tools/TWC/1.0/node_modules/phantom/lib/shim.js
I talked to the developer and guess what. He asked for few hundred dollars to fix it. I was reluctant to spend to fix this so I started my own investigation.
I noticed, shim.js is opened by an application on demand and for some reason, it doesn’t get closed (probably bad code?). I tried killing the process manually and CPU was normal and no impact on application functionality.
And I got my workaround implemented and thought to share with you so you may take advantage of it.
This assumes you are hosting on Linux based OS like CentOS or Ubuntu.
Create a shell script (name it killphantom.sh) with the following
/bin/bash if [[ "$(uname)" = "Linux" ]];then killall --older-than 1h phantomjs;fi
Save the file and change the permission to be executable
chmod 755 killphantom.sh
Note: in above script, I am killing phantomjs process running for older than one hour. You may adjust 1h to base on your requirements.
Execute the script manually to ensure it works.
Now, it’s time to put the script in crontab so it gets executed periodically and maintains CPU utilization.
To create crontab, use crontab –e command
Add the following and save to install cron
*/15 * * * * /yourscript/path/killphantom.sh >/dev/null 2>&1
Above example is to run the crontab every 15 minutes.
To verify, use crontab –l, it should display the script.
All set. Crontab will execute the script every 15 minutes and kill phantomjs.
I know it’s dirty solution but it does the job. I hope this is useful to you.