Better debian-ports.org/debian-cd redirection
[mirror/dsa-puppet.git] / modules / roles / files / mirror_health / mirror-health
index f70cf71..a4df165 100755 (executable)
@@ -5,6 +5,7 @@ import requests
 import time
 import calendar
 import logging
+import subprocess
 from email.utils import parsedate
 logging.basicConfig(level=logging.INFO)
 
@@ -25,28 +26,45 @@ def retrieve_from_host(host, url):
 
 def last_modified(response):
     lm = 0
-    if response.status_code == '200' and response.headers.get('last-modified'):
+    if response.status_code == 200 and response.headers.get('last-modified'):
         lm = calendar.timegm(parsedate(response.headers['last-modified']))
     return lm
 
+def check_shutdown():
+    if subprocess.call(['dsa-is-shutdown-scheduled']) == 0:
+        logging.info("considering myself unhealthy, shutdown scheduled")
+        return False
+    return True
+
+def check_uptodate():
+    global latest_ts
+    for host in HOSTS:
+        try:
+            lm = last_modified(retrieve_from_host(host, URL))
+            logging.debug("lm for host %s: %s", host, lm)
+            latest_ts = max(latest_ts, lm)
+        except (requests.exceptions.ProxyError, requests.exceptions.ReadTimeout):
+            pass
+    try:
+        local_lm = last_modified(retrieve_from_host('localhost', URL))
+    except (requests.exceptions.ProxyError, requests.exceptions.ReadTimeout):
+        return False
+    logging.debug("lm for localhost: %s", local_lm)
+    if local_lm < latest_ts:
+        logging.info("considering myself unhealthy my ts=%s latest_ts=%s", local_lm, latest_ts)
+        return False
+    return True
+
 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_ts:
-            latest_ts = lm
-    local_lm = last_modified(retrieve_from_host('localhost', URL))
-    logging.debug("lm for localhost: %s", lm)
-    if latest_ts <= local_lm:
+    if check_shutdown() and check_uptodate():
+        logging.info("considering myself healthy")
+        open(HEALTH_FILE, 'w').write("OK")
+    else:
         try:
-            logging.info("considering myself unhealthy my ts=%s latest_ts=%s", local_lm, latest_ts)
             os.remove(HEALTH_FILE)
         except OSError:
             pass
-    else:
-        logging.info("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)