multiCMD 1.58__tar.gz → 1.59__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {multicmd-1.58 → multicmd-1.59}/PKG-INFO +43 -7
- {multicmd-1.58 → multicmd-1.59}/README.md +42 -6
- {multicmd-1.58 → multicmd-1.59}/multiCMD.egg-info/PKG-INFO +43 -7
- {multicmd-1.58 → multicmd-1.59}/multiCMD.egg-info/SOURCES.txt +2 -0
- {multicmd-1.58 → multicmd-1.59}/multiCMD.py +152 -38
- {multicmd-1.58 → multicmd-1.59}/tests/test_env.py +22 -7
- multicmd-1.59/tests/test_handover.py +109 -0
- multicmd-1.59/tests/test_pass_fds.py +145 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_run_command.py +3 -0
- {multicmd-1.58 → multicmd-1.59}/LICENSE +0 -0
- {multicmd-1.58 → multicmd-1.59}/multiCMD.egg-info/dependency_links.txt +0 -0
- {multicmd-1.58 → multicmd-1.59}/multiCMD.egg-info/entry_points.txt +0 -0
- {multicmd-1.58 → multicmd-1.59}/multiCMD.egg-info/top_level.txt +0 -0
- {multicmd-1.58 → multicmd-1.59}/scripts/multiCMD +0 -0
- {multicmd-1.58 → multicmd-1.59}/setup.cfg +0 -0
- {multicmd-1.58 → multicmd-1.59}/setup.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_api.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_async_executor.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_cli.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_cli_input.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_cli_summary.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_display.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_expand_ranges.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_helpers.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_interrupts.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_packaging.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_parsing.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_ping.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_pool.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_process_groups.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_pty.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_reader.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_regressions.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_run_commands.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_sudo.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_supervision.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_task.py +0 -0
- {multicmd-1.58 → multicmd-1.59}/tests/test_windows.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: multiCMD
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.59
|
|
4
4
|
Summary: Run commands simultaneously
|
|
5
5
|
Home-page: https://github.com/yufei-pan/multiCMD
|
|
6
6
|
Author: Yufei Pan
|
|
@@ -326,6 +326,26 @@ overrides. `sudo` resets the environment by default, so with `use_sudo` they may
|
|
|
326
326
|
command. On the command line: `mcmd -e LC_ALL=C -e UNSET_ME "cmd"`; `-n` shows them as
|
|
327
327
|
`env LC_ALL=C cmd` ( `env -i ...` for a whole environment ).
|
|
328
328
|
|
|
329
|
+
### Descriptors a command inherits
|
|
330
|
+
|
|
331
|
+
```python
|
|
332
|
+
fd = os.open("out/file", os.O_WRONLY) # a file this process holds
|
|
333
|
+
multiCMD.run_command(["cp", "src/file", "/dev/fd/%d" % fd], pass_fds=(fd,)) # cp writes it through its own copy
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
`pass_fds` names descriptors the command inherits, at the same numbers, as `subprocess`'s `pass_fds`
|
|
337
|
+
( POSIX only ). It takes an int, an object with `fileno()`, or an iterable of either; the default
|
|
338
|
+
passes nothing, and every descriptor past 2 is closed in the command, as before. It is checked
|
|
339
|
+
before anything runs: a negative, `bool` or closed descriptor is a `ValueError`, and so is any
|
|
340
|
+
off POSIX. multiCMD neither closes nor duplicates them, so keep them open until the command has
|
|
341
|
+
started ( with `wait_for_return=False` or `AsyncExecutor`, until its task's `start_time` is set ).
|
|
342
|
+
The command opens its own copy by name: `/dev/fd/N` ( on Linux `/proc/self/fd/N`, a new open of the
|
|
343
|
+
file; on macOS a `dup` that shares the offset and ignores the open's flags ). With `use_sudo`, sudo
|
|
344
|
+
closes descriptors past 2 unless its policy lets the caller keep them ( `sudo -C`,
|
|
345
|
+
`closefrom_override` ); with `shell=True` the shell inherits them too. `AsyncExecutor` takes it as a
|
|
346
|
+
default a call overrides. There is no command-line form: nothing on a command line holds a
|
|
347
|
+
descriptor.
|
|
348
|
+
|
|
329
349
|
`raise_error=True` raises `multiCMD.CommandError`; its `.tasks` holds the failed `Task`
|
|
330
350
|
objects and its message lists each one with its return code and last error line.
|
|
331
351
|
`Task` also records `start_time`, `end_time` and `duration`. With `dry_run=True` nothing
|
|
@@ -432,9 +452,10 @@ stderr, unless quiet.
|
|
|
432
452
|
multiCMD never touches SIGINT's handler (`mcmd` sets its own SIGTERM / SIGHUP handlers, nothing
|
|
433
453
|
else). What your handler raises while a call waits for its commands is handled as a Ctrl-C.
|
|
434
454
|
|
|
435
|
-
A command is registered from the moment `Popen` returns it
|
|
436
|
-
|
|
437
|
-
|
|
455
|
+
A command is registered from the moment `Popen` returns it. Before Python 3.11 the exec wrapper runs
|
|
456
|
+
the command only once it is registered, so a Ctrl-C that Python raises inside `Popen` as a serial run
|
|
457
|
+
starts a command keeps that command from running at all; on 3.11+ such a Ctrl-C (a window of some
|
|
458
|
+
50-70 µs per start) can leave it running, unknown to `kill_all()`. Two Ctrl-Cs microseconds apart can leave a command running, still registered, until
|
|
438
459
|
`kill_all()` or the exit stops it. On Python 3.6-3.9, which raise a Ctrl-C at nearly any instruction,
|
|
439
460
|
even one at a few points between the steps of a run can leave its command registered but not signalled.
|
|
440
461
|
On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a lock can leave it held: one of
|
|
@@ -449,13 +470,14 @@ These and the other known limits are in [docs/limitations.md](docs/limitations.m
|
|
|
449
470
|
run_command(command, timeout=0, max_threads=1, quiet=False, dry_run=False,
|
|
450
471
|
with_stdErr=False, return_code_only=False, return_object=False,
|
|
451
472
|
wait_for_return=True, sem=None, use_sudo=..., raise_error=False,
|
|
452
|
-
prefix=False, color=None, pty=False, shell=False, env=None, extra_env=None
|
|
473
|
+
prefix=False, color=None, pty=False, shell=False, env=None, extra_env=None,
|
|
474
|
+
pass_fds=())
|
|
453
475
|
|
|
454
476
|
run_commands(commands, timeout=0, max_threads=1, quiet=False, dry_run=False,
|
|
455
477
|
with_stdErr=False, return_code_only=False, return_object=False,
|
|
456
478
|
parse=False, wait_for_return=True, sem=None, use_sudo=...,
|
|
457
479
|
raise_error=False, prefix=False, color=None, pty=False, shell=False,
|
|
458
|
-
env=None, extra_env=None)
|
|
480
|
+
env=None, extra_env=None, pass_fds=())
|
|
459
481
|
|
|
460
482
|
ping(hosts, timeout=1, max_threads=0, ...) # returns True/False reachability
|
|
461
483
|
join_threads(threads=..., timeout=None) # join fire-and-forget threads
|
|
@@ -465,7 +487,7 @@ set_sudo(use_sudo) # enable/disable sudo globally
|
|
|
465
487
|
class Task: # command, returncode, stdout, stderr, start_time, end_time, duration
|
|
466
488
|
class CommandError: # raised by raise_error=True; .tasks = the failed Tasks
|
|
467
489
|
class AsyncExecutor: # run_command(s), wait, join, stop, cleanup, get_results, get_return_codes;
|
|
468
|
-
# takes the options above, env / extra_env as defaults a call overrides
|
|
490
|
+
# takes the options above, env / extra_env / pass_fds as defaults a call overrides
|
|
469
491
|
```
|
|
470
492
|
|
|
471
493
|
The module also bundles a few terminal/formatting helpers used internally and
|
|
@@ -491,6 +513,20 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
|
|
|
491
513
|
|
|
492
514
|
`test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
|
|
493
515
|
|
|
516
|
+
## Upgrading to 1.59 from 1.58
|
|
517
|
+
|
|
518
|
+
- Nothing needs doing to upgrade.
|
|
519
|
+
- Fix, Python 3.6 to 3.10: a Ctrl-C, or what your own signal handler raises (a SIGTERM handler's `sys.exit()`),
|
|
520
|
+
inside `Popen` as a serial run starts a command no longer leaves that command running, unknown to `kill_all()`
|
|
521
|
+
and the exit hook. The exec wrapper now waits for one byte that multiCMD writes on a pipe once the command is
|
|
522
|
+
registered; an interrupted start closes the pipe instead, and the wrapper exits 125 without running anything.
|
|
523
|
+
The window was the whole fork and wait for the exec, about 2.5 ms per start of a large program on 3.6: hpcp's copy
|
|
524
|
+
workers ran 66 such commands in 200 early stops on 3.6 and 33 in 200 on 3.10, and none with 1.59. On 3.11+ the
|
|
525
|
+
window stays (about 50 µs per start; 3 in 200 in the same test), see [docs/limitations.md](docs/limitations.md).
|
|
526
|
+
- New: `pass_fds=` on `run_command`, `run_commands` and `AsyncExecutor` (a constructor default, overridden per call):
|
|
527
|
+
descriptors a command inherits, at the same numbers, as `subprocess`'s `pass_fds` (POSIX only). The default passes
|
|
528
|
+
nothing, as before. See "Descriptors a command inherits" above.
|
|
529
|
+
|
|
494
530
|
## Upgrading to 1.58 from 1.57
|
|
495
531
|
|
|
496
532
|
- The `multiCMD` command is now a script file, not an entry point, so `entry_points.txt` no longer has two names that differ only in case. All three commands still work the same way, except in the venv case below. From 1.58 on, stock pip 9 on EL7 and EL8 upgrades and uninstalls multiCMD without `configparser.DuplicateOptionError`.
|
|
@@ -300,6 +300,26 @@ overrides. `sudo` resets the environment by default, so with `use_sudo` they may
|
|
|
300
300
|
command. On the command line: `mcmd -e LC_ALL=C -e UNSET_ME "cmd"`; `-n` shows them as
|
|
301
301
|
`env LC_ALL=C cmd` ( `env -i ...` for a whole environment ).
|
|
302
302
|
|
|
303
|
+
### Descriptors a command inherits
|
|
304
|
+
|
|
305
|
+
```python
|
|
306
|
+
fd = os.open("out/file", os.O_WRONLY) # a file this process holds
|
|
307
|
+
multiCMD.run_command(["cp", "src/file", "/dev/fd/%d" % fd], pass_fds=(fd,)) # cp writes it through its own copy
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
`pass_fds` names descriptors the command inherits, at the same numbers, as `subprocess`'s `pass_fds`
|
|
311
|
+
( POSIX only ). It takes an int, an object with `fileno()`, or an iterable of either; the default
|
|
312
|
+
passes nothing, and every descriptor past 2 is closed in the command, as before. It is checked
|
|
313
|
+
before anything runs: a negative, `bool` or closed descriptor is a `ValueError`, and so is any
|
|
314
|
+
off POSIX. multiCMD neither closes nor duplicates them, so keep them open until the command has
|
|
315
|
+
started ( with `wait_for_return=False` or `AsyncExecutor`, until its task's `start_time` is set ).
|
|
316
|
+
The command opens its own copy by name: `/dev/fd/N` ( on Linux `/proc/self/fd/N`, a new open of the
|
|
317
|
+
file; on macOS a `dup` that shares the offset and ignores the open's flags ). With `use_sudo`, sudo
|
|
318
|
+
closes descriptors past 2 unless its policy lets the caller keep them ( `sudo -C`,
|
|
319
|
+
`closefrom_override` ); with `shell=True` the shell inherits them too. `AsyncExecutor` takes it as a
|
|
320
|
+
default a call overrides. There is no command-line form: nothing on a command line holds a
|
|
321
|
+
descriptor.
|
|
322
|
+
|
|
303
323
|
`raise_error=True` raises `multiCMD.CommandError`; its `.tasks` holds the failed `Task`
|
|
304
324
|
objects and its message lists each one with its return code and last error line.
|
|
305
325
|
`Task` also records `start_time`, `end_time` and `duration`. With `dry_run=True` nothing
|
|
@@ -406,9 +426,10 @@ stderr, unless quiet.
|
|
|
406
426
|
multiCMD never touches SIGINT's handler (`mcmd` sets its own SIGTERM / SIGHUP handlers, nothing
|
|
407
427
|
else). What your handler raises while a call waits for its commands is handled as a Ctrl-C.
|
|
408
428
|
|
|
409
|
-
A command is registered from the moment `Popen` returns it
|
|
410
|
-
|
|
411
|
-
|
|
429
|
+
A command is registered from the moment `Popen` returns it. Before Python 3.11 the exec wrapper runs
|
|
430
|
+
the command only once it is registered, so a Ctrl-C that Python raises inside `Popen` as a serial run
|
|
431
|
+
starts a command keeps that command from running at all; on 3.11+ such a Ctrl-C (a window of some
|
|
432
|
+
50-70 µs per start) can leave it running, unknown to `kill_all()`. Two Ctrl-Cs microseconds apart can leave a command running, still registered, until
|
|
412
433
|
`kill_all()` or the exit stops it. On Python 3.6-3.9, which raise a Ctrl-C at nearly any instruction,
|
|
413
434
|
even one at a few points between the steps of a run can leave its command registered but not signalled.
|
|
414
435
|
On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a lock can leave it held: one of
|
|
@@ -423,13 +444,14 @@ These and the other known limits are in [docs/limitations.md](docs/limitations.m
|
|
|
423
444
|
run_command(command, timeout=0, max_threads=1, quiet=False, dry_run=False,
|
|
424
445
|
with_stdErr=False, return_code_only=False, return_object=False,
|
|
425
446
|
wait_for_return=True, sem=None, use_sudo=..., raise_error=False,
|
|
426
|
-
prefix=False, color=None, pty=False, shell=False, env=None, extra_env=None
|
|
447
|
+
prefix=False, color=None, pty=False, shell=False, env=None, extra_env=None,
|
|
448
|
+
pass_fds=())
|
|
427
449
|
|
|
428
450
|
run_commands(commands, timeout=0, max_threads=1, quiet=False, dry_run=False,
|
|
429
451
|
with_stdErr=False, return_code_only=False, return_object=False,
|
|
430
452
|
parse=False, wait_for_return=True, sem=None, use_sudo=...,
|
|
431
453
|
raise_error=False, prefix=False, color=None, pty=False, shell=False,
|
|
432
|
-
env=None, extra_env=None)
|
|
454
|
+
env=None, extra_env=None, pass_fds=())
|
|
433
455
|
|
|
434
456
|
ping(hosts, timeout=1, max_threads=0, ...) # returns True/False reachability
|
|
435
457
|
join_threads(threads=..., timeout=None) # join fire-and-forget threads
|
|
@@ -439,7 +461,7 @@ set_sudo(use_sudo) # enable/disable sudo globally
|
|
|
439
461
|
class Task: # command, returncode, stdout, stderr, start_time, end_time, duration
|
|
440
462
|
class CommandError: # raised by raise_error=True; .tasks = the failed Tasks
|
|
441
463
|
class AsyncExecutor: # run_command(s), wait, join, stop, cleanup, get_results, get_return_codes;
|
|
442
|
-
# takes the options above, env / extra_env as defaults a call overrides
|
|
464
|
+
# takes the options above, env / extra_env / pass_fds as defaults a call overrides
|
|
443
465
|
```
|
|
444
466
|
|
|
445
467
|
The module also bundles a few terminal/formatting helpers used internally and
|
|
@@ -465,6 +487,20 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
|
|
|
465
487
|
|
|
466
488
|
`test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
|
|
467
489
|
|
|
490
|
+
## Upgrading to 1.59 from 1.58
|
|
491
|
+
|
|
492
|
+
- Nothing needs doing to upgrade.
|
|
493
|
+
- Fix, Python 3.6 to 3.10: a Ctrl-C, or what your own signal handler raises (a SIGTERM handler's `sys.exit()`),
|
|
494
|
+
inside `Popen` as a serial run starts a command no longer leaves that command running, unknown to `kill_all()`
|
|
495
|
+
and the exit hook. The exec wrapper now waits for one byte that multiCMD writes on a pipe once the command is
|
|
496
|
+
registered; an interrupted start closes the pipe instead, and the wrapper exits 125 without running anything.
|
|
497
|
+
The window was the whole fork and wait for the exec, about 2.5 ms per start of a large program on 3.6: hpcp's copy
|
|
498
|
+
workers ran 66 such commands in 200 early stops on 3.6 and 33 in 200 on 3.10, and none with 1.59. On 3.11+ the
|
|
499
|
+
window stays (about 50 µs per start; 3 in 200 in the same test), see [docs/limitations.md](docs/limitations.md).
|
|
500
|
+
- New: `pass_fds=` on `run_command`, `run_commands` and `AsyncExecutor` (a constructor default, overridden per call):
|
|
501
|
+
descriptors a command inherits, at the same numbers, as `subprocess`'s `pass_fds` (POSIX only). The default passes
|
|
502
|
+
nothing, as before. See "Descriptors a command inherits" above.
|
|
503
|
+
|
|
468
504
|
## Upgrading to 1.58 from 1.57
|
|
469
505
|
|
|
470
506
|
- The `multiCMD` command is now a script file, not an entry point, so `entry_points.txt` no longer has two names that differ only in case. All three commands still work the same way, except in the venv case below. From 1.58 on, stock pip 9 on EL7 and EL8 upgrades and uninstalls multiCMD without `configparser.DuplicateOptionError`.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: multiCMD
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.59
|
|
4
4
|
Summary: Run commands simultaneously
|
|
5
5
|
Home-page: https://github.com/yufei-pan/multiCMD
|
|
6
6
|
Author: Yufei Pan
|
|
@@ -326,6 +326,26 @@ overrides. `sudo` resets the environment by default, so with `use_sudo` they may
|
|
|
326
326
|
command. On the command line: `mcmd -e LC_ALL=C -e UNSET_ME "cmd"`; `-n` shows them as
|
|
327
327
|
`env LC_ALL=C cmd` ( `env -i ...` for a whole environment ).
|
|
328
328
|
|
|
329
|
+
### Descriptors a command inherits
|
|
330
|
+
|
|
331
|
+
```python
|
|
332
|
+
fd = os.open("out/file", os.O_WRONLY) # a file this process holds
|
|
333
|
+
multiCMD.run_command(["cp", "src/file", "/dev/fd/%d" % fd], pass_fds=(fd,)) # cp writes it through its own copy
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
`pass_fds` names descriptors the command inherits, at the same numbers, as `subprocess`'s `pass_fds`
|
|
337
|
+
( POSIX only ). It takes an int, an object with `fileno()`, or an iterable of either; the default
|
|
338
|
+
passes nothing, and every descriptor past 2 is closed in the command, as before. It is checked
|
|
339
|
+
before anything runs: a negative, `bool` or closed descriptor is a `ValueError`, and so is any
|
|
340
|
+
off POSIX. multiCMD neither closes nor duplicates them, so keep them open until the command has
|
|
341
|
+
started ( with `wait_for_return=False` or `AsyncExecutor`, until its task's `start_time` is set ).
|
|
342
|
+
The command opens its own copy by name: `/dev/fd/N` ( on Linux `/proc/self/fd/N`, a new open of the
|
|
343
|
+
file; on macOS a `dup` that shares the offset and ignores the open's flags ). With `use_sudo`, sudo
|
|
344
|
+
closes descriptors past 2 unless its policy lets the caller keep them ( `sudo -C`,
|
|
345
|
+
`closefrom_override` ); with `shell=True` the shell inherits them too. `AsyncExecutor` takes it as a
|
|
346
|
+
default a call overrides. There is no command-line form: nothing on a command line holds a
|
|
347
|
+
descriptor.
|
|
348
|
+
|
|
329
349
|
`raise_error=True` raises `multiCMD.CommandError`; its `.tasks` holds the failed `Task`
|
|
330
350
|
objects and its message lists each one with its return code and last error line.
|
|
331
351
|
`Task` also records `start_time`, `end_time` and `duration`. With `dry_run=True` nothing
|
|
@@ -432,9 +452,10 @@ stderr, unless quiet.
|
|
|
432
452
|
multiCMD never touches SIGINT's handler (`mcmd` sets its own SIGTERM / SIGHUP handlers, nothing
|
|
433
453
|
else). What your handler raises while a call waits for its commands is handled as a Ctrl-C.
|
|
434
454
|
|
|
435
|
-
A command is registered from the moment `Popen` returns it
|
|
436
|
-
|
|
437
|
-
|
|
455
|
+
A command is registered from the moment `Popen` returns it. Before Python 3.11 the exec wrapper runs
|
|
456
|
+
the command only once it is registered, so a Ctrl-C that Python raises inside `Popen` as a serial run
|
|
457
|
+
starts a command keeps that command from running at all; on 3.11+ such a Ctrl-C (a window of some
|
|
458
|
+
50-70 µs per start) can leave it running, unknown to `kill_all()`. Two Ctrl-Cs microseconds apart can leave a command running, still registered, until
|
|
438
459
|
`kill_all()` or the exit stops it. On Python 3.6-3.9, which raise a Ctrl-C at nearly any instruction,
|
|
439
460
|
even one at a few points between the steps of a run can leave its command registered but not signalled.
|
|
440
461
|
On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a lock can leave it held: one of
|
|
@@ -449,13 +470,14 @@ These and the other known limits are in [docs/limitations.md](docs/limitations.m
|
|
|
449
470
|
run_command(command, timeout=0, max_threads=1, quiet=False, dry_run=False,
|
|
450
471
|
with_stdErr=False, return_code_only=False, return_object=False,
|
|
451
472
|
wait_for_return=True, sem=None, use_sudo=..., raise_error=False,
|
|
452
|
-
prefix=False, color=None, pty=False, shell=False, env=None, extra_env=None
|
|
473
|
+
prefix=False, color=None, pty=False, shell=False, env=None, extra_env=None,
|
|
474
|
+
pass_fds=())
|
|
453
475
|
|
|
454
476
|
run_commands(commands, timeout=0, max_threads=1, quiet=False, dry_run=False,
|
|
455
477
|
with_stdErr=False, return_code_only=False, return_object=False,
|
|
456
478
|
parse=False, wait_for_return=True, sem=None, use_sudo=...,
|
|
457
479
|
raise_error=False, prefix=False, color=None, pty=False, shell=False,
|
|
458
|
-
env=None, extra_env=None)
|
|
480
|
+
env=None, extra_env=None, pass_fds=())
|
|
459
481
|
|
|
460
482
|
ping(hosts, timeout=1, max_threads=0, ...) # returns True/False reachability
|
|
461
483
|
join_threads(threads=..., timeout=None) # join fire-and-forget threads
|
|
@@ -465,7 +487,7 @@ set_sudo(use_sudo) # enable/disable sudo globally
|
|
|
465
487
|
class Task: # command, returncode, stdout, stderr, start_time, end_time, duration
|
|
466
488
|
class CommandError: # raised by raise_error=True; .tasks = the failed Tasks
|
|
467
489
|
class AsyncExecutor: # run_command(s), wait, join, stop, cleanup, get_results, get_return_codes;
|
|
468
|
-
# takes the options above, env / extra_env as defaults a call overrides
|
|
490
|
+
# takes the options above, env / extra_env / pass_fds as defaults a call overrides
|
|
469
491
|
```
|
|
470
492
|
|
|
471
493
|
The module also bundles a few terminal/formatting helpers used internally and
|
|
@@ -491,6 +513,20 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
|
|
|
491
513
|
|
|
492
514
|
`test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
|
|
493
515
|
|
|
516
|
+
## Upgrading to 1.59 from 1.58
|
|
517
|
+
|
|
518
|
+
- Nothing needs doing to upgrade.
|
|
519
|
+
- Fix, Python 3.6 to 3.10: a Ctrl-C, or what your own signal handler raises (a SIGTERM handler's `sys.exit()`),
|
|
520
|
+
inside `Popen` as a serial run starts a command no longer leaves that command running, unknown to `kill_all()`
|
|
521
|
+
and the exit hook. The exec wrapper now waits for one byte that multiCMD writes on a pipe once the command is
|
|
522
|
+
registered; an interrupted start closes the pipe instead, and the wrapper exits 125 without running anything.
|
|
523
|
+
The window was the whole fork and wait for the exec, about 2.5 ms per start of a large program on 3.6: hpcp's copy
|
|
524
|
+
workers ran 66 such commands in 200 early stops on 3.6 and 33 in 200 on 3.10, and none with 1.59. On 3.11+ the
|
|
525
|
+
window stays (about 50 µs per start; 3 in 200 in the same test), see [docs/limitations.md](docs/limitations.md).
|
|
526
|
+
- New: `pass_fds=` on `run_command`, `run_commands` and `AsyncExecutor` (a constructor default, overridden per call):
|
|
527
|
+
descriptors a command inherits, at the same numbers, as `subprocess`'s `pass_fds` (POSIX only). The default passes
|
|
528
|
+
nothing, as before. See "Descriptors a command inherits" above.
|
|
529
|
+
|
|
494
530
|
## Upgrading to 1.58 from 1.57
|
|
495
531
|
|
|
496
532
|
- The `multiCMD` command is now a script file, not an entry point, so `entry_points.txt` no longer has two names that differ only in case. All three commands still work the same way, except in the venv case below. From 1.58 on, stock pip 9 on EL7 and EL8 upgrades and uninstalls multiCMD without `configparser.DuplicateOptionError`.
|
|
@@ -16,10 +16,12 @@ tests/test_cli_summary.py
|
|
|
16
16
|
tests/test_display.py
|
|
17
17
|
tests/test_env.py
|
|
18
18
|
tests/test_expand_ranges.py
|
|
19
|
+
tests/test_handover.py
|
|
19
20
|
tests/test_helpers.py
|
|
20
21
|
tests/test_interrupts.py
|
|
21
22
|
tests/test_packaging.py
|
|
22
23
|
tests/test_parsing.py
|
|
24
|
+
tests/test_pass_fds.py
|
|
23
25
|
tests/test_ping.py
|
|
24
26
|
tests/test_pool.py
|
|
25
27
|
tests/test_process_groups.py
|
|
@@ -27,9 +27,9 @@ import traceback
|
|
|
27
27
|
from pprint import pformat
|
|
28
28
|
|
|
29
29
|
#%% global vars
|
|
30
|
-
version = '1.
|
|
30
|
+
version = '1.59'
|
|
31
31
|
__version__ = version
|
|
32
|
-
COMMIT_DATE = '2026-11-
|
|
32
|
+
COMMIT_DATE = '2026-11-10'
|
|
33
33
|
# fire-and-forget threads (run_commands with wait_for_return=False) that join_threads() waits on. multiCMD takes no
|
|
34
34
|
# lock for it: each update is one set operation and each snapshot one set.copy(), as for _live_procs below
|
|
35
35
|
__running_threads = set()
|
|
@@ -59,7 +59,10 @@ _HAS_PROCESS_GROUP = sys.version_info >= (3, 11)
|
|
|
59
59
|
# another thread hangs on it.
|
|
60
60
|
# Not a new session ( setsid ) either: that would hide the terminal from sudo.
|
|
61
61
|
# It runs in this process's own environment ( so it starts wherever this Python does, LD_LIBRARY_PATH and the
|
|
62
|
-
# like included ).
|
|
62
|
+
# like included ). It runs the command only once the caller has it registered: its second argument is the read end of a
|
|
63
|
+
# pipe ( passed to it alone ) on which the caller writes one byte then ( see _popen ). A caller interrupted inside Popen
|
|
64
|
+
# once it has forked never has the command, and closes the pipe: the wrapper reads its end and exits 125 without running
|
|
65
|
+
# anything. Its first argument is '-' ( the command inherits the wrapper's environment as it is ) or N:
|
|
63
66
|
# the command's own environment is then the N NAME=VALUE entries in the wrapper's variables
|
|
64
67
|
# _MULTICMD_ENV_0 .. _MULTICMD_ENV_<N-1>, handed over by exec itself ( nothing can be cut short ), and it
|
|
65
68
|
# runs with exactly those, found in their PATH like Python 3.11+'s Popen does. A missing or malformed entry
|
|
@@ -75,7 +78,11 @@ _PGROUP_EXEC = (
|
|
|
75
78
|
"\tif hasattr(_signal,n):_signal.signal(getattr(_signal,n),_signal.SIG_DFL)\n"
|
|
76
79
|
"posix.setpgid(0,0)\n"
|
|
77
80
|
"a=sys.argv\n"
|
|
78
|
-
|
|
81
|
+
# handed over or not: the byte, or the end of the pipe ( 125, as env and timeout fail on their own )
|
|
82
|
+
"h=int(a[2])\n"
|
|
83
|
+
"if not posix.read(h,1):posix._exit(125)\n"
|
|
84
|
+
"posix.close(h)\n"
|
|
85
|
+
"c=a[3]\n"
|
|
79
86
|
"v=None\n"
|
|
80
87
|
"if a[1]!='-':\n"
|
|
81
88
|
"\ttry:\n"
|
|
@@ -84,8 +91,8 @@ _PGROUP_EXEC = (
|
|
|
84
91
|
"\texcept(KeyError,ValueError):\n"
|
|
85
92
|
"\t\tsys.stderr.write('multiCMD: incomplete environment for %r\\n'%c);sys.exit(126)\n"
|
|
86
93
|
"def x(f):\n"
|
|
87
|
-
"\tif v is None:posix.execv(f,a[
|
|
88
|
-
"\tposix.execve(f,a[
|
|
94
|
+
"\tif v is None:posix.execv(f,a[3:])\n"
|
|
95
|
+
"\tposix.execve(f,a[3:],v)\n"
|
|
89
96
|
"def g(f):\n"
|
|
90
97
|
"\ttry:return posix.stat(f).st_mode&0o170000==0o100000\n"
|
|
91
98
|
"\texcept(OSError,ValueError):return False\n"
|
|
@@ -158,6 +165,8 @@ class Task:
|
|
|
158
165
|
# this command's own environment ( see _check_env ): env replaces the inherited one, extra_env is applied on top
|
|
159
166
|
self._env = None
|
|
160
167
|
self._extra_env = None
|
|
168
|
+
# the descriptors the command inherits, at the same numbers ( see _check_pass_fds ): a sorted tuple of ints
|
|
169
|
+
self._pass_fds = ()
|
|
161
170
|
# whether the main thread asked for it once the exit hook had begun ( an atexit handler's call: see _cut_by_exit )
|
|
162
171
|
self._at_exit = False
|
|
163
172
|
|
|
@@ -416,7 +425,7 @@ class _Display:
|
|
|
416
425
|
_display = _Display()
|
|
417
426
|
|
|
418
427
|
class AsyncExecutor:
|
|
419
|
-
def __init__(self, max_threads=1,semaphore=...,timeout=0,quiet=True,dry_run=False,parse=False,shell=False,prefix=False,color=None,pty=False,env=None,extra_env=None):
|
|
428
|
+
def __init__(self, max_threads=1,semaphore=...,timeout=0,quiet=True,dry_run=False,parse=False,shell=False,prefix=False,color=None,pty=False,env=None,extra_env=None,pass_fds=()):
|
|
420
429
|
'''
|
|
421
430
|
AsyncExecutor class to run commands in parallel asynchronously
|
|
422
431
|
|
|
@@ -438,6 +447,8 @@ class AsyncExecutor:
|
|
|
438
447
|
pty: Whether commands write to a pseudo-terminal ( bool, POSIX only )
|
|
439
448
|
env: The whole environment of each command, replacing the inherited one ( Mapping[str, str] | None: inherit ), as subprocess's env
|
|
440
449
|
extra_env: Variables added to the inherited environment, or overriding it ( Mapping[str, str | None] | None ); a None value removes the variable
|
|
450
|
+
pass_fds: Descriptors each command inherits, at the same numbers, as subprocess's pass_fds ( an int, an object with fileno(),
|
|
451
|
+
or an iterable of either; POSIX only ). Keep them open until the command has started ( its task's start_time is set )
|
|
441
452
|
'''
|
|
442
453
|
self.max_threads = max_threads
|
|
443
454
|
if semaphore is ...:
|
|
@@ -457,6 +468,7 @@ class AsyncExecutor:
|
|
|
457
468
|
self.env = None if env is None else env.copy()
|
|
458
469
|
# an empty one ( which _check_env reduces to None ) stays a dict to add to, like env
|
|
459
470
|
self.extra_env = None if extra_env is None else dict(extra or {})
|
|
471
|
+
self.pass_fds = _check_pass_fds(pass_fds)
|
|
460
472
|
# held while tasks, _queue and _dispatching change together
|
|
461
473
|
self._lock = threading.Lock()
|
|
462
474
|
# (task, sem, timeout, quiet, dry_run, decor, use_pty) waiting for a permit
|
|
@@ -570,7 +582,7 @@ class AsyncExecutor:
|
|
|
570
582
|
finally:
|
|
571
583
|
self._finished.append((threading.current_thread(), None))
|
|
572
584
|
|
|
573
|
-
def run_commands(self, commands, timeout=...,max_threads=...,quiet=...,dry_run=...,parse = ...,sem = ...,shell = ...,prefix = ...,color = ...,pty = ...,env = ...,extra_env = ...):
|
|
585
|
+
def run_commands(self, commands, timeout=...,max_threads=...,quiet=...,dry_run=...,parse = ...,sem = ...,shell = ...,prefix = ...,color = ...,pty = ...,env = ...,extra_env = ...,pass_fds = ...):
|
|
574
586
|
'''
|
|
575
587
|
Run multiple commands in parallel asynchronously. Returns right away, the commands are queued
|
|
576
588
|
@params:
|
|
@@ -587,6 +599,7 @@ class AsyncExecutor:
|
|
|
587
599
|
pty: Whether commands write to a pseudo-terminal to override the object default
|
|
588
600
|
env: The whole environment of the commands to override the object default ( None: inherit )
|
|
589
601
|
extra_env: Variables added to / overriding the environment, to override the object default ( None: none )
|
|
602
|
+
pass_fds: Descriptors each command inherits, to override the object default ( see __init__; kept open until each command has started )
|
|
590
603
|
@returns:
|
|
591
604
|
list: The Task Object of the commands ( list[Task] )
|
|
592
605
|
'''
|
|
@@ -614,7 +627,9 @@ class AsyncExecutor:
|
|
|
614
627
|
env = self.env
|
|
615
628
|
if extra_env is ...:
|
|
616
629
|
extra_env = self.extra_env
|
|
617
|
-
|
|
630
|
+
if pass_fds is ...:
|
|
631
|
+
pass_fds = self.pass_fds
|
|
632
|
+
taskObjects, use_sudo = _build_tasks(commands, parse=parse, shell=shell, env=env, extra_env=extra_env, pass_fds=pass_fds)
|
|
618
633
|
if not sem:
|
|
619
634
|
sem = threading.Semaphore(max_threads if max_threads >= 1 else max(len(taskObjects), 1))
|
|
620
635
|
if use_sudo and not dry_run:
|
|
@@ -655,7 +670,7 @@ class AsyncExecutor:
|
|
|
655
670
|
raise
|
|
656
671
|
return taskObjects
|
|
657
672
|
|
|
658
|
-
def run_command(self, command, timeout=...,max_threads=...,quiet=...,dry_run=...,parse = ...,sem = ...,shell = ...,prefix = ...,color = ...,pty = ...,env = ...,extra_env = ...):
|
|
673
|
+
def run_command(self, command, timeout=...,max_threads=...,quiet=...,dry_run=...,parse = ...,sem = ...,shell = ...,prefix = ...,color = ...,pty = ...,env = ...,extra_env = ...,pass_fds = ...):
|
|
659
674
|
'''
|
|
660
675
|
Run a command in parallel asynchronously
|
|
661
676
|
@params:
|
|
@@ -664,7 +679,7 @@ class AsyncExecutor:
|
|
|
664
679
|
@returns:
|
|
665
680
|
Task: The Task Object of the command
|
|
666
681
|
'''
|
|
667
|
-
return self.run_commands([command],timeout=timeout,max_threads=max_threads,quiet=quiet,dry_run=dry_run,parse=parse,sem=sem,shell=shell,prefix=prefix,color=color,pty=pty,env=env,extra_env=extra_env)[0]
|
|
682
|
+
return self.run_commands([command],timeout=timeout,max_threads=max_threads,quiet=quiet,dry_run=dry_run,parse=parse,sem=sem,shell=shell,prefix=prefix,color=color,pty=pty,env=env,extra_env=extra_env,pass_fds=pass_fds)[0]
|
|
668
683
|
|
|
669
684
|
def wait(self, timeout=None, threads = ...):
|
|
670
685
|
'''
|
|
@@ -1085,7 +1100,7 @@ def _file_named(command, dirs, start=0):
|
|
|
1085
1100
|
return index, path
|
|
1086
1101
|
return None, None
|
|
1087
1102
|
|
|
1088
|
-
def _spawn(argv, stdout, stderr, env=None, explicit=False, started=None):
|
|
1103
|
+
def _spawn(argv, stdout, stderr, env=None, explicit=False, started=None, pass_fds=()):
|
|
1089
1104
|
'''
|
|
1090
1105
|
Start a command in a process group of its own ( internal ); see _spawn_process for the arguments
|
|
1091
1106
|
|
|
@@ -1119,7 +1134,7 @@ def _spawn(argv, stdout, stderr, env=None, explicit=False, started=None):
|
|
|
1119
1134
|
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), command)
|
|
1120
1135
|
if wrapped or not bare:
|
|
1121
1136
|
try:
|
|
1122
|
-
return _spawn_process(argv, stdout, stderr, env, explicit, started=started)
|
|
1137
|
+
return _spawn_process(argv, stdout, stderr, env, explicit, started=started, pass_fds=pass_fds)
|
|
1123
1138
|
except OSError as e:
|
|
1124
1139
|
if wrapped:
|
|
1125
1140
|
if e.errno == errno.E2BIG:
|
|
@@ -1142,7 +1157,7 @@ def _spawn(argv, stdout, stderr, env=None, explicit=False, started=None):
|
|
|
1142
1157
|
index += 1
|
|
1143
1158
|
try:
|
|
1144
1159
|
# ( one that can run by now just runs, as it would have a moment ago )
|
|
1145
|
-
return _spawn_process(argv, stdout, stderr, env, explicit, executable=path, started=started)
|
|
1160
|
+
return _spawn_process(argv, stdout, stderr, env, explicit, executable=path, started=started, pass_fds=pass_fds)
|
|
1146
1161
|
except OSError as e:
|
|
1147
1162
|
if e.filename is None:
|
|
1148
1163
|
raise
|
|
@@ -1156,24 +1171,55 @@ def _spawn(argv, stdout, stderr, env=None, explicit=False, started=None):
|
|
|
1156
1171
|
raise PermissionError(failure.errno, failure.strerror, command)
|
|
1157
1172
|
raise _ExecRefused(failure.errno, failure.strerror, command)
|
|
1158
1173
|
|
|
1159
|
-
def
|
|
1174
|
+
def _handover_pipe():
|
|
1175
|
+
'''
|
|
1176
|
+
The exec wrapper's hand-over pipe ( internal; see _popen ): ( read end, write end ). The read end is never 0, 1 or 2:
|
|
1177
|
+
in one the caller has closed, Popen would put the command's stdin, stdout or stderr over it in the child
|
|
1178
|
+
'''
|
|
1179
|
+
r, w = os.pipe()
|
|
1180
|
+
low = []
|
|
1181
|
+
while r <= 2:
|
|
1182
|
+
low.append(r)
|
|
1183
|
+
r = os.dup(r)
|
|
1184
|
+
for fd in low:
|
|
1185
|
+
os.close(fd)
|
|
1186
|
+
return r, w
|
|
1187
|
+
|
|
1188
|
+
def _popen(argv, started=None, grouped=False, handover=None, **kwargs):
|
|
1160
1189
|
'''
|
|
1161
1190
|
Start a process with subprocess.Popen ( internal )
|
|
1162
1191
|
@params:
|
|
1163
1192
|
started: A list the command is appended to, as the registry holds it, the moment Popen returns, so a Ctrl-C from
|
|
1164
1193
|
there on finds it ( see _execute ). One that Python raises inside Popen, once it has forked, loses the
|
|
1165
|
-
command
|
|
1194
|
+
command: through the exec wrapper ( handover ) it then never runs; with Popen(process_group=) it runs on in
|
|
1195
|
+
a process group of its own ( docs/limitations.md )
|
|
1166
1196
|
grouped: Whether the process's pid is its process group id
|
|
1197
|
+
handover: For the exec wrapper, the index in argv of its pipe's read end, filled in here; None otherwise. One
|
|
1198
|
+
byte on the pipe, once the command is in started, lets the wrapper run it; both ends are closed here however
|
|
1199
|
+
Popen ends, and a wrapper that got no byte exits 125 ( see _PGROUP_EXEC )
|
|
1167
1200
|
@returns:
|
|
1168
1201
|
( subprocess.Popen, int | None ): The process and its process group id ( None without a group of its own )
|
|
1169
1202
|
'''
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1203
|
+
pipe = None
|
|
1204
|
+
try:
|
|
1205
|
+
if handover is not None:
|
|
1206
|
+
pipe = _handover_pipe()
|
|
1207
|
+
argv[handover] = str(pipe[0])
|
|
1208
|
+
kwargs['pass_fds'] = tuple(kwargs.get('pass_fds', ())) + (pipe[0],)
|
|
1209
|
+
proc = subprocess.Popen(argv, **kwargs)
|
|
1210
|
+
command = (proc, proc.pid if grouped else None)
|
|
1211
|
+
if started is not None:
|
|
1212
|
+
started.append(command)
|
|
1213
|
+
if pipe is not None:
|
|
1214
|
+
# last in the try: a Ctrl-C that Python 3.6 - 3.9 raise between a try and its finally comes after it
|
|
1215
|
+
os.write(pipe[1], b'1')
|
|
1216
|
+
finally:
|
|
1217
|
+
if pipe is not None:
|
|
1218
|
+
os.close(pipe[0])
|
|
1219
|
+
os.close(pipe[1])
|
|
1174
1220
|
return command
|
|
1175
1221
|
|
|
1176
|
-
def _spawn_process(argv, stdout, stderr, env=None, explicit=False, executable=None, started=None):
|
|
1222
|
+
def _spawn_process(argv, stdout, stderr, env=None, explicit=False, executable=None, started=None, pass_fds=()):
|
|
1177
1223
|
'''
|
|
1178
1224
|
Start a command in a process group of its own ( internal )
|
|
1179
1225
|
|
|
@@ -1203,16 +1249,21 @@ def _spawn_process(argv, stdout, stderr, env=None, explicit=False, executable=No
|
|
|
1203
1249
|
is inherited and the wrapper just runs with it, as it always has
|
|
1204
1250
|
executable: The file to run as the command, instead of looking argv[0] up ( Popen's executable; not with the wrapper )
|
|
1205
1251
|
started: A list the ( Popen, process group id | None ) is appended to the moment Popen returns ( see _popen )
|
|
1252
|
+
pass_fds: Descriptors the command inherits, at the same numbers ( Popen's pass_fds; POSIX only, see _check_pass_fds ).
|
|
1253
|
+
Before 3.11 Popen hands them to the exec wrapper, whose interpreter leaves them alone and whose execv keeps them
|
|
1206
1254
|
|
|
1207
1255
|
@returns:
|
|
1208
1256
|
( subprocess.Popen, int | None ): The process and its process group id ( None without a group of its own )
|
|
1209
1257
|
'''
|
|
1210
1258
|
kwargs = {'stdin': subprocess.DEVNULL, 'stdout': stdout, 'stderr': stderr, 'env': env}
|
|
1259
|
+
if pass_fds:
|
|
1260
|
+
kwargs['pass_fds'] = pass_fds
|
|
1211
1261
|
if executable is not None:
|
|
1212
1262
|
kwargs['executable'] = executable
|
|
1213
1263
|
if not _IS_POSIX:
|
|
1214
1264
|
return _popen(argv, started, **kwargs)
|
|
1215
1265
|
grouped = True
|
|
1266
|
+
handover = None
|
|
1216
1267
|
if _HAS_PROCESS_GROUP:
|
|
1217
1268
|
kwargs['process_group'] = 0
|
|
1218
1269
|
elif _uses_wrapper():
|
|
@@ -1223,17 +1274,19 @@ def _spawn_process(argv, stdout, stderr, env=None, explicit=False, executable=No
|
|
|
1223
1274
|
kwargs['env'] = dict(_snapshot(os.environb, drop_empty=True))
|
|
1224
1275
|
kwargs['env'].update((os.fsencode(_ENV_VAR + str(i)), entry) for i, entry in enumerate(entries))
|
|
1225
1276
|
count = str(len(entries))
|
|
1226
|
-
|
|
1277
|
+
# the hand-over pipe's read end goes in at index 6 ( see _popen )
|
|
1278
|
+
argv = [sys.executable, '-I', '-S', '-c', _PGROUP_EXEC, count, None] + list(argv)
|
|
1279
|
+
handover = 6
|
|
1227
1280
|
else:
|
|
1228
1281
|
grouped = False
|
|
1229
1282
|
if _sigmask is None:
|
|
1230
|
-
return _popen(argv, started, grouped, **kwargs)
|
|
1283
|
+
return _popen(argv, started, grouped, handover, **kwargs)
|
|
1231
1284
|
# the mask as it is, read with a call that changes nothing; the block is in the try, as a Ctrl-C can come out of it
|
|
1232
1285
|
# with the mask already set ( see _sigmask )
|
|
1233
1286
|
old_mask = _sigmask(signal.SIG_BLOCK, ())
|
|
1234
1287
|
try:
|
|
1235
1288
|
_sigmask(signal.SIG_BLOCK, _TTY_SIGNALS)
|
|
1236
|
-
command = _popen(argv, started, grouped, **kwargs)
|
|
1289
|
+
command = _popen(argv, started, grouped, handover, **kwargs)
|
|
1237
1290
|
# ( here too: Python 3.6 - 3.9 can raise a Ctrl-C between the end of a try and its finally, which then never runs )
|
|
1238
1291
|
_sigmask(signal.SIG_SETMASK, old_mask)
|
|
1239
1292
|
finally:
|
|
@@ -1750,6 +1803,48 @@ def _check_env(mapping, name, allow_none=False, drop_empty=False):
|
|
|
1750
1803
|
env[key] = value
|
|
1751
1804
|
return _EnvSnapshot(env) if env or not allow_none else None
|
|
1752
1805
|
|
|
1806
|
+
def _check_pass_fds(pass_fds):
|
|
1807
|
+
'''
|
|
1808
|
+
The descriptors a command inherits, as a sorted tuple of ints, checked before anything runs ( internal )
|
|
1809
|
+
It takes an int, an object with fileno(), or an iterable of either ( None or empty: none ), as subprocess's pass_fds
|
|
1810
|
+
does with the first. A descriptor that is negative, a bool, or not open ( os.fstat says so ) is the caller's mistake,
|
|
1811
|
+
which a command started without it would hide: a ValueError naming it. So is any off POSIX, where no command can
|
|
1812
|
+
inherit one. multiCMD neither closes nor duplicates them: the caller keeps them open until the command has started.
|
|
1813
|
+
'''
|
|
1814
|
+
if pass_fds is None:
|
|
1815
|
+
return ()
|
|
1816
|
+
if isinstance(pass_fds, (str, bytes, bytearray)):
|
|
1817
|
+
raise TypeError(f'pass_fds must be a descriptor, an object with fileno() or an iterable of them, not {type(pass_fds).__name__}')
|
|
1818
|
+
if isinstance(pass_fds, int) or hasattr(pass_fds, 'fileno'):
|
|
1819
|
+
pass_fds = (pass_fds,)
|
|
1820
|
+
try:
|
|
1821
|
+
items = list(pass_fds)
|
|
1822
|
+
except TypeError:
|
|
1823
|
+
raise TypeError(f'pass_fds must be a descriptor, an object with fileno() or an iterable of them, not {type(pass_fds).__name__}') from None
|
|
1824
|
+
if items and not _IS_POSIX:
|
|
1825
|
+
raise ValueError('pass_fds needs a POSIX system')
|
|
1826
|
+
fds = set()
|
|
1827
|
+
for item in items:
|
|
1828
|
+
fd = item
|
|
1829
|
+
if not isinstance(item, int) and hasattr(item, 'fileno'):
|
|
1830
|
+
try:
|
|
1831
|
+
fd = item.fileno()
|
|
1832
|
+
except (OSError, ValueError) as e:
|
|
1833
|
+
# a closed file object
|
|
1834
|
+
raise ValueError(f'pass_fds: {item!r} has no open descriptor ( {e} )') from None
|
|
1835
|
+
if isinstance(fd, bool):
|
|
1836
|
+
raise ValueError(f'pass_fds: {item!r} is not a descriptor')
|
|
1837
|
+
if not isinstance(fd, int):
|
|
1838
|
+
raise TypeError(f'pass_fds: {item!r} is not a descriptor or an object with fileno()')
|
|
1839
|
+
if fd < 0:
|
|
1840
|
+
raise ValueError(f'pass_fds: {fd} is not a descriptor')
|
|
1841
|
+
try:
|
|
1842
|
+
os.fstat(fd)
|
|
1843
|
+
except OSError as e:
|
|
1844
|
+
raise ValueError(f'pass_fds: descriptor {fd} is not open ( {e.strerror} )') from None
|
|
1845
|
+
fds.add(fd)
|
|
1846
|
+
return tuple(sorted(fds))
|
|
1847
|
+
|
|
1753
1848
|
def _apply_extra_env(env, extra_env):
|
|
1754
1849
|
'''
|
|
1755
1850
|
Add extra_env to env in place; a None value removes the variable ( internal )
|
|
@@ -1820,8 +1915,9 @@ def _execute(task, timeout, quiet, decor, use_pty=False):
|
|
|
1820
1915
|
of multiCMD's: the command is stopped and the caller records it ( -1 ). A second interrupt ends the wait for the
|
|
1821
1916
|
stop: the command is sent SIGTERM and stays registered, for kill_all() and the exit hook.
|
|
1822
1917
|
The command is registered from the moment Popen has returned it ( see _popen ). An interrupt that Python raises
|
|
1823
|
-
inside Popen, once it has forked, loses it
|
|
1824
|
-
the
|
|
1918
|
+
inside Popen, once it has forked, loses it. Through the exec wrapper ( Python < 3.11 ) it then never runs: the
|
|
1919
|
+
wrapper waits until the command is registered. With Popen(process_group=) ( 3.11+ ) it runs on in a process group of
|
|
1920
|
+
its own, unknown to kill_all() and the exit hook ( docs/limitations.md ). Python raises one on the main thread only.
|
|
1825
1921
|
|
|
1826
1922
|
@params:
|
|
1827
1923
|
task: The Task
|
|
@@ -1848,7 +1944,7 @@ def _execute(task, timeout, quiet, decor, use_pty=False):
|
|
|
1848
1944
|
master, slave = _open_pty(len(decor[0]))
|
|
1849
1945
|
if master is not None:
|
|
1850
1946
|
try:
|
|
1851
|
-
proc, pgid = _spawn(task.command, slave, slave, _child_env(task, pager=True), explicit, started)
|
|
1947
|
+
proc, pgid = _spawn(task.command, slave, slave, _child_env(task, pager=True), explicit, started, task._pass_fds)
|
|
1852
1948
|
finally:
|
|
1853
1949
|
# only the command keeps the terminal side open, so the master sees EIO once it is gone
|
|
1854
1950
|
os.close(slave)
|
|
@@ -1857,7 +1953,7 @@ def _execute(task, timeout, quiet, decor, use_pty=False):
|
|
|
1857
1953
|
fd, master = master, None
|
|
1858
1954
|
streams = [(io.open(fd, 'rb'), task.stdout)]
|
|
1859
1955
|
else:
|
|
1860
|
-
proc, pgid = _spawn(task.command, subprocess.PIPE, subprocess.PIPE, _child_env(task), explicit, started)
|
|
1956
|
+
proc, pgid = _spawn(task.command, subprocess.PIPE, subprocess.PIPE, _child_env(task), explicit, started, task._pass_fds)
|
|
1861
1957
|
streams = [(proc.stdout, task.stdout), (proc.stderr, task.stderr)]
|
|
1862
1958
|
# ( for kill_all() and the exit hook, which know no quiet of their own: see _give_up_on )
|
|
1863
1959
|
proc._multicmd_quiet = quiet
|
|
@@ -2172,10 +2268,10 @@ def _shell_template(template):
|
|
|
2172
2268
|
i += 1
|
|
2173
2269
|
return ''.join(out)
|
|
2174
2270
|
|
|
2175
|
-
def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, extra_env=None):
|
|
2271
|
+
def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, extra_env=None, pass_fds=()):
|
|
2176
2272
|
'''
|
|
2177
2273
|
Format commands into Tasks, prefixing sudo when requested and available ( internal )
|
|
2178
|
-
env / extra_env ( validated here, before anything runs ) are copied onto every Task
|
|
2274
|
+
env / extra_env / pass_fds ( validated here, before anything runs ) are copied onto every Task
|
|
2179
2275
|
|
|
2180
2276
|
@returns:
|
|
2181
2277
|
tuple[list[Task], bool]: The tasks and whether sudo is used
|
|
@@ -2199,6 +2295,7 @@ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, ext
|
|
|
2199
2295
|
formatedCommands = [[SUDO_PATH] + command for command in formatedCommands]
|
|
2200
2296
|
env = _check_env(env, 'env', drop_empty=True)
|
|
2201
2297
|
extra_env = _check_env(extra_env, 'extra_env', allow_none=True)
|
|
2298
|
+
pass_fds = _check_pass_fds(pass_fds)
|
|
2202
2299
|
# one snapshot shared by every task of the call
|
|
2203
2300
|
tasks = [Task(command) for command in formatedCommands]
|
|
2204
2301
|
# a call the main thread makes once the exit hook has begun ( from an atexit handler: see _cut_by_exit )
|
|
@@ -2206,6 +2303,7 @@ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, ext
|
|
|
2206
2303
|
for task in tasks:
|
|
2207
2304
|
task._env = env
|
|
2208
2305
|
task._extra_env = extra_env
|
|
2306
|
+
task._pass_fds = pass_fds
|
|
2209
2307
|
task._at_exit = at_exit
|
|
2210
2308
|
return tasks, bool(use_sudo)
|
|
2211
2309
|
|
|
@@ -2375,12 +2473,13 @@ def _run_pool(tasks, decors, sem, timeout, quiet, dry_run, max_threads, use_pty=
|
|
|
2375
2473
|
def run_command(command, timeout=0,max_threads=1,quiet=False,dry_run=False,with_stdErr=False,
|
|
2376
2474
|
return_code_only=False,return_object=False,wait_for_return=True, sem = None,
|
|
2377
2475
|
use_sudo = ..., raise_error = False, prefix = False, color = None, pty = False, shell = False,
|
|
2378
|
-
env = None, extra_env = None):
|
|
2476
|
+
env = None, extra_env = None, pass_fds = ()):
|
|
2379
2477
|
'''
|
|
2380
2478
|
Run a command
|
|
2381
2479
|
|
|
2382
|
-
A Ctrl-C ( or a signal handler's exception ) that Python raises inside Popen, once it has forked,
|
|
2383
|
-
running
|
|
2480
|
+
A Ctrl-C ( or a signal handler's exception ) that Python raises inside Popen, once it has forked, keeps the command
|
|
2481
|
+
from running on Python < 3.11 ( the exec wrapper waits until it is registered ); on 3.11+ it leaves the command running
|
|
2482
|
+
unregistered, unknown to kill_all() and the exit hook ( some 50 - 70 us per command ). Only a serial run
|
|
2384
2483
|
( max_threads=1 ) starts its commands on the main thread, where Python raises them. Anywhere else the command is
|
|
2385
2484
|
stopped before the interrupt is re-raised ( see docs/limitations.md for a second one microseconds after it ).
|
|
2386
2485
|
|
|
@@ -2409,6 +2508,13 @@ def run_command(command, timeout=0,max_threads=1,quiet=False,dry_run=False,with_
|
|
|
2409
2508
|
The inherited environment is os.environ when the command starts ( not variables set behind its back with os.putenv or C setenv ); an inherited variable with an empty name ( a corrupt os.environ entry ) is left out of the environment of a command given env / extra_env, and out of an env copied from os.environ ( `env=dict(os.environ)` ); a command given neither, with or without pty, inherits it as before. An empty name in extra_env is a ValueError.
|
|
2410
2509
|
Names and values are str, on POSIX bytes and os.PathLike too; on POSIX the command is looked up in the PATH of the environment it gets ( Windows searches the calling process's PATH )
|
|
2411
2510
|
sudo resets the environment by default ( env_reset ), so with use_sudo the variables may not reach the command
|
|
2511
|
+
pass_fds: Descriptors the command inherits, at the same numbers, as subprocess's pass_fds ( POSIX only ): an int, an object
|
|
2512
|
+
with fileno(), or an iterable of either ( empty: none, and every descriptor past 2 is closed in the command, as before ).
|
|
2513
|
+
Checked before anything runs: a negative, bool or closed one is a ValueError, and so is any off POSIX.
|
|
2514
|
+
multiCMD neither closes nor duplicates them: keep them open until the command has started ( with wait_for_return=False,
|
|
2515
|
+
until its task's start_time is set ). With use_sudo, sudo closes descriptors past 2 unless its policy lets the caller
|
|
2516
|
+
keep them ( sudo -C, closefrom_override ); with shell=True the shell inherits them too. dry_run shows the command as it is.
|
|
2517
|
+
Example: run_command(['cp', src, '/dev/fd/%d' % fd], pass_fds=(fd,)) lets cp write a file this process holds open
|
|
2412
2518
|
|
|
2413
2519
|
@returns:
|
|
2414
2520
|
None | int | list[str] | Task: The output of the command
|
|
@@ -2416,17 +2522,18 @@ def run_command(command, timeout=0,max_threads=1,quiet=False,dry_run=False,with_
|
|
|
2416
2522
|
return run_commands(commands=[command], timeout=timeout, max_threads=max_threads, quiet=quiet,
|
|
2417
2523
|
dry_run=dry_run, with_stdErr=with_stdErr, return_code_only=return_code_only,
|
|
2418
2524
|
return_object=return_object,parse=False,wait_for_return=wait_for_return,sem=sem,
|
|
2419
|
-
use_sudo=use_sudo, raise_error=raise_error, prefix=prefix, color=color, pty=pty, shell=shell, env=env, extra_env=extra_env
|
|
2525
|
+
use_sudo=use_sudo, raise_error=raise_error, prefix=prefix, color=color, pty=pty, shell=shell, env=env, extra_env=extra_env,
|
|
2526
|
+
pass_fds=pass_fds)[0]
|
|
2420
2527
|
|
|
2421
2528
|
def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,with_stdErr=False,
|
|
2422
2529
|
return_code_only=False,return_object=False, parse = False, wait_for_return = True,
|
|
2423
2530
|
sem : threading.Semaphore = None, use_sudo=..., raise_error = False, prefix = False, color = None, pty = False, shell = False,
|
|
2424
|
-
env = None, extra_env = None):
|
|
2531
|
+
env = None, extra_env = None, pass_fds = ()):
|
|
2425
2532
|
'''
|
|
2426
2533
|
Run multiple commands in parallel
|
|
2427
2534
|
|
|
2428
|
-
|
|
2429
|
-
( see run_command ).
|
|
2535
|
+
On Python 3.11+ a Ctrl-C that lands inside Popen as a serial run starts a command can leave that command running
|
|
2536
|
+
unregistered ( see run_command ).
|
|
2430
2537
|
|
|
2431
2538
|
@params:
|
|
2432
2539
|
commands: A list of commands to run ( list[str] | list[list[str]] )
|
|
@@ -2454,12 +2561,19 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
|
|
|
2454
2561
|
The inherited environment is os.environ when the command starts ( not variables set behind its back with os.putenv or C setenv ); an inherited variable with an empty name ( a corrupt os.environ entry ) is left out of the environment of a command given env / extra_env, and out of an env copied from os.environ ( `env=dict(os.environ)` ); a command given neither, with or without pty, inherits it as before. An empty name in extra_env is a ValueError.
|
|
2455
2562
|
Names and values are str, on POSIX bytes and os.PathLike too; on POSIX the command is looked up in the PATH of the environment it gets ( Windows searches the calling process's PATH )
|
|
2456
2563
|
sudo resets the environment by default ( env_reset ), so with use_sudo the variables may not reach the command
|
|
2564
|
+
pass_fds: Descriptors the command inherits, at the same numbers, as subprocess's pass_fds ( POSIX only ): an int, an object
|
|
2565
|
+
with fileno(), or an iterable of either ( empty: none, and every descriptor past 2 is closed in the command, as before ).
|
|
2566
|
+
Checked before anything runs: a negative, bool or closed one is a ValueError, and so is any off POSIX.
|
|
2567
|
+
multiCMD neither closes nor duplicates them: keep them open until the command has started ( with wait_for_return=False,
|
|
2568
|
+
until its task's start_time is set ). With use_sudo, sudo closes descriptors past 2 unless its policy lets the caller
|
|
2569
|
+
keep them ( sudo -C, closefrom_override ); with shell=True the shell inherits them too. dry_run shows the command as it is.
|
|
2570
|
+
Example: run_command(['cp', src, '/dev/fd/%d' % fd], pass_fds=(fd,)) lets cp write a file this process holds open
|
|
2457
2571
|
|
|
2458
2572
|
@returns:
|
|
2459
2573
|
list: The output of the commands ( list[None] | list[int] | list[list[str]] | list[Task] | None )
|
|
2460
2574
|
'''
|
|
2461
2575
|
# initialize the tasks
|
|
2462
|
-
tasks, use_sudo = _build_tasks(commands, parse=parse, use_sudo=use_sudo, shell=shell, env=env, extra_env=extra_env)
|
|
2576
|
+
tasks, use_sudo = _build_tasks(commands, parse=parse, use_sudo=use_sudo, shell=shell, env=env, extra_env=extra_env, pass_fds=pass_fds)
|
|
2463
2577
|
# run the tasks with max_threads. if max_threads is 0, use the number of commands
|
|
2464
2578
|
if max_threads < 1:
|
|
2465
2579
|
max_threads = len(tasks)
|
|
@@ -429,12 +429,29 @@ open(%r, 'w').write(repr((task.returncode, sorted(task.stdout))))
|
|
|
429
429
|
assert 'A=x' in eval(out.read_text())[1] and 'PATH=' + os.environ['PATH'] in eval(out.read_text())[1], fd
|
|
430
430
|
|
|
431
431
|
|
|
432
|
+
def _handed_over():
|
|
433
|
+
'''The read end of a pipe holding the byte with which a caller hands the exec wrapper its command ( see _popen )'''
|
|
434
|
+
r, w = os.pipe()
|
|
435
|
+
os.write(w, b'1')
|
|
436
|
+
os.close(w)
|
|
437
|
+
return r
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _run_wrapper(code, count, command, **kwargs):
|
|
441
|
+
'''Run the exec wrapper ( or code that execs it ) as _spawn_process does, the command handed over'''
|
|
442
|
+
r = _handed_over()
|
|
443
|
+
try:
|
|
444
|
+
return subprocess.run([sys.executable, '-I', '-S', '-c', code, count, str(r)] + command, pass_fds=(r,),
|
|
445
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=30, **kwargs)
|
|
446
|
+
finally:
|
|
447
|
+
os.close(r)
|
|
448
|
+
|
|
449
|
+
|
|
432
450
|
def test_a_missing_part_of_the_environment_stops_the_wrapper_before_it_runs_anything(tmp_path):
|
|
433
451
|
marker = tmp_path / 'ran'
|
|
434
452
|
for count, entries in (('3', {b'_MULTICMD_ENV_0': b'A=1', b'_MULTICMD_ENV_1': b'B=2'}), ('1', {b'_MULTICMD_ENV_0': b'NOEQUALS'}), ('x', {})):
|
|
435
|
-
proc =
|
|
436
|
-
env=dict({k.decode(): v.decode() for k, v in entries.items()}, PATH=os.environ['PATH'])
|
|
437
|
-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=30)
|
|
453
|
+
proc = _run_wrapper(multiCMD._PGROUP_EXEC, count, ['touch', str(marker)],
|
|
454
|
+
env=dict({k.decode(): v.decode() for k, v in entries.items()}, PATH=os.environ['PATH']))
|
|
438
455
|
assert proc.returncode == 126, (count, proc.stderr)
|
|
439
456
|
assert 'incomplete environment' in proc.stderr
|
|
440
457
|
assert not marker.exists()
|
|
@@ -713,8 +730,7 @@ def test_the_wrapper_starts_the_command_with_exactly_the_environment_it_was_give
|
|
|
713
730
|
"def execve(f, a, e):\n\tprint(sorted(e.items()))\n\tsys.exit(0)\n"
|
|
714
731
|
"posix.execve = execve\nexec(%r)" % multiCMD._PGROUP_EXEC)
|
|
715
732
|
env = {'PATH': os.environ['PATH'], '_MULTICMD_ENV_0': 'A=1', '_MULTICMD_ENV_1': 'B=x=y'}
|
|
716
|
-
proc =
|
|
717
|
-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=30)
|
|
733
|
+
proc = _run_wrapper(code, '2', ['true'], env=env)
|
|
718
734
|
assert proc.returncode == 0, proc.stderr
|
|
719
735
|
assert proc.stdout.strip() == "[(b'A', b'1'), (b'B', b'x=y')]"
|
|
720
736
|
|
|
@@ -725,8 +741,7 @@ def test_the_wrapper_starts_nothing_but_built_in_modules(count):
|
|
|
725
741
|
code = ("import posix, sys\nbefore = set(sys.modules)\n"
|
|
726
742
|
"def run(*a):\n\tprint(sorted(set(sys.modules) - before))\n\tsys.exit(0)\n"
|
|
727
743
|
"posix.execv = posix.execve = run\nexec(%r)" % multiCMD._PGROUP_EXEC)
|
|
728
|
-
proc =
|
|
729
|
-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=30)
|
|
744
|
+
proc = _run_wrapper(code, count, ['sh'], env={'PATH': '/usr/bin:/bin'})
|
|
730
745
|
assert proc.returncode == 0, proc.stderr
|
|
731
746
|
assert proc.stdout.strip() == '[]'
|
|
732
747
|
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
'''Through the exec wrapper ( Python < 3.11 ) a command runs only once the caller has it registered ( 1.59 ): the wrapper
|
|
2
|
+
waits for one byte on a pipe that _popen writes once the command is in started, and a caller interrupted inside Popen once
|
|
3
|
+
it has forked closes the pipe instead, so the wrapper exits 125 without running anything.'''
|
|
4
|
+
import os
|
|
5
|
+
import signal
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
import multiCMD
|
|
13
|
+
from conftest import PACKAGE_ROOT, pid_gone
|
|
14
|
+
|
|
15
|
+
pytestmark = pytest.mark.skipif(os.name != 'posix', reason='the exec wrapper runs on POSIX only')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
_INSIDE_POPEN = r'''
|
|
19
|
+
import os, signal, subprocess, sys, threading, time
|
|
20
|
+
sys.path.insert(0, sys.argv[1])
|
|
21
|
+
import multiCMD
|
|
22
|
+
pids, signame, where, marker = sys.argv[2:6]
|
|
23
|
+
multiCMD._HAS_PROCESS_GROUP = False
|
|
24
|
+
signum = getattr(signal, signame)
|
|
25
|
+
if signum != signal.SIGINT:
|
|
26
|
+
def handler(signum, frame):
|
|
27
|
+
raise SystemExit(128 + signum)
|
|
28
|
+
signal.signal(signum, handler)
|
|
29
|
+
# another thread, as a program has ( a pool's queue feeder thread, a reader ): it takes the signal as well as the main
|
|
30
|
+
# thread does, and Python raises it on the main thread all the same
|
|
31
|
+
threading.Thread(target=time.sleep, args=(60,), daemon=True).start()
|
|
32
|
+
real = subprocess.Popen._execute_child
|
|
33
|
+
def execute_child(self, *args, **kwargs):
|
|
34
|
+
if where == 'before':
|
|
35
|
+
os.kill(os.getpid(), signum)
|
|
36
|
+
real(self, *args, **kwargs)
|
|
37
|
+
with open(pids, 'a') as f:
|
|
38
|
+
f.write('%d\n' % self.pid)
|
|
39
|
+
if where == 'after':
|
|
40
|
+
# the signal reaches this process once Popen has forked ( process-directed, as from kill or a terminal ), and Python
|
|
41
|
+
# takes it at one of these instructions, inside Popen
|
|
42
|
+
os.kill(os.getpid(), signum)
|
|
43
|
+
for _ in range(1000):
|
|
44
|
+
pass
|
|
45
|
+
subprocess.Popen._execute_child = execute_child
|
|
46
|
+
try:
|
|
47
|
+
multiCMD.run_command(['sh', '-c', 'touch "$1"; exec sleep 30', 'sh', marker], quiet=True)
|
|
48
|
+
except KeyboardInterrupt:
|
|
49
|
+
sys.exit(130)
|
|
50
|
+
sys.exit(0)
|
|
51
|
+
'''
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@pytest.mark.parametrize('signame', ['SIGINT', 'SIGTERM', 'SIGHUP'])
|
|
55
|
+
@pytest.mark.parametrize('where', ['after', 'before'])
|
|
56
|
+
def test_a_stop_inside_popen_runs_nothing(tmp_path, signame, where):
|
|
57
|
+
# 1.58: a stop Python took inside Popen once it had forked was raised there; the command was never registered and ran on,
|
|
58
|
+
# its process group out of reach ( an early Ctrl-C of hpcp on Python 3.6 lost a cp in about one run in four )
|
|
59
|
+
pids, marker = tmp_path / 'pids', tmp_path / 'ran'
|
|
60
|
+
proc = subprocess.run([sys.executable, '-c', _INSIDE_POPEN, str(PACKAGE_ROOT), str(pids), signame, where, str(marker)],
|
|
61
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=60)
|
|
62
|
+
started = [int(pid) for pid in pids.read_text().split()] if pids.exists() else []
|
|
63
|
+
left = [pid for pid in started if not pid_gone(pid, wait=3)]
|
|
64
|
+
for pid in left:
|
|
65
|
+
try:
|
|
66
|
+
os.killpg(pid, signal.SIGKILL)
|
|
67
|
+
except OSError:
|
|
68
|
+
pass
|
|
69
|
+
assert proc.returncode == (130 if signame == 'SIGINT' else 128 + getattr(signal, signame)), proc.stderr
|
|
70
|
+
assert left == [] and not marker.exists(), (started, left)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _wrapper(tmp_path, handover):
|
|
74
|
+
marker = tmp_path / 'ran'
|
|
75
|
+
return marker, subprocess.Popen([sys.executable, '-I', '-S', '-c', multiCMD._PGROUP_EXEC, '-', str(handover), 'touch', str(marker)],
|
|
76
|
+
pass_fds=(handover,), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_the_wrapper_waits_for_the_hand_over_and_runs_nothing_without_it(tmp_path):
|
|
80
|
+
r, w = os.pipe()
|
|
81
|
+
marker, proc = _wrapper(tmp_path, r)
|
|
82
|
+
os.close(r)
|
|
83
|
+
try:
|
|
84
|
+
time.sleep(0.5)
|
|
85
|
+
assert proc.poll() is None and not marker.exists()
|
|
86
|
+
finally:
|
|
87
|
+
os.close(w)
|
|
88
|
+
out, err = proc.communicate(timeout=30)
|
|
89
|
+
assert proc.returncode == 125 and (out, err) == ('', '')
|
|
90
|
+
assert not marker.exists()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_the_wrapper_runs_the_command_once_handed_over(tmp_path):
|
|
94
|
+
r, w = os.pipe()
|
|
95
|
+
marker, proc = _wrapper(tmp_path, r)
|
|
96
|
+
os.close(r)
|
|
97
|
+
os.write(w, b'1')
|
|
98
|
+
os.close(w)
|
|
99
|
+
assert proc.wait(timeout=30) == 0 and marker.exists()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@pytest.mark.skipif(not os.path.isdir('/proc/self/fd'), reason='needs /proc/self/fd')
|
|
103
|
+
def test_the_hand_over_pipe_reaches_neither_the_command_nor_the_next_start(launcher):
|
|
104
|
+
before = set(os.listdir('/proc/self/fd'))
|
|
105
|
+
for _ in range(20):
|
|
106
|
+
out = multiCMD.run_command([sys.executable, '-c', 'import os; print(sorted(map(int, os.listdir("/proc/self/fd"))))'], quiet=True)
|
|
107
|
+
# 0, 1, 2 and listdir's own
|
|
108
|
+
assert out == ['[0, 1, 2, 3]']
|
|
109
|
+
assert set(os.listdir('/proc/self/fd')) == before
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
'''pass_fds ( 1.59 ): a command inherits the descriptors it is given, at the same numbers, and no others.
|
|
2
|
+
Each test runs with Popen(process_group=) ( 3.11+ ) and with the exec wrapper ( the launcher fixture ).'''
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
import multiCMD
|
|
9
|
+
from multiCMD import AsyncExecutor, run_command, run_commands
|
|
10
|
+
|
|
11
|
+
pytestmark = pytest.mark.skipif(os.name != 'posix', reason='descriptors are inherited on POSIX only')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture(autouse=True)
|
|
15
|
+
def _both_launchers(launcher):
|
|
16
|
+
return launcher
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _pipe(text):
|
|
20
|
+
'''The read end of a pipe holding text, its write end closed: one reader gets it whole, then EOF'''
|
|
21
|
+
r, w = os.pipe()
|
|
22
|
+
os.write(w, text.encode())
|
|
23
|
+
os.close(w)
|
|
24
|
+
return r
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.fixture
|
|
28
|
+
def pipes():
|
|
29
|
+
opened = []
|
|
30
|
+
def make(text):
|
|
31
|
+
r = _pipe(text)
|
|
32
|
+
opened.append(r)
|
|
33
|
+
return r
|
|
34
|
+
yield make
|
|
35
|
+
for fd in opened:
|
|
36
|
+
try:
|
|
37
|
+
os.close(fd)
|
|
38
|
+
except OSError:
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _cat(fd):
|
|
43
|
+
return ['cat', '/dev/fd/%d' % fd]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _executor_run(command, **kwargs):
|
|
47
|
+
ex = AsyncExecutor(quiet=True, **kwargs)
|
|
48
|
+
ex.run_command(command)
|
|
49
|
+
ex.join(print_error=False)
|
|
50
|
+
return ex.get_results()[0]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@pytest.mark.parametrize('route', ['run_command', 'run_commands', 'AsyncExecutor', 'AsyncExecutor-call', 'pty', 'env', 'extra_env', 'shell'])
|
|
54
|
+
def test_a_command_reads_a_passed_descriptor(pipes, route):
|
|
55
|
+
if route == 'run_commands':
|
|
56
|
+
fds = [pipes('passed %d' % i) for i in range(4)]
|
|
57
|
+
out = run_commands([_cat(fd) for fd in fds], max_threads=4, quiet=True, pass_fds=fds)
|
|
58
|
+
assert out == [['passed %d' % i] for i in range(4)]
|
|
59
|
+
return
|
|
60
|
+
fd = pipes('passed')
|
|
61
|
+
if route == 'run_command':
|
|
62
|
+
out = run_command(_cat(fd), quiet=True, pass_fds=(fd,))
|
|
63
|
+
elif route == 'AsyncExecutor':
|
|
64
|
+
out = _executor_run(_cat(fd), pass_fds=fd)
|
|
65
|
+
elif route == 'AsyncExecutor-call':
|
|
66
|
+
ex = AsyncExecutor(quiet=True)
|
|
67
|
+
ex.run_command(_cat(fd), pass_fds=[fd])
|
|
68
|
+
ex.join(print_error=False)
|
|
69
|
+
out = ex.get_results()[0]
|
|
70
|
+
elif route == 'pty':
|
|
71
|
+
out = run_command(_cat(fd), quiet=True, pty=True, pass_fds=(fd,))
|
|
72
|
+
elif route == 'env':
|
|
73
|
+
# before 3.11 the exec wrapper's branch for a command with an environment of its own
|
|
74
|
+
out = run_command(_cat(fd), quiet=True, env={'PATH': os.environ.get('PATH', os.defpath)}, pass_fds=(fd,))
|
|
75
|
+
elif route == 'extra_env':
|
|
76
|
+
out = run_command(_cat(fd), quiet=True, extra_env={'MCMD_PASS_FDS': '1'}, pass_fds=(fd,))
|
|
77
|
+
else:
|
|
78
|
+
out = run_command('cat /dev/fd/%d | cat' % fd, quiet=True, shell=True, pass_fds=(fd,))
|
|
79
|
+
assert out == ['passed']
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_without_pass_fds_nothing_is_inherited(pipes):
|
|
83
|
+
# the default closes every descriptor past 2 in the command, an inheritable one too
|
|
84
|
+
fd = pipes('kept')
|
|
85
|
+
os.set_inheritable(fd, True)
|
|
86
|
+
task = run_command(_cat(fd), quiet=True, return_object=True)
|
|
87
|
+
assert task.returncode != 0 and task.stdout == []
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_only_the_named_descriptors_are_passed(pipes):
|
|
91
|
+
passed, other = pipes('passed'), pipes('other')
|
|
92
|
+
os.set_inheritable(other, True)
|
|
93
|
+
assert run_command(_cat(passed), quiet=True, pass_fds=passed) == ['passed']
|
|
94
|
+
task = run_command(_cat(other), quiet=True, return_object=True, pass_fds=passed)
|
|
95
|
+
assert task.returncode != 0 and task.stdout == []
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_file_objects_and_iterables_are_accepted(pipes, tmp_path):
|
|
99
|
+
path = tmp_path / 'held'
|
|
100
|
+
path.write_text('from a file object')
|
|
101
|
+
with open(str(path), 'rb') as held:
|
|
102
|
+
fd = pipes('from an int')
|
|
103
|
+
assert multiCMD._check_pass_fds(fd) == (fd,)
|
|
104
|
+
assert multiCMD._check_pass_fds(held) == (held.fileno(),)
|
|
105
|
+
assert multiCMD._check_pass_fds([held, fd, fd]) == tuple(sorted({held.fileno(), fd}))
|
|
106
|
+
assert multiCMD._check_pass_fds(None) == multiCMD._check_pass_fds(()) == ()
|
|
107
|
+
out = run_commands([_cat(held.fileno()), _cat(fd)], quiet=True, max_threads=2, pass_fds=[held, fd])
|
|
108
|
+
assert out == [['from a file object'], ['from an int']]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_a_closed_or_bad_descriptor_is_refused_before_anything_runs(tmp_path):
|
|
112
|
+
marker = tmp_path / 'ran'
|
|
113
|
+
r, w = os.pipe()
|
|
114
|
+
os.close(r)
|
|
115
|
+
os.close(w)
|
|
116
|
+
closed_file = open(str(tmp_path / 'f'), 'wb')
|
|
117
|
+
closed_file.close()
|
|
118
|
+
for bad in (r, -1, True, [w], closed_file):
|
|
119
|
+
with pytest.raises(ValueError):
|
|
120
|
+
run_commands([['touch', str(marker)]], quiet=True, pass_fds=bad)
|
|
121
|
+
with pytest.raises(ValueError):
|
|
122
|
+
run_command(['touch', str(marker)], quiet=True, wait_for_return=False, pass_fds=bad)
|
|
123
|
+
with pytest.raises(ValueError):
|
|
124
|
+
AsyncExecutor(pass_fds=bad)
|
|
125
|
+
ex = AsyncExecutor(quiet=True)
|
|
126
|
+
with pytest.raises(ValueError):
|
|
127
|
+
ex.run_command(['touch', str(marker)], pass_fds=bad)
|
|
128
|
+
assert ex.tasks == []
|
|
129
|
+
for wrong in ('3', b'\x03', 1.5, [None]):
|
|
130
|
+
with pytest.raises(TypeError):
|
|
131
|
+
run_command(['touch', str(marker)], quiet=True, pass_fds=wrong)
|
|
132
|
+
multiCMD.join_threads(timeout=5)
|
|
133
|
+
assert not marker.exists()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_pass_fds_off_posix_is_refused(monkeypatch, pipes):
|
|
137
|
+
fd = pipes('x')
|
|
138
|
+
monkeypatch.setattr(multiCMD, '_IS_POSIX', False)
|
|
139
|
+
with pytest.raises(ValueError, match='pass_fds needs a POSIX system'):
|
|
140
|
+
multiCMD._check_pass_fds(fd)
|
|
141
|
+
with pytest.raises(ValueError, match='pass_fds needs a POSIX system'):
|
|
142
|
+
AsyncExecutor(pass_fds=[fd])
|
|
143
|
+
# nothing to pass is fine everywhere
|
|
144
|
+
assert multiCMD._check_pass_fds(()) == ()
|
|
145
|
+
assert AsyncExecutor().pass_fds == ()
|
|
@@ -66,6 +66,9 @@ def test_timeout_returncode_preserved_after_sigint_handler_stderr():
|
|
|
66
66
|
" sys.stderr.flush()\n"
|
|
67
67
|
" sys.exit(0)\n"
|
|
68
68
|
"signal.signal(signal.SIGINT, handler)\n"
|
|
69
|
+
# output restarts the inactivity timeout: it fires 0.3 s after the handler is in, however long two interpreter
|
|
70
|
+
# starts take ( the exec wrapper's and this one's: over 0.3 s at load 200 on 32 cores, 2026-11-10 )
|
|
71
|
+
"print('ready', flush=True)\n"
|
|
69
72
|
"time.sleep(10)\n",
|
|
70
73
|
],
|
|
71
74
|
timeout=0.3,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|