-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathstart.py
More file actions
1518 lines (1285 loc) · 49.2 KB
/
start.py
File metadata and controls
1518 lines (1285 loc) · 49.2 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Director's Console - Unified Launcher
A robust Python launcher for all Director's Console services:
1. Orchestrator API (port 9820) - Job queue/render farm manager
2. CPE Backend (port 9800) - Cinema Prompt Engineering API
3. CPE Frontend (port 5173) - React UI
Features:
- Proper process management with cleanup on exit
- Signal handling for graceful shutdown (Ctrl+C, terminal close, etc.)
- Windows-specific socket cleanup to prevent orphaned ports
- Automatic port cleanup before starting
- Health checks with colored output
- Cross-platform compatible (Windows/Mac/Linux)
- Environment setup and dependency verification
- Auto-install missing packages
- PID lock file to prevent duplicate instances
Usage:
python start.py # Start all services
python start.py --setup # Setup/verify all environments
python start.py --no-orchestrator # Skip orchestrator
python start.py --no-frontend # Backend only
python start.py --no-browser # Don't open browser
python start.py --help # Show help
Author: Director's Console Team
Date: February 2026
"""
from __future__ import annotations
import argparse
import atexit
import os
import platform
import shutil
import signal
import socket
import subprocess
import sys
import time
import webbrowser
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
# === PID LOCK FILE ===
# Prevent duplicate start.py instances from running
LOCK_FILE = Path(__file__).parent / ".start.pid"
def check_and_create_lock():
"""Check for existing start.py instance and create lock file."""
current_pid = os.getpid()
if LOCK_FILE.exists():
try:
old_pid = int(LOCK_FILE.read_text().strip())
# Check if old process is still running
if sys.platform == "win32":
result = subprocess.run(
["tasklist", "/FI", f"PID eq {old_pid}"],
capture_output=True,
text=True,
)
if str(old_pid) in result.stdout and "python" in result.stdout.lower():
print(
f"\033[91mERROR: start.py is already running (PID {old_pid})\033[0m"
)
print(f"\033[93mKill it first: taskkill /F /PID {old_pid}\033[0m")
sys.exit(1)
else:
# Unix: check if process exists
try:
os.kill(old_pid, 0)
print(
f"\033[91mERROR: start.py is already running (PID {old_pid})\033[0m"
)
print(f"\033[93mKill it first: kill {old_pid}\033[0m")
sys.exit(1)
except OSError:
pass # Process doesn't exist, lock is stale
except (ValueError, FileNotFoundError):
pass # Invalid or missing lock file, proceed
# Create/update lock file with current PID
LOCK_FILE.write_text(str(current_pid))
def remove_lock():
"""Remove lock file on exit."""
try:
if LOCK_FILE.exists():
LOCK_FILE.unlink()
except Exception:
pass
# ANSI color codes
class Colors:
RESET = "\033[0m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
GRAY = "\033[90m"
WHITE = "\033[97m"
BOLD = "\033[1m"
def supports_color() -> bool:
"""Check if the terminal supports color output."""
if os.environ.get("NO_COLOR"):
return False
if os.environ.get("FORCE_COLOR"):
return True
if platform.system() == "Windows":
# Enable ANSI on Windows
os.system("")
return True
return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
USE_COLOR = supports_color()
def color(text: str, color_code: str) -> str:
"""Apply color to text if supported."""
if USE_COLOR:
return f"{color_code}{text}{Colors.RESET}"
return text
def log(
prefix: str,
message: str,
prefix_color: str = Colors.WHITE,
msg_color: str = Colors.GRAY,
) -> None:
"""Print a prefixed log message."""
print(f"{color(f'[{prefix}]', prefix_color)} {color(message, msg_color)}")
def log_header(title: str) -> None:
"""Print a section header."""
print()
print(color("=" * 50, Colors.CYAN))
print(color(f" {title}", Colors.CYAN))
print(color("=" * 50, Colors.CYAN))
print()
def print_banner() -> None:
"""Print the Director's Console banner."""
banner = r"""
____ _ _ _
| _ \(_)_ __ ___ ___| |_ ___ _ __( )___
| | | | | '__/ _ \/ __| __/ _ \| '__|// __|
| |_| | | | | __/ (__| || (_) | | \__ \
|____/|_|_| \___|\___|\_/\___/|_| |___/
____ _
/ ___|___ _ __ ___ ___ | | ___
| | / _ \| '_ \/ __|/ _ \| |/ _ \
| |__| (_) | | | \__ \ (_) | | __/
\____\___/|_| |_|___/\___/|_|\___|
"""
for i, line in enumerate(banner.strip().split("\n")):
if i < 5:
print(color(line, Colors.MAGENTA))
else:
print(color(line, Colors.CYAN))
print()
print(color(" AI VFX Production Pipeline - Project Eliot", Colors.GRAY))
print()
@dataclass
class EnvironmentConfig:
"""Configuration for a Python environment."""
name: str
display_name: str
working_dir: Path
venv_path: Path
requirements_file: Path
required_imports: list[str] = field(default_factory=list)
prefix_color: str = Colors.CYAN
@dataclass
class ServiceConfig:
"""Configuration for a service."""
name: str
prefix: str
port: int
working_dir: Path
venv_path: Path
command: list[str]
health_endpoint: str
prefix_color: str = Colors.CYAN
class EnvironmentManager:
"""Manages Python virtual environments and dependencies."""
def __init__(self, script_dir: Path):
self.script_dir = script_dir
self.environments: list[EnvironmentConfig] = []
self.uv_path = shutil.which("uv") # Check if uv is available
self._setup_environments()
def _setup_environments(self) -> None:
"""Define all required environments."""
# Orchestrator environment
orch_dir = self.script_dir / "Orchestrator"
self.environments.append(
EnvironmentConfig(
name="orchestrator",
display_name="Orchestrator",
working_dir=orch_dir,
venv_path=orch_dir / ".venv",
requirements_file=orch_dir / "requirements.txt",
required_imports=[
"fastapi",
"uvicorn",
"pydantic",
"httpx",
"loguru",
"PIL",
],
prefix_color=Colors.CYAN,
)
)
# CPE Backend environment
cpe_dir = self.script_dir / "CinemaPromptEngineering"
self.environments.append(
EnvironmentConfig(
name="cpe",
display_name="CPE Backend",
working_dir=cpe_dir,
venv_path=cpe_dir / "venv",
requirements_file=cpe_dir / "requirements.txt",
required_imports=[
"fastapi",
"uvicorn",
"pydantic",
"httpx",
"loguru",
"PIL",
"cryptography",
],
prefix_color=Colors.BLUE,
)
)
def get_python_exe(self, venv_path: Path) -> Path:
"""Get the Python executable path for a venv."""
if platform.system() == "Windows":
return venv_path / "Scripts" / "python.exe"
return venv_path / "bin" / "python"
def is_uv_venv(self, venv_path: Path) -> bool:
"""Check if a venv was created by uv (lacks pip)."""
python_exe = self.get_python_exe(venv_path)
if not python_exe.exists():
return False
# Check if pip module exists
try:
result = subprocess.run(
[str(python_exe), "-c", "import pip"], capture_output=True, timeout=10
)
return result.returncode != 0 # If pip import fails, it's a uv venv
except:
return True # Assume uv venv if we can't check
def venv_exists(self, env: EnvironmentConfig) -> bool:
"""Check if a virtual environment exists."""
python_exe = self.get_python_exe(env.venv_path)
return python_exe.exists()
def create_venv(self, env: EnvironmentConfig) -> bool:
"""Create a virtual environment."""
log(
env.name.upper(),
f"Creating virtual environment at {env.venv_path}...",
env.prefix_color,
)
try:
# Use system Python to create venv
result = subprocess.run(
[sys.executable, "-m", "venv", str(env.venv_path)],
capture_output=True,
text=True,
timeout=120,
)
if result.returncode != 0:
log(
env.name.upper(),
f"Failed to create venv: {result.stderr}",
Colors.RED,
)
return False
log(env.name.upper(), "Virtual environment created", Colors.GREEN)
return True
except Exception as e:
log(env.name.upper(), f"Error creating venv: {e}", Colors.RED)
return False
def install_requirements(self, env: EnvironmentConfig) -> bool:
"""Install requirements from requirements.txt."""
if not env.requirements_file.exists():
log(
env.name.upper(),
f"Requirements file not found: {env.requirements_file}",
Colors.YELLOW,
)
return True # Not an error, just no requirements
python_exe = self.get_python_exe(env.venv_path)
use_uv = self.uv_path and self.is_uv_venv(env.venv_path)
log(
env.name.upper(),
"Installing dependencies from requirements.txt...",
env.prefix_color,
)
try:
if use_uv:
# Use uv pip for uv-managed venvs
log(
env.name.upper(),
"Using uv pip (uv-managed venv detected)",
Colors.GRAY,
)
result = subprocess.run(
[
self.uv_path,
"pip",
"install",
"-r",
str(env.requirements_file),
"--python",
str(python_exe),
],
capture_output=True,
text=True,
timeout=600,
)
else:
# Standard pip
# Upgrade pip first
subprocess.run(
[str(python_exe), "-m", "pip", "install", "--upgrade", "pip"],
capture_output=True,
timeout=120,
)
# Install requirements
result = subprocess.run(
[
str(python_exe),
"-m",
"pip",
"install",
"-r",
str(env.requirements_file),
],
capture_output=True,
text=True,
timeout=600,
)
if result.returncode != 0:
log(env.name.upper(), f"Failed to install requirements:", Colors.RED)
# Show last few lines of error
error_lines = (
(result.stderr or result.stdout or "").strip().split("\n")[-5:]
)
for line in error_lines:
if line.strip():
log(env.name.upper(), f" {line}", Colors.RED)
return False
log(env.name.upper(), "Dependencies installed successfully", Colors.GREEN)
return True
except subprocess.TimeoutExpired:
log(env.name.upper(), "Installation timed out", Colors.RED)
return False
except Exception as e:
log(env.name.upper(), f"Error installing requirements: {e}", Colors.RED)
return False
def verify_imports(self, env: EnvironmentConfig) -> tuple[bool, list[str]]:
"""Verify that required imports work. Returns (success, failed_imports)."""
python_exe = self.get_python_exe(env.venv_path)
failed_imports = []
for module in env.required_imports:
try:
result = subprocess.run(
[str(python_exe), "-c", f"import {module}"],
capture_output=True,
text=True,
timeout=10,
)
if result.returncode != 0:
failed_imports.append(module)
except Exception:
failed_imports.append(module)
return len(failed_imports) == 0, failed_imports
def install_missing_packages(
self, env: EnvironmentConfig, packages: list[str]
) -> bool:
"""Install specific missing packages."""
python_exe = self.get_python_exe(env.venv_path)
use_uv = self.uv_path and self.is_uv_venv(env.venv_path)
# Map import names to package names
package_map = {
"PIL": "Pillow",
"cv2": "opencv-python",
"yaml": "PyYAML",
}
packages_to_install = [package_map.get(p, p) for p in packages]
log(
env.name.upper(),
f"Installing missing packages: {', '.join(packages_to_install)}",
env.prefix_color,
)
try:
if use_uv:
# Use uv pip for uv-managed venvs
result = subprocess.run(
[self.uv_path, "pip", "install", "--python", str(python_exe)]
+ packages_to_install,
capture_output=True,
text=True,
timeout=300,
)
else:
# Use python -m pip for standard venvs
result = subprocess.run(
[str(python_exe), "-m", "pip", "install"] + packages_to_install,
capture_output=True,
text=True,
timeout=300,
)
if result.returncode != 0:
error_msg = result.stderr or result.stdout or "Unknown error"
log(
env.name.upper(),
f"Failed to install packages: {error_msg}",
Colors.RED,
)
return False
log(env.name.upper(), "Packages installed successfully", Colors.GREEN)
return True
except Exception as e:
log(env.name.upper(), f"Error installing packages: {e}", Colors.RED)
return False
def setup_environment(
self, env: EnvironmentConfig, force_reinstall: bool = False
) -> bool:
"""Set up a complete environment (create venv, install deps, verify)."""
log_header(f"Setting up {env.display_name}")
# Check if venv exists
if not self.venv_exists(env):
log(env.name.upper(), "Virtual environment not found", Colors.YELLOW)
if not self.create_venv(env):
return False
if not self.install_requirements(env):
return False
elif force_reinstall:
log(env.name.upper(), "Force reinstalling requirements...", Colors.YELLOW)
if not self.install_requirements(env):
return False
else:
log(env.name.upper(), "Virtual environment exists", Colors.GREEN)
# Verify imports
log(env.name.upper(), "Verifying dependencies...", env.prefix_color)
success, failed = self.verify_imports(env)
if not success:
log(
env.name.upper(), f"Missing imports: {', '.join(failed)}", Colors.YELLOW
)
# Try to install missing packages
if not self.install_missing_packages(env, failed):
return False
# Verify again
success, failed = self.verify_imports(env)
if not success:
log(
env.name.upper(),
f"Still missing after install: {', '.join(failed)}",
Colors.RED,
)
log(
env.name.upper(),
"Try: --setup --force to reinstall all dependencies",
Colors.YELLOW,
)
return False
log(env.name.upper(), "All dependencies verified", Colors.GREEN)
return True
def verify_environment(self, env: EnvironmentConfig, auto_fix: bool = True) -> bool:
"""Quick verification of an environment, optionally auto-fixing issues."""
if not self.venv_exists(env):
log(env.name.upper(), "Virtual environment not found", Colors.RED)
if auto_fix:
return self.setup_environment(env)
return False
# Verify imports
success, failed = self.verify_imports(env)
if not success:
log(env.name.upper(), f"Missing: {', '.join(failed)}", Colors.YELLOW)
if auto_fix:
if self.install_missing_packages(env, failed):
success, failed = self.verify_imports(env)
if success:
log(
env.name.upper(), "Fixed missing dependencies", Colors.GREEN
)
return True
log(env.name.upper(), "Environment has missing dependencies", Colors.RED)
return False
log(env.name.upper(), "Environment OK", Colors.GREEN)
return True
def setup_all(self, force_reinstall: bool = False) -> bool:
"""Set up all environments."""
log_header("Environment Setup")
all_success = True
for env in self.environments:
if not self.setup_environment(env, force_reinstall):
all_success = False
return all_success
def verify_all(self, auto_fix: bool = True) -> bool:
"""Verify all environments, optionally auto-fixing issues."""
log_header("Verifying Environments")
all_success = True
for env in self.environments:
if not self.verify_environment(env, auto_fix):
all_success = False
return all_success
class ProcessManager:
"""Manages subprocess lifecycle with proper cleanup."""
def __init__(self):
self.processes: dict[str, subprocess.Popen] = {}
self.is_shutting_down = False
self._register_signal_handlers()
atexit.register(self.cleanup_all)
def _register_signal_handlers(self) -> None:
"""Register signal handlers for graceful shutdown."""
# Handle Ctrl+C
signal.signal(signal.SIGINT, self._signal_handler)
# Handle termination
signal.signal(signal.SIGTERM, self._signal_handler)
# Windows-specific: Handle console close events
if platform.system() == "Windows":
try:
import win32api
import win32con
win32api.SetConsoleCtrlHandler(self._windows_ctrl_handler, True)
except ImportError:
# pywin32 not installed, use basic handling
signal.signal(signal.SIGBREAK, self._signal_handler)
def _signal_handler(self, signum: int, frame) -> None:
"""Handle termination signals."""
if not self.is_shutting_down:
print()
log(
"SHUTDOWN",
"Received termination signal, stopping services...",
Colors.YELLOW,
)
self.cleanup_all()
sys.exit(0)
def _windows_ctrl_handler(self, ctrl_type: int) -> bool:
"""Handle Windows console control events."""
# CTRL_C_EVENT = 0, CTRL_BREAK_EVENT = 1, CTRL_CLOSE_EVENT = 2
# CTRL_LOGOFF_EVENT = 5, CTRL_SHUTDOWN_EVENT = 6
if ctrl_type in (0, 1, 2, 5, 6):
self.cleanup_all()
return True
return False
def start_process(self, config: ServiceConfig) -> Optional[subprocess.Popen]:
"""Start a service process."""
try:
# Determine the Python executable
if platform.system() == "Windows":
python_exe = config.venv_path / "Scripts" / "python.exe"
else:
python_exe = config.venv_path / "bin" / "python"
if not python_exe.exists():
log(config.prefix, f"Python not found at {python_exe}", Colors.RED)
return None
# Build the full command
full_command = [str(python_exe)] + config.command
# Set up environment
env = os.environ.copy()
env["PYTHONPATH"] = str(config.working_dir)
env["PYTHONUNBUFFERED"] = "1"
# Start the process
# On Windows, CREATE_NO_WINDOW + CREATE_NEW_PROCESS_GROUP gives isolation without visible windows
kwargs = {
"cwd": config.working_dir,
"env": env,
"bufsize": 1,
"universal_newlines": True,
}
if platform.system() == "Windows":
# CREATE_NO_WINDOW (0x09800000) runs process without a console window
# CREATE_NEW_PROCESS_GROUP (0x200) for signal isolation
kwargs["creationflags"] = (
subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
)
else:
kwargs["start_new_session"] = True
kwargs["stdout"] = subprocess.PIPE
kwargs["stderr"] = subprocess.STDOUT
process = subprocess.Popen(full_command, **kwargs)
self.processes[config.name] = process
# Debug: Log the exact process that was spawned
log(
config.prefix,
f"Spawned PID {process.pid}: {' '.join(full_command[:4])}...",
Colors.CYAN,
)
return process
except Exception as e:
log(config.prefix, f"Failed to start: {e}", Colors.RED)
return None
def stop_process(self, name: str, timeout: int = 5) -> None:
"""Stop a specific process gracefully."""
if name not in self.processes:
return
process = self.processes[name]
if process.poll() is not None:
# Already terminated
del self.processes[name]
return
log("CLEANUP", f"Stopping {name}...", Colors.YELLOW)
try:
if platform.system() == "Windows":
# On Windows, use taskkill for reliable termination
# First try graceful termination
subprocess.run(
["taskkill", "/PID", str(process.pid), "/T"],
capture_output=True,
timeout=2,
)
time.sleep(0.5)
# If still running, force kill
if process.poll() is None:
subprocess.run(
["taskkill", "/F", "/PID", str(process.pid), "/T"],
capture_output=True,
timeout=2,
)
else:
# Unix: send SIGTERM first
process.terminate()
try:
process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
# Force kill if graceful shutdown fails
process.kill()
process.wait(timeout=2)
except Exception as e:
log("CLEANUP", f"Error stopping {name}: {e}", Colors.YELLOW)
try:
process.kill()
except:
pass
finally:
if name in self.processes:
del self.processes[name]
def cleanup_all(self) -> None:
"""Stop all managed processes."""
if self.is_shutting_down:
return
self.is_shutting_down = True
log("SHUTDOWN", "Stopping all services...", Colors.YELLOW)
# Stop in reverse order (frontend, backend, orchestrator)
names = list(self.processes.keys())[::-1]
for name in names:
self.stop_process(name)
# Windows: extra cleanup for orphaned processes
if platform.system() == "Windows":
self._windows_cleanup_orphans()
log("SHUTDOWN", "All services stopped", Colors.GREEN)
def _windows_cleanup_orphans(self) -> None:
"""Clean up any orphaned Python processes on Windows."""
try:
# Find any uvicorn processes that might be orphaned
result = subprocess.run(
[
"wmic",
"process",
"where",
"commandline like '%uvicorn%'",
"get",
"processid",
],
capture_output=True,
text=True,
timeout=5,
)
for line in result.stdout.strip().split("\n")[1:]:
pid = line.strip()
if pid and pid.isdigit():
try:
subprocess.run(
["taskkill", "/F", "/PID", pid],
capture_output=True,
timeout=2,
)
except:
pass
except:
pass
def is_port_in_use(port: int) -> bool:
"""Check if a port is currently in use."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("localhost", port)) == 0
def kill_orphaned_processes() -> None:
"""Kill any orphaned DirectorsConsole processes before starting fresh."""
if platform.system() != "Windows":
return
if not shutil.which("wmic"):
log("CLEANUP", "Skipping orphan cleanup (wmic not available)", Colors.YELLOW)
return
log("CLEANUP", "Checking for orphaned processes...", Colors.YELLOW)
try:
# Find all python processes with DirectorsConsole in the command line
result = subprocess.run(
[
"wmic",
"process",
"where",
"commandline like '%DirectorsConsole%'",
"get",
"processid,commandline",
],
capture_output=True,
text=True,
timeout=10,
)
current_pid = os.getpid()
killed = 0
# Get parent PID to avoid killing our parent process
parent_pid = None
try:
parent_result = subprocess.run(
[
"wmic",
"process",
"where",
f"processid={current_pid}",
"get",
"parentprocessid",
],
capture_output=True,
text=True,
timeout=5,
)
for pline in parent_result.stdout.strip().split("\n")[1:]:
pline = pline.strip()
if pline.isdigit():
parent_pid = int(pline)
break
except:
pass
log(
"CLEANUP",
f"Current PID: {current_pid}, Parent PID: {parent_pid}",
Colors.GRAY,
)
for line in result.stdout.strip().split("\n")[1:]:
line = line.strip()
if not line:
continue
# Extract PID (last number in the line)
parts = line.split()
if not parts:
continue
pid = parts[-1]
if not pid.isdigit():
continue
pid_int = int(pid)
# Don't kill ourselves or our parent
if pid_int == current_pid:
log("CLEANUP", f"Skipping self (PID {pid_int})", Colors.GRAY)
continue
if parent_pid and pid_int == parent_pid:
log("CLEANUP", f"Skipping parent (PID {pid_int})", Colors.GRAY)
continue
# Kill orphaned uvicorn or start.py processes
if "uvicorn" in line or "start.py" in line:
log("CLEANUP", f"Killing orphan PID {pid_int}", Colors.YELLOW)
try:
subprocess.run(
["taskkill", "/F", "/PID", pid], capture_output=True, timeout=5
)
killed += 1
except:
pass
if killed > 0:
log("CLEANUP", f"Killed {killed} orphaned process(es)", Colors.GREEN)
# Wait for sockets to be released
time.sleep(2)
else:
log("CLEANUP", "No orphaned processes found", Colors.GREEN)
except Exception as e:
log("CLEANUP", f"Error checking for orphaned processes: {e}", Colors.YELLOW)
def kill_process_on_port(port: int) -> bool:
"""Kill any process using the specified port."""
if platform.system() == "Windows":
try:
# Find process using the port
result = subprocess.run(
["netstat", "-ano"], capture_output=True, text=True, timeout=10
)
pids_killed = set()
for line in result.stdout.split("\n"):
if f":{port}" in line and "LISTEN" in line:
parts = line.split()
if parts:
pid = parts[-1]
if pid.isdigit() and pid != "0" and pid not in pids_killed:
log(
"CLEANUP",
f"Killing process {pid} on port {port}",
Colors.YELLOW,
)
subprocess.run(
["taskkill", "/F", "/PID", pid],
capture_output=True,
timeout=5,
)
pids_killed.add(pid)
if pids_killed:
# Wait for sockets to be released
time.sleep(2)
return True
except Exception as e:
log("CLEANUP", f"Error cleaning port {port}: {e}", Colors.YELLOW)
else:
# Unix: use lsof and kill
try:
result = subprocess.run(
["lsof", "-ti", f":{port}"], capture_output=True, text=True, timeout=5
)
pids = result.stdout.strip().split("\n")
for pid in pids:
if pid.isdigit():
log(
"CLEANUP",
f"Killing process {pid} on port {port}",
Colors.YELLOW,
)
subprocess.run(["kill", "-9", pid], capture_output=True, timeout=2)
if pids and pids[0]:
time.sleep(1)
return True
except Exception as e:
pass
return False
def wait_for_health(url: str, timeout: int = 30, prefix: str = "WAIT") -> bool:
"""Wait for a health endpoint to respond."""
import urllib.request
import urllib.error
start_time = time.time()
dots_printed = 0
while time.time() - start_time < timeout:
try:
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req, timeout=2) as response:
if response.status == 200:
print() # Newline after dots
return True
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
pass
# Print progress dot
print(".", end="", flush=True)
dots_printed += 1
time.sleep(1)
if dots_printed > 0:
print() # Newline after dots
return False
def stream_output(
process: subprocess.Popen,