Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add task ID pattern to notification skip criteria (#960)
Madison Swain-Bowden3a963fce26d8
diff --git a/openverse_catalog/dags/common/slack.py b/openverse_catalog/dags/common/slack.pyindex 4c888d382..83014bbb5 100644--- a/openverse_catalog/dags/common/slack.py+++ b/openverse_catalog/dags/common/slack.py@@ -50,14 +50,16 @@ variable to `true` in the Airflow UI.import jsonimport logging+import refrom collections.abc import Callablefrom os.path import basename-from typing import Any, TypedDict+from typing import Anyfrom airflow.exceptions import AirflowNotFoundExceptionfrom airflow.models import Variablefrom airflow.providers.http.hooks.http import HttpHookfrom requests import Response+from typing_extensions import NotRequired, TypedDictSLACK_NOTIFICATIONS_CONN_ID = "slack_notifications"@@ -70,14 +72,17 @@ class SilencedSlackNotification(TypedDict):"""Configuration for a silenced Slack notification.- issue: A link to a GitHub issue which describes why the notification- is silenced and tracks resolving the problem.+ issue: A link to a GitHub issue which describes why the notification+ is silenced and tracks resolving the problem.predicate: Slack notifications whose text or username contain thepredicate will be silenced. Matching is case-insensitive.+ task_id_pattern: A regex pattern that matches the task_id of the task+ that triggered the notification. (Optional)"""issue: strpredicate: str+ task_id_pattern: NotRequired[str | None]class SlackMessage:@@ -229,7 +234,12 @@ class SlackMessage:return response-def should_silence_message(text, username, dag_id):+def should_silence_message(+ text: str,+ username: str,+ dag_id: str,+ task_id: str | None = None,+):"""Determine if a Slack message should be silenced.@@ -244,14 +254,29 @@ def should_silence_message(text, username, dag_id):"SILENCED_SLACK_NOTIFICATIONS", default_var={}, deserialize_json=True).get(dag_id, [])- return bool(silenced_notifications) and any(- notification["predicate"].lower() in message.lower()- for notification in silenced_notifications- )+ if not bool(silenced_notifications):+ # No silenced notifications for this DAG, exit early+ return False+ matches = []+ for notification in silenced_notifications:+ # Check that the predicate matches whatever message was raised+ predicate_matches = notification["predicate"].lower() in message.lower()+ # Check that the task ID matches the predicate _if both were supplied_,+ # not all messages supply a task ID but all exception-based alerts do.+ pattern = notification.get("task_id_pattern")+ task_id_matches = (task_id is None or pattern is None) or (+ task_id and pattern and re.search(pattern, task_id)+ )+ matches.append(predicate_matches and task_id_matches)+ return any(matches)def should_send_message(- text, username, dag_id, http_conn_id=SLACK_NOTIFICATIONS_CONN_ID+ text: str,+ username: str,+ dag_id: str,+ http_conn_id: str = SLACK_NOTIFICATIONS_CONN_ID,+ task_id: str | None = None,):"""Determine if a Slack message should actually be sent.@@ -269,8 +294,8 @@ def should_send_message(return False# Exit early if this DAG is configured to skip Slack messaging- if should_silence_message(text, username, dag_id):- log.info(f"Skipping Slack notification for {dag_id}.")+ if should_silence_message(text, username, dag_id, task_id):+ log.info(f"Skipping Slack notification for {dag_id}::{task_id}.")return False# Exit early if we aren't on production or if force alert is not set@@ -290,10 +315,13 @@ def send_message(unfurl_links: bool = False,unfurl_media: bool = False,http_conn_id: str = SLACK_NOTIFICATIONS_CONN_ID,+ task_id: str | None = None,) -> None:"""Send a simple slack message, convenience message for short/simple messages."""log.info(text)- if not should_send_message(text, username, dag_id, http_conn_id):+ if not should_send_message(+ text, username, dag_id, http_conn_id=http_conn_id, task_id=task_id+ ):returnenvironment = Variable.get("ENVIRONMENT", default_var="dev")@@ -316,6 +344,7 @@ def send_alert(markdown: bool = True,unfurl_links: bool = False,unfurl_media: bool = False,+ task_id: str | None = None,):"""Send a slack alert.@@ -332,6 +361,7 @@ def send_alert(unfurl_links,unfurl_media,http_conn_id=SLACK_ALERTS_CONN_ID,+ task_id=task_id,)@@ -342,8 +372,9 @@ def on_failure_callback(context: dict) -> None:Errors are only sent out in production and if a Slack connection is defined."""# Get relevant info- dag = context["dag"]ti = context["task_instance"]+ dag_id = ti.dag_id+ task_id = ti.task_idexecution_date = context["execution_date"]exception: Exception | None = context.get("exception")exception_message = ""@@ -362,10 +393,15 @@ def on_failure_callback(context: dict) -> None:"""message = f"""-*DAG*: `{ti.dag_id}`-*Task*: `{ti.task_id}`+*DAG*: `{dag_id}`+*Task*: `{task_id}`*Execution Date*: {execution_date.strftime('%Y-%m-%dT%H:%M:%SZ')}*Log*: {ti.log_url}{exception_message}"""- send_alert(message, dag_id=dag.dag_id, username="Airflow DAG Failure")+ send_alert(+ message,+ dag_id=dag_id,+ task_id=task_id,+ username="Airflow DAG Failure",+ )diff --git a/openverse_catalog/dags/maintenance/check_silenced_dags.py b/openverse_catalog/dags/maintenance/check_silenced_dags.pyindex f89fcf20f..1276bfff4 100644--- a/openverse_catalog/dags/maintenance/check_silenced_dags.py+++ b/openverse_catalog/dags/maintenance/check_silenced_dags.py@@ -47,7 +47,7 @@ def get_issue_info(issue_url: str) -> tuple[str, str, str]:def get_dags_with_closed_issues(github_pat: str, silenced_dags: dict[str, list[SilencedSlackNotification]]-):+) -> list[tuple[str, str, str, str | None]]:gh = GitHubAPI(github_pat)dags_to_reenable = []@@ -60,7 +60,14 @@ def get_dags_with_closed_issues(if github_issue.get("state") == "closed":# If the associated issue has been closed, this DAG can have# alerting reenabled for this predicate.- dags_to_reenable.append((dag_id, issue_url, notification["predicate"]))+ dags_to_reenable.append(+ (+ dag_id,+ issue_url,+ notification["predicate"],+ notification.get("task_id_pattern"),+ )+ )return dags_to_reenable@@ -81,8 +88,9 @@ def check_configuration(github_pat: str):" closed. Please remove them from the silenced_slack_notifications Airflow"" variable or assign a new issue.")- for (dag, issue, predicate) in dags_to_reenable:- message += f"\n - <{issue}|{dag}: '{predicate}'>"+ for (dag, issue, predicate, task_id_pattern) in dags_to_reenable:+ dag_name = f"{dag} ({task_id_pattern})" if task_id_pattern else dag+ message += f"\n - <{issue}|{dag_name}: '{predicate}'>"send_alert(message, dag_id=DAG_ID, username="Silenced DAG Check", unfurl_links=False)diff --git a/tests/dags/common/test_slack.py b/tests/dags/common/test_slack.pyindex 757ea5cdc..ebb662001 100644--- a/tests/dags/common/test_slack.py+++ b/tests/dags/common/test_slack.py@@ -15,6 +15,7 @@ from common.slack import (_FAKE_IMAGE = "http://image.com/img.jpg"+p = pytest.param@pytest.fixture(autouse=True)@@ -340,9 +341,9 @@ def test_should_send_message_is_false_without_hook(http_hook_mock):"silenced_notifications, should_silence",(# Do not silence when silenced_notifications is empty- ({}, False),+ p({}, False, id="empty notifications"),# dag_id is not in silenced_notifications- (+ p({"another_dag_id": [{@@ -352,9 +353,10 @@ def test_should_send_message_is_false_without_hook(http_hook_mock):]},False,+ id="wrong dag_id",),# dag_id is configured, but text and username do not match- (+ p({"test_dag_id": [{@@ -364,9 +366,10 @@ def test_should_send_message_is_false_without_hook(http_hook_mock):]},False,+ id="unmatched predicate",),# text matches- (+ p({"test_dag_id": [{@@ -376,9 +379,10 @@ def test_should_send_message_is_false_without_hook(http_hook_mock):]},True,+ id="matches predicate",),# a substring of text matches- (+ p({"test_dag_id": [{@@ -388,9 +392,10 @@ def test_should_send_message_is_false_without_hook(http_hook_mock):]},True,+ id="matches substring",),# matches are case-insensitive- (+ p({"test_dag_id": [{@@ -400,9 +405,10 @@ def test_should_send_message_is_false_without_hook(http_hook_mock):]},True,+ id="matches case-insensitive",),# username matches- (+ p({"test_dag_id": [{@@ -412,6 +418,73 @@ def test_should_send_message_is_false_without_hook(http_hook_mock):]},True,+ id="matches message username",+ ),+ # Wrong task ID with pattern+ p(+ {+ "test_dag_id": [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "KeyError",+ "task_id_pattern": "totally_different",+ }+ ]+ },+ False,+ id="wrong task_id",+ ),+ p(+ {+ "test_dag_id": [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "Does not exist",+ "task_id_pattern": "test_task_id_1",+ }+ ]+ },+ False,+ id="matches task pattern but not predicate",+ ),+ p(+ {+ "test_dag_id": [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "KeyError",+ "task_id_pattern": "test_task_id_1",+ }+ ]+ },+ True,+ id="matches task pattern and predicate",+ ),+ p(+ {+ "test_dag_id": [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "KeyError",+ "task_id_pattern": "task_id",+ }+ ]+ },+ True,+ id="matches task pattern (substring) and predicate",+ ),+ p(+ {+ "test_dag_id": [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "KeyError",+ "task_id_pattern": "task_.*?_1",+ }+ ]+ },+ True,+ id="matches task pattern (regex) and predicate",),),)@@ -420,7 +493,10 @@ def test_should_silence_message(silenced_notifications, should_silence):MockVariable.get.side_effect = [silenced_notifications]assert (should_silence_message(- "KeyError: 'image'", "Airflow DAG Failure", "test_dag_id"+ "KeyError: 'image'",+ "Airflow DAG Failure",+ "test_dag_id",+ "test_task_id_1",)== should_silence)@@ -461,6 +537,7 @@ def test_send_alert():False,False,http_conn_id=SLACK_ALERTS_CONN_ID,+ task_id=None,)diff --git a/tests/dags/maintenance/test_check_silenced_dags.py b/tests/dags/maintenance/test_check_silenced_dags.pyindex 52eb95c30..b96a7dc5a 100644--- a/tests/dags/maintenance/test_check_silenced_dags.py+++ b/tests/dags/maintenance/test_check_silenced_dags.py@@ -11,18 +11,22 @@ from maintenance.check_silenced_dags import (from tests.factories.github import make_issue+p = pytest.param++@pytest.mark.parametrize("silenced_dags, dags_to_reenable, should_send_alert",(# No Dags to reenable, task should skip- pytest.param(+ p({},[],False,marks=pytest.mark.raises(exception=AirflowSkipException),+ id="none to re-enable",),# One DAG to reenable- (+ p({"dag_a_id": [{@@ -39,9 +43,10 @@ from tests.factories.github import make_issue),],True,+ id="one to re-enable",),# One DAG, multiple notifications to reenable- (+ p({"dag_a_id": [{@@ -67,9 +72,10 @@ from tests.factories.github import make_issue),],True,+ id="one to re-enable, multiple notifications",),# Multiple DAGs to reenable- (+ p({"dag_a_id": [{@@ -97,6 +103,7 @@ from tests.factories.github import make_issue),],True,+ id="multiple to re-enable",),),)@@ -108,7 +115,8 @@ def test_check_configuration(silenced_dags, dags_to_reenable, should_send_alert)),mock.patch("maintenance.check_silenced_dags.get_dags_with_closed_issues",- return_value=dags_to_reenable,+ # Add in shim task ID+ return_value=[(*dag, None) for dag in dags_to_reenable],) as get_dags_with_closed_issues_mock,mock.patch("maintenance.check_silenced_dags.send_alert") as send_alert_mock,):@@ -121,6 +129,36 @@ def test_check_configuration(silenced_dags, dags_to_reenable, should_send_alert)assert f"<{issue_url}|{dag_id}: '{predicate}'>" in message+def test_check_configuration_formats_dag_correctly():+ issue = "https://github.com/WordPress/openverse/issues/1"+ dag = "dag_a_id"+ predicate = "Test exception"+ task_id_pattern = "task_id_a"+ with (+ mock.patch(+ "maintenance.check_silenced_dags.Variable",+ return_value={+ dag: [+ {+ "issue": issue,+ "predicate": predicate,+ "task_id_pattern": task_id_pattern,+ }+ ]+ },+ ),+ mock.patch(+ "maintenance.check_silenced_dags.get_dags_with_closed_issues",+ # Add in shim task ID+ return_value=[(dag, issue, predicate, task_id_pattern)],+ ),+ mock.patch("maintenance.check_silenced_dags.send_alert"),+ ):+ message = check_configuration("not_set")+ # Called with correct dag_ids+ assert f"<{issue}|{dag} ({task_id_pattern}): '{predicate}'>" in message++@pytest.mark.parametrize("open_issues, closed_issues",(@@ -174,7 +212,7 @@ def test_get_dags_with_closed_issues(open_issues, closed_issues):assert len(dags_to_reenable) == len(closed_issues)for issue in closed_issues:- assert (f"dag_{issue}", issue, "test") in dags_to_reenable+ assert (f"dag_{issue}", issue, "test", None) in dags_to_reenable@pytest.mark.parametrize(