Here is one simple shell script to check whether sidekiq process is running or not and then restart it. I am sure many of you were already aware of tools/gems like Monit, Eye, God and so on. Here lets just do it simply with script.
We going to use three methods check_process, start_service and update_last_run. I assume the method name itself gives you an idea of its purpose.
Here is the complete code for you to copy-paste, do some minor path level changes and run it on your machine. You can also download the same from my GitHub gist.
process='sidekiq' # process name, you can use this to monitor any process project_path="/home/ubuntu/apps/demo/" # This is the one you got to change on your side for your server. #change it based on your configs. start_service="bundle exec sidekiq -d -C /home/ubuntu/apps/demo/config/sidekiq.yml -i 0 -P /home/ubuntu/apps/demo/tmp/pids/sidekiq.pid -L /home/ubuntu/apps/demo/log/sidekiq.log" # Method to simply store last run time in monitor.log file. function update_last_run() { current_time=$(date +'%d/%m/%Y %H:%M:%S') echo "Last run: $current_time" > monitor.log }
Method to start the service, simply we need to navigate to project folder and run the start process command. $? will return status code of last command, if is not equal to zero then some thing went wrong. Successful command will always return 0 as exit code.
function start_service() { cd $project_path && $start_service if [ "$?" == "0" ] then echo "$process started successfully" else echo "Could not start process $process" fi } function check_process() { process_id=$(/bin/ps -fu $USER| grep $process | grep -v "grep" | awk '{print $2}') echo "checking process $process" if $process_id is empty, then it got stopped and you have to start it again if [ "$process_id" == "" ] then echo "Process is not running" echo "Starting the process" start_service else echo "Process is running, PID: $process_id" fi update_last_run } If you want to learn more about exit code click here One last thing is, we got to set executable permission and configure crontab to run this script for every 10 minutes.sudo chmod +x monitor.shsudo crontab -u username -e 10 * * * * /home/ubuntu/monitor.shThat's all and now you got your own shell script to monitor sidekiq.
thanks buddy. excellent work