-
Notifications
You must be signed in to change notification settings - Fork 2.1k
feat(api): add periodic cleanup of stale Attack Paths scans with dead-worker detection #10387
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
josema-xyz
wants to merge
7
commits into
master
Choose a base branch
from
PROWLER-1207-improve-orphan-temporal-scan-databases-deletion-celery-tasks
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+586
−1
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7aec68f
feat(api): add periodic cleanup of stale attack paths scans with dead…
josema-xyz db066be
Merge branch 'master' of github.com:prowler-cloud/prowler into PROWLE…
josema-xyz cb32f7b
refactor(api): rename stale scan threshold setting and use celery.sta…
josema-xyz 380a0ee
Merge branch 'master' of github.com:prowler-cloud/prowler into PROWLE…
josema-xyz f73fbe2
docs(api): add changelog entry for stale attack paths scan cleanup
josema-xyz f580374
refactor(api): harden stale attack paths cleanup with ping cache, err…
josema-xyz 6210fa1
refactor(api): harden stale attack paths cleanup with ping cache, err…
josema-xyz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
api/src/backend/api/migrations/0085_attack_paths_cleanup_periodic_task.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| from django.db import migrations | ||
|
|
||
|
|
||
| TASK_NAME = "attack-paths-cleanup-stale-scans" | ||
| INTERVAL_HOURS = 1 | ||
|
|
||
|
|
||
| def create_periodic_task(apps, schema_editor): | ||
| IntervalSchedule = apps.get_model("django_celery_beat", "IntervalSchedule") | ||
| PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask") | ||
|
|
||
| schedule, _ = IntervalSchedule.objects.get_or_create( | ||
| every=INTERVAL_HOURS, | ||
| period="hours", | ||
| ) | ||
|
|
||
| PeriodicTask.objects.update_or_create( | ||
| name=TASK_NAME, | ||
| defaults={ | ||
| "task": TASK_NAME, | ||
| "interval": schedule, | ||
| "enabled": True, | ||
| }, | ||
| ) | ||
|
|
||
|
|
||
| def delete_periodic_task(apps, schema_editor): | ||
| IntervalSchedule = apps.get_model("django_celery_beat", "IntervalSchedule") | ||
| PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask") | ||
|
|
||
| PeriodicTask.objects.filter(name=TASK_NAME).delete() | ||
|
|
||
| # Clean up the schedule if no other task references it | ||
| IntervalSchedule.objects.filter( | ||
| every=INTERVAL_HOURS, | ||
| period="hours", | ||
| periodictask__isnull=True, | ||
| ).delete() | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
| dependencies = [ | ||
| ("api", "0084_googleworkspace_provider"), | ||
| ("django_celery_beat", "0019_alter_periodictasks_options"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.RunPython(create_periodic_task, delete_periodic_task), | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| from datetime import datetime, timedelta, timezone | ||
|
|
||
| from celery import current_app, states | ||
| from celery.utils.log import get_task_logger | ||
| from config.django.base import ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES | ||
| from tasks.jobs.attack_paths.db_utils import ( | ||
| finish_attack_paths_scan, | ||
| recover_graph_data_ready, | ||
| ) | ||
|
|
||
| from api.attack_paths import database as graph_database | ||
| from api.db_router import MainRouter | ||
| from api.db_utils import rls_transaction | ||
| from api.models import AttackPathsScan, StateChoices | ||
|
|
||
| logger = get_task_logger(__name__) | ||
|
|
||
|
|
||
| def cleanup_stale_attack_paths_scans() -> dict: | ||
| """ | ||
| Find `EXECUTING` `AttackPathsScan` scans whose workers are dead or that have | ||
| exceeded the stale threshold, and mark them as `FAILED`. | ||
|
|
||
| Two-pass detection: | ||
| 1. If `TaskResult.worker` exists, ping the worker. | ||
| - Dead worker: cleanup immediately (any age). | ||
| - Alive + past threshold: revoke the task, then cleanup. | ||
| - Alive + within threshold: skip. | ||
| 2. If no worker field: fall back to time-based heuristic only. | ||
| """ | ||
| threshold = timedelta(minutes=ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES) | ||
| now = datetime.now(tz=timezone.utc) | ||
| cutoff = now - threshold | ||
|
|
||
| executing_scans = ( | ||
| AttackPathsScan.all_objects.using(MainRouter.admin_db) | ||
| .filter(state=StateChoices.EXECUTING) | ||
| .select_related("task__task_runner_task") | ||
| ) | ||
|
|
||
| # Cache worker liveness so each worker is pinged at most once | ||
| executing_scans = list(executing_scans) | ||
| workers = { | ||
| tr.worker | ||
| for scan in executing_scans | ||
| if (tr := getattr(scan.task, "task_runner_task", None) if scan.task else None) | ||
| and tr.worker | ||
| } | ||
| worker_alive = {w: _is_worker_alive(w) for w in workers} | ||
|
|
||
| cleaned_up = [] | ||
|
|
||
| for scan in executing_scans: | ||
| task_result = ( | ||
| getattr(scan.task, "task_runner_task", None) if scan.task else None | ||
| ) | ||
| worker = task_result.worker if task_result else None | ||
|
|
||
| if worker: | ||
| alive = worker_alive.get(worker, True) | ||
|
|
||
| if alive: | ||
| if scan.started_at and scan.started_at >= cutoff: | ||
| continue | ||
|
|
||
| # Alive but stale — revoke before cleanup | ||
| _revoke_task(task_result) | ||
| reason = ( | ||
| "Scan exceeded stale threshold — " "cleaned up by periodic task" | ||
| ) | ||
| else: | ||
| reason = "Worker dead — cleaned up by periodic task" | ||
| else: | ||
| # No worker recorded — time-based heuristic only | ||
| if scan.started_at and scan.started_at >= cutoff: | ||
| continue | ||
| reason = ( | ||
| "No worker recorded, scan exceeded stale threshold — " | ||
| "cleaned up by periodic task" | ||
| ) | ||
|
|
||
| if _cleanup_scan(scan, task_result, reason): | ||
| cleaned_up.append(str(scan.id)) | ||
|
|
||
| logger.info( | ||
| f"Stale `AttackPathsScan` cleanup: {len(cleaned_up)} scan(s) cleaned up" | ||
| ) | ||
| return {"cleaned_up_count": len(cleaned_up), "scan_ids": cleaned_up} | ||
|
|
||
|
|
||
| def _is_worker_alive(worker: str) -> bool: | ||
| """Ping a specific Celery worker. Returns `True` if it responds or on error.""" | ||
| try: | ||
| response = current_app.control.inspect(destination=[worker], timeout=1.0).ping() | ||
| return response is not None and worker in response | ||
| except Exception: | ||
| logger.exception(f"Failed to ping worker {worker}, treating as alive") | ||
| return True | ||
|
|
||
|
|
||
| def _revoke_task(task_result) -> None: | ||
| """Send `SIGTERM` to a hung Celery task. Non-fatal on failure.""" | ||
| try: | ||
| current_app.control.revoke( | ||
| task_result.task_id, terminate=True, signal="SIGTERM" | ||
| ) | ||
| logger.info(f"Revoked task {task_result.task_id}") | ||
| except Exception: | ||
| logger.exception(f"Failed to revoke task {task_result.task_id}") | ||
|
|
||
|
|
||
| def _cleanup_scan(scan, task_result, reason: str) -> bool: | ||
| """ | ||
| Clean up a single stale `AttackPathsScan`: | ||
| drop temp DB, mark `FAILED`, update `TaskResult`, recover `graph_data_ready`. | ||
|
|
||
| Returns `True` if the scan was actually cleaned up, `False` if skipped. | ||
| """ | ||
| scan_id_str = str(scan.id) | ||
|
|
||
| # 1. Drop temp Neo4j database | ||
| tmp_db_name = graph_database.get_database_name(scan.id, temporary=True) | ||
| try: | ||
| graph_database.drop_database(tmp_db_name) | ||
| except Exception: | ||
| logger.exception(f"Failed to drop temp database {tmp_db_name}") | ||
|
|
||
| # 2. Re-fetch within RLS (race guard against normal completion) | ||
| with rls_transaction(str(scan.tenant_id)): | ||
| try: | ||
| fresh_scan = AttackPathsScan.objects.get(id=scan.id) | ||
| except AttackPathsScan.DoesNotExist: | ||
| logger.warning(f"Scan {scan_id_str} no longer exists, skipping") | ||
| return False | ||
|
|
||
| if fresh_scan.state != StateChoices.EXECUTING: | ||
| logger.info(f"Scan {scan_id_str} is now {fresh_scan.state}, skipping") | ||
| return False | ||
|
|
||
| # 3. Mark `AttackPathsScan` as `FAILED` | ||
| finish_attack_paths_scan( | ||
| fresh_scan, | ||
| StateChoices.FAILED, | ||
| {"global_error": reason}, | ||
| ) | ||
|
|
||
| # 4. Mark `TaskResult` as `FAILURE` | ||
| if task_result: | ||
| task_result.status = states.FAILURE | ||
| task_result.save(update_fields=["status", "date_done"]) | ||
|
|
||
| # 5. Recover graph_data_ready if provider data still exists | ||
| recover_graph_data_ready(fresh_scan) | ||
|
|
||
| logger.info(f"Cleaned up stale scan {scan_id_str}: {reason}") | ||
| return True | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.