Skip to content

Commit 4d373b1

Browse files
authored
Merge pull request #260 from HPC-SimTools/services-launch_use-process-groups
services launch(): avoid filling the subprocess pipes and causing blocks
2 parents 5c9ebd0 + 4e8a49d commit 4d373b1

3 files changed

Lines changed: 47 additions & 29 deletions

File tree

‎examples-proposed/024-aggregated-compute-ensemble/instance_component.py‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,7 @@ def step(self, timestamp: float = 0.0, **keywords):
5353
# the `run_ensemble()` `name` argument prepended to a unique number
5454
# for each instance. E.g., ENSEMBLE_INSTANCE might be "MY_INSTANCE_23".
5555
instance_id = self.services.get_config_param('ENSEMBLE_INSTANCE')
56-
self.services.info(f'{instance_id}: Start of step of instance '
57-
f'component.')
56+
self.services.info(f'{instance_id}: Start of step of instance component.')
5857

5958
# Echo the parameters we're expecting, A, B, and C
6059
self.services.info(
@@ -64,35 +63,28 @@ def step(self, timestamp: float = 0.0, **keywords):
6463
)
6564

6665
cmd = create_cmd(
67-
instance_id, Path(self.BIN_PATH),
68-
self.alpha, self.l, self.t_final, self.nx, self.nt
66+
instance_id, Path(self.BIN_PATH), self.alpha, self.l, self.t_final, self.nx, self.nt
6967
)
7068

7169
working_dir = str(Path('.').absolute())
72-
self.services.info(f'{instance_id}: Launching executable in '
73-
f'{working_dir}')
70+
self.services.info(f'{instance_id}: Launching executable in {working_dir}')
7471
run_id = None
7572
try:
7673
cmd = ' '.join(cmd) # need one big ole string for executing tasks
77-
run_id = self.services.launch_task(nproc=1,
78-
working_dir=working_dir,
79-
binary=cmd)
74+
run_id = self.services.launch_task(nproc=1, working_dir=working_dir, binary=cmd)
8075
except Exception:
81-
self.services.critical(f'{instance_id}: Unable to launch executable '
82-
f'in {working_dir}')
76+
self.services.critical(f'{instance_id}: Unable to launch executable in {working_dir}')
8377

8478
return_value = self.services.wait_task(run_id) # block until done
8579

8680
self.services.info(
87-
f'{instance_id}: Completed MPI executable with return value: '
88-
f'{return_value}.'
81+
f'{instance_id}: Completed MPI executable with return value: {return_value}.'
8982
)
9083

9184
# Add the generated data JSON and CSV files to the portal
9285
try:
9386
self.services.add_analysis_data_files(
94-
[f'{instance_id}_solution.json', f'{instance_id}_stats.csv'],
95-
replace=True
87+
[f'{instance_id}_solution.json', f'{instance_id}_stats.csv'], replace=True
9688
)
9789
except Exception:
9890
print('did not add data files to portal, check logs')

‎ipsframework/services.py‎

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import os
1212
import queue
1313
import shutil
14+
import signal
1415
import socket
1516
import subprocess
1617
import sys
@@ -175,7 +176,7 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
175176
f'DVM environment variable PMIX_SERVER_URI41 set in os.environ to {os.environ["PMIX_SERVER_URI41"]}'
176177
)
177178

178-
timeout = float(kwargs.get('timeout', 1.0e9))
179+
timeout = float(kwargs['timeout']) if 'timeout' in kwargs else None
179180

180181
cmd = f'{executable} {" ".join(map(str, args))}'
181182

@@ -193,6 +194,7 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
193194

194195
cmd_lst = cmd.split()
195196
process = None
197+
out, err = None, None
196198
try:
197199
try:
198200
process = subprocess.Popen(
@@ -201,7 +203,7 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
201203
stderr=subprocess_stderr,
202204
cwd=working_dir_path,
203205
text=True,
204-
preexec_fn=os.setsid, # noqa: PLW1509 # TODO - FIX THIS, it is deprecated (https://github.com/python/cpython/issues/82616) (https://docs.astral.sh/ruff/rules/subprocess-popen-preexec-fn/)
206+
start_new_session=True,
205207
env=new_env,
206208
)
207209
except Exception as e:
@@ -219,7 +221,9 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
219221
raise
220222

