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


##########
airflow-core/src/airflow/utils/log/trigger_log_reader.py:
##########
@@ -0,0 +1,610 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Read a trigger's log lines, whatever its kind, live from its triggerer, 
from remote logging and locally."""
+
+from __future__ import annotations
+
+import datetime
+import functools
+import heapq
+import inspect
+import itertools
+import json
+import os
+from collections import deque
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from sqlalchemy import not_, select
+
+from airflow.configuration import conf
+from airflow.jobs.job import Job
+from airflow.logging_config import get_remote_task_log
+from airflow.models.trigger import TriggerKind
+from airflow.utils.log.file_task_handler import (
+    DEFAULT_SORT_DATETIME,
+    FileTaskHandler,
+    LogType,
+    StructuredLogMessage,
+    _get_compatible_log_stream,
+    fetch_logs_from_service,
+    get_log_server_url,
+    log_stream_to_parsed_log_stream,
+)
+from airflow.utils.log.path_log_reader import read_local_logs, 
validate_log_path_component
+from airflow.utils.log.task_log_address import prepare_task_log_contexts, 
render_task_log_filename
+from airflow.utils.log.trigger_log import (
+    TRIGGERER_JOB_ID_KEY,
+    get_callback_trigger_log_relative_path,
+    get_trigger_log_dir,
+    get_trigger_log_held_path,
+    get_trigger_log_relative_path,
+    get_trigger_log_rotated_path,
+    list_trigger_log_files,
+    parse_trigger_log_dir_id,
+)
+
+if TYPE_CHECKING:
+    from collections.abc import Generator, Iterable, Sequence
+
+    from sqlalchemy.orm import Session
+
+    from airflow._shared.logging.remote import RawLogStream
+    from airflow.models.trigger import Trigger
+
+# Bytes asked of a log server per line; a tail with fewer whole lines is asked 
again, GROWTH times larger.
+LIVE_TAIL_BYTES_PER_LINE = 2048
+LIVE_TAIL_GROWTH = 8
+LIVE_TAIL_MAX_BYTES = 64 * 1024 * 1024
+# Most bytes of log lines one request keeps; past it, older files and 
triggerer jobs are not read.
+READ_MAX_BYTES = 64 * 1024 * 1024
+_REMOTE_READ_FAILED = "Could not read remote logs"
+_REMOTE_NOT_READ_AFTER_FAILURE = (
+    "Remote logs of older triggerer jobs were not read: the remote log store 
failed."
+)
+_NOT_READ_PAST_CAP = f"Older lines were not shown: a request keeps at most 
{READ_MAX_BYTES // 2**20} MiB."
+# Most triggerer jobs looked at for a watcher: each costs a remote read, and 
every triggerer start is a job.
+READ_MAX_JOBS = 50
+# Recent lines remembered to drop copies read from another source.
+_SEEN_MAX = 10_000
+
+
+def read_trigger_logs(trigger: Trigger, *, tail_lines: int, session: Session) 
-> list[StructuredLogMessage]:
+    """
+    Return the last ``tail_lines`` lines a trigger logged, read live, from 
remote logging and from local disk.
+
+    A task's trigger logs to ``<try log>.trigger.<triggerer job id>.log``, a 
callback's to the callback's log,
+    and an asset watcher to its own files. Needs ``triggerer_job`` and the 
owner loaded.
+    """
+    job = trigger.triggerer_job
+    owner = (job.id, job.hostname) if job is not None and 
trigger.is_owner_alive() else None
+    kind = trigger.kind
+    if kind == TriggerKind.TASK and (ti := trigger.task_instance) is not None:
+        context = prepare_task_log_contexts([ti], session=session)[ti.id]
+        try_log = render_task_log_filename(ti, ti.try_number, context=context)
+        prefix = f"{FileTaskHandler.add_triggerer_suffix(try_log)}."
+        live = FileTaskHandler.add_triggerer_suffix(try_log, job_id=owner[0]) 
if owner else None
+        if _remote_handler_streams() and (
+            job_ids := _get_triggerer_job_ids(trigger, session=session, 
limit=READ_MAX_JOBS)
+        ):
+            return _read_task_trigger_streams(
+                str(ti.id),
+                try_log,
+                prefix,
+                job_ids,
+                live=live,
+                owner=owner,
+                tail_lines=tail_lines,
+                session=session,
+            )
+        return _read_tail(stored=prefix, local=[prefix], live=live, 
owner=owner, tail_lines=tail_lines)
+    if kind == TriggerKind.CALLBACK and (callback := trigger.callback) is not 
None:
+        path = get_callback_trigger_log_relative_path(callback)
+        try:
+            for component in path.split("/"):
+                validate_log_path_component(component)
+        except ValueError:
+            return [StructuredLogMessage(event=f"Not reading a log outside the 
log folder: {path}")]
+        return _read_tail(
+            stored=path, local=[path], live=path if owner else None, 
owner=owner, tail_lines=tail_lines
+        )
+    return _read_watcher_tail(trigger, owner=owner, tail_lines=tail_lines, 
session=session)
+
+
+def _read_tail(
+    *,
+    stored: str,
+    local: list[str],
+    live: str | None,
+    owner: tuple[int, str | None] | None,
+    tail_lines: int,
+) -> list[StructuredLogMessage]:
+    sources, lines, size = _read_sources(
+        stored=stored, local=local, live=live, owner=owner, 
tail_lines=tail_lines, max_bytes=READ_MAX_BYTES
+    )
+    if size > READ_MAX_BYTES:
+        sources.append(_NOT_READ_PAST_CAP)
+    return _build_tail(sources, lines, tail_lines=tail_lines)
+
+
+def _read_task_trigger_streams(
+    ti_id: str,
+    try_log: str,
+    prefix: str,
+    job_ids: list[int],
+    *,
+    live: str | None,
+    owner: tuple[int, str | None] | None,
+    tail_lines: int,
+    session: Session,
+) -> list[StructuredLogMessage]:
+    """Read a task trigger's remote streams by name: a streaming handler keeps 
one per triggerer job."""
+    sources, lines, size = _read_sources(
+        stored=prefix,
+        local=[prefix],
+        live=live,
+        owner=owner,
+        tail_lines=tail_lines,
+        max_bytes=READ_MAX_BYTES,
+        remote=False,
+    )
+    found = 0
+    ends: dict[int, datetime.datetime] | None = None
+    for job_id in job_ids:
+        if size >= READ_MAX_BYTES:
+            break
+        if found >= tail_lines:
+            # The trigger can be back on a triggerer that ran it before: read 
on while a job wrote after them.
+            if ends is None:
+                ends = _get_triggerer_job_ends(job_ids, session=session)
+            if _ended_before_tail(ends.get(job_id), lines, 
tail_lines=tail_lines):
+                break
+        job_sources, job_lines, job_size = _read_sources(
+            stored=FileTaskHandler.add_triggerer_suffix(try_log, 
job_id=job_id),
+            local=[],
+            live=None,
+            owner=None,
+            tail_lines=tail_lines,
+            max_bytes=READ_MAX_BYTES - size,
+        )
+        # A job that never ran the trigger answers with a notice, not a line 
of the try.
+        job_lines = [stream for stream in job_lines if 
next(_filter_lines(stream, "ti_id", ti_id), None)]
+        failed = any(s.startswith(_REMOTE_READ_FAILED) for s in job_sources)
+        if job_lines or failed:
+            sources.extend(job_sources)
+        lines.extend(job_lines)
+        found += sum(map(len, job_lines))
+        size += job_size
+        if failed:
+            sources.append(_REMOTE_NOT_READ_AFTER_FAILURE)
+            break
+    if size > READ_MAX_BYTES:
+        sources.append(_NOT_READ_PAST_CAP)
+    return _build_tail(sources, lines, tail_lines=tail_lines)
+
+
+def _read_watcher_tail(
+    trigger: Trigger, *, owner: tuple[int, str | None] | None, tail_lines: 
int, session: Session
+) -> list[StructuredLogMessage]:
+    """
+    Read an asset watcher's files newest triggerer first, and stop once enough 
lines are read.
+
+    With no triggerer known, as after ``airflow db clean``, the trigger's 
whole directory is read.
+    """
+    base = Path(os.path.realpath(conf.get("logging", "base_log_folder")))
+    local_by_job: dict[int, list[str]] = {}
+    for job_dir in 
sorted(base.glob(f"{get_trigger_log_dir(trigger.id)}/{TRIGGERER_JOB_ID_KEY}=*")):
+        files = [
+            path.relative_to(base).as_posix() for path in 
list_trigger_log_files(job_dir) if path.is_file()
+        ]
+        if files and (job_id := parse_trigger_log_dir_id(TRIGGERER_JOB_ID_KEY, 
job_dir.name)) is not None:

Review Comment:
   Good catch, there are currently no `Job`-less triggerers but there will be, 
and the details depend on how AIP-92 progresses. With that in mind, those dirs 
are now always read locally, and remotely while no `Job` holds the trigger. 
Once a DB triggerer has it again, the remote files of a `Job`-less triggerer 
aren't found, since nothing records which `Job`-less triggerers ran a trigger. 
For posterity I've added a test that trips when that changes.
   



##########
airflow-core/src/airflow/ui/src/queries/useLogs.tsx:
##########
@@ -413,3 +417,30 @@ export const useCallbackLogs = ({ callbackId, dagId, 
dagRunId, ...displayOptions
 
   return { parsedData: { ...parsedData, searchableText }, ...rest, 
fetchedData: data };
 };
+
+type TriggerLogsProps = { triggerId: number } & Omit<
+  Props,
+  "accept" | "dagId" | "historical" | "limit" | "taskInstance" | "tryNumber"
+>;
+
+export const useTriggerLogs = ({ triggerId, ...displayOptions }: 
TriggerLogsProps) => {
+  const { t: translate } = useTranslation();
+  const refetchInterval = useAutoRefresh({});
+
+  // A live trigger keeps logging; stop on an error, such as the 404 once it 
has finished.
+  const { data, ...rest } = useTriggerServiceGetTriggerLogs(
+    { accept: "application/x-ndjson", triggerId },
+    undefined,
+    { refetchInterval: ({ state }) => state.status !== "error" && 
refetchInterval },

Review Comment:
   Went further than a slower rate for watchers: while a triggerer runs the 
trigger, a refresh only reads what was added to its live file, so it no longer 
calls the remote log store. Otherwise the tab backs off as `useAutoRefresh` 
does, and it stops refreshing once the trigger is gone. All triggers are 
treated the same.
   



##########
airflow-core/src/airflow/jobs/triggerer_job_runner.py:
##########
@@ -1128,12 +1129,15 @@ def record_trigger_success(self, trigger_id: int) -> 
None:
             self._mark_recovered(trigger_id, after_failures)
 
     def _mark_recovered(self, trigger_id: int, after_failures: int) -> None:
-        log.info(
-            "Trigger recovered",
-            trigger_id=trigger_id,
-            trigger_kind=self.trigger_kinds.get(trigger_id),
-            after_failures=after_failures,
-        )
+        fields = {"trigger_kind": self.trigger_kinds.get(trigger_id), 
"after_failures": after_failures}
+        log.info("Trigger recovered", trigger_id=trigger_id, **fields)
+        if isinstance(factory := self.logger_cache.get(trigger_id), 
WatcherLoggingFactory):

Review Comment:
   Yeah, I see what you mean, but I do see this change as being related to 
reading trigger logs: a watcher's file already gets its failures, but "Trigger 
recovered" went only to the triggerer's output, so the Logs tab would show a 
watcher failing and never recovering. Happy to split it out if you'd still 
rather.
   



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