Skip to content

Commit d83090d

Browse files
authored
Merge pull request #261 from HPC-SimTools/dvm_logging
DVM hardening and logging
2 parents 1424d01 + 04ca16a commit d83090d

4 files changed

Lines changed: 95 additions & 16 deletions

File tree

‎ipsframework/resource_helper.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,13 @@ def get_resource_list(services, host, partial_nodes=False):
357357
else:
358358
accurate_nodes = True
359359
elif node_detect_str == 'slurm_env':
360-
num_nodes, ppn, mixed_nodes, list_of_nodes = get_slurm_info()
360+
try:
361+
num_nodes, ppn, mixed_nodes, list_of_nodes = get_slurm_info()
362+
except Exception:
363+
services.critical(
364+
'MISCONFIGURED NODE_DETECTION parameter: you are not running in a Slurm environment'
365+
)
366+
raise
361367
accurate_nodes = True
362368
elif node_detect_str == 'manual':
363369
num_nodes, ppn, mixed_nodes, list_of_nodes = manual_detection(services)

‎ipsframework/services.py‎

Lines changed: 49 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,21 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
162162
log.error(f'DVM URI file {dvm_uri_file} does not exist')
163163
else:
164164
log.debug(f'Using DVM URI file: {dvm_uri_file}')
165+
if worker.dvm_proc.poll() is not None:
166+
log.error(
167+
f'DVM (prte) exited with code {worker.dvm_proc.returncode}, see {worker.dvm_log_file}'
168+
)
169+
# Workers run inside an srun step, which may export its own PMIx
170+
# identity/rendezvous variables; drop them so prun can only reach
171+
# this worker's DVM. PMIX_MCA_* are tuning knobs and are kept.
172+
for key in [
173+
k for k in new_env if k.startswith('PMIX_') and not k.startswith('PMIX_MCA_')
174+
]:
175+
if key not in task_env:
176+
del new_env[key]
177+
new_env['PMIX_SERVER_URI41'] = worker.dvm_uri
178+
# read by TaskManager to pass `prun --dvm-uri file:...`
179+
new_env['IPS_DVM_URI_FILE'] = str(dvm_uri_file)
165180

166181
# PMIX_SERVER_URI41 is used by prun to figure out how to talk to the DVM
167182
# It can be defined in `task_env` or in `os.environ`, so we look in
@@ -3218,19 +3233,22 @@ def send_ensemble_instance_to_portal(ensemble_name: str, data_path: Path) -> Non
32183233

32193234

32203235
class DVMPlugin(WorkerPlugin):
3221-
def __init__(self, logger, oversubscribe=False, hwthreads=False):
3236+
def __init__(self, logger, working_dir, oversubscribe=False, hwthreads=False):
32223237
"""
32233238
Dask worker plugin to launch and manage an OpenMPI PRTE DVM on each
32243239
worker node.
32253240
32263241
:param logger: Logger object
3242+
:param working_dir: Directory for the DVM URI and log files; shared by
3243+
all workers, so file names are suffixed with host and PID.
32273244
:param oversubscribe: Whether to allow oversubscription of nodes
32283245
when launching the ensemble runs. Default is False.
32293246
:param hwthreads: Whether to use hardware threads
32303247
"""
32313248
super().__init__()
32323249

32333250
self.logger = logger
3251+
self.working_dir = Path(working_dir)
32343252
self.oversubscribe = oversubscribe
32353253
self.hwthreads = hwthreads
32363254

@@ -3254,7 +3272,11 @@ def setup(self, worker: Worker):
32543272
worker.logger = self.logger
32553273

32563274
self.logger.info('Launching DVM')
3257-
self.worker.dvm_uri_file = f'/tmp/dvm.uri.{os.getpid()}'
3275+
# The working dir is shared by all workers (possibly across nodes), so
3276+
# each worker needs a unique suffix.
3277+
suffix = f'{socket.gethostname()}.{os.getpid()}'
3278+
self.worker.dvm_uri_file = str(self.working_dir / f'dvm.uri.{suffix}')
3279+
Path(self.worker.dvm_uri_file).unlink(missing_ok=True) # never read a stale URI
32583280
# The command to launch the DVM. Note that we use `prte` instead of
32593281
# `mpirun` or `prun`. This is because we want to launch the DVM
32603282
# itself, not a specific application. The DVM will then manage the
@@ -3287,27 +3309,33 @@ def setup(self, worker: Worker):
32873309
# This environment variable is specific to OpenMPI's PRTE
32883310
os.environ['PRTE_MCA_rmaps_default_mapping_policy'] = mapping_policy
32893311

3312+
# prte output goes to a file, not a PIPE: an undrained pipe can fill
3313+
# up and block the DVM, and the file survives for post-mortems.
3314+
self.worker.dvm_log_file = self.working_dir / f'dvm.log.{suffix}'
3315+
self.worker.dvm_log = open(self.worker.dvm_log_file, 'w')
32903316
try:
32913317
self.logger.debug(f'Executing command: {command!s}')
32923318
self.worker.dvm_proc = subprocess.Popen(
3293-
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
3319+
command, stdout=self.worker.dvm_log, stderr=subprocess.STDOUT
32943320
)
32953321
except Exception as e:
32963322
print(f'Exception during setting up DVM: {e}', file=sys.stderr)
32973323
console.print(Traceback.from_exception(type(e), e, e.__traceback__))
3324+
raise
32983325

