8000 Use PidfdChildWatcher by default when available (#87951) · home-assistant/core@d1e1734 · GitHub
[go: up one dir, main page]

Skip to content

Commit d1e1734

Browse files
authored
Use PidfdChildWatcher by default when available (#87951)
This is a backport from cpython 3.12 https://docs.python.org/3/library/asyncio-policy.html > PidfdChildWatcher is a “Goldilocks” child watcher implementation. It doesn’t require signals or threads, doesn’t interfere with any processes launched outside the event loop, and scales linearly with the number of subprocesses launched by the event loop. The main disadvantage is that pidfds are specific to Linux, and only work on recent (5.3+) kernels. python/cpython#98024 There are some additional fixes in cpython 3.12 in python/cpython#94184 when there is no event loop running in the main thread but this is not a problem we have
1 parent 71b67e2 commit d1e1734

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

homeassistant/runner.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
from __future__ import annotations
33

44
import asyncio
5+
from asyncio import events
56
import dataclasses
67
import logging
8+
import os
79
import threading
810
import traceback
911
from typing import Any
@@ -49,13 +51,46 @@ class RuntimeConfig:
4951
open_ui: bool = False
5052

5153

54+
def can_use_pidfd() -> bool:
55+
"""Check if pidfd_open is available.
56+
57+
Back ported from cpython 3.12
58+
"""
59+
if not hasattr(os, "pidfd_open"):
60+
return False
61+
try:
62+
pid = os.getpid()
63+
os.close(os.pidfd_open(pid, 0)) # pylint: disable=no-member
64+
except OSError:
65+
# blocked by security policy like SECCOMP
66+
return False
67+
return True
68+
69+
5270
class HassEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
5371
"""Event loop policy for Home Assistant."""
5472

5573
def __init__(self, debug: bool) -> None:
5674
"""Init the event loop policy."""
5775
super().__init__()
5876
self.debug = debug
77+
self._watcher: asyncio.AbstractChildWatcher | None = None
78+
79+
def _init_watcher(self) -> None:
80+
"""Initialize the watcher for child processes.
81+
82+
Back ported from cpython 3.12
83+
"""
84+
with events._lock: # type: ignore[attr-defined] # pylint: disable=protected-access
85+
if self._watcher is None: # pragma: no branch
86+
if can_use_pidfd():
87+
self._watcher = asyncio.PidfdChildWatcher()
88+
else:
89+
self._watcher = asyncio.ThreadedChildWatcher()
90+
if threading.current_thread() is threading.main_thread():
91+
self._watcher.attach_loop(
92+
self._local._loop # type: ignore[attr-defined] # pylint: disable=protected-access
93+
)
5994

6095
@property
6196
def loop_name(self) -> str:

0 commit comments

Comments
 (0)
0