seanghaeli commented on code in PR #76631:
URL: https://github.com/apache/airflow/pull/76631#discussion_r4735511428


##########
providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py:
##########
@@ -56,6 +68,184 @@
     )
 
 
+class _CloudWatchLogHandler(watchtower.CloudWatchLogHandler):

Review Comment:
   Moving this to the stream-writer follow-up PR; I'll answer it there.



##########
providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py:
##########
@@ -56,6 +68,184 @@
     )
 
 
+class _CloudWatchLogHandler(watchtower.CloudWatchLogHandler):
+    """
+    watchtower's handler, which can also flush a single stream, and waits 
``FLUSH_TIMEOUT`` in all.
+
+    watchtower's ``flush`` and ``close`` wait ``FLUSH_TIMEOUT`` per stream and 
fail when another thread opens
+    a stream meanwhile. Uploads run on the triggerer's main loop, so skip 
streams waiting out failed creates.
+    """
+
+    NUDGE_S = 5.0
+    MIN_WAIT_S = 1.0
+    creator: _LogStreamCreator
+    _nudged_at = float("-inf")
+
+    def flush(self) -> None:
+        if not self.shutting_down:
+            self._stop(self.FLUSH)
+
+    def close(self) -> None:
+        if not self.shutting_down:
+            self.shutting_down = True
+            skipped = self._stop(self.END)
+            queued = [(name, q) for name, q in self.queues.items() if 
q.unfinished_tasks]
+            left = [(name, q) for name, q in queued if (self.log_group_name, 
name) in skipped]
+            self.creator.left = [(name, q) for name, q in self.creator.left if 
q.unfinished_tasks] + left
+            if unsent := [name for name, _ in queued if (self.log_group_name, 
name) not in skipped]:
+                message = f"Timed out while delivering logs of {', 
'.join(unsent)}"
+                warnings.warn(message, watchtower.WatchtowerWarning, 
stacklevel=2)
+        logging.Handler.close(self)
+
+    def _stop(self, marker: object) -> Container:
+        # A reset of the logging config flushes and closes the handlers too, 
holding logging's lock, which
+        # the senders take to log. The process goes on, and so do the senders: 
a reset doesn't wait for them,
+        # and the next stop waits for the streams a reset left.
+        if _resetting():
+            self._send_queued(list(self.queues.items()), marker, 0)
+            return {(self.log_group_name, name) for name in self.queues}
+        # logging.shutdown flushes and closes each handler, and the handlers 
share the creator: once a wait
+        # of the stop ran out, the next ones wait MIN_WAIT_S at most, so the 
stop takes one FLUSH_TIMEOUT.
+        ran_out = time.monotonic() - self.creator.stop_ran_out_at < 
self.FLUSH_TIMEOUT
+        timeout = self.MIN_WAIT_S if ran_out else self.FLUSH_TIMEOUT
+        if not self._send_queued(list(self.queues.items()), marker, timeout, 
(), self.creator.left):
+            self.creator.stop_ran_out_at = time.monotonic()
+        return ()
+
+    def flush_stream(self, stream_name: str) -> None:
+        """
+        Send the stream's queued records, as ``flush`` does for every stream.
+
+        At most every ``NUDGE_S``, the other streams are told to send theirs 
too, unwaited: watchtower sends a
+        stream only every ``send_interval``, and what it still holds is lost 
if the process dies.
+        """
+        if self.shutting_down:
+            return
+        if (now := time.monotonic()) - self._nudged_at >= self.NUDGE_S:
+            self._nudged_at = now
+            for name, q in list(self.queues.items()):
+                if name != stream_name:
+                    q.put(self.FLUSH)
+        if (stream := self.queues.get(stream_name)) is not None:
+            self._send_queued([(stream_name, stream)], self.FLUSH, 
self.FLUSH_TIMEOUT, self.creator.waiting)
+
+    def _send_queued(
+        self,
+        queues: list[tuple[str, Queue]],
+        marker: object,
+        timeout: float,
+        skip: Container = (),
+        left: Sequence[tuple[str, Queue]] = (),
+    ) -> bool:
+        self.addFilter(watchtower._boto_filter)
+        for _, q in queues:
+            q.put(marker)
+        # One deadline for all of them: streams whose first create hangs cost 
FLUSH_TIMEOUT in all, not each.
+        end = time.monotonic() + timeout
+        for name, q in [*queues, *left]:
+            self._wait_until_sent(name, q, end, skip)
+        return time.monotonic() < end
+
+    def _wait_until_sent(self, stream_name: str, q: Queue, end: float, skip: 
Container) -> None:
+        key = (self.log_group_name, stream_name)
+        with q.all_tasks_done:
+            # In slices, so a sender that starts waiting in the creator 
meanwhile ends this wait too.
+            while not q.all_tasks_done.wait_for(
+                lambda: q.unfinished_tasks == 0 or key in skip,
+                timeout=min(1.0, max(0.0, end - time.monotonic())),
+            ):
+                if time.monotonic() >= end:
+                    break
+
+
+def _exiting() -> bool:
+    """Whether the interpreter is exiting, which stops the main thread before 
logging.shutdown runs."""
+    return not threading.main_thread().is_alive()
+
+
+def _resetting() -> bool:
+    """
+    Whether a reset of the logging config is closing the handlers.
+
+    dictConfig and fileConfig close them holding logging's lock. 
``logging.shutdown`` alone doesn't, as when
+    a forked worker calls it before ``os._exit``, with its main thread still 
running. Where the lock can't
+    tell, the close is taken for a stop: a reset then waits for the streams, 
slower but losing no lines.
+    """
+    try:
+        owned = logging._lock._is_owned()  # type: ignore[attr-defined]

