authentik.enterprise.lifecycle.offboarding.tasks
1from django.apps import apps 2from django.db import transaction 3from django.db.models import F 4from django.utils import timezone 5from django.utils.translation import gettext_lazy as _ 6from dramatiq import actor 7 8from authentik.enterprise.lifecycle.offboarding.models import OffboardingStatus, UserOffboarding 9from authentik.tasks.middleware import CurrentTask 10 11# Retry budget: a due offboarding is retried by dramatiq and the sweeper this 12# many times before it is marked FAILED. 13MAX_OFFBOARDING_ATTEMPTS = 5 14 15 16@actor(description=_("Execute due user offboardings.")) 17def execute_due_offboardings(): 18 task = CurrentTask.get_task() 19 # Only the pk is dispatched, so fetch pks alone rather than whole rows. 20 due_pks = UserOffboarding.objects.filter( 21 status=OffboardingStatus.PENDING, 22 scheduled_at__lte=timezone.now(), 23 ) 24 if not apps.get_app_config("authentik_enterprise").enabled(): 25 due_pks = due_pks.filter(rule__isnull=True) 26 due_pks = due_pks.values_list("pk", flat=True) 27 for pk in due_pks: 28 # rel_obj groups each execution under the sweeper's schedule in the UI. 29 execute_offboarding.send_with_options(args=(str(pk),), rel_obj=task.rel_obj) 30 31 32@actor(description=_("Execute a single user offboarding.")) 33def execute_offboarding(offboarding_pk: str): 34 try: 35 with transaction.atomic(): 36 # Lock the row so two workers can't offboard the same user concurrently. 37 # The status filter is re-evaluated once the lock is held, so a row 38 # another worker already handled is skipped instead of run twice. 39 offboarding = ( 40 UserOffboarding.objects.select_for_update() 41 .filter(pk=offboarding_pk, status=OffboardingStatus.PENDING) 42 .select_related("user") 43 .first() 44 ) 45 if offboarding is None: 46 return 47 offboarding.execute() 48 except Exception: 49 # execute() rolled back, so bump the counter out-of-band and keep the row 50 # PENDING for retry; give up only once the budget is spent. 51 UserOffboarding.objects.filter(pk=offboarding_pk).update(attempts=F("attempts") + 1) 52 attempts = ( 53 UserOffboarding.objects.filter(pk=offboarding_pk) 54 .values_list("attempts", flat=True) 55 .first() 56 ) 57 if attempts is not None and attempts >= MAX_OFFBOARDING_ATTEMPTS: 58 UserOffboarding.objects.filter( 59 pk=offboarding_pk, status=OffboardingStatus.PENDING 60 ).update(status=OffboardingStatus.FAILED, executed_at=timezone.now()) 61 raise
MAX_OFFBOARDING_ATTEMPTS =
5