def handle(self, *args, **options) -> None: # noqa: ARG002
threshold_seconds = options['threshold']
include_pending = options['include_pending']
cutoff_time = time.time() - threshold_seconds
stale_celery_tasks = self._collect_stale_celery_tasks(cutoff_time, include_pending)
if not stale_celery_tasks:
self.stdout.write('No stale CeleryTasks found.')
return
sync_pks: list[int] = []
skipped_pks: list[int] = []
started_failure_candidates: list[int] = []
pending_failure_candidates: list[int] = []
verdict_buckets = {
'sync': sync_pks,
'pending': pending_failure_candidates,
'failure': started_failure_candidates,
'skip': skipped_pks,
}
for pk, celery_task in stale_celery_tasks.items():
verdict_buckets[self._classify_stale(celery_task)].append(pk)
for pk in pending_failure_candidates:
logger.info(
'Reaper: skipping stale queued CeleryTask %s (backend not terminal; the '
'message may still be queued or in flight)',
stale_celery_tasks[pk].task_id,
)
skipped_pks.append(pk)
live_workers = self._live_workers() if started_failure_candidates else None
if live_workers is not None and not live_workers:
logger.warning(
'Reaper: no live worker answered the ping; %d stale CeleryTask(s) will not be '
'marked FAILURE (an unacked message may still be requeued)',
len(started_failure_candidates),
)
active_task_ids = self._active_task_ids() if started_failure_candidates else None
failed_pks: list[int] = []
for pk in started_failure_candidates:
if self._stamp_is_safe(stale_celery_tasks[pk], live_workers, active_task_ids):
failed_pks.append(pk)
else:
skipped_pks.append(pk)
if options['dry_run']:
self.stdout.write(
f'{len(sync_pks)} stale CeleryTask(s) would be synced from the backend.'
)
self.stdout.write(
f'{len(skipped_pks)} stale CeleryTask(s) would be skipped (task still alive).'
)
self.stdout.write(f'{len(failed_pks)} stale CeleryTask(s) would be marked FAILURE.')
return
for pk in sync_pks:
stale_celery_tasks[pk].services.update_from_backend()
stamped = 0
if failed_pks:
stamped = (
CeleryTask.objects.filter(pk__in=failed_pks)
.exclude(state__in=[*states.READY_STATES, *states.EXCEPTION_STATES])
.update(
state=states.FAILURE,
completed_datetime=now(),
_result=self._stale_stamp(),
)
)
self.stdout.write(
self.style.SUCCESS(f'Synced {len(sync_pks)} stale CeleryTask(s) from the backend.')
)
self.stdout.write(
self.style.SUCCESS(
f'Skipped {len(skipped_pks)} stale CeleryTask(s) (task still alive).'
)
)
self.stdout.write(self.style.SUCCESS(f'Marked {stamped} stale CeleryTask(s) as FAILURE.'))