()
| 47 | |
| 48 | |
| 49 | def stop_and_remove_containers(): |
| 50 | docker_compose_cmd = get_docker_command() |
| 51 | compose_file = os.path.join(TEMP_DIR, "docker-compose.yaml") |
| 52 | |
| 53 | # Read the docker-compose.yaml file |
| 54 | try: |
| 55 | with open(compose_file, "r") as file: |
| 56 | compose_config = yaml.safe_load(file) |
| 57 | except Exception as e: |
| 58 | print(t("COMPOSE_FILE_READ_ERROR", error=str(e))) |
| 59 | return |
| 60 | |
| 61 | # Get project name and service names |
| 62 | project_name = compose_config.get("name", "mindsearch") |
| 63 | service_names = list(compose_config.get("services", {}).keys()) |
| 64 | |
| 65 | # Use only the project name as the container prefix |
| 66 | container_prefix = f"{project_name}_" |
| 67 | |
| 68 | try: |
| 69 | # 1. Try to stop containers using the current docker-compose.yaml |
| 70 | subprocess.run( |
| 71 | docker_compose_cmd + ["-f", compose_file, "down", "-v", "--remove-orphans"], |
| 72 | check=True, |
| 73 | ) |
| 74 | except subprocess.CalledProcessError: |
| 75 | print(t("CURRENT_COMPOSE_STOP_FAILED")) |
| 76 | |
| 77 | # 2. Attempt to clean up potentially existing containers, regardless of the success of the previous step |
| 78 | try: |
| 79 | # List all containers (including stopped ones) |
| 80 | result = subprocess.run( |
| 81 | ["docker", "ps", "-a", "--format", "{{.Names}}"], |
| 82 | check=True, |
| 83 | capture_output=True, |
| 84 | text=True, |
| 85 | ) |
| 86 | all_containers = result.stdout.splitlines() |
| 87 | |
| 88 | # 3. Filter out containers belonging to our project |
| 89 | project_containers = [ |
| 90 | c |
| 91 | for c in all_containers |
| 92 | if c.startswith(container_prefix) |
| 93 | or any(c == f"{project_name}-{service}" for service in service_names) |
| 94 | ] |
| 95 | |
| 96 | if project_containers: |
| 97 | # 4. Force stop and remove these containers |
| 98 | for container in project_containers: |
| 99 | try: |
| 100 | subprocess.run(["docker", "stop", container], check=True) |
| 101 | subprocess.run(["docker", "rm", "-f", container], check=True) |
| 102 | print(t("CONTAINER_STOPPED_AND_REMOVED", container=container)) |
| 103 | except subprocess.CalledProcessError as e: |
| 104 | print(t("CONTAINER_STOP_ERROR", container=container, error=str(e))) |
| 105 | |
| 106 | # 5. Clean up potentially leftover networks |
no test coverage detected