Systemd – How to Generate Default Systemd .service File

servicessystemd

TL;DR

How to generate an "editable" systemd .service file from an old system-V service?

Recently, we had the issue that our home-grow "server manager" could not start a service on an "Ubuntu 16.04.1" server, because said serveice was in state "active (exited)", and not "inactive". Googling tells me I could add something like this to the service file:

Restart=always
RestartSec=3

But calling "systemctl edit myservice" gets me an empty file. Clearly, systemd generates some default .service file, based on the "/etc/init.d/myservice" file. Using find, I found there is a generated file under "/run/systemd/generator.late/myservice.service". But it contains a lot of stuff, which might be specific to this "run", like "Before=" and "After=" and I'm not sure if I should use it as base.

I don't want to write the .service file from scratch, since I have no knowledge about systemd .service format, and this is a running 24/7 productive server (without test-server clone I could use to "practice").

Best Answer

You are using a unit generated by systemd-sysv-generator, from a van Smoorenburg rc script, most likely one with LSB header information. systemd-sysv-generator takes a one-size-fits-all approach, modified with some guesswork. van Smoorenburg rc scripts may or may not start long-running dæmon processes, may or may not employ PID files, and so forth. systemd-sysv-generator tries to generate service units that accommodate these several possibilities.

The auto-generated service units have RemainAfterExit=true when generated from van Smoorenburg rc scripts with LSB information. So when the process executing the script exits and does not leave any running processes behind, the service is still considered "active", with the service process having exited. That's what remaining after exit means. Hence, the service enters the active (exited) state.

You should stop using /etc/init.d/myservice and stop relying upon systemd-sysv-generator to wrap it in nonce service units. Make a proper, first class, service unit file.

You can start with the one that systemctl edit --full myservice gives you. But clearly that has an incorrect RemainAfterExit=true setting, for starters.

Certainly, that's also a good reason to not continue as you are and not continue relying upon an auto-generated service unit file.

Further reading

Related Question