1

My setup has a systemd service that should periodically write to a file. I would like to monitor the file for changes, so when it hasn't been modified for a while, I know the service has bugged out. I would like to be able to automatically restart the service when that happens.

I have tried using the path unit file, but it can only start a command when the monitored file is changed, not the other way round.

The opposite question has been asked, where the service needs to be restarted when a file was changed, but the solution doesn't seem to be directly applicable to my situation.

pinealan
  • 13
  • 4
  • https://superuser.com/q/689017/144961 – Michael Hampton Jan 21 '18 at 02:59
  • @Micahel Thank you for raising that point. I did try to debug the program for a while, but I arrived at the conclusion that the bug comes from a library which I have no commit access to. I raised the issue with the team responsible, but before they fix it, I still need a hack to solve the problem temporarily. – pinealan Jan 23 '18 at 13:49
  • Be careful with that. If you're successful at a "temporary" hack, that might become the permanent solution. – Michael Hampton Jan 23 '18 at 14:15

1 Answers1

2

While the comment answer does bring up a good point on where one should be focusing their energy when dealing with an issue like this (debug and try to determine why it might be hanging?), a possible solution to your question could be to set up a systemd-timer that fires at whatever interval you're looking to check that file, and have that run a script that does your testing and actions. Maybe something like (if you're using 1hr as your interval):

Timer

[~]# cat /etc/systemd/system/checkhung.timer 
[Unit]
Description=Check if file not modified in a while and restart service

[Timer]
OnActiveSec=60min
OnUnitActiveSec=60min

Service

[~]# cat /etc/systemd/system/checkhung.service 
[Unit]
Description=Check if file not modified in a while and restart service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/checker.sh

Script

[~]# cat /usr/local/bin/checker.sh
#!/bin/bash

if [[ $(find /path/to/the/file.txt -mmin +60) ]]
then
    /usr/bin/systemctl restart my-service.service
fi

Note that I haven't tested this, so some tweaking may be necessary.

Adam V
  • 188
  • 1
  • 10