Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix _storage_main terminate_on_parent_death not working on mac #9110

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 25 additions & 23 deletions src/ert/services/_storage_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import signal
import socket
import string
import sys
import threading
import time
import warnings
from typing import Any, Dict, List, Optional, Union

Expand Down Expand Up @@ -123,30 +124,23 @@ def run_server(args: Optional[argparse.Namespace] = None, debug: bool = False) -
server.run(sockets=[sock])


def terminate_on_parent_death() -> None:
"""Quit the server when the parent does a SIGABRT or is otherwise destroyed.
This functionality has existed on Linux for a good while, but it isn't
exposed in the Python standard library. Use ctypes to hook into the
functionality.
def terminate_on_parent_death(
stopped: threading.Event, poll_interval: float = 1.0
) -> None:
"""
Quit the server when the parent process is no longer running.
"""
if sys.platform != "linux" or "ERT_COMM_FD" not in os.environ:
return

from ctypes import CDLL, c_int, c_ulong # noqa: PLC0415

lib = CDLL(None)

# from <sys/prctl.h>
# int prctl(int option, ...)
prctl = lib.prctl
prctl.restype = c_int
prctl.argtypes = (c_int, c_ulong)
def check_parent_alive() -> bool:
return os.getppid() != 1

# from <linux/prctl.h>
PR_SET_PDEATHSIG = 1
while check_parent_alive():
if stopped.is_set():
return
time.sleep(poll_interval)

# connect parent death signal to our SIGTERM
prctl(PR_SET_PDEATHSIG, signal.SIGTERM)
# Parent is no longer alive, terminate this process.
os.kill(os.getpid(), signal.SIGTERM)


if __name__ == "__main__":
Expand All @@ -156,6 +150,14 @@ def terminate_on_parent_death() -> None:
warnings.filterwarnings("ignore", category=DeprecationWarning)
uvicorn.config.LOGGING_CONFIG.clear()
uvicorn.config.LOGGING_CONFIG.update(logging_conf)
terminate_on_parent_death()
_stopped = threading.Event()
terminate_on_parent_death_thread = threading.Thread(
target=terminate_on_parent_death, args=[_stopped, 1.0]
)
with ErtPluginContext(logger=logging.getLogger()) as context:
run_server(debug=False)
terminate_on_parent_death_thread.start()
try:
run_server(debug=False)
finally:
_stopped.set()
terminate_on_parent_death_thread.join()
42 changes: 42 additions & 0 deletions tests/ert/ui_tests/cli/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import fileinput
import json
import logging
Expand All @@ -13,6 +14,7 @@
import pytest
import websockets.exceptions
import xtgeo
from psutil import NoSuchProcess, Popen, Process, ZombieProcess
from resdata.summary import Summary

import _ert.threading
Expand Down Expand Up @@ -959,3 +961,43 @@ def raise_connection_error(*args, **kwargs):
ENSEMBLE_EXPERIMENT_MODE,
"poly.ert",
)


@pytest.mark.usefixtures("copy_poly_case")
async def test_that_killed_ert_does_not_leave_storage_server_process():
ert_subprocess = Popen(["ert", "gui", "poly.ert"])
assert ert_subprocess.is_running()

async def _find_storage_process_pid() -> int:
while True:
for ert_child_process in ert_subprocess.children():
try:
if "storage" in "".join(ert_child_process.cmdline()):
return ert_child_process.pid
except (ZombieProcess, NoSuchProcess):
pass
await asyncio.sleep(0.05)

storage_process_pid = await asyncio.wait_for(
_find_storage_process_pid(), timeout=120
)
# wait for storage server to have connected to ert
await asyncio.sleep(5)
storage_process = Process(storage_process_pid)

assert ert_subprocess.is_running()
assert storage_process.is_running()
kill_ert_subprocess = await asyncio.create_subprocess_exec(
"kill", "-9", f"{ert_subprocess.pid}"
)
await kill_ert_subprocess.wait()

async def _wait_for_storage_process_to_shut_down():
storage_server_has_shutdown = asyncio.Event()
while not storage_server_has_shutdown.is_set():
if not storage_process.is_running():
storage_server_has_shutdown.set()
await asyncio.sleep(0.1)

await asyncio.wait_for(_wait_for_storage_process_to_shut_down(), timeout=45)
assert not storage_process.is_running()
1 change: 1 addition & 0 deletions tests/ert/ui_tests/cli/test_field_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from .run_cli import run_cli


@pytest.mark.timeout(600)
def test_field_param_update_using_heat_equation(heat_equation_storage):
config = ErtConfig.from_file("config.ert")
with open_storage(config.ens_path, mode="w") as storage:
Expand Down