Compare commits

...

2 Commits

Author SHA1 Message Date
a5be7878ff
Refactored code to be more readable. 2023-10-05 11:59:07 +02:00
3cebcf2ea4
Made an outage into a datastructure.
* Code-correctness has not been veriefied yet.
2023-10-05 09:32:15 +02:00

View File

@ -17,6 +17,32 @@ class LogEntry:
return f"[{self.date}][{self.host}][{'OK' if not self.failed else 'FAIL'}]"
class Outage:
'''
Class describing an outage.
`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:
'''
Print outages from a log file
@ -46,29 +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
for entries in log_by_host.values():
for _, entries in sorted(log_by_host.items()): # sort by hostname
for entry in entries:
# Continue an outage.
if entry.failed and last_failed:
outages[-1].append(entry)
# Start a new outage.
elif entry.failed and not last_failed:
outages.append([entry])
if entry.failed and not last_failed:
outages.append(Outage(entry))
last_failed = True
# End an outage.
elif not entry.failed and last_failed:
outages[-1].end = entry
last_failed = False
# Print the outages.
for outage_start, outage_end in [(outage[0], outage[-1]) for outage in 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:
@ -77,10 +100,10 @@ def printOutages(filepath: str, time: int) -> None:
# Get hours and minutes for printing.
hours = outage_duration // 60
minutes = outage_duration - (hours * 60)
host = outage_start.host
host = outage.start.host
# Outputs outages in the form of "Outage at: 2023-19-01 06:29:01 lasting for 2 Hours and 39 Minutes".
print(f"[{outage_start.date}][{host}] lasting for {'{} Hours and '.format(hours) if hours >= 1 else ''}{minutes} Minutes")
print(f"[{outage.start.date}][{host}] lasting for {'{} Hours and '.format(hours) if hours >= 1 else ''}{minutes} Minutes")
def isOnline(host: str, timeout: int) -> bool: