Count connections in manager and write the numbers into a CSV file

This commit is contained in:
Lee Miller 2023-09-04 02:31:17 +03:00
parent 48a86815c8
commit eb447a92dc
Signed by untrusted user: lee.miller
GPG Key ID: 4F97A5EA88F4AB63
1 changed files with 47 additions and 0 deletions

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""The main thread, managing connections, nodes and objects"""
import base64
import csv
import logging
import os
import pickle
@ -26,6 +27,10 @@ class Manager(threading.Thread):
# Publish destination 5-15 minutes after start
self.last_published_i2p_destination = \
time.time() - 50 * 60 + random.uniform(-1, 1) * 300 # nosec
self.last_dumped_counts = time.time()
self.connection_counts = []
self.connections_avg = 0
self.connections_max = 0
def run(self):
self.clean_objects()
@ -40,6 +45,7 @@ class Manager(threading.Thread):
self.last_cleaned_objects = now
if now - self.last_cleaned_connections > 2:
self.manage_connections()
self.check_connections_count()
self.last_cleaned_connections = now
if now - self.last_pickled_objects > 100:
self.pickle_objects()
@ -47,9 +53,50 @@ class Manager(threading.Thread):
if now - self.last_pickled_nodes > 60:
self.pickle_nodes()
self.last_pickled_nodes = now
if now - self.last_dumped_counts > 300:
self.dump_counts()
self.last_dumped_counts = now
if now - self.last_published_i2p_destination > 3600:
self.publish_i2p_destination()
self.last_published_i2p_destination = now
logging.info(
'Connections number max: %s, average: %.2f',
self.connections_max, self.connections_avg)
def dump_counts(self):
"""Write connection counts into a csv file"""
total = 0
with open(
os.path.join(shared.data_directory, 'connection_counts.csv'),
'a', newline='', encoding='ascii'
) as dst:
writer = csv.writer(dst)
for timestamp, number in self.connection_counts:
total += number
if number > self.connections_max:
self.connections_max = number
writer.writerow((time.ctime(timestamp), number))
avg = total / len(self.connection_counts)
self.connections_avg = (
(self.connections_avg + avg) / 2 if self.connections_avg else avg)
self.connection_counts = self.connection_counts[-1:]
def check_connections_count(self):
"""Make a record for changed connections count"""
try:
previous_count = self.connection_counts[-1]
except IndexError:
previous_count = 0
count = sum((
1 for c in shared.connections.copy()
if c.status == 'fully_established'))
if count != previous_count:
self.connection_counts.append((time.time(), count))
if count == shared.outgoing_connections:
logging.info('Max outgoing connections reached!')
@staticmethod
def clean_objects():