amoghrajesh commented on code in PR #76631:
URL: https://github.com/apache/airflow/pull/76631#discussion_r4734917043
##########
providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py:
##########
@@ -56,6 +68,184 @@
)
+class _CloudWatchLogHandler(watchtower.CloudWatchLogHandler):
Review Comment:
This depends on watchtower internals - `queues`, `FLUSH`, `END`,
`shutting_down` and `_boto_filter`. We also pin `watchtower>=3.3.1,<4`, so a
minor release can rename them. Logs would then stop reaching CW with no visible
error. Could we try the per thread guard from the review body instead?
##########
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:
`logging._lock._is_owned()` is private Cpython. If it guesses wrong, a real
shutdown skips the wait and loses lines, or a reset blocks the triggerer for up
to 30 s. If we still need to tell the two apart, could we set our own flag
around `configure_logging()`?
##########
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:
A sender thread can sleep here for up to 15 minutes. Meanwhile, its queue,
which has no size limit, keeps growing. `botocore` already retries throttling,
`5xx` and connection errors. Could `AwsLogsHook(...,
config=Config(retries={"mode": "standard", "max_attempts": 10}))` replace this
class?
##########
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:
Only this module uses this. Make it private pls.
##########
providers/alibaba/src/airflow/providers/alibaba/cloud/log/oss_task_handler.py:
##########
@@ -113,13 +113,21 @@ def hook(self):
)
def read(self, relative_path, ti: RuntimeTI | None) ->
tuple[LogSourceInfo, LogMessages | None]:
- logs: list[str] = []
- messages = [relative_path]
-
- if self.oss_log_exists(relative_path):
- logs.append(self.oss_read(relative_path, return_error=True))
- return messages, logs
- return messages, None
+ # Every object the path is a prefix of, such as ``<task
log>.trigger.<triggerer job id>.log``.
+ messages: list[str] = []
+ try:
+ paths = self.oss_list(relative_path)
+ except Exception as e:
Review Comment:
`except Exception` also hides real bugs in `oss_list`. Could this be
narrowed down exception instead?
##########
providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py:
##########
@@ -265,22 +501,54 @@ def read(self, relative_path: str, ti: RuntimeTI | None)
-> LogResponse:
return messages, str_logs
- def stream(self, relative_path: str, ti: RuntimeTI | None) ->
StreamingLogResponse:
- logs: list[RawLogStream] = []
- messages = [
- f"Reading remote log from Cloudwatch log_group: {self.log_group}
log_stream: {relative_path}"
- ]
+ def stream(
+ self, relative_path: str, ti: RuntimeTI | None, *, tail_lines: int |
None = None
+ ) -> StreamingLogResponse:
+ """
+ Read every stream the path is a prefix of, such as ``<task
log>.trigger.<triggerer job id>.log``.
+
+ With ``tail_lines``, read only the last ``tail_lines`` events of each
stream, from its end.
+ """
+ messages: list[str] = []
try:
- gen: RawLogStream = (
- self._parse_log_event_as_dumped_json(event)
- for event in self.get_cloudwatch_logs(relative_path, ti)
+ names = self._list_log_stream_names(relative_path)
Review Comment:
This adds a `DescribeLogStreams` call to every log read, and the UI polls
running tasks. When the per-account quota throttles, the trigger lines quietly
drop out. Could the docs mention the quota? Could we also skip the listing for
tasks that are running and haven't deferred?
##########
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:
`upload()` now passes a stream name, and nothing else calls `close()`
without one. So `_closed` is never set. On workers, a logging reset after the
final upload now rebuilds the handler and starts a new thread, which the old
guard prevented. Is that intended?
##########
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:
This test and the ones at lines 330, 1207, 1239 and 1275 check real elapsed
time with racing `threading.Timers`, so they can flake on a busy CI runner.
Could they assert order instead, e.g. `assert not
release["throttled"].is_set()` after upload returns?
##########
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:
This patches `time.monotonic` for the whole process, so `moto` and
`botocore` see the fake clock too. Same for `time.sleep` at lines 1094 and
1112. Could these patch
`airflow.providers.amazon.aws.log.cloudwatch_task_handler.time.monotonic` (and
`.time.sleep`) instead?
--
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]