1

I have a daemon which is started using systemd service file during boot-up flow. I want to start the daemon based on the execution result of a script. The script is included in service file under ExecStartPre option.

Based on the execution result of the script, I have to handle the service as mentioned below

  1. If the script returns 0, start the service and proceed with bootup
  2. If 1 is returned, stop the service, don't proceed with bootup
  3. If 2 is returned, don't start the service but proceed with bootup

I would like to know whether my scenario is valid. If yes how to achieve this?

Thanks in Advance.

1 Answer 1

2

systemd.service(5) says:

  ExecStartPre=, ExecStartPost=
      Additional commands that are executed before or after the command in
      ExecStart=, respectively. Syntax is the same as for ExecStart=, except that
      multiple command lines are allowed and the commands are executed one after the
      other, serially.

      If any of those commands (not prefixed with "-") fail, the rest are not
      executed and the unit is considered failed.

      ExecStart= commands are only run after all ExecStartPre= commands that were not
      prefixed with a "-" exit successfully.

So you can use a non-zero exit code to fail the service. This satisfies requirements 1 & 3 on your list. This means if ExecStartPre= returns 0, the service starts and everything continues to boot. If ExecStartPre= does not return 0, the service is flagged as failed and everything else continues to boot. If you call systemctl status, you'll see State: degraded.

Condition 2 is a bit confusing. By "don't proceed with bootup" do you either mean "shutdown" or "systemctl stop multi-user.target"? If this service fails to start, you might just shut down the system, and never be able to log-in to solve the problem (unless you enter some type of rescue mode). Regardless of how to stop multi-user.target or start shutdown.target, it's not something you can easily do based on the exit code of an ExecStartPre=. You'd need to replace your ExecStartPre= with a shell script which calls the original line, and deals with the exit code.

I suspect that you might want something like Restart=on-failure instead. The service can be restarted (or a restart can be prevented) based on the exit code of the main process using RestartForceExitStatus= or RestartPreventExitStatus=

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .