blob: 47f07368d7b224162adc72d76c3a4972ab753e49 [file]
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import asyncio
import contextlib
import errno
import os
import pathlib
import socket
import stat
from collections.abc import Awaitable
from typing import Callable
from shared import session
# TODO(https://fxbug.dev/591766314): Remove rollback wait_closed timeout once
# daemon lifecycle uses a per-session lockfile and structured shutdown.
_BIND_ROLLBACK_WAIT_CLOSED_TIMEOUT_S = 0.5
async def bind_daemon_unix_server(
client_connected_cb: Callable[
[asyncio.StreamReader, asyncio.StreamWriter], Awaitable[None]
],
socket_path: pathlib.Path,
session_id: str | None,
) -> tuple[asyncio.AbstractServer, pathlib.Path, tuple[int, int]]:
"""Binds a daemon Unix domain socket server and returns its server, path, and (dev, ino)."""
sock_ctx: contextlib.AbstractContextManager[pathlib.Path]
if session_id is not None:
sock_ctx = session.prepare_session_socket(session_id)
else:
try:
stale_st = os.lstat(socket_path)
except FileNotFoundError:
stale_st = None
if stale_st is not None and (
stat.S_ISLNK(stale_st.st_mode) or not stat.S_ISDIR(stale_st.st_mode)
):
if session.is_unix_socket_live(socket_path):
raise FileExistsError(
errno.EADDRINUSE,
"Active daemon socket already bound",
str(socket_path),
)
socket_path.unlink(missing_ok=True)
sock_ctx = contextlib.nullcontext(socket_path)
with sock_ctx as bound_path:
sock_path = bound_path
srv_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_id: tuple[int, int] | None = None
try:
srv_sock.bind(os.fspath(sock_path))
st = os.lstat(sock_path)
socket_id = (st.st_dev, st.st_ino)
os.chmod(sock_path, 0o600)
srv_sock.listen()
except BaseException:
if session_id is None and socket_id is not None:
try:
cleanup_daemon_socket(sock_path, socket_id, session_id=None)
except OSError:
pass
srv_sock.close()
raise
server: asyncio.AbstractServer | None = None
try:
server = await asyncio.start_unix_server(
client_connected_cb,
path=None,
sock=srv_sock,
start_serving=False,
cleanup_socket=False,
)
await server.start_serving()
except BaseException:
try:
cleanup_daemon_socket(sock_path, socket_id, session_id=session_id)
except (OSError, ValueError):
pass
if server is not None:
server.close()
if hasattr(server, "abort_clients"):
server.abort_clients()
try:
await asyncio.wait_for(
server.wait_closed(),
timeout=_BIND_ROLLBACK_WAIT_CLOSED_TIMEOUT_S,
)
except Exception:
pass
else:
srv_sock.close()
raise
return server, sock_path, socket_id
def cleanup_daemon_socket(
socket_path: pathlib.Path,
socket_id: tuple[int, int] | None,
session_id: str | None,
) -> None:
"""Unlinks socket_path when its (dev, ino) matches socket_id and removes empty session dirs."""
if socket_id is None:
return
with contextlib.ExitStack() as stack:
if session_id is not None:
build_runtime_dir = session.get_build_dir_runtime_dir()
if os.path.islink(str(build_runtime_dir)):
return
if os.path.isdir(str(build_runtime_dir)):
try:
stack.enter_context(session.runtime_lock(build_runtime_dir))
except (FileNotFoundError, NotADirectoryError):
return
except OSError as err:
if err.errno in (errno.ELOOP, errno.ENAMETOOLONG):
return
raise
if os.path.islink(str(socket_path.parent)):
return
try:
st = os.lstat(socket_path)
except (FileNotFoundError, NotADirectoryError):
pass
except OSError as err:
if err.errno in (errno.ELOOP, errno.ENAMETOOLONG):
return
raise
else:
if (st.st_dev, st.st_ino) != socket_id:
return
socket_path.unlink(missing_ok=True)
if session_id is not None:
session.cleanup_session_dir(socket_path)