amoghrajesh commented on code in PR #69877:
URL: https://github.com/apache/airflow/pull/69877#discussion_r3613772496
##########
task-sdk/src/airflow/sdk/execution_time/task_runner.py:
##########
@@ -1998,20 +2002,39 @@ def _send_error_email_notification(
error: BaseException | str | None,
log: Logger,
) -> None:
- """Send email notification for task errors using SmtpNotifier."""
- try:
- from airflow.providers.smtp.notifications.smtp import SmtpNotifier
- except ImportError:
- log.error(
- "Failed to send task failure or retry email notification: "
- "`apache-airflow-providers-smtp` is not installed. "
- "Install this provider to enable email notifications."
- )
- return
+ """
+ Send email notification for task errors through the configured email
backend.
+
+ A non-default ``[email] email_backend`` (an SES, SendGrid or org-internal
callable with the
+ ``airflow.utils.email.send_email`` signature) is wrapped in
+
:class:`~airflow.sdk.execution_time.email_backend._LegacyEmailBackendNotifier`;
otherwise the
+ default :class:`~airflow.providers.smtp.notifications.smtp.SmtpNotifier`
is used.
+ Both the worker task-runner path (:func:`finalize`) and the DAG-processor
callback path
+ (``_execute_email_callbacks``) funnel through this function, so the
resolved backend is used
+ consistently regardless of how the task failed.
+ """
if not task.email:
return
+ email_backend = conf.get("email", "email_backend",
fallback=DEFAULT_EMAIL_BACKEND)
+ notifier_description = "SmtpNotifier"
+
+ if email_backend and email_backend != DEFAULT_EMAIL_BACKEND:
+ notifier_class: type = _LegacyEmailBackendNotifier
Review Comment:
Should be: `type[BaseNotifier]`?
##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -4008,6 +4032,82 @@ def execute(self, context):
)
assert kwargs["from_email"] == self.FROM
+ def test_custom_email_backend_is_used(self, create_runtime_ti,
mock_supervisor_comms):
+ """A custom ``[email] email_backend`` is wrapped and invoked with
rendered fields."""
+ from airflow.sdk.exceptions import AirflowFailException
+ from airflow.sdk.execution_time.task_runner import finalize, run
+
+ backend = mock.create_autospec(_recording_email_backend)
+
+ class FailingOperator(BaseOperator):
+ def execute(self, context):
+ raise AirflowFailException("Task failed on purpose")
+
+ task = FailingOperator(
+ task_id="legacy_backend_task",
+ email=["[email protected]"],
+ email_on_failure=True,
+ )
+
+ runtime_ti = create_runtime_ti(task=task)
+ context = runtime_ti.get_template_context()
+ log = mock.MagicMock()
+
+ with conf_vars(
+ {
+ ("email", "email_backend"):
f"{__name__}._recording_email_backend",
+ ("email", "email_conn_id"): "my_smtp",
+ ("email", "from_email"): self.FROM,
+ }
+ ):
+ with mock.patch(f"{__name__}._recording_email_backend", backend):
+ with mock.patch(
+ "airflow.providers.smtp.notifications.smtp.SmtpNotifier",
autospec=True
+ ) as mock_smtp_notifier:
+ state, _, error = run(runtime_ti, context, log)
+ finalize(runtime_ti, state, context, log, error)
+
+ # The default SMTP notifier must not be used when a custom backend is
configured.
+ mock_smtp_notifier.assert_not_called()
+ backend.assert_called_once()
+ args, kwargs = backend.call_args
+ # send_email(to, subject, html_content, conn_id=..., from_email=...)
+ assert args[0] == ["[email protected]"]
+ assert kwargs["conn_id"] == "my_smtp"
+ assert kwargs["from_email"] == self.FROM
+
+ def test_unresolvable_email_backend_is_logged(self, create_runtime_ti,
mock_supervisor_comms):
+ """An unimportable custom backend is logged, and does not silently
fall back to SMTP."""
+ from airflow.sdk.exceptions import AirflowFailException
+ from airflow.sdk.execution_time.task_runner import finalize, run
Review Comment:
Same here.
##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -4008,6 +4032,82 @@ def execute(self, context):
)
assert kwargs["from_email"] == self.FROM
+ def test_custom_email_backend_is_used(self, create_runtime_ti,
mock_supervisor_comms):
+ """A custom ``[email] email_backend`` is wrapped and invoked with
rendered fields."""
+ from airflow.sdk.exceptions import AirflowFailException
+ from airflow.sdk.execution_time.task_runner import finalize, run
Review Comment:
Top level imports instead please
##########
task-sdk/src/airflow/sdk/execution_time/task_runner.py:
##########
@@ -1998,20 +2002,39 @@ def _send_error_email_notification(
error: BaseException | str | None,
log: Logger,
) -> None:
- """Send email notification for task errors using SmtpNotifier."""
- try:
- from airflow.providers.smtp.notifications.smtp import SmtpNotifier
- except ImportError:
- log.error(
- "Failed to send task failure or retry email notification: "
- "`apache-airflow-providers-smtp` is not installed. "
- "Install this provider to enable email notifications."
- )
- return
+ """
+ Send email notification for task errors through the configured email
backend.
+
+ A non-default ``[email] email_backend`` (an SES, SendGrid or org-internal
callable with the
+ ``airflow.utils.email.send_email`` signature) is wrapped in
+
:class:`~airflow.sdk.execution_time.email_backend._LegacyEmailBackendNotifier`;
otherwise the
+ default :class:`~airflow.providers.smtp.notifications.smtp.SmtpNotifier`
is used.
+ Both the worker task-runner path (:func:`finalize`) and the DAG-processor
callback path
+ (``_execute_email_callbacks``) funnel through this function, so the
resolved backend is used
+ consistently regardless of how the task failed.
+ """
if not task.email:
return
+ email_backend = conf.get("email", "email_backend",
fallback=DEFAULT_EMAIL_BACKEND)
+ notifier_description = "SmtpNotifier"
+
+ if email_backend and email_backend != DEFAULT_EMAIL_BACKEND:
+ notifier_class: type = _LegacyEmailBackendNotifier
+ notifier_description = f"email_backend {email_backend!r}"
Review Comment:
```suggestion
notifier_description = f"configured email_backend {email_backend!r}"
```
##########
task-sdk/src/airflow/sdk/execution_time/email_backend.py:
##########
@@ -0,0 +1,75 @@
+# 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.
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from airflow.sdk.bases.notifier import BaseNotifier
+from airflow.sdk.configuration import conf
+from airflow.sdk.exceptions import AirflowConfigException
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from airflow.sdk.definitions.context import Context
+
+DEFAULT_EMAIL_BACKEND = "airflow.utils.email.send_email_smtp"
Review Comment:
```suggestion
_DEFAULT_EMAIL_BACKEND = "airflow.utils.email.send_email_smtp"
```
better?
##########
task-sdk/src/airflow/sdk/execution_time/task_runner.py:
##########
Review Comment:
This is also called by dag processor path, worth adding some tests there too?
--
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]