-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrun-series.py
More file actions
713 lines (616 loc) · 26.4 KB
/
Copy pathrun-series.py
File metadata and controls
713 lines (616 loc) · 26.4 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
#!/usr/bin/env python3
"""Run ucs-detect re-run.py for each terminal YAML of the current OS, in series or parallel.
Default mode runs inside a Docker container (Arch Linux + Xvfb).
Use --use-system to run directly on the host.
"""
import argparse
import atexit
import os
import platform
import re
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import yaml
from ucs_detect.accessories import (
DiscoveredYAML,
_IS_DOCKER,
_KEY_INJECT_LOCK,
_KEY_INJECT_PRE_DELAY,
_KEY_INJECT_POST_DELAY,
_RE_PAUSE,
build_launch_args,
build_subterminal_launch_args,
check_unmatched_run_only,
discover_yamls,
docker_build,
docker_image_exists,
find_window_for_command,
get_launch_config,
inject_keys,
load_mixins,
parse_run_only,
run_kill_command,
safe_name,
should_skip,
get_project_dir,
get_data_dir,
)
PROJECT_DIR = get_project_dir()
DATA_DIR = get_data_dir()
DOCKER_IMAGE = "ucs-detect:latest"
DOCKERFILE = PROJECT_DIR / "Dockerfile"
_RE_SECONDS_ELAPSED = re.compile(r'^seconds_elapsed:\s*([\d.]+)', re.MULTILINE)
_KEEP_TEMP_ON_EXIT = False
def _sig_keep_temp(signum, frame):
"""Set flag to preserve temp directory on SIGINT/SIGTERM."""
global _KEEP_TEMP_ON_EXIT
_KEEP_TEMP_ON_EXIT = True
raise KeyboardInterrupt()
def _cleanup_temp(temp_path):
"""Remove *temp_path* unless interrupted or --keep-temp was set."""
if not _KEEP_TEMP_ON_EXIT:
shutil.rmtree(temp_path, ignore_errors=True)
def write_run_script(script_path, yaml_path, sentinel_path,
pause_exit=False, extra_args=None):
"""Write a shell script that runs re-run.py and records the exit code."""
yaml_rel = yaml_path.relative_to(PROJECT_DIR)
py_bin = shlex.quote(os.path.dirname(sys.executable))
extra = " ".join(shlex.quote(a) for a in (extra_args or []))
parts = [
"#!/bin/sh",
f"export PATH={py_bin}:$PATH",
f"cd {shlex.quote(str(PROJECT_DIR))} || exit 1",
f"{shlex.quote(sys.executable)} re-run.py {shlex.quote(str(yaml_rel))} {extra}",
"rc=$?",
f"echo $rc > {shlex.quote(str(sentinel_path))}",
'[ $rc -eq 0 ] || read -p "Failed (exit $rc), press enter..." _',
]
if pause_exit:
parts.append('read -p "Press enter to exit..." _')
script_path.write_text("\n".join(parts) + "\n")
script_path.chmod(0o755)
def _build_software_overrides(yaml_path, mixins):
"""Return list of extra CLI args for --set-software-name/version.
Uses the stem-fallback lookup in *mixins* to find the terminal's
``display_name`` and ``version_manual`` / ``version_template``.
Returns an empty list when no overrides are configured.
"""
stem = yaml_path.stem.lower()
entry = mixins.get(stem, {})
args = []
display_name = entry.get("display_name")
if display_name:
args.append("--")
args.extend(["--set-software-name", display_name])
# Resolve version: version_template first, version_manual as fallback
version_str = ""
if entry.get("version_template"):
aur_version = ""
aur_pkg = entry.get("aur_package")
if aur_pkg:
try:
result = subprocess.run(
["pacman", "-Q", aur_pkg],
capture_output=True, text=True, timeout=5,
check=False,
)
if result.returncode == 0:
parts = result.stdout.strip().split(None, 1)
if len(parts) > 1:
aur_version = parts[1]
except (subprocess.TimeoutExpired, OSError):
pass
version_str = entry["version_template"].format(
aur_version=aur_version,
release=entry.get("version_release", ""),
sw_name="", sw_version="", xt_name="", xt_version="",
xtversion_raw="",
)
if not version_str:
version_str = str(entry.get("version_manual", ""))
if version_str:
if not args:
args.append("--")
args.extend(["--set-software-version", version_str])
return args
def _launch_and_inject(yaml_path, sw_name, launch_cfg, host_launch_cfg,
temp_dir, pause_exit=False, extra_args=None):
"""Launch a terminal and inject keys. Does not wait for completion.
Returns (proc, sentinel_path, stderr_path, error_msg).
"""
safe = safe_name(sw_name)
script_path = temp_dir / f"run-{safe}.sh"
sentinel_path = temp_dir / f"exit-{safe}.rc"
stderr_path = temp_dir / f"stderr-{safe}.log"
write_run_script(script_path, yaml_path, sentinel_path,
pause_exit=pause_exit, extra_args=extra_args)
post_delay = launch_cfg.get("post_launch_delay_ms", 0)
post_keys = launch_cfg.get("post_launch_keys", [])
try:
if not launch_cfg["subterminal"]:
argv = build_launch_args(launch_cfg, script_path)
else:
argv = build_subterminal_launch_args(launch_cfg, host_launch_cfg,
script_path)
if not _IS_DOCKER and platform.system().lower() == "linux":
argv = ["systemd-run", "--user", "--scope",
"-p", "CPUQuota=200%", "--"] + argv
snapshot_pre_windows = None
if post_keys:
try:
result = subprocess.run(
["xdotool", "search", "--onlyvisible", ""],
capture_output=True, text=True, timeout=3,
check=False,
)
if result.returncode == 0:
snapshot_pre_windows = set(result.stdout.strip().split("\n"))
except (subprocess.TimeoutExpired, OSError):
pass
with open(stderr_path, "w") as stderr_file:
env = os.environ.copy()
env.pop("TERM_PROGRAM", None)
env.pop("TERM_PROGRAM_VERSION", None)
for key, value in launch_cfg.get("env", {}).items():
if value == "":
env.pop(key, None)
else:
env[key] = value
# pylint: disable=consider-using-with
proc = subprocess.Popen(
argv,
env=env,
stdout=subprocess.DEVNULL,
stderr=stderr_file,
stdin=subprocess.DEVNULL,
)
if post_keys:
with _KEY_INJECT_LOCK:
time.sleep(_KEY_INJECT_PRE_DELAY)
time.sleep(post_delay / 1000.0)
window_cfg = host_launch_cfg if launch_cfg["subterminal"] else launch_cfg
# In Docker, the host terminal is our xterm, not the host's TERM_PROGRAM
if _IS_DOCKER and launch_cfg["subterminal"]:
window_cfg = dict(window_cfg, wm_class="XTerm")
window_id = find_window_for_command(window_cfg, proc.pid, pre_windows=snapshot_pre_windows)
if window_id is not None:
script_str = str(script_path)
resolved_keys = [
key.replace("${SCRIPT}", script_str) for key in post_keys
]
if pause_exit:
resolved_keys = [
re.sub(r'\s*&&\s*(?:exit|pkill\b.*)$', '', k)
for k in resolved_keys
]
text_keys = [k for k in resolved_keys
if k != "\n" and not _RE_PAUSE.match(k)]
print(f"[{sw_name}] injecting: {''.join(text_keys)}", flush=True)
key_delay = launch_cfg.get("key_delay_ms", 30)
inject_keys(window_id, resolved_keys, key_delay_ms=key_delay)
else:
proc.kill()
error_msg = (
"key injection failed: could not find window "
f"for {window_cfg['program']} (PID {proc.pid})"
)
print(f"[{sw_name}] {error_msg}", flush=True)
return (None, sentinel_path, stderr_path, error_msg)
time.sleep(_KEY_INJECT_POST_DELAY)
return (proc, sentinel_path, stderr_path, None)
except FileNotFoundError:
return (None, None, None, f"executable not found: {launch_cfg['program']}")
except OSError as exc:
return (None, None, None, str(exc))
def _poll_sentinel(sw_name, proc, sentinel_path, stderr_path, timeout,
post_keys=None):
"""Wait for sentinel file. Returns (sw_name, exit_code, error_msg).
When *post_keys* is truthy, the deadline is not collapsed on process
exit because key-inject terminals (Hyper, Extraterm, Warp) fork/detach
and the launcher process exits immediately."""
error_msg = None
exit_code = -99
deadline = time.monotonic() + timeout
proc_dead = False
while time.monotonic() < deadline:
if sentinel_path.exists():
try:
text = sentinel_path.read_text().strip()
exit_code = int(text)
except (ValueError, OSError):
exit_code = -2
break
if not post_keys and not proc_dead and proc.poll() is not None:
proc_dead = True
deadline = min(deadline, time.monotonic() + 30)
time.sleep(0.5)
if exit_code == -99:
if proc.poll() is not None:
exit_code = -3
error_msg = (
f"process exited with code {proc.returncode} "
f"but no sentinel file was written"
)
else:
exit_code = -1
error_msg = f"timeout after {timeout}s"
try:
proc.kill()
except OSError:
pass
if error_msg and stderr_path.exists():
try:
stderr_text = stderr_path.read_text().strip()
if stderr_text:
error_msg += f"\nstderr: {stderr_text}"
except OSError:
pass
return (sw_name, exit_code, error_msg)
def _docker_self_run(argv):
"""Re-execute run-series.py inside the Docker container."""
docker_args = [
"docker", "run", "--rm",
"-v", f"{PROJECT_DIR}:/app",
"-e", "DISPLAY=:99",
DOCKER_IMAGE,
"python", "run-series.py",
]
docker_args.extend(argv)
sys.exit(subprocess.call(docker_args))
def _embed_profile_in_yaml(yaml_path, sw_name, session):
"""Append resource_profile data to the terminal's YAML file."""
try:
with open(yaml_path) as f:
data = yaml.safe_load(f)
except (OSError, yaml.YAMLError):
return
if data is None:
return
data["resource_profile"] = session.to_dict()
from ucs_detect.profiler import hardware_info
from ucs_detect.accessories import _atomic_yaml_dump
data["resource_profile"]["hardware"] = hardware_info()
try:
_atomic_yaml_dump(data, yaml_path, default_flow_style=False,
allow_unicode=True)
except OSError:
pass
def _docker_per_terminal_run(args):
"""Run each terminal in its own Docker container, with --cpus=2 each."""
system_name = platform.system()
all_terminals = list(discover_yamls(system_name))
if not all_terminals:
print(f"No terminal YAML files found for {system_name}", file=sys.stderr)
sys.exit(0)
mixins = load_mixins()
run_only = parse_run_only(args.run_only)
matched_run_only = set()
jobs = []
for d in all_terminals:
if d.error_msg:
continue
launch_cfg, _ = get_launch_config(d.software_name, mixins)
if run_only:
name_lower = d.software_name.lower()
prog_lower = launch_cfg.get("program", "").lower()
if name_lower not in run_only and prog_lower not in run_only:
continue
for candidate in (name_lower, prog_lower):
if candidate in run_only:
matched_run_only.add(candidate)
if not run_only and should_skip(launch_cfg, is_docker=True):
continue
if launch_cfg.get("subterminal") and not launch_cfg.get("program"):
continue
jobs.append((d.software_name, d.seconds_elapsed, launch_cfg.get("timeout")))
jobs.sort(key=lambda j: j[1], reverse=True)
if run_only:
check_unmatched_run_only(run_only, matched_run_only)
n_cpus = os.cpu_count() or 2
parallel = max(1, min((n_cpus - 2) // 2, 16))
print(f"Per-terminal Docker: {len(jobs)} terminals, {parallel} parallel "
f"(cpus={n_cpus}, timeout={args.timeout}s)")
with ThreadPoolExecutor(max_workers=parallel) as executor:
futures = {}
for sw_name, _prev_time, term_timeout in jobs:
cmd = [
"docker", "run", "--rm", "--cpus=2",
"-e", "DISPLAY=:99",
"-v", f"{PROJECT_DIR}:/app",
DOCKER_IMAGE,
"python", "run-series.py", "--use-system",
"--continue-after-failure",
"--timeout", str(term_timeout or args.timeout),
"--run-only", sw_name,
]
future = executor.submit(subprocess.run, cmd, capture_output=True,
text=True, timeout=(term_timeout or args.timeout) + 60)
futures[future] = sw_name
time.sleep(30)
for future in as_completed(futures):
sw_name = futures[future]
try:
result = future.result()
status = "OK" if result.returncode == 0 else f"exit={result.returncode}"
print(f"[{sw_name}] {status}", flush=True)
# pylint: disable=broad-exception-caught
except Exception as exc:
print(f"[{sw_name}] EXCEPTION: {exc}", flush=True)
def main():
"""Parse CLI arguments and run ucs-detect for each terminal YAML file."""
parser = argparse.ArgumentParser(
description="Run ucs-detect re-run.py for each terminal YAML of the current OS")
parser.add_argument(
"--parallel", "-p", type=int, default=None,
help="Number of terminals to run in parallel (default: auto)")
parser.add_argument(
"--timeout", "-t", type=float, default=900,
help="Timeout per terminal in seconds (default: 900)")
parser.add_argument(
"--continue-after-failure", "-c", action="store_true",
help="Continue running remaining terminals after a failure")
parser.add_argument(
"--host-terminal", default="ghostty",
help="Terminal used to host subterminals (screen, tmux, etc.) "
"(default: ghostty)")
parser.add_argument(
"--dry-run", "-n", action="store_true",
help="Print what would be executed without actually running")
parser.add_argument(
"--keep-temp", action="store_true",
help="Keep temporary files on exit (for debugging)")
parser.add_argument(
"--run-only", type=str, default="",
help="Comma-separated list of terminal names (software_name or program) "
"to run; all others are skipped")
parser.add_argument(
"--pause-exit", action="store_true",
help="Append 'read' to run scripts so the terminal stays open on error")
parser.add_argument(
"--use-system", action="store_true",
help="Run directly on the host system instead of inside Docker")
parser.add_argument(
"--use-docker", action="store_true",
help="Launch each terminal in its own Docker container (--cpus=2)")
parser.add_argument(
"--all", action="store_true",
help="Pass --all to ucs-detect, testing all codepoints (not just contested)")
args = parser.parse_args()
if args.use_docker and not _IS_DOCKER:
if not docker_image_exists():
docker_build(DOCKERFILE, PROJECT_DIR)
_docker_per_terminal_run(args)
return
if not args.use_system and not _IS_DOCKER:
if not docker_image_exists():
docker_build(DOCKERFILE, PROJECT_DIR)
argv = sys.argv[1:]
argv = [a for a in argv if a != "--use-system"]
_docker_self_run(argv)
system_name = platform.system()
if system_name.lower() not in ("linux", "darwin"):
print(f"Error: unsupported OS '{system_name}'. Only Linux and macOS are supported.",
file=sys.stderr)
sys.exit(1)
if not shutil.which("xdotool"):
print("Warning: xdotool not found; keyboard injection will not work",
file=sys.stderr)
# default parallelism: max(2, min(n_cpus // 2 - 1, 16))
if args.parallel is None:
n_cpus = os.cpu_count() or 2
args.parallel = max(1, min(n_cpus // 3, 8))
mixins = load_mixins()
host_launch_cfg, _ = get_launch_config(args.host_terminal, mixins)
if host_launch_cfg["subterminal"]:
print(f"Error: --host-terminal '{args.host_terminal}' is a subterminal",
file=sys.stderr)
sys.exit(1)
temp_dir = Path(tempfile.mkdtemp(prefix="ucs-run-series-"))
if not args.keep_temp:
signal.signal(signal.SIGINT, _sig_keep_temp)
signal.signal(signal.SIGTERM, _sig_keep_temp)
atexit.register(_cleanup_temp, str(temp_dir))
else:
print(f"Temp directory: {temp_dir}")
all_terminals = list(discover_yamls(system_name))
if not all_terminals:
print(f"No terminal YAML files found for {system_name}", file=sys.stderr)
sys.exit(0)
run_only = parse_run_only(args.run_only)
matched_run_only = set()
jobs = []
skipped = []
for d in all_terminals:
if d.error_msg:
skipped.append((d.software_name, d.error_msg))
continue
launch_cfg, is_explicit = get_launch_config(d.software_name, mixins)
if not is_explicit:
launch_cfg, is_explicit = get_launch_config(d.path.stem, mixins)
if run_only:
name_lower = d.software_name.lower()
prog_lower = launch_cfg.get("program", "").lower()
file_lower = d.path.stem.lower()
if (name_lower not in run_only
and prog_lower not in run_only
and file_lower not in run_only):
continue
for candidate in (name_lower, prog_lower, file_lower):
if candidate in run_only:
matched_run_only.add(candidate)
if not run_only and should_skip(launch_cfg):
reason = launch_cfg.get("skip_reason") or "marked skip in mixins"
skipped.append((d.software_name, reason))
continue
if launch_cfg["subterminal"]:
if not is_explicit:
skipped.append((d.software_name, "subterminal, no launch config"))
continue
if host_launch_cfg is None:
skipped.append((d.software_name, "subterminal, no host terminal available"))
continue
jobs.append((d.path, d.software_name, launch_cfg, d.seconds_elapsed))
jobs.sort(key=lambda j: j[3], reverse=True)
if run_only:
check_unmatched_run_only(run_only, matched_run_only)
if skipped:
print(f"Skipping {len(skipped)} terminals:")
for name, reason in skipped:
print(f" [{name}] {reason}")
print()
if not jobs:
print("No launchable terminals found.", file=sys.stderr)
sys.exit(0)
if args.dry_run:
mode = "Docker" if _IS_DOCKER else "system"
print(f"Would run {len(jobs)} terminals with --parallel={args.parallel}"
f" ({mode} mode):\n")
for yaml_path, sw_name, launch_cfg, _seconds_elapsed in jobs:
safe = safe_name(sw_name)
script_path = temp_dir / f"run-{safe}.sh"
if not launch_cfg["subterminal"]:
argv = build_launch_args(launch_cfg, script_path)
else:
argv = build_subterminal_launch_args(launch_cfg, host_launch_cfg,
script_path)
print(f" {sw_name}: {shlex.join(argv)}")
return
profiler_sessions = {}
try:
from ucs_detect.profiler import ProfileSession # noqa: F811
except ImportError:
ProfileSession = None # type: ignore[assignment]
key_jobs = [j for j in jobs if j[2].get("post_launch_keys")]
direct_jobs = [j for j in jobs if not j[2].get("post_launch_keys")]
mode = "Docker" if _IS_DOCKER else "system"
print(f"Running {len(key_jobs)} key-inject + {len(direct_jobs)} direct"
f" terminals (parallel={args.parallel}, timeout={args.timeout}s, "
f"host={args.host_terminal}, mode={mode})")
print(f"Temp: {temp_dir}")
print()
results = {}
failures = []
t0 = time.monotonic()
max_workers = max(args.parallel, 1)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_map = {}
if key_jobs:
print("--- Key-injection terminals (sequential launch, parallel wait) ---")
for yaml_path, sw_name, launch_cfg, _seconds_elapsed in key_jobs:
print(f"[{sw_name}] launching ...", flush=True)
extra_args = _build_software_overrides(yaml_path, mixins)
if args.all:
extra_args = (extra_args or ['--']) + ['--all']
proc, sentinel_path, stderr_path, launch_error = _launch_and_inject(
yaml_path, sw_name, launch_cfg, host_launch_cfg,
temp_dir,
pause_exit=args.pause_exit,
extra_args=extra_args)
if launch_error:
results[sw_name] = (-4, launch_error)
print(f"[{sw_name}] FAILED: {launch_error}", flush=True)
failures.append((sw_name, -4, launch_error))
if not args.continue_after_failure:
break
continue
profile = None
if ProfileSession is not None and proc is not None:
profile = ProfileSession(sw_name, proc.pid,
program=launch_cfg["program"],
extra_programs=launch_cfg.get("profile_processes") or None)
profile.start()
term_timeout = launch_cfg.get("timeout") or args.timeout
post_keys = launch_cfg.get("post_launch_keys")
future = executor.submit(
_poll_sentinel, sw_name, proc, sentinel_path, stderr_path,
term_timeout, post_keys=post_keys)
future_map[future] = (
sw_name, proc, profile, sentinel_path, yaml_path,
launch_cfg.get("program", sw_name), launch_cfg)
if direct_jobs and not (failures and not args.continue_after_failure):
if key_jobs:
print("\n--- Direct-launch terminals (parallel) ---")
for yaml_path, sw_name, launch_cfg, _seconds_elapsed in direct_jobs:
extra_args = _build_software_overrides(yaml_path, mixins)
if args.all:
extra_args = (extra_args or ['--']) + ['--all']
proc, sentinel_path, stderr_path, launch_error = _launch_and_inject(
yaml_path, sw_name, launch_cfg, host_launch_cfg,
temp_dir,
pause_exit=args.pause_exit,
extra_args=extra_args)
if launch_error:
results[sw_name] = (-4, launch_error)
print(f"[{sw_name}] FAILED: {launch_error}", flush=True)
failures.append((sw_name, -4, launch_error))
if not args.continue_after_failure:
break
continue
profile = None
if ProfileSession is not None and proc is not None:
profile = ProfileSession(sw_name, proc.pid,
program=launch_cfg["program"],
extra_programs=launch_cfg.get("profile_processes") or None)
profile.start()
term_timeout = launch_cfg.get("timeout") or args.timeout
post_keys = launch_cfg.get("post_launch_keys")
future = executor.submit(
_poll_sentinel, sw_name, proc, sentinel_path, stderr_path,
term_timeout, post_keys=post_keys)
future_map[future] = (
sw_name, proc, profile, sentinel_path, yaml_path,
launch_cfg.get("program", sw_name), launch_cfg)
time.sleep(30)
for future in as_completed(future_map):
sw_name, proc, profile, sentinel_path, yaml_path, program, launch_cfg = future_map[future]
try:
name, exit_code, error = future.result()
# pylint: disable=broad-exception-caught
except Exception as exc:
results[sw_name] = (-99, str(exc))
print(f"[{sw_name}] EXCEPTION: {exc}", flush=True)
failures.append((sw_name, -99, str(exc)))
if profile is not None:
profile.stop()
if not args.continue_after_failure:
for f in future_map:
f.cancel()
break
continue
if profile is not None:
profile.stop()
profiler_sessions[name] = profile
_embed_profile_in_yaml(yaml_path, name, profile)
results[name] = (exit_code, error)
if error or exit_code != 0:
status = error or f"exit code {exit_code}"
print(f"[{name}] FAILED: {status}", flush=True)
failures.append((name, exit_code, error))
run_kill_command(launch_cfg)
if not args.continue_after_failure:
for f in future_map:
f.cancel()
break
else:
print(f"[{name}] OK", flush=True)
run_kill_command(launch_cfg)
# Profile graphs and resource scores are generated by
# scripts/make_results_rst.py during docs generation.
elapsed = time.monotonic() - t0
n_ok = len(results) - len(failures)
print(f"\n--- Done in {elapsed:.1f}s: {n_ok} OK, {len(failures)} failed ---")
if failures:
print("\nFailures:")
for name, exit_code, error in failures:
msg = error or f"exit code {exit_code}"
print(f" {name}: {msg}")
sys.exit(1)
if __name__ == "__main__":
main()