How do I prevent my Linux service (Ubuntu 16.04.5 LTS) from restarting when using loops that run in the background? - linux

So I have a script setup that I want to run as a service. The script runs 8 curl commands continuously forever:
#!/bin/bash
threads=8
check_interval=15
batch_url=https://myurl.com
for ((i = 0 ; i < threads ; i++)); do
sleep $i
while true; do
sleep 0.5
has_items=$(curl --silent -m 15.0 --connect-timeout 1.5 $batch_url/$i)
if [ "$has_items" == "false" ]; then
sleep ${check_interval}
continue
fi
done &
done
I have a service file setup in systemd that looks like:
[Unit]
Description=Run the batch forever
After=network.target
[Service]
Type=simple
Restart=always
RestartSec=1
ExecStart=/bin/bash /usr/bin/my_script_location
[Install]
WantedBy=multi-user.target
If I simply run the script it works fine. It loops forever pinging URLs /0 through /7 forever.
However, if I set it up as a service, the service will restart after some time.
I believe the issue is related to having the while loop run in the background, but not sure how to make the service work with this. It's possible that the service approach is the wrong method. I simply need this script to always remain running.

Related

Linux systemd service file to start and stop a minecraft server

I am trying to run a minecraft server on a remote linux instance.
I would like the instance to start up the server on a screen named serverscreen which is owned by the user named minecraft once the system boots up, and run a stop command to the serverscreen when the instance shuts down. Then, it needs to wait untill the server has stopped before actually shutting down.
I am quite new to linux but I have managed to come up with a few commands that work, but I have issues trying to start and stop the server automatically.
I have tried quite a few things, like creating a .sh script to run on startup with crontab -e #reboot script.sh, or create a file in etc/rc.local with #!/bin/sh sh script.sh, but those methods didn't seem to work properly for me. Also, they do not run un shutdown unfortunately. Therefore, I thought it would be best to create a service file named minecraft.service with the following commands:
[Unit]
Description=Minecraft Server
After=network.target
[Service]
User=minecraft
Nice=5
KillMode=none
SuccessExitStatus=0 1
InaccessibleDirectories=/root /sys /srv /media -/lost+found
NoNewPrivileges=true
WorkingDirectory=/opt/minecraft/server
ReadWriteDirectories=/opt/minecraft/server
#### Command to start the server.
ExecStart=sudo -u minecraft screen -dmS serverscreen java -Xms6G -Xmx6G -jar /opt/minecraft/server/forgeserver.jar nogui
#### Command to stop the server.
ExecStop=sudo -u minecraft screen -S serverscreen -p 0 -X eval "stuff stop^M"
##### Try to wait untill the server has stopped. I am not sure about this line of code since I haven't been able to test it properly.
ExecStop=/bin/bash -c "while ps -p $MAINPID > /dev/null; do /bin/sleep 1; done"
[Install]
WantedBy=multi-user.target
but when running this, it gives me an error saying that I did not provide an absolute path for something.
Could someone help me setup a service file that will boot up the server on a screen named serverscreen for the user minecraft, and run command stop when the instance shuts down after the server has been stopped?
Thanks to #Riz, the service now works as intended by using a bash script in order to run the commands.

Running bash script as a service and write to another bash script is not working

