|
| 1 | +# Copyright (c) 2026, RTE (https://www.rte-france.com) |
| 2 | +# |
| 3 | +# See AUTHORS.txt |
| 4 | +# |
| 5 | +# This Source Code Form is subject to the terms of the Mozilla Public |
| 6 | +# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 7 | +# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 8 | +# |
| 9 | +# SPDX-License-Identifier: MPL-2.0 |
| 10 | +# |
| 11 | +# This file is part of the Antares project. |
| 12 | +import logging |
| 13 | +import time |
| 14 | + |
| 15 | +from antarest.core.tasks.service import ITaskService |
| 16 | +from antarest.core.utils.fastapi_sqlalchemy import db |
| 17 | +from antarest.core.utils.lock import LockNotAcquired, create_lock |
| 18 | +from antarest.maintenance.tasks.common import BackGroundTaskStatus, GarbageCollectorTaskResult, LockId |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +def clean_tasks(task_service: ITaskService, dry_run: bool, task_retention_duration: int) -> GarbageCollectorTaskResult: |
| 24 | + start_time = time.time() |
| 25 | + deleted_count = 0 |
| 26 | + try: |
| 27 | + with db(): |
| 28 | + with create_lock(db.session, lock_id=LockId.TASKS_GC): |
| 29 | + logger.info(f"Deleting tasks older than {task_retention_duration} days from the database") |
| 30 | + if not dry_run: |
| 31 | + deleted_count = task_service.delete_task_by_creation_date(task_retention_duration) |
| 32 | + else: |
| 33 | + logger.info(f"[dry-run] Would delete tasks older than {task_retention_duration} days") |
| 34 | + deleted_count = 0 |
| 35 | + |
| 36 | + duration_seconds = time.time() - start_time |
| 37 | + |
| 38 | + except LockNotAcquired: |
| 39 | + logger.warning(f"Could not acquire lock {LockId.TASKS_GC}, another GC is probably running") |
| 40 | + return GarbageCollectorTaskResult( |
| 41 | + status=BackGroundTaskStatus.SKIPPED, |
| 42 | + reason="lock_not_acquired", |
| 43 | + deleted_count=0, |
| 44 | + duration_seconds=time.time() - start_time, |
| 45 | + ) |
| 46 | + |
| 47 | + logger.info(f"Finished tasks GC in {duration_seconds}s (deleted {deleted_count})") |
| 48 | + |
| 49 | + return GarbageCollectorTaskResult( |
| 50 | + status=BackGroundTaskStatus.SUCCESS, |
| 51 | + deleted_count=deleted_count, |
| 52 | + duration_seconds=duration_seconds, |
| 53 | + dry_run=dry_run, |
| 54 | + ) |
0 commit comments