From b02c6d240fe198099d94c64e0bb3fae84bd4c38e Mon Sep 17 00:00:00 2001 From: brb Date: Mon, 10 Jul 2023 16:45:49 +0200 Subject: [PATCH] added code to run main loop of service --- code/main.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 code/main.py diff --git a/code/main.py b/code/main.py new file mode 100644 index 0000000..da1a6be --- /dev/null +++ b/code/main.py @@ -0,0 +1,51 @@ +import time +import logging +import time +import os +from initialise_app import initialise_app +from bandwidth import measure as measure_bandwidth +from database import connect + +def event(): + logging.info('started event') + # get env vars + replicates = int(os.getenv('REPLICATES')) + # setup database connection + db = connect() + # run event + for rep_num in range(replicates): + logging.info(f'running replicate {rep_num}') + # do measurement + try: + res = measure_bandwidth() + except Exception as e: + logging.error(f'failed to measure bandwidth: {e}') + continue + # upload result to database + payload_dict = { + 'user_id': os.getenv('USER_ID'), + 'data': res + } + try: + db_id = db.insert_one(payload_dict).inserted_id + except Exception as e: + logging.error(f'failed sending results to database: {e}') + continue + logging.debug(f'data sent to database received db_id: {db_id}') + time.sleep(1) + logging.info('finished event') + +if __name__ == '__main__': + initialise_app() + trigger_time = time.time() + while True: + if time.time() >= trigger_time: + # set new trigger time + trigger_time += int(os.getenv('TRIGGER_INTERVAL_SECONDS')) + # run event + try: + event() + except Exception as e: + logging.error(e) + time.sleep(1) +