authentik.tasks.models

  1from collections.abc import Iterable
  2from typing import Self
  3from uuid import UUID, uuid4
  4
  5import pgtrigger
  6from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  7from django.contrib.contenttypes.models import ContentType
  8from django.db import models
  9from django.db.utils import IntegrityError
 10from django.utils.translation import gettext_lazy as _
 11from django_dramatiq_postgres.models import TaskBase, TaskState
 12from dramatiq.errors import Retry
 13from structlog.stdlib import get_logger
 14
 15from authentik.events.logs import LogEvent
 16from authentik.events.utils import sanitize_item
 17from authentik.lib.models import InternallyManagedMixin, SerializerModel
 18from authentik.lib.utils.errors import exception_to_dict
 19
 20LOGGER = get_logger()
 21
 22
 23class TaskStatus(models.TextChoices):
 24    """Task aggregated status. Reported by the task runners"""
 25
 26    WAITING_FOR_DEPENDENCIES = TaskState.WAITING_FOR_DEPENDENCIES
 27    QUEUED = TaskState.QUEUED
 28    CONSUMED = TaskState.CONSUMED
 29    PREPROCESS = TaskState.PREPROCESS
 30    RUNNING = TaskState.RUNNING
 31    POSTPROCESS = TaskState.POSTPROCESS
 32    REJECTED = TaskState.REJECTED
 33    DONE = TaskState.DONE
 34    INFO = "info"
 35    WARNING = "warning"
 36    ERROR = "error"
 37
 38
 39class Task(InternallyManagedMixin, SerializerModel, TaskBase):
 40    # Overridden from TaskBase to use a through model
 41    dependencies = models.ManyToManyField(
 42        "self",
 43        verbose_name=_("Tasks that must complete for this task to run."),
 44        symmetrical=False,
 45        through="TaskDependency",
 46        through_fields=("task", "dependency"),
 47    )
 48
 49    rel_obj_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
 50    rel_obj_id = models.TextField(null=True)
 51    rel_obj = GenericForeignKey("rel_obj_content_type", "rel_obj_id")
 52
 53    _uid = models.TextField(blank=True, null=True)
 54    _messages = models.JSONField(default=list)
 55    _previous_messages = models.JSONField(default=list)
 56
 57    aggregated_status = models.TextField(choices=TaskStatus.choices)
 58
 59    class Meta(TaskBase.Meta):
 60        default_permissions = ("view",)
 61        permissions = [
 62            ("retry_task", _("Retry failed task")),
 63        ]
 64        indexes = TaskBase.Meta.indexes + (
 65            # Lists an object's tasks newest first, and finds a schedule's last task
 66            models.Index(fields=("rel_obj_content_type", "rel_obj_id", "mtime")),
 67            # The system tasks page counts tasks by status and lists them newest first
 68            models.Index(fields=("aggregated_status",)),
 69            models.Index(fields=("mtime",)),
 70            # The system tasks page lists tasks without an object. Counting them by status from
 71            # the status index reads each matching task, which is slow once the tasks are out of
 72            # the cache. This index answers the count alone and lists them newest first.
 73            models.Index(
 74                fields=("mtime",),
 75                include=("aggregated_status",),
 76                condition=models.Q(rel_obj_id__isnull=True),
 77                name="authentik_t_standalone_idx",
 78            ),
 79        )
 80        triggers = TaskBase.Meta.triggers + (
 81            pgtrigger.Trigger(
 82                name="update_aggregated_status",
 83                operation=pgtrigger.Insert | pgtrigger.Update,
 84                when=pgtrigger.Before,
 85                func=f"""
 86                    IF NEW.state != '{TaskState.DONE.value}' THEN
 87                        NEW.aggregated_status := NEW.state;
 88                    ELSE
 89                        SELECT CASE
 90                            WHEN bool_or(log_level = 'error') THEN 'error'
 91                            WHEN bool_or(log_level = 'warning') THEN 'warning'
 92                            WHEN bool_or(log_level = 'info') THEN 'info'
 93                            ELSE '{TaskState.DONE.value}'
 94                        END
 95                        INTO NEW.aggregated_status
 96                        FROM authentik_tasks_tasklog
 97                        WHERE task_id = NEW.message_id AND NOT previous;
 98                    END IF;
 99
100                    RETURN NEW;
101                """,  # nosec
102            ),
103        )
104
105    @property
106    def uid(self) -> str:
107        uid = str(self.actor_name)
108        if self._uid:
109            uid += f":{self._uid}"
110        return uid
111
112    @property
113    def serializer(self):
114        from authentik.tasks.api.tasks import TaskSerializer
115
116        return TaskSerializer
117
118    def set_uid(self, uid: str | UUID, save: bool = False):
119        self._uid = str(uid)
120        if save:
121            self.save()
122
123    @classmethod
124    def _make_log(
125        cls, logger: str, log_level: TaskStatus, message: str | Exception, **attributes
126    ) -> LogEvent:
127        if isinstance(message, Exception):
128            exc = message
129            attributes = {
130                "exception": exception_to_dict(exc),
131                **attributes,
132            }
133            message_prefix = (
134                "Task has encountered an error and will be retried"
135                if isinstance(exc, Retry)
136                else "Task has encountered an error"
137            )
138            message = f"{message_prefix}: {str(exc)}"
139        return LogEvent(
140            message,
141            logger=logger,
142            log_level=log_level.value,
143            attributes=attributes,
144        )
145
146    def logs(self, logs: Iterable[LogEvent]):
147        TaskLog.bulk_create_from_log_events(self, logs)
148
149    def log(
150        self,
151        logger: str,
152        log_level: TaskStatus,
153        message: str | Exception,
154        **attributes,
155    ) -> None:
156        TaskLog.create_from_log_event(
157            self,
158            self._make_log(
159                logger,
160                log_level,
161                message,
162                **attributes,
163            ),
164        )
165
166    def info(self, message: str | Exception, **attributes) -> None:
167        self.log(self.uid, TaskStatus.INFO, message, **attributes)
168
169    def warning(self, message: str | Exception, **attributes) -> None:
170        self.log(self.uid, TaskStatus.WARNING, message, **attributes)
171
172    def error(self, message: str | Exception, **attributes) -> None:
173        self.log(self.uid, TaskStatus.ERROR, message, **attributes)
174
175
176class TaskDependency(InternallyManagedMixin, models.Model):
177    pk = models.CompositePrimaryKey("task", "dependency")
178    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="+")
179    dependency = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="+")
180
181    class Meta:
182        default_permissions = []
183        verbose_name = _("Task dependency")
184        verbose_name_plural = _("Task dependencies")
185
186    def __str__(self):
187        return f"Task {self.pk[0]} dependency on {self.pk[1]}"
188
189
190class TaskLog(InternallyManagedMixin, models.Model):
191    id = models.UUIDField(default=uuid4, primary_key=True, editable=False)
192
193    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="tasklogs")
194    event = models.TextField()
195    log_level = models.TextField()
196    logger = models.TextField()
197    timestamp = models.DateTimeField()
198    attributes = models.JSONField()
199
200    previous = models.BooleanField(default=False, db_index=True)
201
202    class Meta:
203        default_permissions = []
204        verbose_name = _("Task log")
205        verbose_name_plural = _("Task logs")
206        indexes = (models.Index(fields=("task", "previous")),)
207
208    def __str__(self):
209        return str(self.pk)
210
211    @classmethod
212    def create_from_log_event(cls, task: Task, log_event: LogEvent) -> Self | None:
213        if not task.message:
214            return None
215        try:
216            return cls.objects.create(
217                task=task,
218                event=log_event.event,
219                log_level=log_event.log_level,
220                logger=log_event.logger,
221                timestamp=log_event.timestamp,
222                attributes=sanitize_item(log_event.attributes),
223            )
224        except IntegrityError as exc:
225            LOGGER.warning("failed to save log event, writing it to console instead", exc=exc)
226            log_event.log()
227            return None
228
229    @classmethod
230    def bulk_create_from_log_events(
231        cls,
232        task: Task,
233        log_events: Iterable[LogEvent],
234    ) -> list[Self] | None:
235        if not task.message:
236            return None
237        try:
238            return cls.objects.bulk_create(
239                [
240                    cls(
241                        task=task,
242                        event=log_event.event,
243                        log_level=log_event.log_level,
244                        logger=log_event.logger,
245                        timestamp=log_event.timestamp,
246                        attributes=sanitize_item(log_event.attributes),
247                    )
248                    for log_event in log_events
249                ]
250            )
251        except IntegrityError as exc:
252            LOGGER.warning("failed to save log events, writing it to console instead", exc=exc)
253            for log_event in log_events:
254                log_event.log()
255            return None
256
257    def to_log_event(self) -> LogEvent:
258        return LogEvent(
259            event=self.event,
260            log_level=self.log_level,
261            logger=self.logger,
262            timestamp=self.timestamp,
263            attributes=self.attributes,
264        )
265
266
267class TasksModel(models.Model):
268    tasks = GenericRelation(
269        Task, content_type_field="rel_obj_content_type", object_id_field="rel_obj_id"
270    )
271
272    class Meta:
273        abstract = True
274
275
276class WorkerStatus(models.Model):
277    id = models.UUIDField(primary_key=True, default=uuid4)
278    hostname = models.TextField()
279    version = models.TextField()
280    last_seen = models.DateTimeField(auto_now_add=True)
281
282    class Meta:
283        default_permissions = []
284        verbose_name = _("Worker status")
285        verbose_name_plural = _("Worker statuses")
286
287    def __str__(self):
288        return f"{self.id} - {self.hostname} - {self.version} - {self.last_seen}"
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class TaskStatus(django.db.models.enums.TextChoices):
24class TaskStatus(models.TextChoices):
25    """Task aggregated status. Reported by the task runners"""
26
27    WAITING_FOR_DEPENDENCIES = TaskState.WAITING_FOR_DEPENDENCIES
28    QUEUED = TaskState.QUEUED
29    CONSUMED = TaskState.CONSUMED
30    PREPROCESS = TaskState.PREPROCESS
31    RUNNING = TaskState.RUNNING
32    POSTPROCESS = TaskState.POSTPROCESS
33    REJECTED = TaskState.REJECTED
34    DONE = TaskState.DONE
35    INFO = "info"
36    WARNING = "warning"
37    ERROR = "error"

