This is an automated email from the ASF dual-hosted git repository.

ash pushed a commit to branch v2-0-test
in repository https://gitbox.apache.org/repos/asf/airflow.git

commit 132825be0c67e1ca855e3500736fc9e87d691d8c
Author: Ash Berlin-Taylor <[email protected]>
AuthorDate: Wed Mar 31 23:18:01 2021 +0100

    Avoid scheduler/parser manager deadlock by using non-blocking IO (#15112)
    
    There have been long standing issues where the scheduler would "stop
    responding" that we haven't been able to track down.
    
    Someone was able to catch the scheduler in this state in 2.0.1 and
    inspect it with py-spy (thanks, MatthewRBruce!)
    
    The stack traces (slightly shortened) were:
    
    ```
    Process 6: /usr/local/bin/python /usr/local/bin/airflow scheduler
    Python v3.8.7 (/usr/local/bin/python3.8)
    Thread 0x7FF5C09C8740 (active): "MainThread"
        _send (multiprocessing/connection.py:368)
        _send_bytes (multiprocessing/connection.py:411)
        send (multiprocessing/connection.py:206)
        send_callback_to_execute (airflow/utils/dag_processing.py:283)
        _send_dag_callbacks_to_processor (airflow/jobs/scheduler_job.py:1795)
        _schedule_dag_run (airflow/jobs/scheduler_job.py:1762)
    
    Process 77: airflow scheduler -- DagFileProcessorManager
    Python v3.8.7 (/usr/local/bin/python3.8)
    Thread 0x7FF5C09C8740 (active): "MainThread"
        _send (multiprocessing/connection.py:368)
        _send_bytes (multiprocessing/connection.py:405)
        send (multiprocessing/connection.py:206)
        _run_parsing_loop (airflow/utils/dag_processing.py:698)
        start (airflow/utils/dag_processing.py:596)
    ```
    
    What this shows is that both processes are stuck trying to send data to
    each other, but neither can proceed as both buffers are full, but since
    both are trying to send, neither side is going to read and make more
    space in the buffer. A classic deadlock!
    
    The fix for this is two fold:
    
    1) Enable non-blocking IO on the DagFileProcessorManager side.
    
       The only thing the Manager sends back up the pipe is (now, as of 2.0)
       the DagParsingStat object, and the scheduler will happily continue
       without receiving these, so in the case of a blocking error, it is
       simply better to ignore the error, continue the loop and try sending
       one again later.
    
    2) Reduce the size of DagParsingStat
    
       In the case of a large number of dag files we included the path for
       each and every one (in full) in _each_ parsing stat. Not only did the
       scheduler do nothing with this field, meaning it was larger than it
       needed to be, by making it such a large object, it increases the
       likely hood of hitting this send-buffer-full deadlock case!
    
    (cherry picked from commit b0e68ebcb88af8352919a883e38e759e6ceb4d2c)
---
 airflow/utils/dag_processing.py    | 32 +++++++++++----
 pylintrc-tests                     |  4 +-
 tests/utils/test_dag_processing.py | 80 +++++++++++++++++++++++++++++++++++++-
 3 files changed, 106 insertions(+), 10 deletions(-)

diff --git a/airflow/utils/dag_processing.py b/airflow/utils/dag_processing.py
index f93847c..5ba44e3 100644
--- a/airflow/utils/dag_processing.py
+++ b/airflow/utils/dag_processing.py
@@ -139,7 +139,6 @@ class AbstractDagFileProcessorProcess(metaclass=ABCMeta):
 class DagParsingStat(NamedTuple):
     """Information on processing progress"""
 
-    file_paths: List[str]
     done: bool
     all_files_processed: bool
 
@@ -513,6 +512,15 @@ class DagFileProcessorManager(LoggingMixin):  # pylint: 
disable=too-many-instanc
         self._async_mode = async_mode
         self._parsing_start_time: Optional[int] = None
 
+        # Set the signal conn in to non-blocking mode, so that attempting to
+        # send when the buffer is full errors, rather than hangs for-ever
+        # attempting to send (this is to avoid deadlocks!)
+        #
+        # Don't do this in sync_mode, as we _need_ the DagParsingStat sent to
+        # continue the scheduler
+        if self._async_mode:
+            os.set_blocking(self._signal_conn.fileno(), False)
+
         self._parallelism = conf.getint('scheduler', 'parsing_processes')
         if 'sqlite' in conf.get('core', 'sql_alchemy_conn') and 
