uranusjr commented on code in PR #67635: URL: https://github.com/apache/airflow/pull/67635#discussion_r3324849793
########## task-sdk/src/airflow/sdk/coordinators/socket/coordinator.py: ########## @@ -0,0 +1,323 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Common socket-based subprocess coordinator scaffolding. + +Coordinators that launch a subprocess and communicate with it over two TCP +sockets (``--comm`` and ``--logs``) — Java, native executables, and any +future runtime that follows the same wire convention — can subclass +:class:`SocketCoordinator` and reuse the resource-tracking, accept, and +draining machinery in this module rather than re-implementing it. +""" + +from __future__ import annotations + +import itertools +import os +import selectors +import signal +import socket +import subprocess +import time +from typing import TYPE_CHECKING, TypeVar, cast + +import attrs +import structlog + +from airflow.sdk.execution_time.coordinator import BaseCoordinator +from airflow.sdk.execution_time.supervisor import ActivitySubprocess, NeverRaised, ProcessTracker + +if TYPE_CHECKING: + from collections.abc import Sequence + + from structlog.typing import FilteringBoundLogger + from typing_extensions import Self + + from airflow.sdk.api.client import Client + from airflow.sdk.api.datamodels._generated import BundleInfo + from airflow.sdk.execution_time.workloads.task import TaskInstanceDTO + + Tracked = TypeVar("Tracked", socket.socket, subprocess.Popen) + +log: FilteringBoundLogger = structlog.get_logger(logger_name="coordinators.socket") + + +def _start_server() -> socket.socket: + server = socket.socket() + server.bind(("127.0.0.1", 0)) + server.setblocking(True) + server.listen(1) # Just need to listen to the child process. + return server + + +def _accept_connections( + servers: dict[str, socket.socket], + drains: dict[str, socket.socket], + proc: subprocess.Popen, + *, + max_wait: float = 10.0, + drain_size: int = 4096, +) -> tuple[dict[socket.socket, socket.socket], dict[socket.socket, bytes]]: + """Block until the subprocess connects to servers, draining stdout/stderr along the way.""" + accepted: dict[socket.socket, socket.socket] = {} + drained: dict[socket.socket, bytes] = {s: b"" for s in drains.values()} + with selectors.DefaultSelector() as sel: + for key, soc in itertools.chain(servers.items(), drains.items()): + sel.register(soc, selectors.EVENT_READ, data=key) + deadline = time.monotonic() + max_wait + while len(accepted) < len(servers): + remaining = deadline - time.monotonic() + if remaining <= 0: + for s in accepted.values(): + s.close() + raise TimeoutError("process did not connect within timeout") + if proc.poll() is not None: + for s in accepted.values(): + s.close() + raise RuntimeError(f"process exited with {proc.returncode} before connecting") + for event, _ in sel.select(timeout=min(remaining, 1.0)): + soc = cast("socket.socket", event.fileobj) + if soc in drained: + if incoming := soc.recv(drain_size): + log.debug("Draining child process stream", key=event.data) + drained[soc] += incoming + else: + log.warning("Child stream closed before ready!", key=event.data) + sel.unregister(soc) + else: + log.debug("Accepting child process connection", key=event.data) + conn, _ = soc.accept() + sel.unregister(soc) + accepted[soc] = conn + return accepted, drained + + +class PopenTracker(ProcessTracker): + """ + Process tracker backed by :class:`subprocess.Popen`. + + :meta private: + """ + + ProcessNotFound = NeverRaised + TimeoutExpired = subprocess.TimeoutExpired + + def __init__(self, impl: subprocess.Popen) -> None: + self._impl = impl + + @property + def pid(self) -> int: + return self._impl.pid + + def send_signal(self, s: signal.Signals) -> None: + self._impl.send_signal(s) + + def wait(self, timeout: float | None) -> int: + return self._impl.wait(timeout) + + [email protected](kw_only=True) +class _ResourceTracker: + """ + Context manager that auto-closes tracked sockets and terminates tracked Popen objects. + + A subprocess startup is built up incrementally: bind sockets, spawn the + child, accept its connections. If any step fails, the half-set-up state + must be released. Calling :meth:`track` after each successful step records + what to release; :meth:`untrack` removes ownership once another component + (e.g. the activity subprocess instance) has taken over. + """ + + timeout: float + tracked: dict[int, socket.socket | subprocess.Popen] = attrs.field(init=False, factory=dict) + + def __enter__(self): + return self + + def __exit__(self, *exc_info): + for o in self.tracked.values(): + match o: + case socket.socket(): + o.close() + case subprocess.Popen(): + o.terminate() + try: + o.wait(self.timeout) + except subprocess.TimeoutExpired: + o.kill() + + def track(self, *objects: Tracked) -> tuple[Tracked, ...]: + self.tracked.update((id(o), o) for o in objects) + return objects + + def untrack(self, *objects: Tracked) -> tuple[Tracked, ...]: + for o in objects: + self.tracked.pop(id(o), None) + return objects + + [email protected](kw_only=True) +class _SocketActivitySubprocess(ActivitySubprocess): Review Comment: This is a misnomer since it not only assumes _TCP_ sockets (not just “sockets” in general) but also a subprocess being used. It should likely be named after either the subprocess aspect instead. (The TCP aspect is not important to subclasses; the subprocess is more so.) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
