uranusjr commented on code in PR #65958: URL: https://github.com/apache/airflow/pull/65958#discussion_r3309889132
########## task-sdk/src/airflow/sdk/coordinators/java/coordinator.py: ########## @@ -0,0 +1,369 @@ +# +# 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 itertools +import os +import pathlib +import selectors +import socket +import subprocess +import time +import zipfile +from typing import TYPE_CHECKING, TypeVar, cast + +import attrs +import structlog + +from airflow.sdk.execution_time.coordinator import BaseCoordinator +from airflow.sdk.execution_time.schema import get_schema_version_migrator +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 + + Tracked = TypeVar("Tracked", socket.socket, subprocess.Popen) + +log: FilteringBoundLogger = structlog.get_logger(logger_name="coordinators.java") + + +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 _calculate_classpath(jars_root: Sequence[pathlib.Path]) -> str: + jars = (p.as_posix() for root in jars_root for p in root.iterdir() if p.suffix == ".jar") + return os.pathsep.join(jars) + + [email protected] +class _JarMetadata: + main_class: str + schema_version: str + + @classmethod + def from_jar(cls, path: pathlib.Path) -> Self | None: + try: + with zipfile.ZipFile(path) as zf: + try: + manifest_info = zf.getinfo("META-INF/MANIFEST.MF") + except KeyError: + log.debug("JAR does not contain META-INF/MANIFEST.MF; ignored", path=path) + return None + with zf.open(manifest_info) as f: + manifest = email.message_from_binary_file(f) + return cls(manifest["Main-Class"], manifest["Airflow-Supervisor-Schema-Version"]) + except zipfile.BadZipFile: + log.exception("Cannot read JAR; ignored", path=path) + return None + + +def _validate_schema_version(instance, _, value) -> str: + return get_schema_version_migrator().resolve_version(str(value)) + + [email protected] +class _JarInfo: + main_class: str + schema_version: str = attrs.field(validator=_validate_schema_version) + + @attrs.define + class _Progress: + main_class: str | None = attrs.field(init=False, default=None) + schema_version: str | None = attrs.field(init=False, default=None) + + def collect(self) -> _JarInfo | None: + if self.main_class is None or self.schema_version is None: + return None + return _JarInfo(self.main_class, self.schema_version) + + @classmethod + def find(cls, roots: Sequence[pathlib.Path], main_class: str) -> _JarInfo: + progress = cls._Progress() + for root in roots: + log.debug("Finding required JAR metadata in directory", dir=root) + for p in root.iterdir(): + if p.suffix != ".jar": + continue + if (metadata := _JarMetadata.from_jar(p)) is None: + continue + if metadata.main_class and ((main_class == metadata.main_class) or not main_class): + log.debug("JAR located with Main-Class metadata", path=p, main_class=metadata.main_class) + progress.main_class = metadata.main_class + if metadata.schema_version: + log.debug( + "JAR located with Airflow-Supervisor-Schema-Version metadata", + path=p, + schema_version=metadata.schema_version, + ) + progress.schema_version = metadata.schema_version + if (result := progress.collect()) is not None: + return result + if progress.main_class is not None: + tp = "cannot find a JAR with Airflow-Supervisor-Schema-Version metadata in {1}" + elif main_class: + tp = "cannot find a JAR with Main-Class matching {0!r} in {1}" + else: + tp = "cannot find a JAR with Main-Class metadata in {1}" + raise FileNotFoundError(tp.format(main_class, os.pathsep.join(os.fspath(p.resolve()) for p in roots))) + + +def _accept_connections( + servers: dict[str, socket.socket], + drains: dict[str, socket.socket], + proc: subprocess.Popen, + *, + max_wait: float = 10.0, Review Comment: Added -- 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]
