Skip to content

Commit

Permalink
Utilize atexit to cleanup remaining service-files if not deleted
Browse files Browse the repository at this point in the history
  • Loading branch information
oysteoh committed Nov 18, 2021
1 parent 024da43 commit e2a8371
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
22 changes: 22 additions & 0 deletions ert_shared/services/_base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import threading
import json
import time
import atexit
import signal

from select import select, PIPE_BUF
from subprocess import Popen, TimeoutExpired
Expand All @@ -22,6 +24,7 @@
TypeVar,
Union,
TYPE_CHECKING,
Set,
)

if TYPE_CHECKING:
Expand All @@ -32,6 +35,21 @@
ConnInfo = Union[Mapping[str, Any], Exception, None]


SERVICE_NAMES: Set[str] = set()


@atexit.register
def cleanup_service_files():
for service_name in SERVICE_NAMES:
file = Path(f"{service_name}_server.json")
if file.exists():
file.unlink()


signal.signal(signal.SIGTERM, cleanup_service_files)
signal.signal(signal.SIGINT, cleanup_service_files)


def local_exec_args(script_args: Union[str, List[str]]) -> List[str]:
"""
Convenience function that returns the exec_args for executing a Python
Expand Down Expand Up @@ -94,6 +112,10 @@ def __init__(

env = os.environ.copy()
env["ERT_COMM_FD"] = str(fd_write)

global SERVICE_NAMES
SERVICE_NAMES.add(self._service_name)

self._proc = Popen(
self._exec_args,
pass_fds=(fd_write,),
Expand Down
23 changes: 23 additions & 0 deletions tests/ert_tests/services/test_base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
ServerBootFail,
BaseService,
local_exec_args,
cleanup_service_files,
SERVICE_NAMES,
)
import time

Expand Down Expand Up @@ -301,3 +303,24 @@ def test_local_exec_args_multi():
assert exec_args[0] == sys.executable
assert exec_args[2] == "foo"
assert exec_args[3] == "-bar"


def test_cleanup_service_files(tmpdir):
storage_service_name = "storage"
storage_service_file = f"{storage_service_name}_server.json"
with open(storage_service_file, "w") as f:
f.write("storage_service info")
assert Path(storage_service_file).exists()
SERVICE_NAMES.add(storage_service_name)

webviz_service_name = "webviz-ert"
webviz_service_file = f"{webviz_service_name}_server.json"
with open(webviz_service_file, "w") as f:
f.write("webviz-ert info")
assert Path(webviz_service_file).exists()
SERVICE_NAMES.add(webviz_service_name)

cleanup_service_files()

assert not Path(storage_service_file).exists()
assert not Path(webviz_service_file).exists()

0 comments on commit e2a8371

Please sign in to comment.