|
| 1 | +import dataclasses |
| 2 | +from collections import defaultdict |
| 3 | +from collections.abc import Callable |
| 4 | +from functools import partial |
| 5 | + |
| 6 | +from django.db.models import Model |
| 7 | +from django.db.models.query import QuerySet |
| 8 | +from shared.bundle_analysis import StoragePaths |
| 9 | +from shared.django_apps.compare.models import CommitComparison |
| 10 | +from shared.django_apps.core.models import Commit, Pull |
| 11 | +from shared.django_apps.profiling.models import ProfilingUpload |
| 12 | +from shared.django_apps.reports.models import CommitReport, ReportDetails |
| 13 | +from shared.django_apps.reports.models import ReportSession as Upload |
| 14 | +from shared.django_apps.staticanalysis.models import StaticAnalysisSingleFileSnapshot |
| 15 | + |
| 16 | +from services.archive import ArchiveService, MinioEndpoints |
| 17 | +from services.cleanup.utils import CleanupContext, CleanupResult |
| 18 | + |
| 19 | +MANUAL_QUERY_CHUNKSIZE = 5_000 |
| 20 | +DELETE_FILES_BATCHSIZE = 50 |
| 21 | + |
| 22 | + |
| 23 | +def cleanup_files_batched( |
| 24 | + context: CleanupContext, buckets_paths: dict[str, list[str]] |
| 25 | +) -> int: |
| 26 | + def delete_file(bucket_path: tuple[str, str]) -> bool: |
| 27 | + return context.storage.delete_file(bucket_path[0], bucket_path[1]) |
| 28 | + |
| 29 | + iter = ((bucket, path) for bucket, paths in buckets_paths.items() for path in paths) |
| 30 | + results = context.threadpool.map(delete_file, iter) |
| 31 | + return sum(results) |
| 32 | + |
| 33 | + |
| 34 | +def cleanup_with_storage_field( |
| 35 | + path_field: str, |
| 36 | + context: CleanupContext, |
| 37 | + query: QuerySet, |
| 38 | +) -> CleanupResult: |
| 39 | + cleaned_files = 0 |
| 40 | + |
| 41 | + # delete `None` `path_field`s right away |
| 42 | + cleaned_models = query.filter(**{f"{path_field}__isnull": True})._raw_delete( |
| 43 | + query.db |
| 44 | + ) |
| 45 | + |
| 46 | + # delete all those files from storage, using chunks based on the `id` column |
| 47 | + storage_query = query.filter(**{f"{path_field}__isnull": False}).order_by("id") |
| 48 | + |
| 49 | + while True: |
| 50 | + storage_paths = storage_query.values_list(path_field, flat=True)[ |
| 51 | + :MANUAL_QUERY_CHUNKSIZE |
| 52 | + ] |
| 53 | + if len(storage_paths) == 0: |
| 54 | + break |
| 55 | + |
| 56 | + cleaned_files += cleanup_files_batched( |
| 57 | + context, {context.default_bucket: storage_paths} |
| 58 | + ) |
| 59 | + cleaned_models += query.filter( |
| 60 | + id__in=storage_query[:MANUAL_QUERY_CHUNKSIZE] |
| 61 | + )._raw_delete(query.db) |
| 62 | + |
| 63 | + return CleanupResult(cleaned_models, cleaned_files) |
| 64 | + |
| 65 | + |
| 66 | +def cleanup_archivefield( |
| 67 | + field_name: str, context: CleanupContext, query: QuerySet |
| 68 | +) -> CleanupResult: |
| 69 | + model_field_name = f"_{field_name}_storage_path" |
| 70 | + |
| 71 | + return cleanup_with_storage_field(model_field_name, context, query) |
| 72 | + |
| 73 | + |
| 74 | +# This has all the `Repository` fields needed by `get_archive_hash` |
| 75 | +@dataclasses.dataclass |
| 76 | +class FakeRepository: |
| 77 | + repoid: int |
| 78 | + service: str |
| 79 | + service_id: str |
| 80 | + |
| 81 | + |
| 82 | +def cleanup_commitreport(context: CleanupContext, query: QuerySet) -> CleanupResult: |
| 83 | + coverage_reports = query.values_list( |
| 84 | + "report_type", |
| 85 | + "code", |
| 86 | + "external_id", |
| 87 | + "commit__commitid", |
| 88 | + "commit__repository__repoid", |
| 89 | + "commit__repository__author__service", |
| 90 | + "commit__repository__service_id", |
| 91 | + ).order_by("id") |
| 92 | + |
| 93 | + cleaned_models = 0 |
| 94 | + cleaned_files = 0 |
| 95 | + repo_hashes: dict[int, str] = {} |
| 96 | + |
| 97 | + while True: |
| 98 | + reports = coverage_reports[:MANUAL_QUERY_CHUNKSIZE] |
| 99 | + if len(reports) == 0: |
| 100 | + break |
| 101 | + |
| 102 | + buckets_paths: dict[str, list[str]] = defaultdict(list) |
| 103 | + for ( |
| 104 | + report_type, |
| 105 | + report_code, |
| 106 | + external_id, |
| 107 | + commit_sha, |
| 108 | + repoid, |
| 109 | + repo_service, |
| 110 | + repo_service_id, |
| 111 | + ) in reports: |
| 112 | + if repoid not in repo_hashes: |
| 113 | + fake_repo = FakeRepository( |
| 114 | + repoid=repoid, service=repo_service, service_id=repo_service_id |
| 115 | + ) |
| 116 | + repo_hashes[repoid] = ArchiveService.get_archive_hash(fake_repo) |
| 117 | + repo_hash = repo_hashes[repoid] |
| 118 | + |
| 119 | + # depending on the `report_type`, we have: |
| 120 | + # - a `chunks` file for coverage |
| 121 | + # - a `bundle_report.sqlite` for BA |
| 122 | + if report_type == "bundle_analysis": |
| 123 | + path = StoragePaths.bundle_report.path( |
| 124 | + repo_key=repo_hash, report_key=external_id |
| 125 | + ) |
| 126 | + buckets_paths[context.bundleanalysis_bucket].append(path) |
| 127 | + elif report_type == "test_results": |
| 128 | + # TA has cached rollups, but those are based on `Branch` |
| 129 | + pass |
| 130 | + else: |
| 131 | + chunks_file_name = report_code if report_code is not None else "chunks" |
| 132 | + path = MinioEndpoints.chunks.get_path( |
| 133 | + version="v4", |
| 134 | + repo_hash=repo_hash, |
| 135 | + commitid=commit_sha, |
| 136 | + chunks_file_name=chunks_file_name, |
| 137 | + ) |
| 138 | + buckets_paths[context.default_bucket].append(path) |
| 139 | + |
| 140 | + cleaned_files += cleanup_files_batched(context, buckets_paths) |
| 141 | + cleaned_models += query.filter( |
| 142 | + id__in=query.order_by("id")[:MANUAL_QUERY_CHUNKSIZE] |
| 143 | + )._raw_delete(query.db) |
| 144 | + |
| 145 | + return CleanupResult(cleaned_models, cleaned_files) |
| 146 | + |
| 147 | + |
| 148 | +def cleanup_upload(context: CleanupContext, query: QuerySet) -> CleanupResult: |
| 149 | + cleaned_files = 0 |
| 150 | + |
| 151 | + # delete `None` `storage_path`s right away |
| 152 | + cleaned_models = query.filter(storage_path__isnull=True)._raw_delete(query.db) |
| 153 | + |
| 154 | + # delete all those files from storage, using chunks based on the `id` column |
| 155 | + storage_query = query.filter(storage_path__isnull=False).order_by("id") |
| 156 | + |
| 157 | + while True: |
| 158 | + uploads = storage_query.values_list("report__report_type", "storage_path")[ |
| 159 | + :MANUAL_QUERY_CHUNKSIZE |
| 160 | + ] |
| 161 | + if len(uploads) == 0: |
| 162 | + break |
| 163 | + |
| 164 | + buckets_paths: dict[str, list[str]] = defaultdict(list) |
| 165 | + for report_type, storage_path in uploads: |
| 166 | + if report_type == "bundle_analysis": |
| 167 | + buckets_paths[context.bundleanalysis_bucket].append(storage_path) |
| 168 | + else: |
| 169 | + buckets_paths[context.default_bucket].append(storage_path) |
| 170 | + |
| 171 | + cleaned_files += cleanup_files_batched(context, buckets_paths) |
| 172 | + cleaned_models += query.filter( |
| 173 | + id__in=storage_query[:MANUAL_QUERY_CHUNKSIZE] |
| 174 | + )._raw_delete(query.db) |
| 175 | + |
| 176 | + return CleanupResult(cleaned_models, cleaned_files) |
| 177 | + |
| 178 | + |
| 179 | +# All the models that need custom python code for deletions so a bulk `DELETE` query does not work. |
| 180 | +MANUAL_CLEANUP: dict[ |
| 181 | + type[Model], Callable[[CleanupContext, QuerySet], CleanupResult] |
| 182 | +] = { |
| 183 | + Commit: partial(cleanup_archivefield, "report"), |
| 184 | + Pull: partial(cleanup_archivefield, "flare"), |
| 185 | + ReportDetails: partial(cleanup_archivefield, "files_array"), |
| 186 | + CommitReport: cleanup_commitreport, |
| 187 | + Upload: cleanup_upload, |
| 188 | + CommitComparison: partial(cleanup_with_storage_field, "report_storage_path"), |
| 189 | + ProfilingUpload: partial(cleanup_with_storage_field, "raw_upload_location"), |
| 190 | + StaticAnalysisSingleFileSnapshot: partial( |
| 191 | + cleanup_with_storage_field, "content_location" |
| 192 | + ), |
| 193 | +} |
0 commit comments