Cron task that executes pm2 process manager - pm2

I created the following bash script that it works
#!/bin/bash
if lsof -Pi :1337 -sTCP:LISTEN -t >/dev/null ; then
pm2 status>/dev/null
else
pm2 start server>/dev/null
fi
Then I create a cron job with the following syntax
*/1 * * * * /home/deploy/Develop/Classy-Backend/pm2automation.sh>/dev/null
but when the cronjob executes, nothing happens and the pm2 process never starts.
Is there something that I missing here?

I found that solution for my problem

Related

Crontab in Docker with flask application

I'm trying to create cronjob within the docker container, But the it doesn't work. Below is my code
Dockerfile
FROM python:3
LABEL image for a very management application
# We copy just the requirements.txt first to leverage Docker cache
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN apt-get install -y default-libmysqlclient-dev
RUN pip3 install -r requirements.txt
RUN apt-get update && apt-get -y install cron
RUN touch /var/log/cron.log
COPY crontab /etc/cron.d/cjob
RUN chmod 0644 /etc/cron.d/cjob
ENV PYTHONUNBUFFERED 1
CMD cron -f
EXPOSE 5000
COPY . .
CMD ["cron", "-f"]
CMD [ "python3", "app.py" ]
crontab
*/5 * * * * root /test.py >> /logfile
test.py
from datetime import datetime
print("Our test works at", datetime.now())
I'm tring to run cronjob with the
docker-compose up
Is anything wrong i'm doing, Is their any other way for cronjob to work. Please can anyone help me. Thank you all
Since you can mainly run one CMD you will need to use the ENTRYPOINT directive. I can give you an example of how I made it work.
The theory behind the solution is that in the base image during build time you prepare all the necessary documents:
copy in the crontab file and apply it
Copy in the additional launch script
set ENTRYPOINT to the launch script
run CMD and start your app
Example:
COPY token-renewal-cron /etc/cron.d/token-renewal-cron
RUN crontab /etc/cron.d/token-renewal-cron
where crontab logic is inside token-renewal-cron
Then you need to copy the launch script into the /usr/local/bin/ directory
COPY launch.sh /usr/local/bin/launch.sh
RUN chmod 0777 /usr/local/bin/launch.sh #0777 as long as it works for POC :)
Where in our case launch.sh contains:
cron # this starts the cron process
TMP # some commands we need to run next to cron command (we prepare app env here)
# Append CMD from Dockerfile NOTE this is important so you can then use CMD after ENTRYPOINT inside DOCKERFILE
exec "$#"
Then at the end of the DOCKERFILE you just prepare ENTRYPOINT and CMD commands
#Launch our entrypoint script
ENTRYPOINT ["launch.sh"]
#Launch our application
CMD ["dotnet", "APPLICATION.dll"]

Mysql cli not returning data in bash script run by crontab

I have a bash script that is executed via a cron job
#!/bin/bash
# abort on errors
set -e
ABS_DIR=/path/
# extract the creds for the mysql db
DB_USER="USERNAME"
DB_PASS="PASSWORD"
function extract_data() {
file=$2
sql_query=`cat $ABS_DIR/$1`
data=`mysql -u $DB_USER --password="$DB_PASS" -D "database" -e "$sql_query" | tail -n +2`
echo -e "Data:"
echo -e "$data"
}
extract_data "sql_query.sql" "log.csv"
When running it manually with bash extract.sh the mysql cmd fetches the data correctly and I see the echo -e "$data" on the console.
When running the script via a cron job
* 12 * * * /.../extract.sh > /.../cron_log.txt
then I get an empty line saved to the cron_log.txt file!?
This is a common problem; a script behaves differently when run from user shell and when run from crontab. The cause is typically due to differences in the environment variables in the user shell, and in the crontab shell; by default, they are not the same.
To begin debugging this issue, you could direct stderr as well as stdout from crontab, hopefully to capture an error message:
extract.sh &> /.../cron_log.txt
(notice the &)
Also: you have three dots (/.../) -- that is likely a typo, could also be the cause.

suspend then wake: cron of rtcwake, Beaglebone Black

I'm trying to configure the beaglebone black [wireless version - 4.9.82-ti-r102 #1 SMP PREEMPT] -- running debian 9.3 stretch.
This command works fine in a bash terminal:
sudo /usr/sbin/rtcwake -m mem -u -t $(date +%s -d "+2 minutes")
I've setup a cron job via
sudo crontab -e
In it, I have the following line:
10,40 * * * * /usr/sbin/rtcwake -m mem -u -t $(date +%s -d "20 minutes")
However, the device is not suspending.
What am I doing wrong? How do I debug this?
Thanks for your help
M
The % char is the problem in the crontab approach. That char has a special meaning in crontab (newline...start of stdin, see manual).
Instead of -t $(date +%s -d "1 minutes") you can simply use -s 60 for sleeping 60 seconds and not having to use % at all. Or you might escape it with \% or use '+%s' or "+%s".
OK,
In case there is anyone else trying to solve this. I don't know why this works, however it does...
1. make a script with the rtcwake comand in it....:
#!/bin/bash
# suspend then wake from a bash script
echo attempting to suspend!
/usr/sbin/rtcwake -m mem -u -t $(date +%s -d "1 minutes")
I called this wakesleep, and placed it in /usr/local/bin (on the PATH), make it executable...
sudo chmod +x /usr/local/bin/sleepwake
Then added a line in crontab, the su version:
sudo crontab -e
The added line in the root crontab is of this sort of format:
10 * * * * /usr/local/bin/sleepwake
... and it works. This is a mystery to me, why the previous approach did not work, but it works. Very keen to hear from someone what the difference between the two approaches is.

