From a5be7878ff732ec4da2f7c9e111eeacb29fe9e94 Mon Sep 17 00:00:00 2001 From: Kristian Krsnik Date: Thu, 5 Oct 2023 11:59:07 +0200 Subject: [PATCH] Refactored code to be more readable. --- outage_detector/main.py | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/outage_detector/main.py b/outage_detector/main.py index 571cc23..a6bfd44 100644 --- a/outage_detector/main.py +++ b/outage_detector/main.py @@ -18,12 +18,30 @@ class LogEntry: class Outage: - '''Class describing an outage.''' + ''' + Class describing an outage. - def __init__(self, start: LogEntry, end: LogEntry): + `self.start` The start of the outage represented by a LogEntry object. + + `self.end` The end of an outage represented by a LogEntry object. + Could be None to represent that the outage is still ongoing. + ''' + + def __init__(self, start: LogEntry, end: None | LogEntry = None): self.start = start self.end = end + def duration(self) -> datetime: + ''' + Return the duration of the outage as datetime object. + If the outage does not have an end, the time from the start to now will be returned. + ''' + + if self.end is None: + return self.end.date - datetime.now() + else: + return self.end.date - self.start.date + def printOutages(filepath: str, time: int) -> None: ''' @@ -54,27 +72,26 @@ def printOutages(filepath: str, time: int) -> None: # We consider the time of subsequent failed connection attempts to the same host an outage. outages: list = [] last_failed = False - outage_start = None - for entries in log_by_host.values(): + + for _, entries in sorted(log_by_host.items()): # sort by hostname + for entry in entries: # Start a new outage. if entry.failed and not last_failed: - outage_start = entry + outages.append(Outage(entry)) last_failed = True # End an outage. elif not entry.failed and last_failed: - outages.append(Outage(outage_start, entry)) + outages[-1].end = entry last_failed = False # Print the outages. for outage in outages: # Get duration of outage in hours and minutes. - outage_duration = round( - (outage.end.date - outage.start.date).seconds / 60 - ) + outage_duration = round(outage.duration().seconds / 60) # Skip printing if outage is shorter than the minimum duration. if outage_duration < time: