diff --git a/healthcheck.py b/healthcheck.py new file mode 100644 index 0000000..33d63a4 --- /dev/null +++ b/healthcheck.py @@ -0,0 +1,49 @@ +import requests +import subprocess + +from dotenv import load_dotenv +from os import getenv +from time import sleep + +load_dotenv() + +CHECK_INTERVAL = int(getenv('CHECK_INTERVAL')) + +CONFIG = [ + {'url': getenv('MOSHFERATU_DEV_URL'), 'container_name': getenv('MOSHFERATU_DEV_CONTAINER')}, + {'url': getenv('MOSHINGTON_URL'), 'container_name': getenv('MOSHINGTON_CONTAINER')} +] + +def healthy(url): + """Check the health of a web application by pinging the given URL.""" + try: + response = requests.get(url, timeout = 20) + if response.status_code == 200: + print(f'Healthcheck successful for {url}') + return True + else: + print(f'Healthcheck failed for {url} with status code: {response.status_code}') + return False + except requests.RequestException as e: + print(f'Healthcheck request failed for {url}: {e}') + return False + +def restart_docker_container(container_name): + """Restart the specified Docker container.""" + print(f'Restarting Docker container: {container_name}...') + result = subprocess.run(['docker', 'restart', container_name], capture_output = True, text = True) + if result.returncode == 0: + print(f'Docker container {container_name} restarted successfully.') + else: + print(f'Failed to restart Docker container {container_name}: {result.stderr}') + +if __name__ == '__main__': + while True: + for config in CONFIG: + url = config['url'] + container_name = config['container_name'] + + if not healthy(url): + restart_docker_container(container_name) + + sleep(CHECK_INTERVAL) \ No newline at end of file