#! /usr/bin/python3 import os import requests import time import calendar import logging from email.utils import parsedate logging.basicConfig(level=logging.INFO) HOSTS = os.environ['MIRROR_CHECK_HOSTS'].split() OUTPUT_DIR = "/run/dsa-mirror-health-{}".format(os.environ['MIRROR_CHECK_SERVICE']) HEALTH_FILE = os.path.join(OUTPUT_DIR, "health") URL = os.environ['MIRROR_CHECK_URL'] INTERVAL = int(os.environ.get('MIRROR_CHECK_INTERVAL', '60')) latest_tz = 0 def retrieve_from_host(host, url): proxies = { 'http': 'http://{}:80'.format(host), 'https': 'http://{}:443'.format(host), } return requests.get(url, timeout=5, proxies=proxies) def last_modified(response): lm = 0 if response.status_code == '200' and response.headers.get('last-modified'): lm = calendar.timegm(parsedate(response.headers['last-modified'])) return lm while True: start = time.time() for host in HOSTS: lm = last_modified(retrieve_from_host(host, URL)) logging.debug("lm for host %s: %s", host, lm) if lm > latest_tz: latest_tz = lm local_lm = last_modified(retrieve_from_host('localhost', URL)) logging.debug("lm for localhost: %s", lm) if latest_tz <= local_lm: try: logging.debug("considering myself unhealthy") os.remove(HEALTH_FILE) except OSError: pass else: logging.debug("considering myself healthy") open(HEALTH_FILE, 'w').write("OK") sleep_time = start + INTERVAL - time.time() logging.debug("sleeping for %d seconds", sleep_time) time.sleep(sleep_time)