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

Kill subprocess on main thread shutting down #3120

Open
wants to merge 5 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
2 changes: 1 addition & 1 deletion nvflare/app_common/launchers/subprocess_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _start_external_process(self, fl_ctx: FLContext):
self._process = subprocess.Popen(
command_seq, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self._app_dir, env=env
)
self._log_thread = Thread(target=log_subprocess_output, args=(self._process, self.logger))
self._log_thread = Thread(target=log_subprocess_output, args=(self._process, self.logger), daemon=True)
self._log_thread.start()

def _stop_external_process(self):
Expand Down
28 changes: 27 additions & 1 deletion nvflare/client/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@

import logging
import os
import signal
import threading
import time
from enum import Enum
from threading import Thread
from typing import Any, Dict, Optional

from nvflare.apis.analytix import AnalyticsDataType
Expand All @@ -24,6 +28,8 @@
from .api_spec import CLIENT_API_KEY, CLIENT_API_TYPE_KEY, APISpec
from .ex_process.api import ExProcessClientAPI

logger = logging.getLogger(__name__)


class ClientAPIType(Enum):
IN_PROCESS_API = "IN_PROCESS_API"
Expand All @@ -34,6 +40,23 @@ class ClientAPIType(Enum):
data_bus = DataBus()


def death_watch():
"""
Python's main thread doesn't die if there are running thread pools.
This function kills the process when the main thread is in the shutdown process
"""
try:
while True:
if threading._SHUTTING_DOWN:
os.kill(os.getpid(), signal.SIGKILL)
# Just in case kill doesn't work
logger.error(f"Process {os.getpid()} is killed but still running")
break
time.sleep(1)
except Exception as ex:
logger.warning(f"Death watch failed with error: {ex}")


def init(rank: Optional[str] = None):
"""Initializes NVFlare Client API environment.

Expand All @@ -44,6 +67,9 @@ def init(rank: Optional[str] = None):
Returns:
None
"""

Thread(target=death_watch, name="death_watch", daemon=False).start()

api_type_name = os.environ.get(CLIENT_API_TYPE_KEY, ClientAPIType.IN_PROCESS_API.value)
api_type = ClientAPIType(api_type_name)
global client_api
Expand All @@ -54,7 +80,7 @@ def init(rank: Optional[str] = None):
client_api = ExProcessClientAPI()
client_api.init(rank=rank)
else:
logging.warning("Warning: called init() more than once. The subsequence calls are ignored")
logger.warning("Warning: called init() more than once. The subsequence calls are ignored")


def receive(timeout: Optional[float] = None) -> Optional[FLModel]:
Expand Down
Loading