"""
A very plain watchdog for DaCHS; essentially, it checks that the PID
is still there.

This is mainly to help when debugging DaCHS dependencies that make the
thing segfault (or similar).  Also systemd does the equivalent of this
itself, so don't bother there.
"""

import os
import time

from gavo.user import serve

if os.getuid()!=0:
	raise Exception("Only makes sense if running as root")

while True:
	serverPID = serve.PIDManager.getPID()
	if serverPID is None:
		print("%s: Server found dead, starting"%time.asctime())
		os.system("service dachs start")
		time.sleep(10)
	
	else:

		if not os.path.exists("/proc/%s"%serverPID):
			print("%s: Server has terminated, restarting"%(
				time.asctime()))
			os.system("service dachs restart")
			time.sleep(10)
		else:
			time.sleep(1)
