Skip to content

Commit c6afce1

Browse files
committed
feat(emerg): move csl status checker to celerybeat task
1 parent 99123cf commit c6afce1

File tree

4 files changed

+44
-32
lines changed

4 files changed

+44
-32
lines changed

intranet/apps/emerg/tasks.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1+
import requests
12
from celery import shared_task
23
from celery.utils.log import get_task_logger
4+
from django.conf import settings
5+
from django.core.cache import cache
6+
from requests.adapters import HTTPAdapter
7+
from urllib3 import Retry
38

49
from .views import update_emerg_cache
510

@@ -10,3 +15,30 @@
1015
def update_emerg_cache_task() -> None:
1116
logger.debug("Updating FCPS emergency info")
1217
update_emerg_cache(custom_logger=logger)
18+
19+
20+
@shared_task
21+
def update_csl_status_task() -> None:
22+
"""Updates the cached status of the tjCSL status page.
23+
24+
Returns:
25+
Nothing
26+
"""
27+
logger.debug("Updating CSL Status")
28+
session = requests.Session()
29+
adapter = HTTPAdapter(
30+
max_retries=Retry(
31+
total=settings.CSL_STATUS_PAGE_MAX_RETRIES, backoff_factor=0.3, status_forcelist=[500, 502, 503, 504], allowed_methods=["GET"]
32+
)
33+
)
34+
session.mount("https://", adapter)
35+
36+
try:
37+
response = session.get(settings.CSL_STATUS_PAGE, timeout=settings.CSL_STATUS_PAGE_TIMEOUT)
38+
response.raise_for_status()
39+
status = response.json()["data"]["attributes"]["aggregate_state"]
40+
except Exception as ex:
41+
status = "error"
42+
logger.error(f"Could not fetch status page or incorrect status page JSON format: {ex}")
43+
44+
cache.set("emerg:csl_status", status, settings.CACHE_AGE["csl_status"])

intranet/apps/emerg/views.py

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
import logging
22
import time
3+
from typing import Literal
34

45
import requests
56
from bs4 import BeautifulSoup
67
from django.conf import settings
78
from django.core.cache import cache
89
from django.utils import timezone
9-
from requests.adapters import HTTPAdapter
10-
from urllib3 import Retry
1110

1211
from ...utils.html import get_domain_name, safe_fcps_emerg_html
1312

@@ -123,38 +122,14 @@ def update_emerg_cache(*, custom_logger=None) -> None:
123122
cache.set(key, result, timeout=settings.CACHE_AGE["emerg"])
124123

125124

126-
def get_csl_status() -> tuple[str, bool]:
125+
def get_csl_status() -> Literal["error", "operational", "downtime", "degraded", "maintenance"]:
127126
"""Get the cached status of the TJCSL status page.
128127
129128
Returns:
130-
Tuple with a string consisting of the aggregate status
131-
of the TJ computer systems lab and a bool indicating whether
132-
the status cache was updated
129+
A string consisting of the aggregate status
130+
of the TJ computer systems lab.
133131
134132
The string of the tuple will be one of the following: "error" (parse error), "operational", "downtime", "degraded", "maintenance"
135133
"""
136134

137-
status = cache.get("emerg:csl_status")
138-
updated = False
139-
140-
if not status:
141-
session = requests.Session()
142-
adapter = HTTPAdapter(
143-
max_retries=Retry(
144-
total=settings.CSL_STATUS_PAGE_MAX_RETRIES, backoff_factor=0.3, status_forcelist=[500, 502, 503, 504], allowed_methods=["GET"]
145-
)
146-
)
147-
session.mount("https://", adapter)
148-
149-
try:
150-
response = session.get(settings.CSL_STATUS_PAGE, timeout=settings.CSL_STATUS_PAGE_TIMEOUT)
151-
response.raise_for_status()
152-
status = response.json()["data"]["attributes"]["aggregate_state"]
153-
updated = True
154-
except Exception as ex:
155-
status = "error"
156-
logger.error(f"Could not fetch status page or incorrect status page JSON format: {ex}")
157-
158-
cache.set("emerg:csl_status", status, settings.CACHE_AGE["csl_status"])
159-
160-
return status, updated
135+
return cache.get("emerg:csl_status", "error")

intranet/apps/templatetags/status_helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def get_cache(key):
1616

1717
class GetCSLStatusNode(template.Node):
1818
def render(self, context):
19-
context["csl_status"] = get_csl_status()[0]
19+
context["csl_status"] = get_csl_status()
2020
return ""
2121

2222

intranet/settings/__init__.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,7 @@ def get_month_seconds():
535535
"users_list": int(datetime.timedelta(hours=24).total_seconds()),
536536
"printers_list": int(datetime.timedelta(minutes=10).total_seconds()),
537537
"emerg": int(datetime.timedelta(minutes=5).total_seconds()),
538-
"csl_status": int(datetime.timedelta(minutes=5).total_seconds()),
538+
"csl_status": int(datetime.timedelta(minutes=10).total_seconds()),
539539
"sports_school_events": int(datetime.timedelta(hours=1).total_seconds()),
540540
}
541541

@@ -963,6 +963,11 @@ def get_log(name): # pylint: disable=redefined-outer-name; 'name' is used as th
963963
"schedule": FCPS_EMERGENCY_CACHE_UPDATE_INTERVAL,
964964
"args": (),
965965
},
966+
"update-csl-status-cache": {
967+
"task": "intranet.apps.emerg.tasks.update_csl_status_task",
968+
"schedule": celery.schedules.crontab(minute="*/5"),
969+
"args": (),
970+
},
966971
"reset-routes-afternoon": {
967972
"task": "intranet.apps.bus.tasks.reset_routes",
968973
"schedule": celery.schedules.crontab(hour=0, minute=0),

0 commit comments

Comments
 (0)