Skip to content
Advertisement

start-stop-daemon run with external script condition

I need know how run a service with start-stop-daemon with external script condition. Similar to what is done in a systemctl .service file, for example:

NOTE: I need to do the same as the ExecCondition parameter does

[Unit]
Description=My description

[Service]
Type=simple
ExecCondition=/usr/local/bin/checksome.sh
ExecStart=mainscript.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Regards.

Advertisement

Answer

Inside the /etc/init.d directory is the file with the service we want to modify, for example the emqx service. We will have something like this:

do_start()
{
    start-stop-daemon --start 
        --name emqx 
        --user emqx 
        --exec /usr/local/bin/checkconditionandrun.sh emqx -- start 
        || return 2
}

case "$1" in
start)
    log_daemon_msg "Starting emqx"
    do_start
    case "$?" in
        0|1) log_end_msg 0 ;;
        2) log_end_msg 1
            exit 1
            ;;
    esac
    ;;
stop)
    log_daemon_msg "Stopping emqx"
    do_stop
    case "$?" in
        0|1) log_end_msg 0 ;;
        2) log_end_msg 1
            exit 1
            ;;
    esac
    ;;

The key to all this is in two things:

  1. In the do_start() function, the start-stop-daemon –start command should not directly call the “emqx start” command. A script must be called to verify what we need to verify and then that script will or will not execute the command passed as parameter.

  2. Now if we want our service to restart automatically if it has failed, as would be done through a .service with the inputs Restart=always and RestartSec=10, we must know the following:

    a) systemd supports legacy scripts /etc/init.d this way, when systemd loads service definitions, systemd-sysv-generator autogenerates .service files on the fly from the scripts in /etc/init.d.

    b) We can add configuration to an auto-generated service by adding “drop-in” files called “restart.conf” to a folder with the following name: /etc/systemd/system/servicename.service.d/

As explained above and assuming that our service is called “emqx”, we can create a file in the following folder:

/etc/systemd/system/emqx.service.d/restart.conf

with the following content:

[Service]
Restart=always
RestartSec=10

In this way we achieve that a service contained in init.d can control both its startup and its subsequent reboot retry by systemd itself.

For more information about it:

https://singlebrook.com/2017/10/23/auto-restart-crashed-service-systemd/

https://www.freedesktop.org/software/systemd/man/systemd.service.html

https://www.digitalocean.com/community/tutorial_series/how-to-configure-a-linux-service-to-start-automatically-after-a-crash-or-reboot

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement