Skip to content

Commit 16c8bd3

Browse files
authored
Merge pull request #683 from yadavchiragg/feat/cli-run-command
feat(cli): add concore run to start a built study
2 parents 72b27db + f9e770d commit 16c8bd3

5 files changed

Lines changed: 459 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ concore validate workflow.graphml
5858
# Compile your workflow
5959
concore build workflow.graphml --auto-build
6060

61+
# Start the built study
62+
concore run out --wait
63+
6164
# Monitor running processes
6265
concore status
6366

‎concore_cli/README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ concore validate workflow.graphml
2323
# Build your workflow
2424
concore build workflow.graphml
2525

26+
# Start the built study and wait for it to finish
27+
concore run out --wait
28+
2629
# Check running processes
2730
concore status
2831

@@ -103,6 +106,27 @@ concore validate workflow.graphml
103106
concore validate workflow.graphml --source ./src
104107
```
105108

109+
### `concore run <study_dir>`
110+
111+
Starts a built study (the folder `concore build` created) by running its generated `run` script, so you do not have to `cd` into it.
112+
113+
**Options:**
114+
- `--build` - Run the study's `build` script first (stops if the build fails)
115+
- `--wait` - Wait until every node has exited. `Ctrl+C` stops the study's nodes
116+
- `--timeout <seconds>` - With `--wait`, stop the study after this many seconds (exit code 124)
117+
118+
**Examples:**
119+
```bash
120+
concore run out
121+
concore run out --build --wait
122+
concore run out --wait --timeout 300
123+
```
124+
125+
**Notes:**
126+
- `--wait` needs the node process ids that POSIX and macOS builds record; for Docker and Windows builds the study is started and a warning explains there is nothing to wait for.
127+
- `--wait` reports when the nodes have exited, not whether they succeeded. Check each node's `concoreout.txt` for errors.
128+
- Exit codes: `0` success, `124` timeout, `130` interrupted, or the exit code of the failing script.
129+
106130
### `concore status`
107131

108132
Shows all currently running concore processes with details:

‎concore_cli/cli.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from .commands.validate import validate_workflow
99
from .commands.status import show_status
1010
from .commands.stop import stop_all
11+
from .commands.run import run_study
1112
from .commands.inspect import inspect_workflow
1213
from .commands.watch import watch_study
1314
from .commands.doctor import doctor_check
@@ -155,6 +156,33 @@ def status():
155156
sys.exit(1)
156157

157158

159+
@cli.command()
160+
@click.argument("study_dir", type=click.Path(exists=True))
161+
@click.option(
162+
"--build", "build_first", is_flag=True, help="Run the study's build script first"
163+
)
164+
@click.option(
165+
"--wait", is_flag=True, help="Wait until every node exits (Ctrl+C stops the study)"
166+
)
167+
@click.option(
168+
"--timeout",
169+
type=click.FloatRange(min=0, min_open=True),
170+
default=None,
171+
help="With --wait: stop the study after this many seconds",
172+
)
173+
def run(study_dir, build_first, wait, timeout):
174+
"""Start a built study (the folder created by concore build)"""
175+
try:
176+
code = run_study(
177+
study_dir, console, build=build_first, wait=wait, timeout=timeout
178+
)
179+
except Exception as e:
180+
console.print(f"[red]Error:[/red] {str(e)}")
181+
sys.exit(1)
182+
if code:
183+
sys.exit(code)
184+
185+
158186
@cli.command()
159187
@click.confirmation_option(prompt="Stop all running concore processes?")
160188
def stop():

‎concore_cli/commands/run.py‎

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
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

Comments
 (0)