|
| 1 | +""" |
| 2 | +Management command to remove recordings from the system. |
| 3 | +""" |
| 4 | + |
| 5 | +import logging |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import djclick as click |
| 9 | + |
| 10 | +from bats_ai.core.models import Recording |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | +exclude_help = "A newline-delimited list of recording IDs to keep" |
| 15 | +batch_size_help = "The number of recordings to delete at a time. Lower it for memory-limited systems" |
| 16 | +dry_run_help = "If true, report number of recordings that would be deleted, instead of deleting recordings." |
| 17 | + |
| 18 | + |
| 19 | +@click.command() |
| 20 | +@click.option( |
| 21 | + "--exclude", |
| 22 | + type=click.Path(exists=True, dir_okay=False, path_type=Path), |
| 23 | + help=exclude_help |
| 24 | +) |
| 25 | +@click.option("--batch-size", type=click.INT, default=1000, help=batch_size_help) |
| 26 | +@click.option("--dry-run", type=click.BOOL, is_flag=True, help=dry_run_help) |
| 27 | +def purge_recordings(exclude: Path, batch_size: int, dry_run: bool): |
| 28 | + to_skip = set() |
| 29 | + if exclude: |
| 30 | + with open(exclude) as f: |
| 31 | + lines = f.readlines() |
| 32 | + for recording_id in lines: |
| 33 | + stripped_id = recording_id.strip() |
| 34 | + if stripped_id: |
| 35 | + to_skip.add(int(stripped_id)) |
| 36 | + if len(to_skip): |
| 37 | + logger.info("Purging all recordings. %d recordings will be skipped...", len(to_skip)) |
| 38 | + else: |
| 39 | + logger.info("Purging all recordings...") |
| 40 | + |
| 41 | + total_deleted_count = 0 |
| 42 | + total_deleted_stats = {} |
| 43 | + to_delete = Recording.objects.exclude(pk__in=to_skip).order_by("pk") |
| 44 | + if dry_run: |
| 45 | + total_deleted_count = to_delete.count() |
| 46 | + else: |
| 47 | + while True: |
| 48 | + batch_ids = list(to_delete[:batch_size].values_list("pk", flat=True)) |
| 49 | + if not batch_ids: |
| 50 | + break |
| 51 | + total_deleted, deleted_stats = Recording.objects.filter(pk__in=batch_ids).delete() |
| 52 | + total_deleted_count += total_deleted |
| 53 | + for key in deleted_stats: |
| 54 | + if key in total_deleted_stats: |
| 55 | + total_deleted_stats[key] += deleted_stats[key] |
| 56 | + else: |
| 57 | + total_deleted_stats[key] = deleted_stats[key] |
| 58 | + |
| 59 | + |
| 60 | + if dry_run: |
| 61 | + logger.info("Done. %d recordings would have been deleted.", total_deleted_count) |
| 62 | + else: |
| 63 | + logger.info("Done. Deleted %d objects.", total_deleted_count) |
| 64 | + for key in total_deleted_stats: |
| 65 | + logger.info("\t %d instances of %s deleted.", total_deleted_stats[key], key) |
0 commit comments