3299-
# If there was an exception, dump any stdout/stderr we have
3300-
if hasattr(self.worker.dvm_proc, 'stdout'):
3301-
print(self.worker.dvm_proc.stdout, file=sys.stderr, flush=True)
3302-
print(self.worker.dvm_proc.stderr, file=sys.stderr, flush=True)
3303-
3304-
# TODO What if there was a subprocess exception?
3305-
3306-
ready = self.worker.dvm_proc.stdout.readline()
3307-
self.logger.info(f'Ready Message : {ready}')
3326+
# Wait for prte to write its URI; fail loudly if it dies or stalls.
3327+
uri_path = Path(self.worker.dvm_uri_file)
3328+
deadline = time.time() + 30
3329+
while not (uri_path.exists() and uri_path.stat().st_size > 0):
3330+
if self.worker.dvm_proc.poll() is not None or time.time() > deadline:
3331+
raise RuntimeError(
3332+
f'DVM failed to start (exit code {self.worker.dvm_proc.poll()}), '
3333+
f'see {self.worker.dvm_log_file}:\n{self.worker.dvm_log_file.read_text()}'
3334+
)
3335+
time.sleep(0.1)
33083336

33093337
with open(self.worker.dvm_uri_file, 'r') as f:
3310-
self.worker.dvm_uri = f.readline()
3338+
self.worker.dvm_uri = f.readline().strip()
33113339
self.logger.debug(f'Read DVM URI: {self.worker.dvm_uri}')
33123340

33133341
os.environ['PMIX_SERVER_URI41'] = self.worker.dvm_uri
@@ -3333,6 +3361,7 @@ def teardown(self, worker: Worker):
33333361
# kill the process directly.
33343362
self.worker.dvm_proc.terminate()
33353363
self.worker.dvm_proc.kill()
3364+
self.worker.dvm_log.close()
33363365

33373366
self.logger.info('DVM shutdown')
33383367

@@ -3652,7 +3681,7 @@ def _make_worker_args(
36523681
# TODO better error handling than just re-raising the exception
36533682
raise
36543683

3655-
dask_nodes = 1 if dask_nodes is None else dask_nodes
3684+
dask_nodes = dask_nodes or 1 # None or 0 (nodes unspecified) -> 1
36563685
self.services.info(
36573686
f'Launching {dask_nodes} Dask workers with {dask_ppw} processes per worker'
36583687
)
@@ -3752,7 +3781,12 @@ def _make_worker_args(
37523781
# the DVM for the workers so that OpenMPI can work properly.
37533782
self.services.debug('Registering DVMPlugin')
37543783
self.dask_client.register_plugin(
3755-
DVMPlugin(logger=services.logger, oversubscribe=oversubscribe, hwthreads=hwthreads)
3784+
DVMPlugin(
3785+
logger=services.logger,
3786+
working_dir=services.get_working_dir(),
3787+
oversubscribe=oversubscribe,
3788+
hwthreads=hwthreads,
3789+
)
37563790
)
37573791
self.services.debug('Registered DVMPlugin')
37583792

‎ipsframework/task_manager.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,14 @@ def build_launch_cmd(
436436
ppn_flag = '-npernode'
437437
host_select = '-H'
438438
if mpi_binary == 'prun':
439+
# Point prun at this node's DVM explicitly instead of
440+
# letting it discover one; set by services.launch().
441+
dvm_uri_file = os.environ.get('IPS_DVM_URI_FILE')
442+
if not dvm_uri_file:
443+
raise RuntimeError(
444+
'MPIRUN_VERSION is OPENMPI-DVM but IPS_DVM_URI_FILE is not set; '
445+
'this instance was not launched from a Dask worker with a DVMPlugin'
446+
)
439447
# --display MAP-DEVEL is added to show the DVM state when
440448
# invoking this prun. We do this so that we can verify the
441449
# resources managed by DVM for this task as displayed in
@@ -444,6 +452,8 @@ def build_launch_cmd(
444452
cmd = ' '.join(
445453
[
446454
mpicmd,
455+
'--dvm-uri',
456+
f'file:{dvm_uri_file}',
447457
'--display',
448458
'ALLOCATION,MAP-DEVEL,BINDINGS',
449459
nproc_flag,

‎tests/new/test_task_manager.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,3 +1027,32 @@ def init_final_task_pool(nproc=1, tppn=0, number_of_tasks=1, tcpp=0, msg=None):
10271027
}
10281028
with pytest.raises(ResourceRequestMismatchError):
10291029
init_final_task_pool(msg=msg)
1030+
1031+
1032+
def test_build_launch_cmd_prun_uses_explicit_dvm_uri(monkeypatch):
1033+
tm = TaskManager(mock.Mock())
1034+
tm.task_launch_cmd = 'mpirun'
1035+
tm.mpicmd = '/usr/bin/prun'
1036+
tm.resource_mgr = mock.Mock(nodes=['node1'])
1037+
tm.config_mgr = mock.Mock(get_platform_parameter=lambda *a, **k: 'OPENMPI-DVM')
1038+
1039+
kwargs = {
1040+
'nproc': 1,
1041+
'binary': 'executable',
1042+
'cmd_args': (),
1043+
'working_dir': None,
1044+
'ppn': 1,
1045+
'max_ppn': 1,
1046+
'nodes': 'dummynode0',
1047+
'accurate_nodes': False,
1048+
'partial_nodes': False,
1049+
'task_id': None,
1050+
}
1051+
1052+
monkeypatch.delenv('IPS_DVM_URI_FILE', raising=False)
1053+
with pytest.raises(RuntimeError):
1054+
tm.build_launch_cmd(**kwargs)
1055+
1056+
monkeypatch.setenv('IPS_DVM_URI_FILE', '/work/dvm.uri.nid001.42')
1057+
cmd, _ = tm.build_launch_cmd(**kwargs)
1058+
assert cmd.startswith('/usr/bin/prun --dvm-uri file:/work/dvm.uri.nid001.42 ')

0 commit comments

Comments
 (0)