Make `systemd-run` fail gracefully if the unit name already exists?
I have found systemd-run
which allows one to run processes in the background once off ("transient services"). I always specify the service unit name with --unit $NAME
. But if I have already run the systemd-run
command and my process is running, then systemd-run
will fail, with non-zero exit code. Is there anyway to tell systemd-run
to be more idempotent and not fail in this case?
Currently I'm doing:
systemctl is-active $NAME || systemd-run --unit $NAME $COMMAND
Is there a better way?
This is on Ubuntu 18.04, with the current systemd for that (version 237?)
-G, --collect
Unload the transient unit after it completed, even if it failed. Normally, without this option, all units that ran and failed are kept in memory until the user explicitly resets their failure state with systemctl reset-failed or an equivalent command. On the other hand, units that ran successfully are unloaded immediately. If this option is turned on the "garbage collection" of units is more aggressive, and unloads units regardless if they exited successfully or failed. This option is a shortcut for --property=CollectMode=inactive-or-failed, see the explanation for CollectMode= in systemd.unit(5) for further information.
systemd-run --collect --unit $NAME $COMMAND
I don't think there is a way not to fail.
The problem here is that systemd unit names must be unique. If they aren't, then manipulating the units could become ambiguous. For this reason systemd perceives an error if you try to duplicate unit names, and I don't think there is a way to make it think otherwise.
If you could convince systemd-run
to run the second service with the same name, what would happen if you issue a systemctl stop
command? Which of the two identically named units should stop? The one you ran first? The last? Both?