Review Comment:
   Moving this to the stream-writer follow-up PR; I'll answer it there.



##########
providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py:
##########
@@ -56,6 +68,184 @@
     )
 
 
+class _CloudWatchLogHandler(watchtower.CloudWatchLogHandler):
+    """
+    watchtower's handler, which can also flush a single stream, and waits 
``FLUSH_TIMEOUT`` in all.
+
+    watchtower's ``flush`` and ``close`` wait ``FLUSH_TIMEOUT`` per stream and 
fail when another thread opens
+    a stream meanwhile. Uploads run on the triggerer's main loop, so skip 
streams waiting out failed creates.
+    """
+
+    NUDGE_S = 5.0
+    MIN_WAIT_S = 1.0
+    creator: _LogStreamCreator
+    _nudged_at = float("-inf")
+
+    def flush(self) -> None:
+        if not self.shutting_down:
+            self._stop(self.FLUSH)
+
+    def close(self) -> None:
+        if not self.shutting_down:
+            self.shutting_down = True
+            skipped = self._stop(self.END)
+            queued = [(name, q) for name, q in self.queues.items() if 
q.unfinished_tasks]
+            left = [(name, q) for name, q in queued if (self.log_group_name, 
name) in skipped]
+            self.creator.left = [(name, q) for name, q in self.creator.left if 
q.unfinished_tasks] + left
+            if unsent := [name for name, _ in queued if (self.log_group_name, 
name) not in skipped]:
+                message = f"Timed out while delivering logs of {', 
'.join(unsent)}"
+                warnings.warn(message, watchtower.WatchtowerWarning, 
stacklevel=2)
+        logging.Handler.close(self)
+
+    def _stop(self, marker: object) -> Container:
+        # A reset of the logging config flushes and closes the handlers too, 
holding logging's lock, which
+        # the senders take to log. The process goes on, and so do the senders: 
a reset doesn't wait for them,
+        # and the next stop waits for the streams a reset left.
+        if _resetting():
+            self._send_queued(list(self.queues.items()), marker, 0)
+            return {(self.log_group_name, name) for name in self.queues}
+        # logging.shutdown flushes and closes each handler, and the handlers 
share the creator: once a wait
+        # of the stop ran out, the next ones wait MIN_WAIT_S at most, so the 
stop takes one FLUSH_TIMEOUT.
+        ran_out = time.monotonic() - self.creator.stop_ran_out_at < 
self.FLUSH_TIMEOUT
+        timeout = self.MIN_WAIT_S if ran_out else self.FLUSH_TIMEOUT
+        if not self._send_queued(list(self.queues.items()), marker, timeout, 
(), self.creator.left):
+            self.creator.stop_ran_out_at = time.monotonic()
+        return ()
+
+    def flush_stream(self, stream_name: str) -> None:
+        """
+        Send the stream's queued records, as ``flush`` does for every stream.
+
+        At most every ``NUDGE_S``, the other streams are told to send theirs 
too, unwaited: watchtower sends a
+        stream only every ``send_interval``, and what it still holds is lost 
if the process dies.
+        """
+        if self.shutting_down:
+            return
+        if (now := time.monotonic()) - self._nudged_at >= self.NUDGE_S:
+            self._nudged_at = now
+            for name, q in list(self.queues.items()):
+                if name != stream_name:
+                    q.put(self.FLUSH)
+        if (stream := self.queues.get(stream_name)) is not None:
+            self._send_queued([(stream_name, stream)], self.FLUSH, 
self.FLUSH_TIMEOUT, self.creator.waiting)
+
+    def _send_queued(
+        self,
+        queues: list[tuple[str, Queue]],
+        marker: object,
+        timeout: float,
+        skip: Container = (),
+        left: Sequence[tuple[str, Queue]] = (),
+    ) -> bool:
+        self.addFilter(watchtower._boto_filter)
+        for _, q in queues:
+            q.put(marker)
+        # One deadline for all of them: streams whose first create hangs cost 
FLUSH_TIMEOUT in all, not each.
+        end = time.monotonic() + timeout
+        for name, q in [*queues, *left]:
+            self._wait_until_sent(name, q, end, skip)
+        return time.monotonic() < end
+
+    def _wait_until_sent(self, stream_name: str, q: Queue, end: float, skip: 
Container) -> None:
+        key = (self.log_group_name, stream_name)
+        with q.all_tasks_done:
+            # In slices, so a sender that starts waiting in the creator 
meanwhile ends this wait too.
+            while not q.all_tasks_done.wait_for(
+                lambda: q.unfinished_tasks == 0 or key in skip,
+                timeout=min(1.0, max(0.0, end - time.monotonic())),
+            ):
+                if time.monotonic() >= end:
+                    break
+
+
+def _exiting() -> bool:
+    """Whether the interpreter is exiting, which stops the main thread before 
logging.shutdown runs."""
+    return not threading.main_thread().is_alive()
+
+
+def _resetting() -> bool:
+    """
+    Whether a reset of the logging config is closing the handlers.
+
+    dictConfig and fileConfig close them holding logging's lock. 
``logging.shutdown`` alone doesn't, as when
+    a forked worker calls it before ``os._exit``, with its main thread still 
running. Where the lock can't
+    tell, the close is taken for a stop: a reset then waits for the streams, 
slower but losing no lines.
+    """
+    try:
+        owned = logging._lock._is_owned()  # type: ignore[attr-defined]
+    except Exception:
+        return False
+    return owned is True and not _exiting()
+
+
+class _LogStreamCreator:
+    """
+    Create each log stream before its first PutLogEvents, retrying transient 
failures.
+
+    watchtower creates a stream only after a put to it fails, and while it 
does, the handler drops every
+    record, of every stream. Retrying here holds only that stream's sender 
thread.
+    """
+
+    DEADLINE_S = 900.0

