Refactored code to be more readable.

This commit is contained in:
Kristian Krsnik 2023-10-05 11:59:07 +02:00
parent 3cebcf2ea4
commit a5be7878ff
Signed by: Kristian
GPG Key ID: FD1330AC9F909E85
1 changed files with 26 additions and 9 deletions

View File

@ -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: