From 77a5f1a0718ed86a072384c2bb2dd230e860dfa4 Mon Sep 17 00:00:00 2001 From: vvzvlad Date: Fri, 17 Jan 2025 07:20:54 +0300 Subject: [PATCH] Refactor upload_stats_to_grist function in grpc-balancer.py to consolidate server statistics into a single dictionary, improving clarity and maintainability. Update error logging to include exception details. --- grpcbalancer/grpc-balancer.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/grpcbalancer/grpc-balancer.py b/grpcbalancer/grpc-balancer.py index 6a877d5..796bdca 100644 --- a/grpcbalancer/grpc-balancer.py +++ b/grpcbalancer/grpc-balancer.py @@ -268,25 +268,26 @@ def select_servers(): def upload_stats_to_grist(update_row): while True: try: - stats = {} - stats['failures'] = 0 - stats['successes'] = 0 - stats['rps'] = 0 + total_stats = { + 'failures': 0, + 'successes': 0, + 'rps': 0 + } + with STATS_LOCK: for server in BACKEND_SERVERS: server_id = server['id'] - stats = SERVER_STATS[server_id] - failures = sum(1 for t, success in stats if not success) - successes = len(stats) - failures - stats['failures'] += failures - stats['successes'] += successes - stats['rps'] += len(stats)/STATISTICS_WINDOW.total_seconds() - #logging.info(f"Server {server_id}: {successes} successes, {failures} failures, Weight: {weight:.2f}") + server_stats = SERVER_STATS[server_id] + failures = sum(1 for t, success in server_stats if not success) + successes = len(server_stats) - failures + total_stats['failures'] += failures + total_stats['successes'] += successes + total_stats['rps'] += len(server_stats)/STATISTICS_WINDOW.total_seconds() - health = f"{stats['successes']}/{stats['failures']}/{stats['rps']}" + health = f"{total_stats['successes']}/{total_stats['failures']}/{total_stats['rps']:.2f}" update_row({"Health": health}) except Exception as e: - logging.error(f"Failed to upload stats to Grist: {e}") + logging.error(f"Failed to upload stats to Grist: {str(e)}") time.sleep(30) if __name__ == '__main__':