Skip to content

feat(multiprocess): restart child processes if they are not alive #1550

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

Merged
merged 5 commits into from
Jul 9, 2024
Merged
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
31 changes: 30 additions & 1 deletion faststream/cli/supervisors/multiprocess.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import signal
from typing import TYPE_CHECKING, Any, List, Tuple

from faststream.cli.supervisors.basereload import BaseReload
Expand All @@ -17,8 +18,9 @@ def __init__(
target: "DecoratedCallable",
args: Tuple[Any, ...],
workers: int,
reload_delay: float = 0.5,
) -> None:
super().__init__(target, args, None)
super().__init__(target, args, reload_delay)

self.workers = workers
self.processes: List[SpawnProcess] = []
Expand All @@ -38,3 +40,30 @@ def shutdown(self) -> None:
process.join()

logger.info(f"Stopping parent process [{self.pid}]")

def restart(self) -> None:
active_processes = []

for process in self.processes:
if process.is_alive():
active_processes.append(process)
continue

pid = process.pid
exitcode = process.exitcode

log_msg = "Worker (pid:%s) exited with code %s."
if exitcode and abs(exitcode) == signal.SIGKILL:
log_msg += " Perhaps out of memory?"
logger.error(log_msg, pid, exitcode)

process.kill()

new_process = self._start_process()
logger.info(f"Started child process [{new_process.pid}]")
active_processes.append(new_process)

self.processes = active_processes

def should_restart(self) -> bool:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably we can use smth like not all((p.is_alive() for p in process))? It looks much explicit for me

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, it looks better. Fixed

return not all(p.is_alive() for p in self.processes)
Loading