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


##########
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
+    _THROTTLED = frozenset({"ThrottlingException", "LimitExceededException", 
"ServiceUnavailableException"})
+
+    def __init__(self, client) -> None:
+        self.client = client
+        self.created: set[tuple[str, str]] = set()
+        # Streams whose sender waits out failed creates: an upload does not 
wait for them.
+        self.waiting: set[tuple[str, str]] = set()
+        # When a stop's wait last ran out of time, for every handler of this 
creator.
+        self.stop_ran_out_at = float("-inf")
+        # Streams a reset of the logging config left to their senders, and 
that the stop waits for.
+        self.left: list[tuple[str, Queue]] = []
+
+    def register(self) -> None:
+        service = self.client.meta.service_model.service_id.hyphenize()
+        self.client.meta.events.register(
+            f"before-parameter-build.{service}.PutLogEvents",
+            self,
+            unique_id=f"airflow-create-log-stream-{id(self)}",
+        )
+
+    def __call__(self, params, **kwargs) -> None:
+        key = (params["logGroupName"], params["logStreamName"])
+        if key in self.created:
+            return
+        try:
+            if self.create_log_stream(*key):
+                self.created.add(key)
+        finally:
+            self.waiting.discard(key)
+
+    def create_log_stream(self, log_group: str, log_stream: str) -> bool:
+        deadline = time.monotonic() + self.DEADLINE_S
+        delay = 0.5
+        while True:
+            try:
+                self.client.create_log_stream(logGroupName=log_group, 
logStreamName=log_stream)
+                return True
+            except ClientError as e:
+                code = e.response.get("Error", {}).get("Code")
+                if code == "ResourceAlreadyExistsException":
+                    return True
+                status = e.response.get("ResponseMetadata", 
{}).get("HTTPStatusCode") or 0
+                if code not in self._THROTTLED and status not in (408, 429) 
and status < 500:
+                    return False  # left to watchtower's own attempts
+            except (BotoConnectionError, HTTPClientError):
+                pass  # a timed-out or dropped call is retried like throttling
+            if time.monotonic() + delay > deadline:
+                return False
+            # Only now: an upload still waits for a stream whose first create 
is in flight.
+            self.waiting.add((log_group, log_stream))
+            time.sleep(delay * random.uniform(0.5, 1.5))
+            delay = min(delay * 2, 10.0)
+
+
+# Core's layout for a trigger's own logs, repeated because older Airflow 
versions don't define it.
+TRIGGER_LOG_PREFIX = "triggers/trigger_id="

Review Comment:
   Moving this with the log group option to its follow-up PR; I'll make it 
private 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