Issues with MySQL restart on running through a crontab scheduler

I have written a shell script which starts MySQL when its killed/terminated. I am running this shell script using a crontab.
My cron looks for the script file named mysql.sh under /root/mysql.sh
sh /root/mysql.sh
mysql.sh:
cd /root/validate-mysql-status
sh /root/validate-mysql-status/validate-mysql-status.sh
validate-mysql-status.sh:
# mysql root/admin username
MUSER="xxxx"
# mysql admin/root password
MPASS="xxxxxx"
# mysql server hostname
MHOST="localhost"
MSTART="/etc/init.d/mysql start"
# path mysqladmin
MADMIN="$(which mysqladmin)"
# see if MySQL server is alive or not
# 2&1 could be better but i would like to keep it simple
$MADMIN -h $MHOST -u $MUSER -p${MPASS} ping 2>/dev/null 1>/dev/null
if [ $? -ne 0 ]; then
# MySQL's status log file
MYSQL_STATUS_LOG=/root/validate-mysql-status/mysql-status.log
# If log file not exist, create a new file
if [ ! -f $MYSQL_STATUS_LOG ]; then
cat "Creating MySQL status log file.." > $MYSQL_STATUS_LOG
now="$(date)"
echo [$now] error : MySQL not running >> $MYSQL_STATUS_LOG
else
now="$(date)"
echo [$now] error : MySQL not running >> $MYSQL_STATUS_LOG
fi
# Restarting MySQL
/etc/init.d/mysql start
now1="$(date)"
echo [$now1] info : MySQL started >> $MYSQL_STATUS_LOG
cat $MYSQL_STATUS_LOG
fi
When I run the above mysql shell script manually using webmin's crontab, MySQL started successfully (when its killed).
However, when I schedule it using a cron job, MySQL doesn't starts. The logs are printed properly (it means my cron runs the scheduled script successfully, however MySQL is not restarting).
crontab -l displays:
* * * * * sh /root/mysql.sh
I found from URL's that we should give absolute path to restart MySQL through schedulers like cron. However, it haven't worked for me.
Can anyone please help me!
Thank You.
First, crontab normaly looks like this:
* * * * * /root/mysql.sh
So remove the surplus sh and put it at the beginning of the script - #!/bin/bash I suppose (why are you referring to sh instead of bash?) and don't forget to have an execute permission on the file (chmod +x /root/mysql.sh)
Second, running scripts within crontab is tricky, because the environment is different! You have to set it manually. We start with PATH: go to console and do echo $PATH, and then copy-paste the result into export PATH=<your path> to your cron script:
mysql.sh:
#!/bin/bash
export PATH=.:/bin:/usr/local/bin:/usr/bin:/opt/bin:/usr/games:./:/sbin:/usr/sbin:/usr/local/sbin
{
cd /root/validate-mysql-status
/root/validate-mysql-status/validate-mysql-status.sh
} >> OUT 2>> ERR
Note that I also redirected all the output to files so that you don't receive emails from cron.
Problem is how to know which other variables (besides PATH) matter. Try to go through set | less and try to figure out which variables might be important to set in the cron script too. If there are any MYSQL related variables, you must set them! You may also examine the cron script environment by putting set > cron.env to the cron script and then diff-ing it against console environment to look for significant differences.

Using Monit with Puma in Jruby

I have Rails app set up using Jruby with puma as the web server. Puma doesn't daemonize on its own, so I wrapped it in a bash script to handle generating a pid (as described in the Monit FAQ). The script is below:
#!/bin/bash
APP_ROOT="/home/user/public_html/app"
export RAILS_ENV=production
export JRUBY_OPTS="--1.9"
export PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH
case $1 in
start)
echo $$ > $APP_ROOT/puma.pid;
cd $APP_ROOT;
exec 2>&1 puma -b tcp://127.0.0.1:5000 1>/tmp/puma.out
;;
stop)
kill `cat $APP_ROOT/puma.pid` ;;
*)
echo "usage: puma {start|stop}" ;;
esac
exit 0
This works from the command line and it works even if I execute it after running the below to simulate the monit shell:
env -i PATH=/bin:/usr/bin:/sbin:/usr/sbin /bin/sh
The relevant monitrc lines are below:
check process puma with pidfile /home/user/public_html/app/puma.pid
start program = "/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh start"
stop program = "/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh stop"
The monit log shows it constantly try to start puma, and it even gets so far as regenerating a new PID, but is never able to actually start puma. Every time I try to run this script from every other context I can think of it works - except from monit.
I managed to get this to work after reading this post: running delayed_job under monit with ubuntu
For some reason, changing my monitrc to use the following syntax made this work. I have no idea why:
start program = "/bin/su - user -c '/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh start'"
stop program = "/bin/su - user -c '/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh stop'"