TechSomething

(sorta) monitoring two related systemd services

update: systemd supports this feature
see: https://stackoverflow.com/questions/47253020/systemd-stop-dependent-service-when-main-service-crashes

Scope: #

I need to stop service2 when service1 is down.

Why: #

For example in "DIY balancer using DNS" I want to kill bind/named when haproxy is dead so I won't receive any connection that would not be served by haproxy.

Script: #

the script is executed every n minutes by cron,
it checks service1, if it's dead it checks the status of service2 and if needed it kills service2

it also works in the reverse flow:
when service1 is up it checks that service2 is up and running, if not it starts service2

#!/usr/bin/env bash

service1="haproxy.service"
service2="bind.service"
logfile="services_monitor.log"

#check if service1 is running:
if systemctl is-active --quiet $service1 ; then
echo "$(date +"%Y-%m-%d_%H:%M:%S") - $service1 UP, which is good"

#check if service2 is running, if not, let's start it:
if systemctl is-active --quiet $service2 ; then
echo "$(date +"%Y-%m-%d_%H:%M:%S") - $service2 UP, all is good"
else
echo "$(date +"%Y-%m-%d_%H:%M:%S") - $service1 is UP but $service2 is DOWN, let's start $service2" | tee -a $logfile
systemctl start $service2
fi

else
echo "$(date +"%Y-%m-%d_%H:%M:%S") - $service1 DOWN, which is bad"

#check if service2 is running, if it is, let's stop it:
if systemctl is-active --quiet $service2 ; then
echo "$(date +"%Y-%m-%d_%H:%M:%S") - $service1 is DOWN but $service2 UP, let's stop $service2" | tee -a $logfile
systemctl stop $service2
else
echo "$(date +"%Y-%m-%d_%H:%M:%S") - $service2 is DOWN, all is good"
fi

fi