birb_latency_reporter/reporter.py

75 lines
2.2 KiB
Python
Raw Permalink Normal View History

2021-11-17 19:31:43 +01:00
import os
import time
import requests
from apscheduler.schedulers.blocking import BlockingScheduler
2021-12-02 23:57:33 +01:00
from typing import List, Tuple
2021-11-17 19:31:43 +01:00
2021-12-02 23:57:33 +01:00
def run_report_task(hostname: str, test_urls: list, report_urls: list):
2021-12-02 23:58:27 +01:00
print('.', end='', flush=True)
2021-12-02 23:57:33 +01:00
for testpoint_name, testpoint_url in test_urls:
2021-11-17 19:31:43 +01:00
start_time = time.time()
try:
2021-12-02 23:57:33 +01:00
r = requests.get(testpoint_url, timeout=10)
2021-11-17 19:31:43 +01:00
except requests.exceptions.Timeout:
2021-12-02 23:57:33 +01:00
print(testpoint_name, testpoint_url, "Timed out")
2021-11-17 19:31:43 +01:00
continue
else:
latency_s = time.time() - start_time
if r.status_code != 204:
2021-12-02 23:57:33 +01:00
print(testpoint_name, testpoint_url, "Wrong response:", r.status_code)
2021-11-17 19:31:43 +01:00
continue
report = {
"client": hostname,
2021-12-02 23:57:33 +01:00
"site": testpoint_name,
2021-11-17 19:31:43 +01:00
"measurements": {
"latency": latency_s * 1000
}
}
2021-12-02 23:57:33 +01:00
for report_name, report_url in report_urls:
2021-11-17 19:31:43 +01:00
r = requests.post(report_url, json=report)
if r.status_code != 201:
2021-12-02 23:57:33 +01:00
print(report_name, report_url, "Wrong response:", r.status_code)
2021-11-17 19:31:43 +01:00
continue
2021-12-02 23:57:33 +01:00
def parse_url_list(url_list: str) -> List[Tuple[str, str]]:
parsed_urls = []
for pair in url_list.split(' '):
parsed_urls.append(
tuple(pair.split(';', 1))
)
return parsed_urls
2021-11-17 19:31:43 +01:00
def main():
2021-12-02 23:57:33 +01:00
test_urls = parse_url_list(os.environ.get("TEST_URLS", ""))
report_urls = parse_url_list(os.environ.get("REPORT_URLS", ""))
2021-11-17 19:31:43 +01:00
frequency = float(os.environ.get("FREQUENCY", 15))
2021-12-02 23:57:33 +01:00
hostname = os.environ['HOSTNAME']
2021-11-17 19:31:43 +01:00
if (not test_urls) or (not report_urls):
print("No urls defined")
return
2021-12-02 23:57:33 +01:00
print("Testing the following endpoints:")
for testpoint_name, testpoint_url in test_urls:
print(testpoint_name, testpoint_url)
print("Reporting to the following endpoints:")
for report_name, report_url in report_urls:
print(report_name, report_url)
2021-11-17 19:31:43 +01:00
scheduler = BlockingScheduler()
scheduler.add_job(lambda: run_report_task(hostname, test_urls, report_urls), trigger='interval', seconds=frequency)
scheduler.start()
if __name__ == '__main__':
main()