9 from email.utils import parsedate
10 import urllib3.util.connection
12 logging.basicConfig(level=logging.INFO)
14 if 'MIRROR_CHECK_HOSTS' in os.environ:
15 HOSTS = os.environ['MIRROR_CHECK_HOSTS'].split()
17 HOSTS = open(os.environ['MIRROR_CHECK_HOSTS_FILE']).read().split()
19 OUTPUT_DIR = "/run/dsa-mirror-health-{}".format(os.environ['MIRROR_CHECK_SERVICE'])
20 HEALTH_FILE = os.path.join(OUTPUT_DIR, "health")
21 URL = os.environ['MIRROR_CHECK_URL']
22 HEALTH_CHECK_URL = os.environ['MIRROR_CHECK_HEALTH_URL']
23 INTERVAL = int(os.environ.get('MIRROR_CHECK_INTERVAL', '60'))
25 def retrieve_from_host(host, url):
26 orig_create_connection = urllib3.util.connection.create_connection
27 def patched_create_connection(address, *args, **kwargs):
29 return orig_create_connection((host, port), *args, **kwargs)
30 headers = {'User-Agent': 'mirror-health'}
31 urllib3.util.connection.create_connection = patched_create_connection
33 return requests.get(url, headers=headers, timeout=5, allow_redirects=False)
35 urllib3.util.connection.create_connection = orig_create_connection
37 def last_modified(response):
39 if response.status_code == 200 and response.headers.get('last-modified'):
40 lm = calendar.timegm(parsedate(response.headers['last-modified']))
43 def healthy(response):
44 if response.status_code == 200:
49 if os.path.exists('/run/systemd/shutdown/scheduled'):
50 logging.info("considering myself unhealthy, shutdown scheduled")
58 lm = last_modified(retrieve_from_host(host, URL))
59 logging.debug("lm for host %s: %s", host, lm)
60 if healthy(retrieve_from_host(host, HEALTH_CHECK_URL)):
61 latest_ts = max(latest_ts, lm)
62 except (requests.exceptions.ProxyError, requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError):
65 local_lm = last_modified(retrieve_from_host('localhost', URL))
66 except (requests.exceptions.ProxyError, requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError):
68 logging.debug("lm for localhost: %s", local_lm)
69 if local_lm < latest_ts:
70 logging.info("considering myself unhealthy my ts=%s latest_ts=%s", local_lm, latest_ts)
76 if check_shutdown() and check_uptodate():
77 logging.info("considering myself healthy")
78 open(HEALTH_FILE, 'w').write("OK")
81 os.remove(HEALTH_FILE)
84 sleep_time = start + INTERVAL - time.time()
85 logging.debug("sleeping for %d seconds", sleep_time)
86 time.sleep(sleep_time)