First iteration fix socket activation

This commit is contained in:
2025-12-03 22:37:16 +01:00
parent a860d809d1
commit 94b1730c24

View File

@@ -1127,47 +1127,19 @@ class PromptServer():
await call_on_start() await call_on_start()
def _get_systemd_sockets(self) -> List[socket.socket]: def _get_systemd_sockets(self) -> List[socket.socket]:
""" sockets = []
Detect systemd socket activation and return a list of readytouse
``socket.socket`` objects.
The function follows the systemd protocol:
* `LISTEN_FDS` tells how many file descriptors have been passed.
* `LISTEN_PID` must match ``os.getpid()``.
* File descriptors start at 3.
* After we have consumed them we *unset* the environment variables so
that any child processes dont accidentally try to reuse the same
fds.
"""
sockets: List[socket.socket] = []
if "LISTEN_FDS" not in os.environ or "LISTEN_PID" not in os.environ: if "LISTEN_FDS" not in os.environ or "LISTEN_PID" not in os.environ:
return sockets return sockets
try:
listen_fds = int(os.getenv("LISTEN_FDS", "0")) listen_fds = int(os.getenv("LISTEN_FDS", "0"))
listen_pid = int(os.getenv("LISTEN_PID", "0")) listen_pid = int(os.getenv("LISTEN_PID", "0"))
except ValueError:
logging.error("Invalid LISTEN_FDS/LISTEN_PID values")
return sockets
if listen_pid != os.getpid(): if listen_pid != os.getpid():
# The activation was meant for a *different* process (e.g. a
# parent that forked before exec). Ignore it.
return sockets return sockets
for i in range(listen_fds): for i in range(listen_fds):
fd = 3 + i fd = 3 + i
try: try:
sock = _fd_to_socket(fd) sockets.append(_fd_to_socket(fd))
sockets.append(sock) except Exception as e:
logging.debug(f"systemd socket #{i} fd {fd} family {sock.family} " logging.error(f"Failed to convert fd {fd}: {e}")
f"type {sock.type} proto {sock.proto}")
except OSError as exc:
logging.error(f"Failed to convert fd {fd} into a socket: {exc}")
# Remove the activation envvars child processes will otherwise think
# they have been passed sockets as well.
os.unsetenv("LISTEN_FDS") os.unsetenv("LISTEN_FDS")
os.unsetenv("LISTEN_PID") os.unsetenv("LISTEN_PID")
return sockets return sockets