I have the following problem using bash script.
Here is what I have inside the 'startup' script file:
#!/bin/bash
java -cp ../lib/online-store.jar:../lib/* com.online.store.Main
OnlineStorePID=$!
if [$OnlineStorePID -ne 0] then
echo "kill $OnlineStorePID" > shutdown
fi
Basically what I do, is to run a java application, get the process id and write it to another bash file. All this process works when I execute the startup script, and the 'shutdown' script file is updated successfully with a line containing 'kill processIDNumber' cmd.
Now I have tried to create a service on Ubuntu for this script using the following commands:
sudo systemctl daemon-reload
sudo systemctl enable online-store.service
sudo systemctl start online-store
When I start the service the java application starts successfully, but the shutdown script file is not updated. It seems that the 'echo "kill $OnlineStorePID" > shutdown' line is not executed. I don't get any complain errors. Does anyone knows what's the problem here.
Here is my service file:
[Unit]
Description=Online store service
Requires=multi-user.target
After=multi-user.target
Wants=mysql.service
[Service]
WorkingDirectory=/home/user/Desktop/online-store-service
#path to executable.
ExecStart=/home/user/Desktop/online-store-service/bin/startup
ExecStop=/home/user/Desktop/online-store-service/bin/shutdown
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
Change your script and run the java command like below as back ground process
java -cp ../lib/online-store.jar:../lib/* com.online.store.Main >/dev/null 2>&1 &

BASH - why my NodeJS server script crashing?

Running CentOS (Linux signal-server 3.10.0-123.8.1.el7.x86_64). When i login to the server using SSH and then execute this following line manually it works, but crash when i exit my SSH connection to the server.
$ node /var/www/html/signal-server/avi.js &
This robot also fails to let the server run when i am not manually logged in via SSH:
#!/bin/bash
while :
do
# 1
avi=$(pgrep -f "avi.js")
if [[ "$avi" ]]; then
log1="1 - running avi.js $1 $2"
else
log1="1 - re-launch avi.js $1 $2"
ps aux | grep "avi.js" | awk '{print $2}' | xargs kill
sleep 1
# same if nohup also used
node /var/www/html/signal-server/avi.js &
fi
tt=$(date +"%Y-%m-%d %T")
echo "$tt" "$log1"
sleep 2
done
How can i make it run for-ever please? (i have also other services they are working fine only this one always crashing when i logout from the SSH session)
nohup will do what you want
nohup node /var/www/html/signal-server/avi.js &
You should really write a systemd script for you service, then if your server restarts your service will startup again.
This is a rough idea what such a script may look like
[Service]
ExecStart=node /var/www/html/signal-server/avi.js
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=node-avi
User=some-user
Group=some-group
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
Spend a bit of time reading the systemd documentation

Register daemon controllable by start and stop command in Linux

Many system daemon can be started using start/stop command. I was just curious how start/stop works on Linux system. Say I wrote a daemon executable, how should I configure it so that it can be controlled by start/stop in Linux.
I make a daemon in linux (ArchLinux) few years ago, and it works every day perfectly.
There are 2 ways to do this. Short way and long way:
Short Way:
Create a file in /etc/systemd/system/ called for example mydaemon.service :
/etc/systemd/system/mydaemon.service
[Unit]
Description=This is my first daemon! - Fernando Pucci
After=network.target
[Service]
User=root
WorkingDirectory=/root
Type=oneshotmc
RemainAfterExit=yes
ExecStart=/bin/echo -e "Daemon started"
ExecStop=/bin/echo -e "Daemon Stopped"
[Install]
WantedBy=multi-user.target
This service does nothing but show Daemon Started or Stopped. You can change echoes by the sentences you need.
If you need to run some script, try the Long way:
Long way
Create a file in some directory, like root folder or /usr/lib/systemd/scripts called for example
/root/mydaemon.sh
start() {
<your start sentences here
and here>
}
stop() {
<your stop sentences here
and here>
}
case $1 in
start|stop) "$1" ;;
esac
You must to make it runnable (chmod x)
(And you can execute it with start or stop parameter to test it.)
And as second step, create another file in
/usr/lib/systemd/system/mydaemon.service
[Unit]
Description=Second daemon of Fernando Pucci
After=network.target
[Service]
User=root
WorkingDirectory=/root
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c '/root/mydaemon.sh start'
ExecStart=/bin/echo -e "MyDaemon Started"
ExecStop=/bin/bash -c '/root/mydaemon.sh stop'
ExecStop=/bin/echo -e "MyDaemon Stopped"
[Install]
WantedBy=multi-user.target
Starting and Stopping
systemctl start mydaemon
systemctl stop mydaemon
systemctl status mydaemon
systemctl enable mydaemon
systemctl disable mydaemon
You (and someone) can send me a private msg for help about that.

How to run last and print my script output during boot with systemd?

I’m trying to configure my host during deployment process and to give an output to the screen of what my configuration script is doing.
In RHEL6 it was easy i was echoing what I want to screen or used dialog to display the output, and only when my script was done i got the login prompt.
( I used rc3.d or rc5.d folder with script name S99.myscript.sh)
In RHEL7 i can’t mimic this process.
rc.local does not display my output during booting and also its not guaranteed it will run last.
I guess I need to create a systemd service file that will run my script.
But how do I output the result to the screen while booting?
And how do I make sure I will not get the log-in prompt before my script ends?
below service example works like a charm :)
[Unit]
Description=ldt_bootscript1.service
After=network.target
Before=getty#tty1.service
[Service]
Type=oneshot
ExecStart=/bin/bash -c "/bin/bash /tmp/ldt_scripts/postinstall/rc.firstboot.qas | /usr/bin/dialog --clear --backtitle \"Linux Deployment\" --title \"tests\" --progressbox 20 70 > /dev/console 2>&1"
ExecStartPre=/usr/bin/echo -e \033%G
ExecReload=/bin/kill -HUP $MAINPID
RemainAfterExit=no
WorkingDirectory=/
Environment=TERM=xterm
[Install]
WantedBy=multi-user.target

Resources