You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "james5418 (via GitHub)" <gi...@apache.org> on 2025/04/04 07:19:37 UTC

[PR] HdfsTaskHandler structlog rework [airflow]

james5418 opened a new pull request, #48788:
URL: https://github.com/apache/airflow/pull/48788

   <!--
    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.
    -->
   
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   
   
   <!-- Please keep an empty line above the dashes. -->
   
   related: #48685
   
   Also, unit tests for hdfs logging (`HdfsTaskHandler`) were added.
   
   ---
   **^ Add meaningful description above**
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2028396729


##########
airflow-core/src/airflow/config_templates/airflow_local_settings.py:
##########
@@ -129,7 +129,16 @@
 ##################
 
 REMOTE_LOGGING: bool = conf.getboolean("logging", "remote_logging")
-REMOTE_TASK_LOG: RemoteLogIO | None = None
+REMOTE_TASK_LOG: (
+    RemoteLogIO
+    | S3RemoteLogIO
+    | CloudWatchRemoteLogIO
+    | GCSRemoteLogIO
+    | WasbRemoteLogIO
+    | OSSRemoteLogIO
+    | HdfsRemoteLogIO
+    | None
+) = None

Review Comment:
   This shouldn't be required -- RemoteLogIO is a protocol that say what the types need to implement



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "james5418 (via GitHub)" <gi...@apache.org>.
james5418 commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2036649771


##########
airflow-core/src/airflow/config_templates/airflow_local_settings.py:
##########
@@ -129,7 +129,7 @@
 ##################
 
 REMOTE_LOGGING: bool = conf.getboolean("logging", "remote_logging")
-REMOTE_TASK_LOG: RemoteLogIO | None = None
+REMOTE_TASK_LOG: RemoteLogIO | None = None  # type: ignore

Review Comment:
   There was a mypy error before, but now it passes. I can remove it!



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "eladkal (via GitHub)" <gi...@apache.org>.
eladkal commented on PR #48788:
URL: https://github.com/apache/airflow/pull/48788#issuecomment-2779175485

   There are mypy failures


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2028811424


##########
airflow-core/src/airflow/config_templates/airflow_local_settings.py:
##########
@@ -129,7 +129,16 @@
 ##################
 
 REMOTE_LOGGING: bool = conf.getboolean("logging", "remote_logging")
-REMOTE_TASK_LOG: RemoteLogIO | None = None
+REMOTE_TASK_LOG: (
+    RemoteLogIO
+    | S3RemoteLogIO
+    | CloudWatchRemoteLogIO
+    | GCSRemoteLogIO
+    | WasbRemoteLogIO
+    | OSSRemoteLogIO
+    | HdfsRemoteLogIO
+    | None
+) = None

Review Comment:
   As anything that fails to match this type would fail at runtime.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb merged PR #48788:
