Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix stale columns data #127

Merged
merged 5 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/howitz/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from howitz.users.utils import authenticate_user

from .config.defaults import DEFAULT_TIMEZONE
from .utils import login_check, date_str_without_timezone
from .utils import login_check, date_str_without_timezone, shorten_downtime, calculate_event_age_no_seconds

main = Blueprint('main', __name__)

Expand Down Expand Up @@ -92,6 +92,7 @@ def auth_handler(username, password):
session["errors"] = {}
session["event_ids"] = []
session["sort_by"] = current_app.howitz_config.get("sort_by", "default")
session["events_last_refreshed"] = None
return user

raise AuthenticationError('Unexpected error on Zino authentication')
Expand All @@ -109,6 +110,7 @@ def logout_handler():
session.pop('errors', {})
session.pop('event_ids', [])
session.pop('sort_by', "raw")
session.pop('events_last_refreshed', None)
current_app.cache.clear()
current_app.logger.info("Logged out successfully.")

Expand All @@ -135,6 +137,7 @@ def clear_ui_state():
session["expanded_events"] = {}
session["errors"] = {}
session["event_ids"] = []
session["events_last_refreshed"] = None
session.modified = True

current_app.cache.clear()
Expand Down Expand Up @@ -168,6 +171,8 @@ def get_sorted_table_event_list(events: dict):
for c in events_sorted.values():
table_events.append(create_table_event(c, expanded=str(c.id) in session["expanded_events"],
selected=str(c.id) in session["selected_events"]))

session["events_last_refreshed"] = datetime.now(timezone.utc)
return table_events


Expand Down Expand Up @@ -227,7 +232,9 @@ def refresh_current_events():
current_app.cache.set("events", current_events)

table_events = []
if is_resort:
has_stale_data = session["events_last_refreshed"] is None or (
datetime.now(timezone.utc) - session["events_last_refreshed"]).total_seconds() > 60
if is_resort or has_stale_data:
table_events = get_sorted_table_event_list(current_events)

return removed_events, modified_events, added_events, table_events
Expand Down Expand Up @@ -317,11 +324,10 @@ def create_table_event(event, expanded=False, selected=False):
common["description"] = event.description
common["port"] = event.port

age = datetime.now(timezone.utc) - event.opened
common["age"] = str(age)[:-10]
common["age"] = calculate_event_age_no_seconds(event.opened)

if event.type == Event.Type.PORTSTATE:
common["downtime"] = ":".join(str(event.get_downtime()).split(":")[:-1]) # some values have only seconds, some both seconds and microseconds
common["downtime"] = shorten_downtime(event.get_downtime())
else:
common["downtime"] = ""
except Exception:
Expand Down
30 changes: 29 additions & 1 deletion src/howitz/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import functools
import traceback
from datetime import datetime, timezone
from datetime import datetime, timezone, timedelta

from flask import current_app
from flask_login import current_user
Expand Down Expand Up @@ -52,3 +52,31 @@ def set_correct_timezone(dt: datetime):
def date_str_without_timezone(dt: datetime):
dt_aware = set_correct_timezone(dt)
return dt_aware.strftime("%Y-%m-%d %H:%M:%S")


# Implementation copied from curitz
def shorten_downtime(td: timedelta):
"""
Shortens downtime to single greatest applicable timedelta unit (days, hours, minutes, seconds).
:param td: downtime as `datetime.timedelta`
:return: formatted downtime as string
"""
if td.days > 0:
return "{:2d}d".format(td.days)
if td.seconds < 60:
return "{:2d}s".format(td.seconds)
if td.seconds / 60 < 60:
return "{:2.0f}m".format(td.seconds / 60)
if td.seconds / 60 / 60 < 60:
return "{:2.0f}h".format(td.seconds / 60 / 60)


def calculate_event_age_no_seconds(opened: datetime):
"""
Calculate event age and remove seconds.
:param opened: event opened time as `datetime.datetime`
:return: event age without seconds as string
"""
age = datetime.now(timezone.utc) - opened
age_formatted = str(age)[:-10]
return age_formatted
Comment on lines +80 to +82
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's soo tempting making a "tznow" utils-function for datetime.now(timezone.utc).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free 😄