|
| 1 | +import os |
| 2 | +import re |
| 3 | +import subprocess |
| 4 | +import sys |
| 5 | +import time |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import psutil |
| 9 | + |
| 10 | +EXIT_TIMEOUT = 124 |
| 11 | +EXIT_INTERRUPTED = 130 |
| 12 | +PID_WAIT_SECONDS = 10.0 |
| 13 | +POLL_SECONDS = 0.5 |
| 14 | + |
| 15 | + |
| 16 | +def _find_script(study_path, name): |
| 17 | + """Return the generated `<name>` script for this platform, or None.""" |
| 18 | + if sys.platform == "win32": |
| 19 | + candidate = study_path / f"{name}.bat" |
| 20 | + if candidate.is_file(): |
| 21 | + return candidate |
| 22 | + candidate = study_path / name |
| 23 | + if candidate.is_file(): |
| 24 | + return candidate |
| 25 | + return None |
| 26 | + |
| 27 | + |
| 28 | +def _command(script): |
| 29 | + if script.suffix.lower() == ".bat": |
| 30 | + return ["cmd", "/c", str(script)] |
| 31 | + if os.access(script, os.X_OK): |
| 32 | + return [str(script)] |
| 33 | + return ["bash", str(script)] |
| 34 | + |
| 35 | + |
| 36 | +def _node_dirs(run_script): |
| 37 | + """Node folders started by a POSIX run script: lines like `(cd CZ; ... &`.""" |
| 38 | + try: |
| 39 | + text = run_script.read_text() |
| 40 | + except OSError: |
| 41 | + return [] |
| 42 | + dirs = [] |
| 43 | + for match in re.finditer(r"\(cd\s+([^;\s]+)\s*;", text): |
| 44 | + folder = match.group(1).strip("'\"") |
| 45 | + if folder not in dirs: |
| 46 | + dirs.append(folder) |
| 47 | + return dirs |
| 48 | + |
| 49 | + |
| 50 | +def _read_pid(pid_file, newer_than): |
| 51 | + """Read a pid file written by this run (older files are stale).""" |
| 52 | + try: |
| 53 | + if pid_file.stat().st_mtime < newer_than: |
| 54 | + return None |
| 55 | + return int(pid_file.read_text().strip()) |
| 56 | + except (OSError, ValueError): |
| 57 | + return None |
| 58 | + |
| 59 | + |
| 60 | +def _alive(pid): |
| 61 | + try: |
| 62 | + return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE |
| 63 | + except psutil.NoSuchProcess: |
| 64 | + return False |
| 65 | + except psutil.AccessDenied: |
| 66 | + return True |
| 67 | + |
| 68 | + |
| 69 | +def _collect_pids(study_path, node_dirs, started, console): |
| 70 | + """Wait briefly for each node's pid file, then return {folder: pid}.""" |
| 71 | + pids = {} |
| 72 | + deadline = time.monotonic() + PID_WAIT_SECONDS |
| 73 | + while True: |
| 74 | + for folder in node_dirs: |
| 75 | + if folder not in pids: |
| 76 | + pid = _read_pid(study_path / folder / "concorepid", started) |
| 77 | + if pid is not None: |
| 78 | + pids[folder] = pid |
| 79 | + if len(pids) == len(node_dirs) or time.monotonic() > deadline: |
| 80 | + break |
| 81 | + time.sleep(0.2) |
| 82 | + for folder in node_dirs: |
| 83 | + if folder not in pids: |
| 84 | + console.print( |
| 85 | + f"[yellow]Warning:[/yellow] no process id found for node '{folder}'" |
| 86 | + ) |
| 87 | + return pids |
| 88 | + |
| 89 | + |
| 90 | +def _stop_study(study_path, pids): |
| 91 | + """Stop one study: run its own stop script, then make sure its pids are gone.""" |
| 92 | + stop_script = _find_script(study_path, "stop") |
| 93 | + if stop_script is not None: |
| 94 | + subprocess.run( |
| 95 | + _command(stop_script), |
| 96 | + cwd=study_path, |
| 97 | + capture_output=True, |
| 98 | + text=True, |
| 99 | + ) |
| 100 | + for pid in pids.values(): |
| 101 | + if _alive(pid): |
| 102 | + try: |
| 103 | + psutil.Process(pid).kill() |
| 104 | + except (psutil.NoSuchProcess, psutil.AccessDenied): |
| 105 | + pass |
| 106 | + |
| 107 | + |
| 108 | +def run_study(study_dir, console, build=False, wait=False, timeout=None): |
| 109 | + """Start a built study. Returns the process exit code for the command.""" |
| 110 | + study_path = Path(study_dir).resolve() |
| 111 | + if not study_path.is_dir(): |
| 112 | + console.print(f"[red]Error:[/red] '{study_dir}' is not a directory") |
| 113 | + return 1 |
| 114 | + if timeout is not None and not wait: |
| 115 | + console.print("[red]Error:[/red] --timeout requires --wait") |
| 116 | + return 1 |
| 117 | + |
| 118 | + run_script = _find_script(study_path, "run") |
| 119 | + if run_script is None: |
| 120 | + console.print( |
| 121 | + f"[red]Error:[/red] No run script found in {study_path}\n" |
| 122 | + "[dim]Build the workflow first: concore build <workflow.graphml> " |
| 123 | + "--output <dir>[/dim]" |
| 124 | + ) |
| 125 | + return 1 |
| 126 | + |
| 127 | + if build: |
| 128 | + build_script = _find_script(study_path, "build") |
| 129 | + if build_script is None: |
| 130 | + console.print(f"[red]Error:[/red] No build script found in {study_path}") |
| 131 | + return 1 |
| 132 | + console.print("[cyan]Building study...[/cyan]") |
| 133 | + build_result = subprocess.run(_command(build_script), cwd=study_path) |
| 134 | + if build_result.returncode != 0: |
| 135 | + console.print( |
| 136 | + f"[red]Build failed[/red] (exit code {build_result.returncode})" |
| 137 | + ) |
| 138 | + return build_result.returncode |
| 139 | + |
| 140 | + node_dirs = _node_dirs(run_script) |
| 141 | + console.print(f"[cyan]Starting study:[/cyan] {study_path}") |
| 142 | + started = time.time() - 1 |
| 143 | + run_result = subprocess.run(_command(run_script), cwd=study_path) |
| 144 | + if run_result.returncode != 0: |
| 145 | + console.print( |
| 146 | + f"[red]Run script failed[/red] (exit code {run_result.returncode})" |
| 147 | + ) |
| 148 | + return run_result.returncode |
| 149 | + |
| 150 | + if not wait: |
| 151 | + console.print( |
| 152 | + "[green]✓[/green] Study started\n" |
| 153 | + "[dim]Monitor it with: concore watch <dir> " |
| 154 | + "Stop it with: concore stop[/dim]" |
| 155 | + ) |
| 156 | + return 0 |
| 157 | + |
| 158 | + if not node_dirs: |
| 159 | + console.print( |
| 160 | + "[yellow]Warning:[/yellow] --wait needs a study that records node " |
| 161 | + "process ids (a posix/macOS build). The study was started, but " |
| 162 | + "there is nothing to wait for." |
| 163 | + ) |
| 164 | + return 0 |
| 165 | + |
| 166 | + pids = _collect_pids(study_path, node_dirs, started, console) |
| 167 | + console.print("[dim]Waiting for the study to finish (Ctrl+C to stop it)...[/dim]") |
| 168 | + start = time.monotonic() |
| 169 | + try: |
| 170 | + while any(_alive(pid) for pid in pids.values()): |
| 171 | + if timeout is not None and time.monotonic() - start > timeout: |
| 172 | + console.print( |
| 173 | + f"[yellow]Timeout:[/yellow] study still running after {timeout}s, stopping it" |
| 174 | + ) |
| 175 | + _stop_study(study_path, pids) |
| 176 | + return EXIT_TIMEOUT |
| 177 | + time.sleep(POLL_SECONDS) |
| 178 | + except KeyboardInterrupt: |
| 179 | + console.print("\n[yellow]Interrupted:[/yellow] stopping the study...") |
| 180 | + _stop_study(study_path, pids) |
| 181 | + return EXIT_INTERRUPTED |
| 182 | + |
| 183 | + console.print("[green]✓[/green] Study finished") |
| 184 | + return 0 |
0 commit comments