-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_run.py
More file actions
343 lines (296 loc) · 11.6 KB
/
docker_run.py
File metadata and controls
343 lines (296 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#!/usr/bin/env python3
"""Convenient orchestrator for local Papers2Code development services.
This utility makes it simple to spin up the Keycloak mock OAuth server (via Docker
Compose) and run the backend & frontend dev servers with a single command.
Example usage:
uv run docker_run.py # Start Keycloak, backend, and frontend
uv run docker_run.py --skip-frontend
uv run docker_run.py stop # Stop only the Keycloak container
"""
from __future__ import annotations
import argparse
import os
import shlex
import shutil
import signal
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import List, Optional
# Load .env file early so ENV_TYPE and other settings are available
try:
from dotenv import load_dotenv
ROOT_DIR = Path(__file__).resolve().parent
env_file = ROOT_DIR / ".env"
if env_file.exists():
load_dotenv(env_file)
print(f"[docker_run] Loaded environment from {env_file}")
except ImportError:
ROOT_DIR = Path(__file__).resolve().parent
print("[docker_run] Warning: python-dotenv not installed, .env file not loaded")
UI_DIR = ROOT_DIR / "papers2code-ui"
DEFAULT_COMPOSE_FILE = ROOT_DIR / "docker-compose.dev.yml"
DEFAULT_BACKEND_CMD = "uv run run.py"
DEFAULT_FRONTEND_CMD = "npm run dev -- --host 0.0.0.0 --port 5173"
def print_header(message: str) -> None:
"""Utility logger with a consistent prefix."""
print(f"[docker_run] {message}")
def detect_compose_command(compose_file: Path) -> List[str]:
"""Return the base docker compose command list, preferring v2 syntax."""
compose_file = compose_file.resolve()
docker_path = shutil.which("docker")
docker_compose_path = shutil.which("docker-compose")
if docker_path:
# Check whether `docker compose` is supported
result = subprocess.run(
[docker_path, "compose", "version"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if result.returncode == 0:
return [docker_path, "compose", "-f", str(compose_file)]
if docker_compose_path:
return [docker_compose_path, "-f", str(compose_file)]
raise RuntimeError(
"Neither `docker compose` nor `docker-compose` is available. "
"Please install Docker Desktop or Docker Compose v2."
)
class ComposeClient:
"""Tiny helper around docker compose commands."""
def __init__(self, compose_file: Path):
if not compose_file.exists():
raise FileNotFoundError(f"Compose file not found: {compose_file}")
self.compose_file = compose_file
self.base_cmd = detect_compose_command(compose_file)
def run(self, *args: str, check: bool = True) -> subprocess.CompletedProcess:
command = [*self.base_cmd, *args]
result = subprocess.run(command)
if check and result.returncode != 0:
raise RuntimeError(
f"Command failed ({result.returncode}): {' '.join(command)}"
)
return result
def up_detached(self, services: List[str], rebuild: bool = False) -> None:
if rebuild:
self.run("build", *services)
self.run("up", "-d", *services)
def stop(self, services: Optional[List[str]] = None) -> None:
args: List[str] = ["stop"]
if services:
args.extend(services)
self.run(*args, check=False)
class ManagedProcess:
"""Represents a long-running subprocess whose logs should be streamed."""
def __init__(self, name: str, command: List[str], cwd: Path, env: Optional[dict] = None):
self.name = name
self.command = command
self.cwd = cwd
self.env = env or os.environ.copy()
self.process: Optional[subprocess.Popen] = None
self._stdout_thread: Optional[threading.Thread] = None
self._stderr_thread: Optional[threading.Thread] = None
self._reported = False
def start(self) -> None:
print_header(f"Starting {self.name}: {' '.join(self.command)}")
self.process = subprocess.Popen(
self.command,
cwd=str(self.cwd),
env=self.env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
assert self.process.stdout
assert self.process.stderr
self._stdout_thread = threading.Thread(
target=self._stream_output,
args=(self.process.stdout, False),
daemon=True,
)
self._stderr_thread = threading.Thread(
target=self._stream_output,
args=(self.process.stderr, True),
daemon=True,
)
self._stdout_thread.start()
self._stderr_thread.start()
def _stream_output(self, stream, is_err: bool) -> None:
prefix = f"[{self.name}{'::err' if is_err else ''}] "
for line in iter(stream.readline, ""):
print(prefix + line.rstrip())
stream.close()
@property
def is_running(self) -> bool:
return self.process is not None and self.process.poll() is None
@property
def returncode(self) -> Optional[int]:
return None if self.process is None else self.process.poll()
def stop(self, timeout: float = 10.0) -> None:
if not self.process:
return
if self.is_running:
print_header(f"Stopping {self.name}...")
self.process.terminate()
try:
self.process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
print_header(f"Force killing {self.name}")
self.process.kill()
if self._stdout_thread:
self._stdout_thread.join(timeout=1)
if self._stderr_thread:
self._stderr_thread.join(timeout=1)
class DevEnvironmentOrchestrator:
"""Coordinates Docker + local dev servers."""
def __init__(self, args: argparse.Namespace):
self.args = args
self.compose = ComposeClient(Path(args.compose_file))
self.processes: List[ManagedProcess] = []
self._shutdown = False
def start(self) -> None:
if not self.args.skip_dex:
print_header("Ensuring Keycloak container is up (docker compose)...")
self.compose.up_detached(["keycloak"], rebuild=self.args.rebuild_dex)
print_header("Keycloak is running on http://localhost:8080")
print_header(" - Mock GitHub: http://localhost:8080/realms/mock-github")
print_header(" - Mock Google: http://localhost:8080/realms/mock-google")
print_header(" - Admin Console: http://localhost:8080 (admin/admin)")
if not self.args.skip_backend:
backend_cmd = shlex.split(self.args.backend_command)
backend_env = os.environ.copy()
backend_env.setdefault("ENV_TYPE", "DEV")
backend_proc = ManagedProcess("backend", backend_cmd, ROOT_DIR, backend_env)
backend_proc.start()
self.processes.append(backend_proc)
if not self.args.skip_frontend:
if not UI_DIR.exists():
raise FileNotFoundError(f"Frontend directory not found: {UI_DIR}")
frontend_cmd = shlex.split(self.args.frontend_command)
frontend_proc = ManagedProcess("frontend", frontend_cmd, UI_DIR)
frontend_proc.start()
self.processes.append(frontend_proc)
if not self.processes:
print_header("Nothing else to run. Exiting.")
return
self._install_signal_handlers()
print_header("All services started. Press Ctrl+C to stop.")
self._monitor_processes()
def _install_signal_handlers(self) -> None:
def handler(signum, _frame):
print_header(f"Received signal {signum}; shutting down...")
self.stop()
for sig in (signal.SIGINT, signal.SIGTERM):
try:
signal.signal(sig, handler)
except ValueError:
# Signal handling may fail in some threaded contexts (e.g. Windows)
pass
def _monitor_processes(self) -> None:
try:
while not self._shutdown:
for proc in self.processes:
if proc.is_running:
continue
if proc.returncode is not None and not proc._reported:
proc._reported = True
print_header(
f"{proc.name} exited with code {proc.returncode}" # noqa: SLF001
)
self._shutdown = True
break
if self._shutdown:
break
time.sleep(0.5)
except KeyboardInterrupt:
print_header("Keyboard interrupt received; stopping...")
finally:
self.stop()
def stop(self) -> None:
if self._shutdown:
return
self._shutdown = True
for proc in self.processes:
proc.stop()
if self.args.stop_dex and not self.args.skip_dex:
print_header("Stopping Keycloak container...")
self.compose.stop(["keycloak"])
print_header("All services stopped.")
def stop_only(self) -> None:
print_header("Stopping Keycloak service via docker compose...")
self.compose.stop(["keycloak"])
print_header("Keycloak stopped. Manually terminate any local dev servers if needed.")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Start Keycloak (Docker) plus backend & frontend dev servers with one command.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"action",
nargs="?",
choices=["start", "stop"],
default="start",
help="What to do: start everything or just stop Keycloak.",
)
parser.add_argument(
"--compose-file",
default=str(DEFAULT_COMPOSE_FILE),
help="Path to docker compose file used for Keycloak.",
)
parser.add_argument(
"--backend-command",
default=DEFAULT_BACKEND_CMD,
help="Command used to start the backend (runs inside project root).",
)
parser.add_argument(
"--frontend-command",
default=DEFAULT_FRONTEND_CMD,
help="Command used to start the frontend (runs inside papers2code-ui).",
)
parser.add_argument(
"--skip-dex",
action="store_true",
help="Do not manage the Keycloak Docker container.",
)
parser.add_argument(
"--skip-backend",
action="store_true",
help="Do not launch the backend process.",
)
parser.add_argument(
"--skip-frontend",
action="store_true",
help="Do not launch the frontend process.",
)
parser.add_argument(
"--rebuild-dex",
action="store_true",
help="Rebuild the Keycloak image before starting it (docker compose build).",
)
parser.add_argument(
"--stop-dex",
action="store_true",
help="Stop the Keycloak container when shutting down.",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
try:
orchestrator = DevEnvironmentOrchestrator(args)
if args.action == "start":
orchestrator.start()
else:
orchestrator.stop_only()
except FileNotFoundError as exc:
print_header(str(exc))
sys.exit(1)
except RuntimeError as exc:
print_header(f"Error: {exc}")
sys.exit(1)
except Exception as exc: # pragma: no cover - safety net
print_header(f"Unexpected error: {exc}")
sys.exit(1)
if __name__ == "__main__":
main()