|
| 1 | +import atexit |
1 | 2 | import json |
| 3 | +import logging |
2 | 4 | import os |
3 | 5 | import shutil |
| 6 | +import signal |
| 7 | +import time |
4 | 8 | from os import environ, remove |
5 | 9 | from pathlib import Path |
6 | 10 | from typing import Dict, List |
7 | 11 |
|
8 | 12 | import certifi |
| 13 | +import docker |
9 | 14 | import minio |
10 | 15 | import networkx as nx |
11 | 16 | import pytest |
| 17 | +import requests |
12 | 18 | import urllib3 |
13 | 19 | from packaging import version |
14 | 20 |
|
|
24 | 30 | from . import schema_uuid as schema_uuid_module |
25 | 31 |
|
26 | 32 |
|
| 33 | +# Configure logging for container management |
| 34 | +logger = logging.getLogger(__name__) |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +# Global container registry for cleanup |
| 40 | +_active_containers = set() |
| 41 | +_docker_client = None |
| 42 | + |
| 43 | + |
| 44 | +def _get_docker_client(): |
| 45 | + """Get or create docker client""" |
| 46 | + global _docker_client |
| 47 | + if _docker_client is None: |
| 48 | + _docker_client = docker.from_env() |
| 49 | + return _docker_client |
| 50 | + |
| 51 | + |
| 52 | +def _cleanup_containers(): |
| 53 | + """Clean up any remaining containers""" |
| 54 | + if _active_containers: |
| 55 | + logger.info(f"Emergency cleanup: {len(_active_containers)} containers to clean up") |
| 56 | + try: |
| 57 | + client = _get_docker_client() |
| 58 | + for container_id in list(_active_containers): |
| 59 | + try: |
| 60 | + container = client.containers.get(container_id) |
| 61 | + container.remove(force=True) |
| 62 | + logger.info(f"Emergency cleanup: removed container {container_id[:12]}") |
| 63 | + except docker.errors.NotFound: |
| 64 | + logger.debug(f"Container {container_id[:12]} already removed") |
| 65 | + except Exception as e: |
| 66 | + logger.error(f"Error cleaning up container {container_id[:12]}: {e}") |
| 67 | + finally: |
| 68 | + _active_containers.discard(container_id) |
| 69 | + except Exception as e: |
| 70 | + logger.error(f"Error during emergency cleanup: {e}") |
| 71 | + else: |
| 72 | + logger.debug("No containers to clean up") |
| 73 | + |
| 74 | + |
| 75 | +def _register_container(container): |
| 76 | + """Register a container for cleanup""" |
| 77 | + _active_containers.add(container.id) |
| 78 | + logger.debug(f"Registered container {container.id[:12]} for cleanup") |
| 79 | + |
| 80 | + |
| 81 | +def _unregister_container(container): |
| 82 | + """Unregister a container from cleanup""" |
| 83 | + _active_containers.discard(container.id) |
| 84 | + logger.debug(f"Unregistered container {container.id[:12]} from cleanup") |
| 85 | + |
| 86 | + |
| 87 | +# Register cleanup functions |
| 88 | +atexit.register(_cleanup_containers) |
| 89 | + |
| 90 | + |
| 91 | +def _signal_handler(signum, frame): |
| 92 | + """Handle signals to ensure container cleanup""" |
| 93 | + logger.warning(f"Received signal {signum}, performing emergency container cleanup...") |
| 94 | + _cleanup_containers() |
| 95 | + |
| 96 | + # Restore default signal handler and re-raise the signal |
| 97 | + # This allows pytest to handle the cancellation normally |
| 98 | + signal.signal(signum, signal.SIG_DFL) |
| 99 | + os.kill(os.getpid(), signum) |
| 100 | + |
| 101 | + |
| 102 | +# Register signal handlers for graceful cleanup, but only for non-interactive scenarios |
| 103 | +# In pytest, we'll rely on fixture teardown and atexit handlers primarily |
| 104 | +try: |
| 105 | + import pytest |
| 106 | + # If we're here, pytest is available, so only register SIGTERM (for CI/batch scenarios) |
| 107 | + signal.signal(signal.SIGTERM, _signal_handler) |
| 108 | + # Don't intercept SIGINT (Ctrl+C) to allow pytest's normal cancellation behavior |
| 109 | +except ImportError: |
| 110 | + # If pytest isn't available, register both handlers |
| 111 | + signal.signal(signal.SIGINT, _signal_handler) |
| 112 | + signal.signal(signal.SIGTERM, _signal_handler) |
| 113 | + |
| 114 | + |
| 115 | +@pytest.fixture(scope="session") |
| 116 | +def docker_client(): |
| 117 | + """Docker client for managing containers.""" |
| 118 | + return _get_docker_client() |
| 119 | + |
| 120 | + |
| 121 | +@pytest.fixture(scope="session") |
| 122 | +def mysql_container(docker_client): |
| 123 | + """Start MySQL container and wait for it to be healthy.""" |
| 124 | + mysql_ver = os.environ.get("MYSQL_VER", "8.0") |
| 125 | + container_name = f"datajoint_test_mysql_{os.getpid()}" |
| 126 | + |
| 127 | + logger.info(f"Starting MySQL container {container_name} with version {mysql_ver}") |
| 128 | + |
| 129 | + # Remove existing container if it exists |
| 130 | + try: |
| 131 | + existing = docker_client.containers.get(container_name) |
| 132 | + logger.info(f"Removing existing MySQL container {container_name}") |
| 133 | + existing.remove(force=True) |
| 134 | + except docker.errors.NotFound: |
| 135 | + logger.debug(f"No existing MySQL container {container_name} found") |
| 136 | + |
| 137 | + # Start MySQL container |
| 138 | + container = docker_client.containers.run( |
| 139 | + f"datajoint/mysql:{mysql_ver}", |
| 140 | + name=container_name, |
| 141 | + environment={ |
| 142 | + "MYSQL_ROOT_PASSWORD": "password" |
| 143 | + }, |
| 144 | + command="mysqld --default-authentication-plugin=mysql_native_password", |
| 145 | + ports={"3306/tcp": None}, # Let Docker assign random port |
| 146 | + detach=True, |
| 147 | + remove=True, |
| 148 | + healthcheck={ |
| 149 | + "test": ["CMD", "mysqladmin", "ping", "-h", "localhost"], |
| 150 | + "timeout": 30000000000, # 30s in nanoseconds |
| 151 | + "retries": 5, |
| 152 | + "interval": 15000000000, # 15s in nanoseconds |
| 153 | + } |
| 154 | + ) |
| 155 | + |
| 156 | + # Register container for cleanup |
| 157 | + _register_container(container) |
| 158 | + logger.info(f"MySQL container {container_name} started with ID {container.id[:12]}") |
| 159 | + |
| 160 | + # Wait for health check |
| 161 | + max_wait = 120 # 2 minutes |
| 162 | + start_time = time.time() |
| 163 | + logger.info(f"Waiting for MySQL container {container_name} to become healthy (max {max_wait}s)") |
| 164 | + |
| 165 | + while time.time() - start_time < max_wait: |
| 166 | + container.reload() |
| 167 | + health_status = container.attrs["State"]["Health"]["Status"] |
| 168 | + logger.debug(f"MySQL container {container_name} health status: {health_status}") |
| 169 | + if health_status == "healthy": |
| 170 | + break |
| 171 | + time.sleep(2) |
| 172 | + else: |
| 173 | + logger.error(f"MySQL container {container_name} failed to become healthy within {max_wait}s") |
| 174 | + container.remove(force=True) |
| 175 | + raise RuntimeError("MySQL container failed to become healthy") |
| 176 | + |
| 177 | + # Get the mapped port |
| 178 | + port_info = container.attrs["NetworkSettings"]["Ports"]["3306/tcp"] |
| 179 | + if port_info: |
| 180 | + host_port = port_info[0]["HostPort"] |
| 181 | + logger.info(f"MySQL container {container_name} is healthy and accessible on localhost:{host_port}") |
| 182 | + else: |
| 183 | + raise RuntimeError("Failed to get MySQL port mapping") |
| 184 | + |
| 185 | + yield container, "localhost", int(host_port) |
| 186 | + |
| 187 | + # Cleanup |
| 188 | + logger.info(f"Cleaning up MySQL container {container_name}") |
| 189 | + _unregister_container(container) |
| 190 | + container.remove(force=True) |
| 191 | + logger.info(f"MySQL container {container_name} removed") |
| 192 | + |
| 193 | + |
| 194 | +@pytest.fixture(scope="session") |
| 195 | +def minio_container(docker_client): |
| 196 | + """Start MinIO container and wait for it to be healthy.""" |
| 197 | + minio_ver = os.environ.get("MINIO_VER", "RELEASE.2025-02-28T09-55-16Z") |
| 198 | + container_name = f"datajoint_test_minio_{os.getpid()}" |
| 199 | + |
| 200 | + logger.info(f"Starting MinIO container {container_name} with version {minio_ver}") |
| 201 | + |
| 202 | + # Remove existing container if it exists |
| 203 | + try: |
| 204 | + existing = docker_client.containers.get(container_name) |
| 205 | + logger.info(f"Removing existing MinIO container {container_name}") |
| 206 | + existing.remove(force=True) |
| 207 | + except docker.errors.NotFound: |
| 208 | + logger.debug(f"No existing MinIO container {container_name} found") |
| 209 | + |
| 210 | + # Start MinIO container |
| 211 | + container = docker_client.containers.run( |
| 212 | + f"minio/minio:{minio_ver}", |
| 213 | + name=container_name, |
| 214 | + environment={ |
| 215 | + "MINIO_ACCESS_KEY": "datajoint", |
| 216 | + "MINIO_SECRET_KEY": "datajoint" |
| 217 | + }, |
| 218 | + command=['server', '--address', ':9000', '/data'], |
| 219 | + ports={"9000/tcp": None}, # Let Docker assign random port |
| 220 | + detach=True, |
| 221 | + remove=True |
| 222 | + ) |
| 223 | + |
| 224 | + # Register container for cleanup |
| 225 | + _register_container(container) |
| 226 | + logger.info(f"MinIO container {container_name} started with ID {container.id[:12]}") |
| 227 | + |
| 228 | + # Get the mapped port |
| 229 | + container.reload() |
| 230 | + port_info = container.attrs["NetworkSettings"]["Ports"]["9000/tcp"] |
| 231 | + if port_info: |
| 232 | + host_port = port_info[0]["HostPort"] |
| 233 | + logger.info(f"MinIO container {container_name} mapped to localhost:{host_port}") |
| 234 | + else: |
| 235 | + raise RuntimeError("Failed to get MinIO port mapping") |
| 236 | + |
| 237 | + # Wait for MinIO to be ready |
| 238 | + minio_url = f"http://localhost:{host_port}" |
| 239 | + max_wait = 60 |
| 240 | + start_time = time.time() |
| 241 | + logger.info(f"Waiting for MinIO container {container_name} to become ready (max {max_wait}s)") |
| 242 | + |
| 243 | + while time.time() - start_time < max_wait: |
| 244 | + try: |
| 245 | + response = requests.get(f"{minio_url}/minio/health/live", timeout=5) |
| 246 | + if response.status_code == 200: |
| 247 | + logger.info(f"MinIO container {container_name} is ready and accessible at {minio_url}") |
| 248 | + break |
| 249 | + except requests.exceptions.RequestException: |
| 250 | + logger.debug(f"MinIO container {container_name} not ready yet, retrying...") |
| 251 | + pass |
| 252 | + time.sleep(2) |
| 253 | + else: |
| 254 | + logger.error(f"MinIO container {container_name} failed to become ready within {max_wait}s") |
| 255 | + container.remove(force=True) |
| 256 | + raise RuntimeError("MinIO container failed to become ready") |
| 257 | + |
| 258 | + yield container, "localhost", int(host_port) |
| 259 | + |
| 260 | + # Cleanup |
| 261 | + logger.info(f"Cleaning up MinIO container {container_name}") |
| 262 | + _unregister_container(container) |
| 263 | + container.remove(force=True) |
| 264 | + logger.info(f"MinIO container {container_name} removed") |
| 265 | + |
| 266 | + |
27 | 267 | @pytest.fixture(scope="session") |
28 | 268 | def prefix(): |
29 | 269 | return os.environ.get("DJ_TEST_DB_PREFIX", "djtest") |
@@ -56,18 +296,20 @@ def enable_filepath_feature(monkeypatch): |
56 | 296 |
|
57 | 297 |
|
58 | 298 | @pytest.fixture(scope="session") |
59 | | -def db_creds_test() -> Dict: |
| 299 | +def db_creds_test(mysql_container) -> Dict: |
| 300 | + _, host, port = mysql_container |
60 | 301 | return dict( |
61 | | - host=os.getenv("DJ_TEST_HOST", "db"), |
| 302 | + host=f"{host}:{port}", |
62 | 303 | user=os.getenv("DJ_TEST_USER", "datajoint"), |
63 | 304 | password=os.getenv("DJ_TEST_PASSWORD", "datajoint"), |
64 | 305 | ) |
65 | 306 |
|
66 | 307 |
|
67 | 308 | @pytest.fixture(scope="session") |
68 | | -def db_creds_root() -> Dict: |
| 309 | +def db_creds_root(mysql_container) -> Dict: |
| 310 | + _, host, port = mysql_container |
69 | 311 | return dict( |
70 | | - host=os.getenv("DJ_HOST", "db"), |
| 312 | + host=f"{host}:{port}", |
71 | 313 | user=os.getenv("DJ_USER", "root"), |
72 | 314 | password=os.getenv("DJ_PASS", "password"), |
73 | 315 | ) |
@@ -190,9 +432,10 @@ def connection_test(connection_root, prefix, db_creds_test): |
190 | 432 |
|
191 | 433 |
|
192 | 434 | @pytest.fixture(scope="session") |
193 | | -def s3_creds() -> Dict: |
| 435 | +def s3_creds(minio_container) -> Dict: |
| 436 | + _, host, port = minio_container |
194 | 437 | return dict( |
195 | | - endpoint=os.environ.get("S3_ENDPOINT", "minio:9000"), |
| 438 | + endpoint=f"{host}:{port}", |
196 | 439 | access_key=os.environ.get("S3_ACCESS_KEY", "datajoint"), |
197 | 440 | secret_key=os.environ.get("S3_SECRET_KEY", "datajoint"), |
198 | 441 | bucket=os.environ.get("S3_BUCKET", "datajoint.test"), |
|
0 commit comments