prefill in app startup

Signed-off-by: Jens Langhammer <jens@goauthentik.io>
This commit is contained in:
Jens Langhammer 2024-01-13 20:54:42 +01:00
parent 7fd9d31101
commit 1033b114c7
No known key found for this signature in database
3 changed files with 32 additions and 23 deletions

View File

@ -11,11 +11,11 @@ from structlog.stdlib import BoundLogger, get_logger
class ManagedAppConfig(AppConfig): class ManagedAppConfig(AppConfig):
"""Basic reconciliation logic for apps""" """Basic reconciliation logic for apps"""
_logger: BoundLogger logger: BoundLogger
def __init__(self, app_name: str, *args, **kwargs) -> None: def __init__(self, app_name: str, *args, **kwargs) -> None:
super().__init__(app_name, *args, **kwargs) super().__init__(app_name, *args, **kwargs)
self._logger = get_logger().bind(app_name=app_name) self.logger = get_logger().bind(app_name=app_name)
def ready(self) -> None: def ready(self) -> None:
self.reconcile() self.reconcile()
@ -36,11 +36,11 @@ class ManagedAppConfig(AppConfig):
continue continue
name = meth_name.replace(prefix, "") name = meth_name.replace(prefix, "")
try: try:
self._logger.debug("Starting reconciler", name=name) self.logger.debug("Starting reconciler", name=name)
meth() meth()
self._logger.debug("Successfully reconciled", name=name) self.logger.debug("Successfully reconciled", name=name)
except (DatabaseError, ProgrammingError, InternalError) as exc: except (DatabaseError, ProgrammingError, InternalError) as exc:
self._logger.warning("Failed to run reconcile", name=name, exc=exc) self.logger.warning("Failed to run reconcile", name=name, exc=exc)
class AuthentikBlueprintsConfig(ManagedAppConfig): class AuthentikBlueprintsConfig(ManagedAppConfig):

View File

@ -43,3 +43,14 @@ class AuthentikEventsConfig(ManagedAppConfig):
replacement_env=replace_env, replacement_env=replace_env,
message=msg, message=msg,
).save() ).save()
def reconcile_prefill_tasks(self):
"""Prefill tasks"""
from authentik.events.models import SystemTask
from authentik.events.monitored_tasks import _prefill_tasks
for task in _prefill_tasks:
if SystemTask.objects.filter(name=task.name).exists():
continue
task.save()
self.logger.debug("prefilled task", task_name=task.name)

View File

@ -4,12 +4,12 @@ from timeit import default_timer
from typing import Any, Optional from typing import Any, Optional
from celery import Task from celery import Task
from django.db import DatabaseError, InternalError, ProgrammingError
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from structlog.stdlib import get_logger from structlog.stdlib import get_logger
from authentik.events.models import Event, EventAction, SystemTask, TaskStatus from authentik.events.models import Event, EventAction, SystemTask, TaskStatus
from authentik.events.utils import sanitize_item
from authentik.lib.utils.errors import exception_to_string from authentik.lib.utils.errors import exception_to_string
LOGGER = get_logger() LOGGER = get_logger()
@ -78,7 +78,7 @@ class MonitoredTask(Task):
"task_call_args": args, "task_call_args": args,
"task_call_kwargs": kwargs, "task_call_kwargs": kwargs,
"status": self._status, "status": self._status,
"messages": self._messages, "messages": sanitize_item(self._messages),
"expires": now() + timedelta(hours=self.result_timeout_hours), "expires": now() + timedelta(hours=self.result_timeout_hours),
"expiring": True, "expiring": True,
}, },
@ -104,7 +104,7 @@ class MonitoredTask(Task):
"task_call_args": args, "task_call_args": args,
"task_call_kwargs": kwargs, "task_call_kwargs": kwargs,
"status": self._status, "status": self._status,
"messages": self._messages, "messages": sanitize_item(self._messages),
"expires": now() + timedelta(hours=self.result_timeout_hours), "expires": now() + timedelta(hours=self.result_timeout_hours),
"expiring": True, "expiring": True,
}, },
@ -120,20 +120,18 @@ class MonitoredTask(Task):
def prefill_task(func): def prefill_task(func):
"""Ensure a task's details are always in cache, so it can always be triggered via API""" """Ensure a task's details are always in cache, so it can always be triggered via API"""
try: _prefill_tasks.append(
status = SystemTask.objects.filter(name=func.__name__).first() SystemTask(
except (DatabaseError, InternalError, ProgrammingError):
return func
if status:
return func
SystemTask.objects.create(
name=func.__name__, name=func.__name__,
description=func.__doc__, description=func.__doc__,
status=TaskStatus.UNKNOWN, status=TaskStatus.UNKNOWN,
messages=[_("Task has not been run yet.")], messages=sanitize_item([_("Task has not been run yet.")]),
task_call_module=func.__module__, task_call_module=func.__module__,
task_call_func=func.__name__, task_call_func=func.__name__,
expiring=False, expiring=False,
) )
LOGGER.debug("prefilled task", task_name=func.__name__) )
return func return func
_prefill_tasks = []