Review Comment:
   Moving this to the stream-writer follow-up PR; I'll answer it there.



##########
providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py:
##########
@@ -221,25 +453,29 @@ def proc(logger: structlog.typing.WrappedLogger, 
method_name: str, event: struct
 
         return (proc,)
 
-    def close(self):
+    def close(self, stream_name: str | None = None):
         """
-        Flush pending events one last time and mark the IO closed.
+        Flush the pending events of ``stream_name``, or of every stream.
 
-        Only ever called from :meth:`upload`. Mark the IO closed first so 
``handler`` stops
-        rebuilding: a record arriving after teardown must be dropped, not 
revive a fresh
-        handler. Read the cached handler directly so we never build one just 
to flush it.
+        :meth:`upload` closes only its stream: a triggerer uploads each 
trigger's log and goes on.
+        A full close marks the IO closed first so ``handler`` stops 
rebuilding: a record arriving
+        after teardown must be dropped, not revive a fresh handler. Read the 
cached handler
+        directly so we never build one just to flush it.
         """
-        self._closed = True
-        handler = self._cached_handler
-        if handler is None or handler.shutting_down:
-            return
-
-        handler.flush()
+        if stream_name is None:
+            self._closed = True
+        for handler in (self._cached_handler, self._cached_trigger_handler):
+            if handler is None or handler.shutting_down:
+                continue
+            if stream_name is None:
+                handler.flush()
+            else:
+                handler.flush_stream(stream_name)
 
     def upload(self, path: os.PathLike | str, ti: RuntimeTI | None = None) -> 
None:
         """Upload the given log path to the remote storage."""
         # No batch upload — logs stream in real-time. Flush pending events and 
clean up.
-        self.close()
+        self.close(Path(path).as_posix().replace(":", "_"))

Review Comment:
   Moving this to the stream-writer follow-up PR; I'll answer it there.



##########
providers/amazon/tests/unit/amazon/aws/log/test_cloudwatch_task_handler.py:
##########
@@ -767,3 +1052,228 @@ def generate_log_events(conn, log_group_name, 
log_stream_name, log_events):
     conn.create_log_group(logGroupName=log_group_name)
     conn.create_log_stream(logGroupName=log_group_name, 
logStreamName=log_stream_name)
     conn.put_log_events(logGroupName=log_group_name, 
logStreamName=log_stream_name, logEvents=log_events)
+
+
+def _client_error(code, status=400):
+    return ClientError(
+        {"Error": {"Code": code}, "ResponseMetadata": {"HTTPStatusCode": 
status}}, "CreateLogStream"
+    )
+
+
+def _mock_create_log_stream(client, errors):
+    create, errors = client.create_log_stream, iter(errors)
+
+    def create_after_errors(**kwargs):
+        if (error := next(errors, None)) is not None:
+            raise error
+        return create(**kwargs)
+
+    return mock.patch.object(client, "create_log_stream", autospec=True, 
side_effect=create_after_errors)
+
+
+def _put_first_line(client):
+    client.put_log_events(
+        logGroupName="tasks",
+        logStreamName="new-stream",
+        logEvents=[{"timestamp": int(time.time() * 1000), "message": "first 
line"}],
+    )
+
+
+class TestLogStreamCreator:
+    @pytest.mark.parametrize(
+        "errors",
+        [
+            pytest.param([], id="created"),
+            pytest.param([_client_error("ThrottlingException")] * 8, 
id="throttled-for-minutes"),
+            pytest.param([_client_error("408", 408)], id="request-timeout"),
+            pytest.param([_client_error("InternalFailure", 500)], 
id="internal-failure"),
+            pytest.param([ReadTimeoutError(endpoint_url="https://logs";)], 
id="read-timeout"),
+            
pytest.param([EndpointConnectionError(endpoint_url="https://logs";)], 
id="connection"),
+        ],
+    )
+    @mock.patch("time.sleep", autospec=True)
+    def test_a_new_stream_is_created_before_its_first_put(self, mock_sleep, 
errors):
+        conn = boto3.client("logs", region_name="us-west-2")
+        conn.create_log_group(logGroupName="tasks")
+        client = _subject().handler.cwl_client
+        clock = itertools.count(0, 30)
+
+        with (
+            _mock_create_log_stream(client, errors) as mock_create,
+            mock.patch("time.monotonic", autospec=True, side_effect=lambda: 
next(clock)),
+        ):
+            _put_first_line(client)
+
+        assert mock_create.call_count == len(errors) + 1
+        assert mock_sleep.call_count == len(errors)
+        events = conn.get_log_events(logGroupName="tasks", 
logStreamName="new-stream")["events"]
+        assert [event["message"] for event in events] == ["first line"]
+
+    @mock.patch("time.sleep", autospec=True)
+    def test_a_new_stream_is_left_to_watchtower_on_other_errors(self, 
mock_sleep):
+        boto3.client("logs", 
region_name="us-west-2").create_log_group(logGroupName="tasks")
+        client = _subject().handler.cwl_client
+
+        with _mock_create_log_stream(client, 
[_client_error("AccessDeniedException")]) as mock_create:
+            with pytest.raises(ClientError, match="ResourceNotFoundException"):
+                _put_first_line(client)
+
+        assert mock_create.call_count == 1
+        mock_sleep.assert_not_called()
+
+
+class TestCloudWatchLogHandler:
+    STREAMS = ("slow", "throttled-0", "throttled-1", "fine")
+
+    @pytest.fixture
+    def parked(self):
+        """Emit to ``STREAMS``: "slow" and "throttled-*" (after one 
throttling) are created once ``release``-d."""
+        boto3.client("logs", 
region_name="us-west-2").create_log_group(logGroupName="tasks")
+        subject = _subject(delete_local_copy=False)
+        handler, client = subject.handler, subject.handler.cwl_client
+        create = client.create_log_stream
+        parked, failed = threading.Semaphore(0), set()
+        release = {"slow": threading.Event(), "throttled": threading.Event()}
+
+        def create_when_released(**kwargs):
+            if (name := kwargs["logStreamName"]) != "fine":
+                if name.startswith("throttled-") and name not in failed:
+                    failed.add(name)
+                    raise _client_error("ThrottlingException")
+                parked.release()
+                release[name.split("-")[0]].wait(10)
+            return create(**kwargs)
+
+        with mock.patch.object(client, "create_log_stream", autospec=True, 
side_effect=create_when_released):
+            handler.send_interval, handler.FLUSH_TIMEOUT, handler.MIN_WAIT_S = 
0.05, 2, 0.5
+            for stream in self.STREAMS:
+                handler.log_stream_name = stream
+                handler.emit(logging.makeLogRecord({"msg": f"to {stream}"}))
+            assert all(parked.acquire(timeout=10) for _ in range(3))
+            yield subject, release
+            for event in release.values():
+                event.set()
+            # So no sender outlives the test and writes into the next one's 
moto backend.
+            handler.close()
+            for thread in handler.threads:
+                thread.join(5)
+
+    @pytest.fixture
+    def exiting(self):
+        with mock.patch(_EXITING, return_value=True):
+            yield
+
+    @staticmethod
+    def _sent(handler, streams):
+        get_log_events = handler.cwl_client.get_log_events
+        return {
+            s: [e["message"] for e in get_log_events(logGroupName="tasks", 
logStreamName=s)["events"]]
+            for s in streams
+        }
+
+    @pytest.mark.usefixtures("exiting")
+    @pytest.mark.parametrize("call", ["flush", "close", "upload"])
+    def test_a_stream_still_being_created_is_waited_for(self, parked, call):
+        subject, release = parked
+        streams = ["slow"] if call == "upload" else self.STREAMS
+        threading.Timer(0.5, release["slow"].set).start()
+        threading.Timer(1, release["throttled"].set).start()  # after "slow" 
is sent
+        subject.upload("slow") if call == "upload" else 
getattr(subject.handler, call)()
+
+        # Read right away: a stop exits once close returns, and the daemon 
sender threads with it.
+        assert self._sent(subject.handler, streams) == {s: [f"to {s}"] for s 
in streams}
+
+    def test_an_upload_does_not_wait_for_a_stream_waiting_out_throttling(self, 
parked):
+        subject, _ = parked
+        started = time.monotonic()
+        subject.upload("throttled-0")
+
+        assert time.monotonic() - started < 1  # FLUSH_TIMEOUT is 2

Review Comment:
   Moving this to the stream-writer follow-up PR; I'll answer it there.



##########
providers/amazon/tests/unit/amazon/aws/log/test_cloudwatch_task_handler.py:
##########
@@ -767,3 +1052,228 @@ def generate_log_events(conn, log_group_name, 
log_stream_name, log_events):
     conn.create_log_group(logGroupName=log_group_name)
     conn.create_log_stream(logGroupName=log_group_name, 
logStreamName=log_stream_name)
     conn.put_log_events(logGroupName=log_group_name, 
logStreamName=log_stream_name, logEvents=log_events)
+
+
+def _client_error(code, status=400):
+    return ClientError(
+        {"Error": {"Code": code}, "ResponseMetadata": {"HTTPStatusCode": 
status}}, "CreateLogStream"
+    )
+
+
+def _mock_create_log_stream(client, errors):
+    create, errors = client.create_log_stream, iter(errors)
+
+    def create_after_errors(**kwargs):
+        if (error := next(errors, None)) is not None:
+            raise error
+        return create(**kwargs)
+
+    return mock.patch.object(client, "create_log_stream", autospec=True, 
side_effect=create_after_errors)
+
+
+def _put_first_line(client):
+    client.put_log_events(
+        logGroupName="tasks",
+        logStreamName="new-stream",
+        logEvents=[{"timestamp": int(time.time() * 1000), "message": "first 
line"}],
+    )
+
+
+class TestLogStreamCreator:
+    @pytest.mark.parametrize(
+        "errors",
+        [
+            pytest.param([], id="created"),
+            pytest.param([_client_error("ThrottlingException")] * 8, 
id="throttled-for-minutes"),
+            pytest.param([_client_error("408", 408)], id="request-timeout"),
+            pytest.param([_client_error("InternalFailure", 500)], 
id="internal-failure"),
+            pytest.param([ReadTimeoutError(endpoint_url="https://logs";)], 
id="read-timeout"),
+            
pytest.param([EndpointConnectionError(endpoint_url="https://logs";)], 
id="connection"),
+        ],
+    )
+    @mock.patch("time.sleep", autospec=True)
+    def test_a_new_stream_is_created_before_its_first_put(self, mock_sleep, 
errors):
+        conn = boto3.client("logs", region_name="us-west-2")
+        conn.create_log_group(logGroupName="tasks")
+        client = _subject().handler.cwl_client
+        clock = itertools.count(0, 30)
+
+        with (
+            _mock_create_log_stream(client, errors) as mock_create,
+            mock.patch("time.monotonic", autospec=True, side_effect=lambda: 
next(clock)),

Review Comment:
   Moving this to the stream-writer follow-up PR; I'll answer it there.



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