Skip to content

Commit 79be507

Browse files
committed
fix(composer): add beam_pipe_deadlock_fix
1 parent e656254 commit 79be507

1 file changed

Lines changed: 123 additions & 0 deletions

File tree

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
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. You do not need to restart the environment.
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 logging
39+
import shlex
40+
import subprocess
41+
from typing import Callable
42+
43+
# Airflow 3.1+ provides AirflowPlugin through the Task SDK; Airflow 2.5 to 3.0
44+
# provides it through airflow.plugins_manager.
45+
try:
46+
from airflow.sdk.plugins_manager import AirflowPlugin
47+
except ImportError:
48+
from airflow.plugins_manager import AirflowPlugin
49+
50+
51+
def _patched_run_beam_command(
52+
cmd: list[str],
53+
log: logging.Logger,
54+
process_line_callback: Callable[[str], None] | None = None,
55+
working_directory: str | None = None,
56+
is_dataflow_job_id_exist_callback: Callable[[], bool] | None = None,
57+
check_job_id_by_name_callback: Callable[[], bool] | None = None,
58+
*,
59+
check_job_status_callback: Callable[[], bool | None] | None = None,
60+
**_kwargs: object,
61+
) -> None:
62+
# Import from the Beam hook module so the raised exception matches the
63+
# installed provider on both Airflow 2 and Airflow 3.
64+
from airflow.providers.apache.beam.hooks.beam import AirflowException
65+
66+
# Support early exit across provider versions: 5.5-6.0 uses
67+
# check_job_status_callback; 6.0.1+ uses is_dataflow_job_id_exist_callback.
68+
stop_callback = is_dataflow_job_id_exist_callback or check_job_status_callback
69+
70+
log.info("Running command: %s", " ".join(shlex.quote(c) for c in cmd))
71+
# Merge stderr into stdout so a single reader drains all subprocess output.
72+
proc = subprocess.Popen(
73+
cmd,
74+
cwd=working_directory,
75+
shell=False,
76+
stdout=subprocess.PIPE,
77+
stderr=subprocess.STDOUT,
78+
close_fds=True,
79+
)
80+
log.info("Start waiting for Apache Beam process to complete.")
81+
82+
# Close only the pipe in finally. Streaming and deferrable jobs require an
83+
# early return once stop_callback succeeds, so proc.wait() runs only after EOF.
84+
try:
85+
if proc.stdout is not None:
86+
for raw_line in iter(proc.stdout.readline, b""):
87+
line = raw_line.decode("utf-8", errors="replace")
88+
if process_line_callback:
89+
process_line_callback(line)
90+
log.info("%s", line.rstrip("\r\n"))
91+
if stop_callback and stop_callback():
92+
return
93+
finally:
94+
if proc.stdout is not None:
95+
proc.stdout.close()
96+
97+
proc.wait()
98+
log.info("Process exited with return code: %s", proc.returncode)
99+
if proc.returncode != 0:
100+
raise AirflowException(
101+
f"Apache Beam process failed with return code {proc.returncode}"
102+
)
103+
104+
# Preserve provider 6.3.2+ fallback for pipelines that disable job ID logs.
105+
if check_job_id_by_name_callback and not (stop_callback and stop_callback()):
106+
check_job_id_by_name_callback()
107+
108+
109+
class BeamPipeDeadlockFixPlugin(AirflowPlugin):
110+
"""Registers the patched Beam command runner when Airflow loads plugins."""
111+
112+
name = "beam_pipe_deadlock_fix"
113+
114+
@classmethod
115+
def on_load(cls, *args, **kwargs) -> None:
116+
# Airflow calls on_load once per process before running tasks.
117+
try:
118+
import airflow.providers.apache.beam.hooks.beam as beam_hook_mod
119+
except ImportError:
120+
return
121+
beam_hook_mod.run_beam_command = _patched_run_beam_command
122+
123+
# [END composer_beam_pipe_deadlock_fix]

0 commit comments

Comments
 (0)