|
| 1 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 2 | +# VulnerableCode is a trademark of nexB Inc. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. |
| 5 | +# See https://github.com/aboutcode-org/vulnerablecode for support or download. |
| 6 | +# See https://aboutcode.org for more information about nexB OSS projects. |
| 7 | +# |
| 8 | + |
| 9 | + |
| 10 | +from datetime import timedelta |
| 11 | + |
| 12 | +from django.utils import timezone |
| 13 | + |
| 14 | +from vulnerabilities.models import PipelineSchedule |
| 15 | +from vulnerabilities.pipelines import LoopProgress |
| 16 | +from vulnerabilities.pipelines import VulnerableCodePipeline |
| 17 | +from vulnerablecode.settings import ( |
| 18 | + VULNERABLECODE_MINIMUM_PIPELINE_RUNS_TO_RETAIN as minimum_number_of_runs_to_keep, |
| 19 | +) |
| 20 | +from vulnerablecode.settings import VULNERABLECODE_PIPELINE_RUN_RETENTION_DAYS as retention_days |
| 21 | + |
| 22 | + |
| 23 | +class CleanupPipelineRuns(VulnerableCodePipeline): |
| 24 | + """Remove pipeline runs older than the retention period while preserving the configured minimum number of runs.""" |
| 25 | + |
| 26 | + pipeline_id = "cleanup_pipeline_runs" |
| 27 | + |
| 28 | + run_interval = 1440 |
| 29 | + run_priority = PipelineSchedule.ExecutionPriority.DEFAULT |
| 30 | + |
| 31 | + @classmethod |
| 32 | + def steps(cls): |
| 33 | + return (cls.cleanup_old_pipeline_runs,) |
| 34 | + |
| 35 | + def cleanup_old_pipeline_runs(self): |
| 36 | + """Remove pipeline runs older than the retention period while preserving the configured minimum number of runs.""" |
| 37 | + |
| 38 | + pipelines = PipelineSchedule.objects.all() |
| 39 | + pipeline_count = 0 |
| 40 | + deleted_run_count = 0 |
| 41 | + |
| 42 | + progress = LoopProgress( |
| 43 | + total_iterations=pipelines.count(), progress_step=5, logger=self.log |
| 44 | + ) |
| 45 | + for pipeline in progress.iter(pipelines): |
| 46 | + cutoff = timezone.now() - timedelta(days=retention_days) |
| 47 | + runs = pipeline.pipelineruns.filter(run_exitcode__isnull=False).order_by( |
| 48 | + "-created_date" |
| 49 | + ) |
| 50 | + runs_to_keep = runs[:minimum_number_of_runs_to_keep] |
| 51 | + runs_to_delete = runs.filter(created_date__lt=cutoff).exclude( |
| 52 | + run_id__in=runs_to_keep.values("run_id") |
| 53 | + ) |
| 54 | + |
| 55 | + if runs_to_delete.exists(): |
| 56 | + pipeline_count += 1 |
| 57 | + |
| 58 | + for run in runs_to_delete.iterator(): |
| 59 | + run.delete() |
| 60 | + deleted_run_count += 1 |
| 61 | + |
| 62 | + self.log( |
| 63 | + f"Successfully removed {deleted_run_count:,d} runs from {pipeline_count} pipelines that were older than {retention_days} days." |
| 64 | + ) |
0 commit comments