221223
try:
222-
ret_val = process.wait(timeout)
224+
# communicate() drains the pipes while waiting; wait() deadlocks once a PIPE fills
225+
out, err = process.communicate(timeout=timeout)
226+
ret_val = process.returncode
223227
finish_time = time.time()
224228
worker.log_event(
225229
'ips',
@@ -245,7 +249,9 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
245249
'comment': f'task_name = {task_name}, timed-out after {timeout}s',
246250
},
247251
)
248-
process.kill()
252+
# child is a session leader (setsid); kill the whole group so no grandchild keeps the pipe open
253+
os.killpg(process.pid, signal.SIGKILL)
254+
out, err = process.communicate()
249255
log.error(f'Task {task_name} with command {cmd} timed out after {timeout}s')
250256
ret_val = -1
251257
except Exception as e:
@@ -260,10 +266,10 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
260266
)
261267
log.error(f'Task {task_name} with command {cmd} failed with {e!s}')
262268
finally:
263-
if 'logfile' not in kwargs:
264-
print(process.stdout.read() if process and process.stdout else '')
265-
if 'errfile' not in kwargs:
266-
print(process.stderr.read() if process and process.stderr else '', file=sys.stderr)
269+
if out:
270+
print(out)
271+
if err:
272+
print(err, file=sys.stderr)
267273

268274
if close_stdout:
269275
subprocess_stdout.close()
@@ -3257,10 +3263,11 @@ def setup(self, worker: Worker):
32573263
# 253-dvm-daemons-should-be-in-scheduler-plugin and just needs
32583264
# vetting.
32593265
command = [
3260-
'prte',
3261-
'--host', 'localhost',
3262-
'--report-uri',
3263-
self.worker.dvm_uri_file,
3266+
'prte',
3267+
'--host',
3268+
'localhost',
3269+
'--report-uri',
3270+
self.worker.dvm_uri_file,
32643271
]
32653272

32663273
mapping_policy = 'core' # by default bind to cores
@@ -3642,8 +3649,9 @@ def _make_worker_args(
36423649
raise
36433650

36443651
dask_nodes = 1 if dask_nodes is None else dask_nodes
3645-
self.services.info(f'Launching {dask_nodes} Dask workers with '
3646-
f'{dask_ppw} processes per worker')
3652+
self.services.info(
3653+
f'Launching {dask_nodes} Dask workers with {dask_ppw} processes per worker'
3654+
)
36473655
# if services.get_config_param('MPIRUN') == 'eval':
36483656
# # TODO Why?
36493657
# Commenting this out for now since it seems to be a hack that is no

‎tests/new/test_run_ensemble.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,3 +223,21 @@ def get_worker():
223223
'stdout-line\n',
224224
'stderr-line\n',
225225
]
226+
227+
228+
def test_launch_does_not_deadlock_when_output_exceeds_pipe_buffer(tmpdir, monkeypatch, capsys):
229+
script = tmpdir.join('big_output.sh')
230+
script.write('#!/bin/sh\nhead -c 1000000 /dev/zero | tr "\\0" x\n')
231+
script.chmod(448) # 700
232+
233+
monkeypatch.setattr(services_module, 'get_worker', DummyDaskWorker)
234+
235+
# without logfile/errfile, stdout is a PIPE; 1 MB overflows the ~64 KiB pipe buffer
236+
assert services_module.launch(str(script), 'task_0', str(tmpdir), timeout=30) == ('task_0', 0)
237+
assert capsys.readouterr().out.count('x') == 1000000
238+
239+
240+
def test_launch_timeout_kills_task(tmpdir, monkeypatch):
241+
monkeypatch.setattr(services_module, 'get_worker', DummyDaskWorker)
242+
243+
assert services_module.launch('sleep', 'task_0', str(tmpdir), 100, timeout=1) == ('task_0', -1)

0 commit comments

Comments
 (0)