Garbage collect old containers for a platform type, keeping only the newest ones. This function: - Retrieves all containers for the specified platform_type - Keeps the newest max_containers containers - Removes older containers (stops and deletes them) Args: platform_ty
(
platform_type: str, max_containers: int = 2, db: Optional[ContainerDatabase] = None
)
| 651 | |
| 652 | |
| 653 | def garbage_collect_platform_containers( |
| 654 | platform_type: str, max_containers: int = 2, db: Optional[ContainerDatabase] = None |
| 655 | ) -> int: |
| 656 | """Garbage collect old containers for a platform type, keeping only the newest ones. |
| 657 | |
| 658 | This function: |
| 659 | - Retrieves all containers for the specified platform_type |
| 660 | - Keeps the newest max_containers containers |
| 661 | - Removes older containers (stops and deletes them) |
| 662 | |
| 663 | Args: |
| 664 | platform_type: Platform family (e.g., "avr", "esp-32s3") |
| 665 | max_containers: Maximum number of containers to keep (default: 2) |
| 666 | db: Database instance (creates new if None) |
| 667 | |
| 668 | Returns: |
| 669 | Number of containers cleaned up |
| 670 | """ |
| 671 | if db is None: |
| 672 | db = ContainerDatabase() |
| 673 | |
| 674 | # Get all containers for this platform, ordered by creation time (oldest first) |
| 675 | all_containers = db.get_by_platform_type(platform_type, order_by_created_at=True) |
| 676 | |
| 677 | # Calculate how many to remove |
| 678 | containers_to_remove = len(all_containers) - max_containers |
| 679 | |
| 680 | if containers_to_remove <= 0: |
| 681 | return 0 # Nothing to clean up |
| 682 | |
| 683 | cleaned_count = 0 |
| 684 | |
| 685 | # Remove oldest containers |
| 686 | for container in all_containers[:containers_to_remove]: |
| 687 | print( |
| 688 | f"Garbage collecting old container {container.container_id} (platform: {platform_type})" |
| 689 | ) |
| 690 | |
| 691 | # Force remove the container with retry logic |
| 692 | success, error_msg = docker_force_remove_container(container.container_id) |
| 693 | if not success: |
| 694 | print( |
| 695 | f"⚠️ Warning: Failed to remove container {container.container_id}: {error_msg}" |
| 696 | ) |
| 697 | print(" Database record will still be cleaned up") |
| 698 | |
| 699 | # Remove from DB (even if container removal failed) |
| 700 | db.delete_by_id(container.container_id) |
| 701 | cleaned_count += 1 |
| 702 | |
| 703 | return cleaned_count |
no test coverage detected