How to tell why a systemd service was started

centos7systemd

I am trying to figure out why a specific service is started on a system, and I wonder if there is a command to tell why a specific service was started?

When asking for status on the service, systemctl claims that it is disabled, yet it is running and I haven't explicitly asked to start it, AFAICT. Output below (slightly anonymized)

# systemctl status myservice
● myservice.service - My Service
   Loaded: loaded (/usr/lib/systemd/system/myservice.service; disabled; vendor preset: disabled)
   Active: active (running) since mån 2017-02-27 13:57:15 CET; 30min ago
     Docs: http://www.example.com/
 Main PID: 4680 (ewe)
   CGroup: /system.slice/myservice.service
           ├─4680 /opt/myservice/vbc/bin/myservice
           └─4944 /opt/myservice/vbc/bin/myservice

I am starting a service that has set Before=myservice.service in its .service file (no Requires), so I am suspecting that, but I can't tell for sure.

This is running on a CentOS 7.3 system.

EDITED: I have been able to work around the issue by making sure that a service that the above service has a Requires=, After= and Wants= relationship to, and which is started by a transient run-once service, is explicitly stopped. When doing this, the service is not started. I am not closer to figuring out why it was started in the first place, however.

EDITED: It seems that my service file is started whenever one of the
services it has a Requires relationship to is restarted. I did not expect
that to happen, I assumed that it would only mean that my service would
start the other service when started, not that it would also start mine.
Removing Requires fixes the phantom restarts.

Best Answer

Running sudo systemctl status might help, as might systemctl list-dependencies.

I had heard of services being started on install on (I think) Ubuntu, but never on CentOS. However, IF your service has a socket unit defined, then traffic to a given socket/port could be causing your service to start automatically.

I have such a setup for TFTP, for example:

sudo systemctl list-dependencies | grep socket

│ ├─sockets.target
│ │ ├─dbus.socket
<snip>
│ │ └─tftp.socket

Config for it says to start the service if UDP/69 traffic is received:

# /usr/lib/systemd/system/tftp.socket
[Unit]
Description=Tftp Server Activation Socket

[Socket]
ListenDatagram=69

[Install]
WantedBy=sockets.target