Task aggregated status. Reported by the task runners

WAITING_FOR_DEPENDENCIES = TaskStatus.WAITING_FOR_DEPENDENCIES
CONSUMED = TaskStatus.CONSUMED
PREPROCESS = TaskStatus.PREPROCESS
RUNNING = TaskStatus.RUNNING
POSTPROCESS = TaskStatus.POSTPROCESS
REJECTED = TaskStatus.REJECTED
WARNING = TaskStatus.WARNING
class Task(authentik.lib.models.InternallyManagedMixin, authentik.lib.models.SerializerModel, django_dramatiq_postgres.models.TaskBase):
 40class Task(InternallyManagedMixin, SerializerModel, TaskBase):
 41    # Overridden from TaskBase to use a through model
 42    dependencies = models.ManyToManyField(
 43        "self",
 44        verbose_name=_("Tasks that must complete for this task to run."),
 45        symmetrical=False,
 46        through="TaskDependency",
 47        through_fields=("task", "dependency"),
 48    )
 49
 50    rel_obj_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
 51    rel_obj_id = models.TextField(null=True)
 52    rel_obj = GenericForeignKey("rel_obj_content_type", "rel_obj_id")
 53
 54    _uid = models.TextField(blank=True, null=True)
 55    _messages = models.JSONField(default=list)
 56    _previous_messages = models.JSONField(default=list)
 57
 58    aggregated_status = models.TextField(choices=TaskStatus.choices)
 59
 60    class Meta(TaskBase.Meta):
 61        default_permissions = ("view",)
 62        permissions = [
 63            ("retry_task", _("Retry failed task")),
 64        ]
 65        indexes = TaskBase.Meta.indexes + (
 66            # Lists an object's tasks newest first, and finds a schedule's last task
 67            models.Index(fields=("rel_obj_content_type", "rel_obj_id", "mtime")),
 68            # The system tasks page counts tasks by status and lists them newest first
 69            models.Index(fields=("aggregated_status",)),
 70            models.Index(fields=("mtime",)),
 71            # The system tasks page lists tasks without an object. Counting them by status from
 72            # the status index reads each matching task, which is slow once the tasks are out of
 73            # the cache. This index answers the count alone and lists them newest first.
 74            models.Index(
 75                fields=("mtime",),
 76                include=("aggregated_status",),
 77                condition=models.Q(rel_obj_id__isnull=True),
 78                name="authentik_t_standalone_idx",
 79            ),
 80        )
 81        triggers = TaskBase.Meta.triggers + (
 82            pgtrigger.Trigger(
 83                name="update_aggregated_status",
 84                operation=pgtrigger.Insert | pgtrigger.Update,
 85                when=pgtrigger.Before,
 86                func=f"""
 87                    IF NEW.state != '{TaskState.DONE.value}' THEN
 88                        NEW.aggregated_status := NEW.state;
 89                    ELSE
 90                        SELECT CASE
 91                            WHEN bool_or(log_level = 'error') THEN 'error'
 92                            WHEN bool_or(log_level = 'warning') THEN 'warning'
 93                            WHEN bool_or(log_level = 'info') THEN 'info'
 94                            ELSE '{TaskState.DONE.value}'
 95                        END
 96                        INTO NEW.aggregated_status
 97                        FROM authentik_tasks_tasklog
 98                        WHERE task_id = NEW.message_id AND NOT previous;
 99                    END IF;
100
101                    RETURN NEW;
102                """,  # nosec
103            ),
104        )
105
106    @property
107    def uid(self) -> str:
108        uid = str(self.actor_name)
109        if self._uid:
110            uid += f":{self._uid}"
111        return uid
112
113    @property
114    def serializer(self):
115        from authentik.tasks.api.tasks import TaskSerializer
116
117        return TaskSerializer
118
119    def set_uid(self, uid: str | UUID, save: bool = False):
120        self._uid = str(uid)
121        if save:
122            self.save()
123
124    @classmethod
125    def _make_log(
126        cls, logger: str, log_level: TaskStatus, message: str | Exception, **attributes
127    ) -> LogEvent:
128        if isinstance(message, Exception):
129            exc = message
130            attributes = {
131                "exception": exception_to_dict(exc),
132                **attributes,
133            }
134            message_prefix = (
135                "Task has encountered an error and will be retried"
136                if isinstance(exc, Retry)
137                else "Task has encountered an error"
138            )
139            message = f"{message_prefix}: {str(exc)}"
140        return LogEvent(
141            message,
142            logger=logger,
143            log_level=log_level.value,
144            attributes=attributes,
145        )
146
147    def logs(self, logs: Iterable[LogEvent]):
148        TaskLog.bulk_create_from_log_events(self, logs)
149
150    def log(
151        self,
152        logger: str,
153        log_level: TaskStatus,
154        message: str | Exception,
155        **attributes,
156    ) -> None:
157        TaskLog.create_from_log_event(
158            self,
159            self._make_log(
160                logger,
161                log_level,
162                message,
163                **attributes,
164            ),
165        )
166
167    def info(self, message: str | Exception, **attributes) -> None:
168        self.log(self.uid, TaskStatus.INFO, message, **attributes)
169
170    def warning(self, message: str | Exception, **attributes) -> None:
171        self.log(self.uid, TaskStatus.WARNING, message, **attributes)
172
173    def error(self, message: str | Exception, **attributes) -> None:
174        self.log(self.uid, TaskStatus.ERROR, message, **attributes)