URL: https://github.com/apache/airflow/pull/48788


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #48788:
URL: https://github.com/apache/airflow/pull/48788#issuecomment-2777756741

   Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide (https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
   Here are some useful points:
   - Pay attention to the quality of your code (ruff, mypy and type annotations). Our [pre-commits]( https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#prerequisites-for-pre-commit-hooks) will help you with that.
   - In case of a new feature add useful documentation (in docstrings or in `docs/` directory). Adding a new operator? Check this short [guide](https://github.com/apache/airflow/blob/main/airflow-core/docs/howto/custom-operator.rst) Consider adding an example DAG that shows how users should use it.
   - Consider using [Breeze environment](https://github.com/apache/airflow/blob/main/dev/breeze/doc/README.rst) for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
   - Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
   - Please follow [ASF Code of Conduct](https://www.apache.org/foundation/policies/conduct) for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
   - Be sure to read the [Airflow Coding style]( https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#coding-style-and-best-practices).
   - Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
   Apache Airflow is a community-driven project and together we are making it better 🚀.
   In case of doubts contact the developers at:
   Mailing List: dev@airflow.apache.org
   Slack: https://s.apache.org/airflow-slack
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2028810751


##########
airflow-core/src/airflow/config_templates/airflow_local_settings.py:
##########
@@ -129,7 +129,16 @@
 ##################
 
 REMOTE_LOGGING: bool = conf.getboolean("logging", "remote_logging")
-REMOTE_TASK_LOG: RemoteLogIO | None = None
+REMOTE_TASK_LOG: (
+    RemoteLogIO
+    | S3RemoteLogIO
+    | CloudWatchRemoteLogIO
+    | GCSRemoteLogIO
+    | WasbRemoteLogIO
+    | OSSRemoteLogIO
+    | HdfsRemoteLogIO
+    | None
+) = None

Review Comment:
   ```suggestion
   REMOTE_TASK_LOG: RemoteLogIO | None = None
   ```



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "eladkal (via GitHub)" <gi...@apache.org>.
eladkal commented on PR #48788:
URL: https://github.com/apache/airflow/pull/48788#issuecomment-2779504525

   Needs also to apply patch for ti read similar to https://github.com/apache/airflow/pull/48804


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "james5418 (via GitHub)" <gi...@apache.org>.
james5418 commented on PR #48788:
URL: https://github.com/apache/airflow/pull/48788#issuecomment-2780354328

   > There are mypy failures
   
   I just added `# type: ignore` on this line to bypass the mypy type-checking error.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2036295899


##########
airflow-core/src/airflow/config_templates/airflow_local_settings.py:
##########
@@ -129,7 +129,7 @@
 ##################
 
 REMOTE_LOGGING: bool = conf.getboolean("logging", "remote_logging")
-REMOTE_TASK_LOG: RemoteLogIO | None = None
+REMOTE_TASK_LOG: RemoteLogIO | None = None  # type: ignore

Review Comment:
   Yeah, shouldn't be needed unless you haven't implemented the protocol fully.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on PR #48788:
URL: https://github.com/apache/airflow/pull/48788#issuecomment-2779546607

   > Needs also to apply patch for ti read similar to #48804
   
   And now upload.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #48788:
URL: https://github.com/apache/airflow/pull/48788#issuecomment-2792269140

   Awesome work, congrats on your first merged pull request! You are invited to check our [Issue Tracker](https://github.com/apache/airflow/issues) for additional contributions.
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "eladkal (via GitHub)" <gi...@apache.org>.
eladkal commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2036289723


##########
airflow-core/src/airflow/config_templates/airflow_local_settings.py:
##########
@@ -129,7 +129,7 @@
 ##################
 
 REMOTE_LOGGING: bool = conf.getboolean("logging", "remote_logging")
-REMOTE_TASK_LOG: RemoteLogIO | None = None
+REMOTE_TASK_LOG: RemoteLogIO | None = None  # type: ignore

Review Comment:
   why type ignore was added?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2036299087


##########
providers/apache/hdfs/src/airflow/providers/apache/hdfs/log/hdfs_task_handler.py:
##########
@@ -17,45 +17,102 @@
 # under the License.
 from __future__ import annotations
 
+import logging
 import os
-import pathlib
 import shutil
 from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING
 from urllib.parse import urlsplit
 
+import attrs
+
 from airflow.configuration import conf
 from airflow.providers.apache.hdfs.hooks.webhdfs import WebHDFSHook
 from airflow.utils.log.file_task_handler import FileTaskHandler
 from airflow.utils.log.logging_mixin import LoggingMixin
 
+if TYPE_CHECKING:
+    from airflow.models.taskinstance import TaskInstance
+    from airflow.sdk.types import RuntimeTaskInstanceProtocol as RuntimeTI
+    from airflow.utils.log.file_task_handler import LogMessages, LogSourceInfo
+
+
+@attrs.define(kw_only=True)
+class HdfsRemoteLogIO(LoggingMixin):  # noqa: D101
+    remote_base: str
+    base_log_folder: Path = attrs.field(converter=Path)
+    delete_local_copy: bool
+
+    processors = ()
+
+    def upload(self, path: os.PathLike | str, ti: RuntimeTI):
+        """Upload the given log path to the remote storage."""
+        path = Path(path)
+        if path.is_absolute():
+            local_loc = path
+            remote_loc = os.path.join(self.remote_base, path.relative_to(self.base_log_folder))
+        else:
+            local_loc = self.base_log_folder.joinpath(path)
+            remote_loc = os.path.join(self.remote_base, path)
+
+        if local_loc.is_file():
+            self.hook.load_file(local_loc, remote_loc)
+            if self.delete_local_copy:
+                shutil.rmtree(os.path.dirname(local_loc))
+
+    @cached_property
+    def hook(self):
+        """Returns WebHDFSHook."""
+        return WebHDFSHook(webhdfs_conn_id=conf.get("logging", "REMOTE_LOG_CONN_ID"))
+
+    def read(self, relative_path: str, ti: RuntimeTI) -> tuple[LogSourceInfo, LogMessages]:
+        logs = []
+        messages = []
+        file_path = os.path.join(self.remote_base, relative_path)
+        if self.hook.check_for_path(file_path):
+            logs.append(self.hook.read_file(file_path).decode("utf-8"))
+        else:
+            messages.append(f"No logs found on hdfs for ti={ti}")
+        return messages, logs
+
 
 class HdfsTaskHandler(FileTaskHandler, LoggingMixin):
-    """Logging handler to upload and read from HDFS."""
+    """
+    HdfsTaskHandler is a Python logging handler that handles and reads task instance logs.
+
+    It extends airflow FileTaskHandler and uploads to and reads from HDFS.
+    """
 
     def __init__(self, base_log_folder: str, hdfs_log_folder: str, **kwargs):
         super().__init__(base_log_folder)
+        self.handler: logging.FileHandler | None = None
         self.remote_base = urlsplit(hdfs_log_folder).path
         self.log_relative_path = ""
         self._hook = None
         self.closed = False
         self.upload_on_close = True
-        self.delete_local_copy = kwargs.get(
-            "delete_local_copy", conf.getboolean("logging", "delete_local_logs")
-        )
 
-    @cached_property
-    def hook(self):
-        """Returns WebHDFSHook."""
-        return WebHDFSHook(webhdfs_conn_id=conf.get("logging", "REMOTE_LOG_CONN_ID"))
+        self.io = HdfsRemoteLogIO(
+            remote_base=hdfs_log_folder,
+            base_log_folder=base_log_folder,
+            delete_local_copy=kwargs.get(
+                "delete_local_copy", conf.getboolean("logging", "delete_local_logs")
+            ),
+        )
 
-    def set_context(self, ti):
+    def set_context(self, ti: TaskInstance, *, identifier: str | None = None) -> None:

Review Comment:
   Why is `identifer` added here? Nothing ever calls it with it



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] HdfsTaskHandler structlog rework [airflow]

Posted by "james5418 (via GitHub)" <gi...@apache.org>.
james5418 commented on code in PR #48788:
URL: https://github.com/apache/airflow/pull/48788#discussion_r2036622749


##########
providers/apache/hdfs/src/airflow/providers/apache/hdfs/log/hdfs_task_handler.py:
##########
@@ -17,45 +17,102 @@
 # under the License.
 from __future__ import annotations
 
+import logging
 import os
-import pathlib
 import shutil
 from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING
 from urllib.parse import urlsplit
 
+import attrs
+
 from airflow.configuration import conf
 from airflow.providers.apache.hdfs.hooks.webhdfs import WebHDFSHook
 from airflow.utils.log.file_task_handler import FileTaskHandler
 from airflow.utils.log.logging_mixin import LoggingMixin
 
+if TYPE_CHECKING:
+    from airflow.models.taskinstance import TaskInstance
+    from airflow.sdk.types import RuntimeTaskInstanceProtocol as RuntimeTI
+    from airflow.utils.log.file_task_handler import LogMessages, LogSourceInfo
+
+
+@attrs.define(kw_only=True)
+class HdfsRemoteLogIO(LoggingMixin):  # noqa: D101
+    remote_base: str
+    base_log_folder: Path = attrs.field(converter=Path)
+    delete_local_copy: bool
+
+    processors = ()
+
+    def upload(self, path: os.PathLike | str, ti: RuntimeTI):
+        """Upload the given log path to the remote storage."""
+        path = Path(path)
+        if path.is_absolute():
+            local_loc = path
+            remote_loc = os.path.join(self.remote_base, path.relative_to(self.base_log_folder))
+        else:
+            local_loc = self.base_log_folder.joinpath(path)
+            remote_loc = os.path.join(self.remote_base, path)
+
+        if local_loc.is_file():
+            self.hook.load_file(local_loc, remote_loc)
+            if self.delete_local_copy:
+                shutil.rmtree(os.path.dirname(local_loc))
+
+    @cached_property
+    def hook(self):
+        """Returns WebHDFSHook."""
+        return WebHDFSHook(webhdfs_conn_id=conf.get("logging", "REMOTE_LOG_CONN_ID"))
+
+    def read(self, relative_path: str, ti: RuntimeTI) -> tuple[LogSourceInfo, LogMessages]:
+        logs = []
+        messages = []
+        file_path = os.path.join(self.remote_base, relative_path)
+        if self.hook.check_for_path(file_path):
+            logs.append(self.hook.read_file(file_path).decode("utf-8"))
+        else:
+            messages.append(f"No logs found on hdfs for ti={ti}")
+        return messages, logs
+
 
 class HdfsTaskHandler(FileTaskHandler, LoggingMixin):
-    """Logging handler to upload and read from HDFS."""
+    """
+    HdfsTaskHandler is a Python logging handler that handles and reads task instance logs.
+
+    It extends airflow FileTaskHandler and uploads to and reads from HDFS.
+    """
 
     def __init__(self, base_log_folder: str, hdfs_log_folder: str, **kwargs):
         super().__init__(base_log_folder)
+        self.handler: logging.FileHandler | None = None
         self.remote_base = urlsplit(hdfs_log_folder).path
         self.log_relative_path = ""
         self._hook = None
         self.closed = False
         self.upload_on_close = True
-        self.delete_local_copy = kwargs.get(
-            "delete_local_copy", conf.getboolean("logging", "delete_local_logs")
-        )
 
-    @cached_property
-    def hook(self):
-        """Returns WebHDFSHook."""
-        return WebHDFSHook(webhdfs_conn_id=conf.get("logging", "REMOTE_LOG_CONN_ID"))
+        self.io = HdfsRemoteLogIO(
+            remote_base=hdfs_log_folder,
+            base_log_folder=base_log_folder,
+            delete_local_copy=kwargs.get(
+                "delete_local_copy", conf.getboolean("logging", "delete_local_logs")
+            ),
+        )
 
-    def set_context(self, ti):
+    def set_context(self, ti: TaskInstance, *, identifier: str | None = None) -> None:

Review Comment:
   It’s added to avoid a mypy error.
   ![image](https://github.com/user-attachments/assets/2291235f-3662-408d-94dd-5d7078be264b)
   



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org