|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START composer_beam_pipe_deadlock_fix] |
| 16 | +"""Workaround for Apache Beam subprocess pipe deadlock in Cloud Composer. |
| 17 | +
|
| 18 | +When the JVM prints a JAVA_TOOL_OPTIONS startup message to stderr and a Beam |
| 19 | +command writes more than 64 KB to stdout, the Apache Beam provider can deadlock |
| 20 | +while reading the two pipes separately. This plugin replaces run_beam_command |
| 21 | +with a version that merges stderr into stdout so one reader drains both streams. |
| 22 | +
|
| 23 | +Install: |
| 24 | + Upload this file to the plugins/ folder in your environment's Cloud Storage |
| 25 | + bucket. |
| 26 | +
|
| 27 | +Side effect: |
| 28 | + Beam subprocess stderr lines appear in task logs at INFO level instead of |
| 29 | + WARNING. |
| 30 | +
|
| 31 | +Cleanup: |
| 32 | + Delete this file after upgrading to a Cloud Composer version that includes |
| 33 | + the upstream fix in apache-airflow-providers-apache-beam. |
| 34 | +""" |
| 35 | + |
| 36 | +from __future__ import annotations |
| 37 | + |
| 38 | +import shlex |
| 39 | +import subprocess |
| 40 | +from typing import Callable |
| 41 | + |
| 42 | +import logging |
| 43 | + |
| 44 | +# Airflow 3.1+ provides AirflowPlugin through the Task SDK; Airflow 2.5 to 3.0 |
| 45 | +# provides it through airflow.plugins_manager. |
| 46 | +try: |
| 47 | + from airflow.sdk.plugins_manager import AirflowPlugin |
| 48 | +except ImportError: |
| 49 | + from airflow.plugins_manager import AirflowPlugin |
| 50 | + |
| 51 | + |
| 52 | +def _patched_run_beam_command( |
| 53 | + cmd: list[str], |
| 54 | + log: logging.Logger, |
| 55 | + process_line_callback: Callable[[str], None] | None = None, |
| 56 | + working_directory: str | None = None, |
| 57 | + is_dataflow_job_id_exist_callback: Callable[[], bool] | None = None, |
| 58 | + check_job_id_by_name_callback: Callable[[], bool] | None = None, |
| 59 | + *, |
| 60 | + check_job_status_callback: Callable[[], bool | None] | None = None, |
| 61 | + **_kwargs: object, |
| 62 | +) -> None: |
| 63 | + # Import from the Beam hook module so the raised exception matches the |
| 64 | + # installed provider on both Airflow 2 and Airflow 3. |
| 65 | + from airflow.providers.apache.beam.hooks.beam import AirflowException |
| 66 | + |
| 67 | + # Support early exit across provider versions: 5.5-6.0 uses |
| 68 | + # check_job_status_callback; 6.0.1+ uses is_dataflow_job_id_exist_callback. |
| 69 | + stop_callback = is_dataflow_job_id_exist_callback or check_job_status_callback |
| 70 | + |
| 71 | + log.info("Running command: %s", " ".join(shlex.quote(c) for c in cmd)) |
| 72 | + # Merge stderr into stdout so a single reader drains all subprocess output. |
| 73 | + proc = subprocess.Popen( |
| 74 | + cmd, |
| 75 | + cwd=working_directory, |
| 76 | + shell=False, |
| 77 | + stdout=subprocess.PIPE, |
| 78 | + stderr=subprocess.STDOUT, |
| 79 | + close_fds=True, |
| 80 | + ) |
| 81 | + log.info("Start waiting for Apache Beam process to complete.") |
| 82 | + |
| 83 | + # Close only the pipe in finally. Streaming and deferrable jobs require an |
| 84 | + # early return once stop_callback succeeds, so proc.wait() runs only after EOF. |
| 85 | + try: |
| 86 | + if proc.stdout is not None: |
| 87 | + for raw_line in iter(proc.stdout.readline, b""): |
| 88 | + line = raw_line.decode("utf-8", errors="replace") |
| 89 | + if process_line_callback: |
| 90 | + process_line_callback(line) |
| 91 | + log.info("%s", line.rstrip("\r\n")) |
| 92 | + if stop_callback and stop_callback(): |
| 93 | + return |
| 94 | + finally: |
| 95 | + if proc.stdout is not None: |
| 96 | + proc.stdout.close() |
| 97 | + |
| 98 | + proc.wait() |
| 99 | + log.info("Process exited with return code: %s", proc.returncode) |
| 100 | + if proc.returncode != 0: |
| 101 | + raise AirflowException( |
| 102 | + f"Apache Beam process failed with return code {proc.returncode}" |
| 103 | + ) |
| 104 | + |
| 105 | + # Preserve provider 6.3.2+ fallback for pipelines that disable job ID logs. |
| 106 | + if check_job_id_by_name_callback and not (stop_callback and stop_callback()): |
| 107 | + check_job_id_by_name_callback() |
| 108 | + |
| 109 | + |
| 110 | +class BeamPipeDeadlockFixPlugin(AirflowPlugin): |
| 111 | + """Registers the patched Beam command runner when Airflow loads plugins.""" |
| 112 | + |
| 113 | + name = "beam_pipe_deadlock_fix" |
| 114 | + |
| 115 | + @classmethod |
| 116 | + def on_load(cls, *args, **kwargs) -> None: |
| 117 | + # Airflow calls on_load once per process before running tasks. |
| 118 | + try: |
| 119 | + import airflow.providers.apache.beam.hooks.beam as beam_hook_mod |
| 120 | + except ImportError: |
| 121 | + return |
| 122 | + beam_hook_mod.run_beam_command = _patched_run_beam_command |
| 123 | + |
| 124 | + |
| 125 | +# [END composer_beam_pipe_deadlock_fix] |
0 commit comments