self._parallelism > 1:
             self.log.warning(
@@ -621,6 +629,7 @@ class DagFileProcessorManager(LoggingMixin):  # pylint: 
disable=too-many-instanc
             ready = multiprocessing.connection.wait(self.waitables.keys(), 
timeout=poll_time)
             if self._signal_conn in ready:
                 agent_signal = self._signal_conn.recv()
+
                 self.log.debug("Received %s signal from 
DagFileProcessorAgent", agent_signal)
                 if agent_signal == DagParsingSignal.TERMINATE_MANAGER:
                     self.terminate()
@@ -693,12 +702,21 @@ class DagFileProcessorManager(LoggingMixin):  # pylint: 
disable=too-many-instanc
             all_files_processed = all(self.get_last_finish_time(x) is not None 
for x in self.file_paths)
             max_runs_reached = self.max_runs_reached()
 
-            dag_parsing_stat = DagParsingStat(
-                self._file_paths,
-                max_runs_reached,
-                all_files_processed,
-            )
-            self._signal_conn.send(dag_parsing_stat)
+            try:
+                self._signal_conn.send(
+                    DagParsingStat(
+                        max_runs_reached,
+                        all_files_processed,
+                    )
+                )
+            except BlockingIOError:
+                # Try again next time around the loop!
+
+                # It is better to fail, than it is deadlock. This should
+                # "almost never happen" since the DagParsingStat object is
+                # small, and in async mode this stat is not actually _required_
+                # for normal operation (It only drives "max runs")
+                self.log.debug("BlockingIOError recived trying to send 
DagParsingStat, ignoring")
 
             if max_runs_reached:
                 self.log.info(
diff --git a/pylintrc-tests b/pylintrc-tests
index 5b360a9..8a7e56e 100644
--- a/pylintrc-tests
+++ b/pylintrc-tests
@@ -439,6 +439,7 @@ good-names=e,
            i,
            j,
            k,
+           n,
            v, # Commonly used when iterating dict.items()
            _,
            ti,  # Commonly used in Airflow as shorthand for taskinstance
@@ -450,7 +451,8 @@ good-names=e,
            cm,  # Commonly used as shorthand for context manager
            ds,  # Used in Airflow templates
            ts,  # Used in Airflow templates
-           id   # Commonly used as shorthand for identifier
+           id,  # Commonly used as shorthand for identifier
+           fd,  # aka "file-descriptor" -- common in socket code
 
 # Include a hint for the correct naming format with invalid-name.
 include-naming-hint=no
diff --git a/tests/utils/test_dag_processing.py 
b/tests/utils/test_dag_processing.py
index 68a950f..913711d2 100644
--- a/tests/utils/test_dag_processing.py
+++ b/tests/utils/test_dag_processing.py
@@ -16,10 +16,13 @@
 # specific language governing permissions and limitations
 # under the License.
 
+import logging
 import multiprocessing
 import os
 import pathlib
+import socket
 import sys
+import threading
 import unittest
 from datetime import datetime, timedelta
 from tempfile import TemporaryDirectory
@@ -35,7 +38,7 @@ from airflow.models import DagBag, DagModel, TaskInstance as 
TI
 from airflow.models.serialized_dag import SerializedDagModel
 from airflow.models.taskinstance import SimpleTaskInstance
 from airflow.utils import timezone
-from airflow.utils.callback_requests import TaskCallbackRequest
+from airflow.utils.callback_requests import CallbackRequest, 
TaskCallbackRequest
 from airflow.utils.dag_processing import (
     DagFileProcessorAgent,
     DagFileProcessorManager,
@@ -425,17 +428,90 @@ class TestDagFileProcessorManager(unittest.TestCase):
 
         manager._run_parsing_loop()
 
+        result = None
         while parent_pipe.poll(timeout=None):
             result = parent_pipe.recv()
             if isinstance(result, DagParsingStat) and result.done:
                 break
 
         # Three files in folder should be processed
-        assert len(result.file_paths) == 3
+        assert sum(stat.run_count for stat in manager._file_stats.values()) == 
3
 
         with create_session() as session:
             assert session.query(DagModel).get(dag_id) is not None
 
+    @conf_vars({('core', 'load_examples'): 'False'})
+    @pytest.mark.backend("mysql", "postgres")
+    @pytest.mark.execution_timeout(30)
+    def test_pipe_full_deadlock(self):
+        dag_filepath = TEST_DAG_FOLDER / "test_scheduler_dags.py"
+
+        child_pipe, parent_pipe = multiprocessing.Pipe()
+
+        # Shrink the buffers to exacerbate the problem!
+        for fd in (parent_pipe.fileno(),):
+            sock = socket.socket(fileno=fd)
+            sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024)
+            sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024)
+            sock.detach()
+
+        exit_event = threading.Event()
+
+        # To test this behaviour we need something that continually fills the
+        # parent pipe's buffer (and keeps it full).
+        def keep_pipe_full(pipe, exit_event):
+            n = 0
+            while True:
+                if exit_event.is_set():
+                    break
+
+                req = CallbackRequest(str(dag_filepath))
+                try:
+                    logging.debug("Sending CallbackRequests %d", n + 1)
+                    pipe.send(req)
+                except TypeError:
+                    # This is actually the error you get when the parent pipe
+                    # is closed! Nicely handled, eh?
+                    break
+                except OSError:
+                    break
+                n += 1
+                logging.debug("   Sent %d CallbackRequests", n)
+
+        thread = threading.Thread(target=keep_pipe_full, args=(parent_pipe, 
exit_event))
+
+        fake_processors = []
+
+        def fake_processor_factory(*args, **kwargs):
+            nonlocal fake_processors
+            processor = 
FakeDagFileProcessorRunner._fake_dag_processor_factory(*args, **kwargs)
+            fake_processors.append(processor)
+            return processor
+
+        manager = DagFileProcessorManager(
+            dag_directory=dag_filepath,
+            dag_ids=[],
+            # A reasonable large number to ensure that we trigger the deadlock
+            max_runs=100,
+            processor_factory=fake_processor_factory,
+            processor_timeout=timedelta(seconds=5),
+            signal_conn=child_pipe,
+            pickle_dags=False,
+            async_mode=True,
+        )
+
+        try:
+            thread.start()
+
+            # If this completes without hanging, then the test is good!
+            manager._run_parsing_loop()
+            exit_event.set()
+        finally:
+            logging.info("Closing pipes")
+            parent_pipe.close()
+            child_pipe.close()
+            thread.join(timeout=1.0)
+
 
 class TestDagFileProcessorAgent(unittest.TestCase):
     def setUp(self):

Reply via email to