Task(message_id, queue_name, actor_name, message, state, mtime, retries, eta, result, result_expiry, rel_obj_content_type, rel_obj_id, _uid, _messages, _previous_messages, aggregated_status)

dependencies

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

rel_obj_content_type

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def rel_obj_id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

rel_obj

Provide a generic many-to-one relation through the content_type and object_id fields.

This class also doubles as an accessor to the related object (similar to ForwardManyToOneDescriptor) by adding itself as a model attribute.

def aggregated_status(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

uid: str
106    @property
107    def uid(self) -> str:
108        uid = str(self.actor_name)
109        if self._uid:
110            uid += f":{self._uid}"
111        return uid
serializer
113    @property
114    def serializer(self):
115        from authentik.tasks.api.tasks import TaskSerializer
116
117        return TaskSerializer

Get serializer for this model

def set_uid(self, uid: str | uuid.UUID, save: bool = False):
119    def set_uid(self, uid: str | UUID, save: bool = False):
120        self._uid = str(uid)
121        if save:
122            self.save()
def logs(self, logs: Iterable[authentik.events.logs.LogEvent]):
147    def logs(self, logs: Iterable[LogEvent]):
148        TaskLog.bulk_create_from_log_events(self, logs)
def log( self, logger: str, log_level: TaskStatus, message: str | Exception, **attributes) -> None:
150    def log(
151        self,
152        logger: str,
153        log_level: TaskStatus,
154        message: str | Exception,
155        **attributes,
156    ) -> None:
157        TaskLog.create_from_log_event(
158            self,
159            self._make_log(
160                logger,
161                log_level,
162                message,
163                **attributes,
164            ),
165        )
def info(self, message: str | Exception, **attributes) -> None:
167    def info(self, message: str | Exception, **attributes) -> None:
168        self.log(self.uid, TaskStatus.INFO, message, **attributes)
def warning(self, message: str | Exception, **attributes) -> None:
170    def warning(self, message: str | Exception, **attributes) -> None:
171        self.log(self.uid, TaskStatus.WARNING, message, **attributes)
def error(self, message: str | Exception, **attributes) -> None:
173    def error(self, message: str | Exception, **attributes) -> None:
174        self.log(self.uid, TaskStatus.ERROR, message, **attributes)
def message_id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def queue_name(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def actor_name(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def message(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def state(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def mtime(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def retries(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def eta(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def result(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def result_expiry(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

rel_obj_content_type_id
def get_aggregated_status_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_state_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_next_by_mtime(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_mtime(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def objects(unknown):

The type of the None singleton.

task_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

tasklogs

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class Task.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class Task.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class TaskDependency(authentik.lib.models.InternallyManagedMixin, django.db.models.base.Model):
177class TaskDependency(InternallyManagedMixin, models.Model):
178    pk = models.CompositePrimaryKey("task", "dependency")
179    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="+")
180    dependency = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="+")
181
182    class Meta:
183        default_permissions = []
184        verbose_name = _("Task dependency")
185        verbose_name_plural = _("Task dependencies")
186
187    def __str__(self):
188        return f"Task {self.pk[0]} dependency on {self.pk[1]}"

TaskDependency(pk, task, dependency)

pk
task

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

dependency

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

task_id
dependency_id
def objects(unknown):

The type of the None singleton.

class TaskDependency.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class TaskDependency.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class TaskLog(authentik.lib.models.InternallyManagedMixin, django.db.models.base.Model):
191class TaskLog(InternallyManagedMixin, models.Model):
192    id = models.UUIDField(default=uuid4, primary_key=True, editable=False)
193
194    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="tasklogs")
195    event = models.TextField()
196    log_level = models.TextField()
197    logger = models.TextField()
198    timestamp = models.DateTimeField()
199    attributes = models.JSONField()
200
201    previous = models.BooleanField(default=False, db_index=True)
202
203    class Meta:
204        default_permissions = []
205        verbose_name = _("Task log")
206        verbose_name_plural = _("Task logs")
207        indexes = (models.Index(fields=("task", "previous")),)
208
209    def __str__(self):
210        return str(self.pk)
211
212    @classmethod
213    def create_from_log_event(cls, task: Task, log_event: LogEvent) -> Self | None:
214        if not task.message:
215            return None
216        try:
217            return cls.objects.create(
218                task=task,
219                event=log_event.event,
220                log_level=log_event.log_level,
221                logger=log_event.logger,
222                timestamp=log_event.timestamp,
223                attributes=sanitize_item(log_event.attributes),
224            )
225        except IntegrityError as exc:
226            LOGGER.warning("failed to save log event, writing it to console instead", exc=exc)
227            log_event.log()
228            return None
229
230    @classmethod
231    def bulk_create_from_log_events(
232        cls,
233        task: Task,
234        log_events: Iterable[LogEvent],
235    ) -> list[Self] | None:
236        if not task.message:
237            return None
238        try:
239            return cls.objects.bulk_create(
240                [
241                    cls(
242                        task=task,
243                        event=log_event.event,
244                        log_level=log_event.log_level,
245                        logger=log_event.logger,
246                        timestamp=log_event.timestamp,
247                        attributes=sanitize_item(log_event.attributes),
248                    )
249                    for log_event in log_events
250                ]
251            )
252        except IntegrityError as exc:
253            LOGGER.warning("failed to save log events, writing it to console instead", exc=exc)
254            for log_event in log_events:
255                log_event.log()
256            return None
257
258    def to_log_event(self) -> LogEvent:
259        return LogEvent(
260            event=self.event,
261            log_level=self.log_level,
262            logger=self.logger,
263            timestamp=self.timestamp,
264            attributes=self.attributes,
265        )

TaskLog(id, task, event, log_level, logger, timestamp, attributes, previous)

def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

task

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def event(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def log_level(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def logger(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def timestamp(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def attributes(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def previous(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

@classmethod
def create_from_log_event( cls, task: Task, log_event: authentik.events.logs.LogEvent) -> Self | None:
212    @classmethod
213    def create_from_log_event(cls, task: Task, log_event: LogEvent) -> Self | None:
214        if not task.message:
215            return None
216        try:
217            return cls.objects.create(
218                task=task,
219                event=log_event.event,
220                log_level=log_event.log_level,
221                logger=log_event.logger,
222                timestamp=log_event.timestamp,
223                attributes=sanitize_item(log_event.attributes),
224            )
225        except IntegrityError as exc:
226            LOGGER.warning("failed to save log event, writing it to console instead", exc=exc)
227            log_event.log()
228            return None
@classmethod
def bulk_create_from_log_events( cls, task: Task, log_events: Iterable[authentik.events.logs.LogEvent]) -> list[Self] | None:
230    @classmethod
231    def bulk_create_from_log_events(
232        cls,
233        task: Task,
234        log_events: Iterable[LogEvent],
235    ) -> list[Self] | None:
236        if not task.message:
237            return None
238        try:
239            return cls.objects.bulk_create(
240                [
241                    cls(
242                        task=task,
243                        event=log_event.event,
244                        log_level=log_event.log_level,
245                        logger=log_event.logger,
246                        timestamp=log_event.timestamp,
247                        attributes=sanitize_item(log_event.attributes),
248                    )
249                    for log_event in log_events
250                ]
251            )
252        except IntegrityError as exc:
253            LOGGER.warning("failed to save log events, writing it to console instead", exc=exc)
254            for log_event in log_events:
255                log_event.log()
256            return None
def to_log_event(self) -> authentik.events.logs.LogEvent:
258    def to_log_event(self) -> LogEvent:
259        return LogEvent(
260            event=self.event,
261            log_level=self.log_level,
262            logger=self.logger,
263            timestamp=self.timestamp,
264            attributes=self.attributes,
265        )
task_id
def get_next_by_timestamp(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_timestamp(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def objects(unknown):

The type of the None singleton.

class TaskLog.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class TaskLog.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class TasksModel(django.db.models.base.Model):
268class TasksModel(models.Model):
269    tasks = GenericRelation(
270        Task, content_type_field="rel_obj_content_type", object_id_field="rel_obj_id"
271    )
272
273    class Meta:
274        abstract = True

Make subclasses preserve the alters_data attribute on overridden methods.

tasks

Accessor to the related objects manager on the one-to-many relation created by GenericRelation.

In the example::

class Post(Model):
    comments = GenericRelation(Comment)

post.comments is a ReverseGenericManyToOneDescriptor instance.

class TasksModel.Meta:
273    class Meta:
274        abstract = True
abstract = False
class WorkerStatus(django.db.models.base.Model):
277class WorkerStatus(models.Model):
278    id = models.UUIDField(primary_key=True, default=uuid4)
279    hostname = models.TextField()
280    version = models.TextField()
281    last_seen = models.DateTimeField(auto_now_add=True)
282
283    class Meta:
284        default_permissions = []
285        verbose_name = _("Worker status")
286        verbose_name_plural = _("Worker statuses")
287
288    def __str__(self):
289        return f"{self.id} - {self.hostname} - {self.version} - {self.last_seen}"

WorkerStatus(id, hostname, version, last_seen)

def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def hostname(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def version(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def last_seen(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def get_next_by_last_seen(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_last_seen(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def objects(unknown):

The type of the None singleton.

class WorkerStatus.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class WorkerStatus.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.