shivaam commented on code in PR #65958:
URL: https://github.com/apache/airflow/pull/65958#discussion_r3293662574


##########
task-sdk/src/airflow/sdk/execution_time/coordinator.py:
##########
@@ -0,0 +1,227 @@
+#
+# 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.
+"""
+Runtime coordinator for non-Python DAG file processing and task execution.
+
+Provides :class:`BaseCoordinator`, the base class for
+SDK-specific coordinators that bridge subprocess I/O between the
+Airflow supervisor and an external-SDK runtime (Java, Go, Rust, etc.),
+and :class:`CoordinatorManager`, the registry that loads coordinator
+instances from the ``[sdk] coordinators`` configuration.
+
+The coordinator's :meth:`~BaseCoordinator.run_task_execution` handles the full
+lifecycle:
+
+1. Creates TCP servers for comm and logs channels, and a socketpair for stderr.
+2. Calls :meth:`~BaseCoordinator.task_execution_cmd` (provided by the subclass)
+   to obtain the subprocess command.
+3. Spawns the subprocess and accepts TCP connections from it.
+4. Runs a selector-based bridge that transparently forwards bytes
+   between fd 0 (supervisor) and the subprocess comm socket, and
+   re-emits the subprocess's log and stderr output through structlog.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+from typing import TYPE_CHECKING, Any
+
+import attrs
+import pydantic
+
+from airflow.sdk._shared.module_loading import import_string
+from airflow.sdk.configuration import conf
+
+if TYPE_CHECKING:
+    from collections.abc import Mapping
+    from os import PathLike
+
+    from structlog.typing import FilteringBoundLogger
+    from typing_extensions import Self
+
+    from airflow.sdk.api.client import Client
+    from airflow.sdk.execution_time.workloads.task import TaskInstanceDTO
+
+__all__ = [
+    "BaseCoordinator",
+    "CoordinatorManager",
+    "get_coordinator_manager",
+    "reset_coordinator_manager",
+]
+
+
+class BaseCoordinator:
+    """
+    Base coordinator for runtime-specific DAG file processing and task 
execution.
+
+    Coordinators are instantiated from the ``[sdk] coordinators`` configuration
+    (see :class:`CoordinatorManager`) — each entry's ``classpath`` is resolved
+    via :func:`~airflow.sdk._shared.module_loading.import_string` and
+    constructed with the entry's ``kwargs``.
+    """
+
+    @attrs.define(slots=True)
+    class ExecutionResult:
+        """Return value for :meth:`BaseCoordinator.execute_task`."""
+
+        exit_code: Any
+        final_state: str
+
+    def execute_task(
+        self,
+        *,
+        what: TaskInstanceDTO,
+        dag_rel_path: str | PathLike[str],
+        bundle_info,
+        client: Client,
+        logger: FilteringBoundLogger | None = None,
+        sentry_integration: str = "",
+        subprocess_logs_to_stdout: bool,
+        **kwargs,
+    ) -> ExecutionResult:
+        """
+        Start task execution.
+
+        This should execute the task and return a result.
+        """
+        raise NotImplementedError
+
+
+class _CoordinatorSpec(pydantic.BaseModel):
+    classpath: str
+    kwargs: dict[str, Any]
+
+
+class _PythonCoordinator(BaseCoordinator):
+    """
+    Coordinator implementation to execute Python tasks.
+
+    This is not supposed to be specified by users directly, but the fallback
+    used by default when nothing is specified.
+    """
+
+    def execute_task(
+        self,
+        *,
+        what: TaskInstanceDTO,
+        dag_rel_path: str | PathLike[str],
+        bundle_info,
+        client: Client,
+        logger: FilteringBoundLogger | None = None,
+        sentry_integration: str = "",
+        subprocess_logs_to_stdout: bool,
+        **kwargs,
+    ) -> BaseCoordinator.ExecutionResult:
+        # TODO: Move this to somewhere that makes more sense.
+        from airflow.sdk.execution_time.supervisor import ActivitySubprocess
+
+        process = ActivitySubprocess.start(
+            dag_rel_path=dag_rel_path,
+            what=what,
+            client=client,
+            logger=logger,
+            bundle_info=bundle_info,
+            subprocess_logs_to_stdout=subprocess_logs_to_stdout,
+            sentry_integration=sentry_integration,
+        )
+        exit_code = process.wait()
+        return self.ExecutionResult(exit_code, process.final_state)
+
+
[email protected]
+def _build_python_coordinator() -> _PythonCoordinator:
+    return _PythonCoordinator()
+
+
[email protected](kw_only=True)
+class CoordinatorManager:
+    """
+    Registry of coordinator instances loaded from ``[sdk]`` configurations.
+
+    The ``[sdk] coordinators`` value is a JSON object keyed by coordinator 
name::
+
+        {
+            "jdk-11": {
+                "classpath": "airflow.sdk.coordinators.java.JavaCoordinator",
+                "kwargs": {"java_executable": "/usr/lib/jvm/jdk-11/bin/java", 
...},
+            }
+        }
+
+    The ``classpath`` is resolved via
+    :func:`~airflow.sdk._shared.module_loading.import_string` (no
+    :class:`ProvidersManager` involvement) and constructed with ``kwargs`` on
+    first use. A coordinator entry that is never looked up incurs no startup
+    cost. At most one coordinator object can be created from each entry.
+
+    The ``[sdk] queue_to_coordinator`` config maps queue names to a key in the
+    object, which lets users reuse existing queue assignments to route tasks to
+    a specific coordinator instance (for example, a ``"legacy-java"`` queue
+    routed to a JDK 11 coordinator, and a ``"modern-java"`` queue routed to a
+    JDK 17 coordinator).
+
+    :meta private:
+    """
+
+    _coordinator_specs: Mapping[str, _CoordinatorSpec]
+    _queue_to_coordinator: Mapping[str, str]
+
+    _created_coordinators: dict[str, BaseCoordinator] = 
attrs.field(init=False, factory=dict)
+
+    @classmethod
+    def from_config(cls) -> Self:
+        """Load coordinator specs from configuration without initialization."""
+        coordinator_specs = {
+            k: _CoordinatorSpec.model_validate(v)
+            for k, v in conf.getjson("sdk", "coordinators", 
fallback={}).items()
+        }
+        queue_to_coordinator = conf.getjson("sdk", "queue_to_coordinator", 
fallback={})
+        for key in queue_to_coordinator.values():
+            if key not in coordinator_specs:
+                raise ValueError(f"[sdk] queue_to_coordinator references 
invalid coordinator key: {key!r}")
+        return cls(coordinator_specs=coordinator_specs, 
queue_to_coordinator=queue_to_coordinator)
+
+    def _for_queue_internal(self, queue: str) -> BaseCoordinator:
+        key = self._queue_to_coordinator[queue]
+        with contextlib.suppress(KeyError):
+            return self._created_coordinators[key]
+        spec = self._coordinator_specs[key]
+        coordinator = self._created_coordinators[key] = 
import_string(spec.classpath)(**spec.kwargs)
+        return coordinator
+
+    def for_queue(self, queue: str) -> BaseCoordinator:
+        """
+        Find the coordinator for *queue*.
+
+        If an entry is not registered, a Python coordinator is returned.
+        """
+        try:
+            return self._for_queue_internal(queue)
+        except KeyError:
+            return _build_python_coordinator()

Review Comment:
   Worth a DEBUG log on the fall through? If queue_to_coordinator has a typo, 
the task silently runs as Python with no hint.
   



##########
task-sdk/src/airflow/sdk/coordinators/java/coordinator.py:
##########
@@ -0,0 +1,261 @@
+#
+# 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.
+"""Java runtime coordinator that launches a JVM subprocess for Dag file 
processing and task execution."""
+
+from __future__ import annotations
+
+import email
+import os
+import pathlib
+import selectors
+import socket
+import subprocess
+import time
+import zipfile
+from typing import TYPE_CHECKING, cast
+
+import attrs
+import psutil
+import structlog
+
+from airflow.sdk.execution_time.coordinator import BaseCoordinator
+from airflow.sdk.execution_time.supervisor import ActivitySubprocess
+
+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
+
+log: FilteringBoundLogger = 
structlog.get_logger(logger_name="coordinators.java")
+
+
+def _start_server() -> socket.socket:

Review Comment:
   The `_start_server`, `_accept_connections`, the `stdout/stderr` socketpair 
setup isn't actually JVM-specific. Would it make sense to move just the generic 
helpers into BaseCoordinator? Each coordinator would still work the same way, 
just without re-implementing the same plumbing per language. 



-- 
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]

Reply via email to