Clean up containers from dead processes. This function implements the orphan cleanup phase: - Scans all tracked containers - Identifies containers whose owner PIDs are dead - Stops and removes orphaned containers - Cleans up database records Args: db: Database insta
(db: Optional[ContainerDatabase] = None)
| 609 | |
| 610 | |
| 611 | def cleanup_orphaned_containers(db: Optional[ContainerDatabase] = None) -> int: |
| 612 | """Clean up containers from dead processes. |
| 613 | |
| 614 | This function implements the orphan cleanup phase: |
| 615 | - Scans all tracked containers |
| 616 | - Identifies containers whose owner PIDs are dead |
| 617 | - Stops and removes orphaned containers |
| 618 | - Cleans up database records |
| 619 | |
| 620 | Args: |
| 621 | db: Database instance (creates new if None) |
| 622 | |
| 623 | Returns: |
| 624 | Number of containers cleaned up |
| 625 | """ |
| 626 | if db is None: |
| 627 | db = ContainerDatabase() |
| 628 | |
| 629 | all_tracked = db.get_all() |
| 630 | cleaned_count = 0 |
| 631 | |
| 632 | for container in all_tracked: |
| 633 | if not process_exists(container.owner_pid): |
| 634 | print( |
| 635 | f"Found orphaned container {container.container_id} from dead PID {container.owner_pid}" |
| 636 | ) |
| 637 | |
| 638 | # Force remove the container with retry logic |
| 639 | success, error_msg = docker_force_remove_container(container.container_id) |
| 640 | if not success: |
| 641 | print( |
| 642 | f"⚠️ Warning: Failed to remove container {container.container_id}: {error_msg}" |
| 643 | ) |
| 644 | print(" Database record will still be cleaned up") |
| 645 | |
| 646 | # Remove from DB (even if container removal failed) |
| 647 | db.delete_by_id(container.container_id) |
| 648 | cleaned_count += 1 |
| 649 | |
| 650 | return cleaned_count |
| 651 | |
| 652 | |
| 653 | def garbage_collect_platform_containers( |
no test coverage detected