Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Use Airflow variable to omit DAGs from any Slack notification (#644)

Staci Coopercec68932ff5d
diff --git a/DAGs.md b/DAGs.md
index 741f405c5..b741d27fd 100644
--- a/DAGs.md
+++ b/DAGs.md
@@ -204,15 +204,17 @@ Checks for DAGs that have silenced Slack alerts which may need to be turned back
on.
When a DAG has known failures, it can be ommitted from Slack error reporting by adding
-an entry to the `silenced_slack_alerts` Airflow variable. This is a dictionary where the
-key is the `dag_id` of the affected DAG, and the value is the URL of a GitHub issue
-tracking the error.
-
-The `check_silenced_alert` DAG iterates over the entries in the `silenced_slack_alerts`
-configuration and verifies that the associated GitHub issues are still open. If an issue
-has been closed, it is assumed that the DAG should have Slack reporting reenabled, and
-an alert is sent to prompt manual update of the configuration. This prevents developers
-from forgetting to reenable Slack reporting after the issue has been resolved.
+an entry to the `silenced_slack_notifications` Airflow variable. This is a dictionary
+where thekey is the `dag_id` of the affected DAG, and the value is a list of
+SilencedSlackNotifications (which map silenced notifications to GitHub URLs) for that
+DAG.
+
+The `check_silenced_dags` DAG iterates over the entries in the
+`silenced_slack_notifications` configuration and verifies that the associated GitHub
+issues are still open. If an issue has been closed, it is assumed that the DAG should
+have Slack reporting reenabled, and an alert is sent to prompt manual update of the
+configuration. This prevents developers from forgetting to reenable Slack reporting
+after the issue has been resolved.
The DAG runs weekly.
diff --git a/openverse_catalog/dags/common/loader/reporting.py b/openverse_catalog/dags/common/loader/reporting.py
index 57d273152..422d3d4e4 100644
--- a/openverse_catalog/dags/common/loader/reporting.py
+++ b/openverse_catalog/dags/common/loader/reporting.py
@@ -163,5 +163,5 @@ def report_completion(
" pulls that may happen concurrently."
)
- send_message(message, username="Airflow DAG Load Data Complete")
+ send_message(message, dag_id=dag_id, username="Airflow DAG Load Data Complete")
return message
diff --git a/openverse_catalog/dags/common/slack.py b/openverse_catalog/dags/common/slack.py
index 122fb3503..330d41991 100644
--- a/openverse_catalog/dags/common/slack.py
+++ b/openverse_catalog/dags/common/slack.py
@@ -51,7 +51,7 @@ variable to `true` in the Airflow UI.
import json
import logging
from os.path import basename
-from typing import Any, Callable, Optional
+from typing import Any, Callable, Optional, TypedDict
from airflow.exceptions import AirflowNotFoundException
from airflow.models import Variable
@@ -65,6 +65,20 @@ JsonDict = dict[str, Any]
log = logging.getLogger(__name__)
+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.
+ predicate: Slack notifications whose text or username contain the
+ predicate will be silenced. Matching is case-insensitive.
+ """
+
+ issue: str
+ predicate: str
+
+
class SlackMessage:
"""Slack Block Message Builder"""
@@ -214,8 +228,57 @@ class SlackMessage:
return response
+def should_silence_message(text, username, dag_id):
+ """
+ Checks the `silenced_slack_notifications` Airflow variable to see if the message
+ should be silenced for this DAG.
+ """
+ # Match on message text and username
+ message = username + text
+
+ # Get the configuration for silenced messages for this DAG
+ silenced_notifications: list[SilencedSlackNotification] = Variable.get(
+ "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
+ )
+
+
+def should_send_message(
+ text, username, dag_id, http_conn_id=SLACK_NOTIFICATIONS_CONN_ID
+):
+ """
+ Returns True if:
+ * A Slack connection is defined
+ * The DAG is not configured to silence messages of this type
+ * We are in the prod env OR the message override is set.
+ """
+ # Exit early if no slack connection exists
+ hook = HttpHook(http_conn_id=http_conn_id)
+ try:
+ hook.get_conn()
+ except AirflowNotFoundException:
+ 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}.")
+ return False
+
+ # Exit early if we aren't on production or if force alert is not set
+ environment = Variable.get("environment", default_var="dev")
+ force_message = Variable.get(
+ "slack_message_override", default_var=False, deserialize_json=True
+ )
+ return environment == "prod" or force_message
+
+
def send_message(
text: str,
+ dag_id: str,
username: str = "Airflow",
icon_emoji: str = ":airflow:",
markdown: bool = True,
@@ -225,7 +288,7 @@ def send_message(
) -> None:
"""Send a simple slack message, convenience message for short/simple messages."""
log.info(text)
- if not should_send_message(http_conn_id):
+ if not should_send_message(text, username, dag_id, http_conn_id):
return
environment = Variable.get("environment", default_var="dev")
@@ -240,29 +303,9 @@ def send_message(
s.send(text)
-def should_send_message(http_conn_id=SLACK_NOTIFICATIONS_CONN_ID):
- """
- Returns true if a Slack connection is defined and we are in production (or
- the message override is set).
- """
- # Exit early if no slack connection exists
- hook = HttpHook(http_conn_id=http_conn_id)
- try:
- hook.get_conn()
- except AirflowNotFoundException:
- return False
-
- # Exit early if we aren't on production or if force alert is not set
- environment = Variable.get("environment", default_var="dev")
- force_message = Variable.get(
- "slack_message_override", default_var=False, deserialize_json=True
- )
- return environment == "prod" or force_message
-
-
def send_alert(
text: str,
- dag_id: str | None = None,
+ dag_id: str,
username: str = "Airflow Alert",
icon_emoji: str = ":airflow:",
markdown: bool = True,
@@ -273,18 +316,9 @@ def send_alert(
Wrapper for send_message that allows sending a message to the configured alerts
channel instead of the default notification channel.
"""
-
- known_failures = Variable.get(
- "silenced_slack_alerts", default_var={}, deserialize_json=True
- )
- if dag_id in known_failures and any(
- error.lower() in text.lower() for error in known_failures[dag_id]["errors"]
- ):
- log.info(f"Skipping Slack alert for {dag_id}: {text}")
- return
-
send_message(
text,
+ dag_id,
username,
icon_emoji,
markdown,
diff --git a/openverse_catalog/dags/data_refresh/dag_factory.py b/openverse_catalog/dags/data_refresh/dag_factory.py
index 0db6c9ae2..b40874af2 100644
--- a/openverse_catalog/dags/data_refresh/dag_factory.py
+++ b/openverse_catalog/dags/data_refresh/dag_factory.py
@@ -233,6 +233,7 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
after_record_count.task_id, "return_value"
),
"media_type": data_refresh.media_type,
+ "dag_id": data_refresh.dag_id,
},
)
diff --git a/openverse_catalog/dags/data_refresh/record_reporting.py b/openverse_catalog/dags/data_refresh/record_reporting.py
index fdd6c8a77..992a68ede 100644
--- a/openverse_catalog/dags/data_refresh/record_reporting.py
+++ b/openverse_catalog/dags/data_refresh/record_reporting.py
@@ -6,7 +6,7 @@ from common import slack
log = logging.getLogger(__name__)
-def report_record_difference(before: str, after: str, media_type: str):
+def report_record_difference(before: str, after: str, media_type: str, dag_id: str):
before = int(before)
after = int(after)
count_diff = after - before
@@ -20,5 +20,7 @@ _Note: All values are row estimates and are not (but nearly) exact_
*Record count difference for `{media_type}`*: {before:,} → {after:,}
*Change*: {count_diff:+,} ({percent_diff:+}% Δ)
"""
- slack.send_message(text=message, username="Data refresh record difference")
+ slack.send_message(
+ text=message, dag_id=dag_id, username="Data refresh record difference"
+ )
return message
diff --git a/openverse_catalog/dags/database/report_pending_reported_media.py b/openverse_catalog/dags/database/report_pending_reported_media.py
index 8ee4f1910..d0fbbf842 100644
--- a/openverse_catalog/dags/database/report_pending_reported_media.py
+++ b/openverse_catalog/dags/database/report_pending_reported_media.py
@@ -127,7 +127,7 @@ The following media have been reported and require manual review:
{media_type_reports}
"""
- slack.send_alert(message, username="Reported Media Requires Review")
+ slack.send_alert(message, dag_id=DAG_ID, username="Reported Media Requires Review")
def create_dag():
diff --git a/openverse_catalog/dags/maintenance/check_silenced_dags.py b/openverse_catalog/dags/maintenance/check_silenced_dags.py
new file mode 100644
index 000000000..e9bd749b0
--- /dev/null
+++ b/openverse_catalog/dags/maintenance/check_silenced_dags.py
@@ -0,0 +1,118 @@
+"""
+Checks for DAGs that have silenced Slack alerts which may need to be turned back
+on.
+
+When a DAG has known failures, it can be ommitted from Slack error reporting by adding
+an entry to the `silenced_slack_notifications` Airflow variable. This is a dictionary
+where thekey is the `dag_id` of the affected DAG, and the value is a list of
+SilencedSlackNotifications (which map silenced notifications to GitHub URLs) for that
+DAG.
+
+The `check_silenced_dags` DAG iterates over the entries in the
+`silenced_slack_notifications` configuration and verifies that the associated GitHub
+issues are still open. If an issue has been closed, it is assumed that the DAG should
+have Slack reporting reenabled, and an alert is sent to prompt manual update of the
+configuration. This prevents developers from forgetting to reenable Slack reporting
+after the issue has been resolved.
+
+The DAG runs weekly.
+"""
+
+import logging
+from datetime import datetime, timedelta
+from typing import Tuple
+
+from airflow.exceptions import AirflowException, AirflowSkipException
+from airflow.models import DAG, Variable
+from airflow.operators.python import PythonOperator
+from common.constants import DAG_DEFAULT_ARGS
+from common.github import GitHubAPI
+from common.slack import SilencedSlackNotification, send_alert
+
+
+logger = logging.getLogger(__name__)
+
+
+DAG_ID = "check_silenced_dags"
+MAX_ACTIVE = 1
+GITHUB_PAT = Variable.get("GITHUB_API_KEY", default_var="not_set")
+
+
+def get_issue_info(issue_url: str) -> Tuple[str, str, str]:
+ """
+ Parses out the owner, repo, and issue_number from a GitHub issue url.
+ """
+ url_split = issue_url.split("/")
+ if len(url_split) < 4:
+ raise AirflowException(f"Issue url {issue_url} could not be parsed.")
+ return url_split[-4], url_split[-3], url_split[-1]
+
+
+def get_dags_with_closed_issues(
+ github_pat: str, silenced_dags: dict[str, list[SilencedSlackNotification]]
+):
+ gh = GitHubAPI(github_pat)
+
+ dags_to_reenable = []
+ for dag_id, silenced_notifications in silenced_dags.items():
+ for notification in silenced_notifications:
+ issue_url = notification["issue"]
+ owner, repo, issue_number = get_issue_info(issue_url)
+ github_issue = gh.get_issue(repo, issue_number, owner)
+
+ 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"]))
+ return dags_to_reenable
+
+
+def check_configuration(github_pat: str):
+ silenced_dags = Variable.get(
+ "silenced_slack_notifications", default_var={}, deserialize_json=True
+ )
+ dags_to_reenable = get_dags_with_closed_issues(github_pat, silenced_dags)
+
+ if not dags_to_reenable:
+ raise AirflowSkipException(
+ "All DAGs configured to silence messages have work still in progress."
+ " No configuration updates needed."
+ )
+
+ message = (
+ "The following DAGs have Slack messages silenced, but the associated issue is"
+ " 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}'>"
+ send_alert(
+ message, dag_id=DAG_ID, username="Silenced DAG Check", unfurl_links=False
+ )
+ return message
+
+
+dag = DAG(
+ dag_id=DAG_ID,
+ default_args={
+ **DAG_DEFAULT_ARGS,
+ "retry_delay": timedelta(minutes=1),
+ },
+ start_date=datetime(2022, 7, 29),
+ schedule_interval="@weekly",
+ max_active_tasks=MAX_ACTIVE,
+ max_active_runs=MAX_ACTIVE,
+ catchup=False,
+ # Use the docstring at the top of the file as md docs in the UI
+ doc_md=__doc__,
+ tags=["maintenance"],
+)
+
+with dag:
+ PythonOperator(
+ task_id="check_silenced_dags_configuration",
+ python_callable=check_configuration,
+ op_kwargs={
+ "github_pat": GITHUB_PAT,
+ },
+ )
diff --git a/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags.py b/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags.py
deleted file mode 100644
index 4676c4422..000000000
--- a/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags.py
+++ /dev/null
@@ -1,57 +0,0 @@
-import logging
-from typing import Tuple
-
-from airflow.exceptions import AirflowException, AirflowSkipException
-from airflow.models import Variable
-from common.github import GitHubAPI
-from common.slack import send_alert
-
-
-logger = logging.getLogger(__name__)
-
-
-def get_issue_info(issue_url: str) -> Tuple[str, str, str]:
- """
- Parses out the owner, repo, and issue_number from a GitHub issue url.
- """
- url_split = issue_url.split("/")
- if len(url_split) < 4:
- raise AirflowException(f"Issue url {issue_url} could not be parsed.")
- return url_split[-4], url_split[-3], url_split[-1]
-
-
-def get_dags_with_closed_issues(github_pat, silenced_dags):
- gh = GitHubAPI(github_pat)
-
- dags_to_reenable = []
- for dag_id, conf in silenced_dags.items():
- issue_url = conf["issue"]
- owner, repo, issue_number = get_issue_info(issue_url)
- github_issue = gh.get_issue(repo, issue_number, owner)
-
- if github_issue.get("state") == "closed":
- # If the associated issue has been closed, this DAG can have
- # alerting reenabled.
- dags_to_reenable.append((dag_id, issue_url))
- return dags_to_reenable
-
-
-def check_configuration(github_pat: str, airflow_variable: str):
- silenced_dags = Variable.get(airflow_variable, {}, deserialize_json=True)
- dags_to_reenable = get_dags_with_closed_issues(github_pat, silenced_dags)
-
- if not dags_to_reenable:
- raise AirflowSkipException(
- "All DAGs configured to silence messages have work still in progress."
- " No configuration updates needed."
- )
-
- message = (
- "The following DAGs have Slack messages silenced, but the associated issue is"
- f" closed. Please remove them from the `{airflow_variable}` Airflow variable"
- " or assign a new issue."
- )
- for (dag, issue) in dags_to_reenable:
- message += f"\n - <{issue}|{dag}>"
- send_alert(message, username="Silenced DAG Check", unfurl_links=False)
- return message
diff --git a/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags_dag.py b/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags_dag.py
deleted file mode 100644
index 61654c6e7..000000000
--- a/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags_dag.py
+++ /dev/null
@@ -1,60 +0,0 @@
-"""
-Checks for DAGs that have silenced Slack alerts which may need to be turned back
-on.
-
-When a DAG has known failures, it can be ommitted from Slack error reporting by adding
-an entry to the `silenced_slack_alerts` Airflow variable. This is a dictionary where the
-key is the `dag_id` of the affected DAG, and the value is the URL of a GitHub issue
-tracking the error.
-
-The `check_silenced_alert` DAG iterates over the entries in the `silenced_slack_alerts`
-configuration and verifies that the associated GitHub issues are still open. If an issue
-has been closed, it is assumed that the DAG should have Slack reporting reenabled, and
-an alert is sent to prompt manual update of the configuration. This prevents developers
-from forgetting to reenable Slack reporting after the issue has been resolved.
-
-The DAG runs weekly.
-"""
-
-import logging
-from datetime import datetime, timedelta
-
-from airflow.models import DAG, Variable
-from airflow.operators.python import PythonOperator
-from common.constants import DAG_DEFAULT_ARGS
-from maintenance.check_silenced_dags import check_silenced_dags
-
-
-logger = logging.getLogger(__name__)
-
-
-DAG_ID = "check_silenced_dags"
-MAX_ACTIVE = 1
-GITHUB_PAT = Variable.get("GITHUB_API_KEY", default_var="not_set")
-
-
-dag = DAG(
- dag_id=DAG_ID,
- default_args={
- **DAG_DEFAULT_ARGS,
- "retry_delay": timedelta(minutes=1),
- },
- start_date=datetime(2022, 7, 29),
- schedule_interval="@weekly",
- max_active_tasks=MAX_ACTIVE,
- max_active_runs=MAX_ACTIVE,
- catchup=False,
- # Use the docstring at the top of the file as md docs in the UI
- doc_md=__doc__,
- tags=["maintenance"],
-)
-
-with dag:
- PythonOperator(
- task_id="check_silenced_alert_configuration",
- python_callable=check_silenced_dags.check_configuration,
- op_kwargs={
- "github_pat": GITHUB_PAT,
- "airflow_variable": "silenced_slack_alerts",
- },
- )
diff --git a/tests/dags/common/loader/test_reporting.py b/tests/dags/common/loader/test_reporting.py
index 81ca2c610..eb7eb4495 100644
--- a/tests/dags/common/loader/test_reporting.py
+++ b/tests/dags/common/loader/test_reporting.py
@@ -24,7 +24,7 @@ def test_report_completion(should_send_message):
"common.slack.should_send_message", return_value=should_send_message
):
report_completion(
- "Jamendo",
+ "jamendo_workflow",
[
"audio",
],
@@ -154,7 +154,7 @@ def test_report_completion_contents(
):
with mock.patch("common.loader.reporting.send_message"):
message = report_completion(
- "Jamendo",
+ "jamendo_workflow",
["audio", "image"],
None,
{**audio_data, **image_data},
diff --git a/tests/dags/common/test_slack.py b/tests/dags/common/test_slack.py
index 00fff3290..1909780f9 100644
--- a/tests/dags/common/test_slack.py
+++ b/tests/dags/common/test_slack.py
@@ -10,6 +10,7 @@ from common.slack import (
send_alert,
send_message,
should_send_message,
+ should_silence_message,
)
@@ -287,24 +288,142 @@ def test_send_fails(http_hook_mock):
@pytest.mark.parametrize(
- "environment, slack_message_override, expected_result",
+ "environment, slack_message_override, silenced_notifications, expected_result",
[
- ("dev", False, False),
- ("dev", True, True),
- ("prod", False, True),
- ("prod", True, True),
+ # Dev
+ # Message is not sent by default. It is only sent if the override is enabled,
+ # AND notifications are not silenced.
+ # Default
+ ("dev", False, False, False),
+ # Override is not enabled AND notifications are silenced
+ ("dev", False, True, False),
+ # Override is enabled AND notifications NOT silenced
+ ("dev", True, False, True),
+ # Override is enabled but notifications are silenced
+ ("dev", True, True, False),
+ # Prod
+ # Message is sent by default; the override has no effect, but messages are
+ # not sent when notifications are silenced.
+ # Default
+ ("prod", False, False, True),
+ # Override not enabled, notifications ARE silenced
+ ("prod", False, True, False),
+ # Override enabled, notifications are NOT silenced
+ ("prod", True, False, True),
+ # Override enabled, notifications ARE silenced
+ ("prod", True, True, False),
],
)
-def test_should_send_message(environment, slack_message_override, expected_result):
- with mock.patch("common.slack.Variable") as MockVariable:
+def test_should_send_message(
+ environment, slack_message_override, silenced_notifications, expected_result
+):
+ with (
+ mock.patch("common.slack.Variable") as MockVariable,
+ mock.patch(
+ "common.slack.should_silence_message", return_value=silenced_notifications
+ ),
+ ):
# Mock the calls to Variable.get, in order
- MockVariable.get.side_effect = [environment, slack_message_override]
- assert should_send_message() == expected_result
+ MockVariable.get.side_effect = [
+ environment,
+ slack_message_override,
+ ]
+ assert should_send_message("text", "user", "mock_dag_id") == expected_result
def test_should_send_message_is_false_without_hook(http_hook_mock):
http_hook_mock.get_conn.side_effect = AirflowNotFoundException("nope")
- assert not should_send_message()
+ assert not should_send_message("text", "user", "test_workflow")
+
+
+ "silenced_notifications, should_silence",
+ (
+ # Do not silence when silenced_notifications is empty
+ ({}, False),
+ # dag_id is not in silenced_notifications
+ (
+ {
+ "another_dag_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "KeyError",
+ }
+ ]
+ },
+ False,
+ ),
+ # dag_id is configured, but text and username do not match
+ (
+ {
+ "test_dag_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "Unit codes",
+ }
+ ]
+ },
+ False,
+ ),
+ # text matches
+ (
+ {
+ "test_dag_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "KeyError: 'image'",
+ }
+ ]
+ },
+ True,
+ ),
+ # a substring of text matches
+ (
+ {
+ "test_dag_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "KeyError",
+ }
+ ]
+ },
+ True,
+ ),
+ # matches are case-insensitive
+ (
+ {
+ "test_dag_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "kEYErrOR",
+ }
+ ]
+ },
+ True,
+ ),
+ # username matches
+ (
+ {
+ "test_dag_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "Airflow DAG Failure",
+ }
+ ]
+ },
+ True,
+ ),
+ ),
+)
+def test_should_silence_message(silenced_notifications, should_silence):
+ with mock.patch("common.slack.Variable") as MockVariable:
+ MockVariable.get.side_effect = [silenced_notifications]
+ assert (
+ should_silence_message(
+ "KeyError: 'image'", "Airflow DAG Failure", "test_dag_id"
+ )
+ == should_silence
+ )
@pytest.mark.parametrize("environment", ["dev", "prod"])
@@ -313,7 +432,7 @@ def test_send_message(environment, http_hook_mock):
"common.slack.Variable"
) as MockVariable:
MockVariable.get.side_effect = [environment]
- send_message("Sample text", username="DifferentUser")
+ send_message("Sample text", dag_id="test_workflow", username="DifferentUser")
http_hook_mock.run.assert_called_with(
endpoint=None,
data=f'{{"username": "DifferentUser | {environment}", "unfurl_links": true, "unfurl_media": true,'
@@ -326,15 +445,16 @@ def test_send_message(environment, http_hook_mock):
def test_send_message_does_not_send_if_checks_fail(http_hook_mock):
with mock.patch("common.slack.should_send_message", return_value=False):
- send_message("Sample text", username="DifferentUser")
+ send_message("Sample text", dag_id="test_workflow", username="DifferentUser")
http_hook_mock.run.assert_not_called()
def test_send_alert():
with mock.patch("common.slack.send_message") as send_message_mock:
- send_alert("Sample text", username="DifferentUser")
+ send_alert("Sample text", dag_id="test_workflow", username="DifferentUser")
send_message_mock.assert_called_with(
"Sample text",
+ "test_workflow",
"DifferentUser",
":airflow:",
True,
@@ -344,57 +464,6 @@ def test_send_alert():
)
- "silenced_errors, alert, should_send",
- [
- # silenced errors includes alert being raised
- (
- [
- "Error triggering data refresh",
- ],
- "Error triggering data refresh",
- False,
- ),
- # alert contains substring matching a silenced error
- (
- [
- "Authorization failed",
- "data refresh",
- ],
- "Error triggering data refresh",
- False,
- ),
- # error matches are case-insensitive
- (
- [
- "kEYeRROR",
- ],
- "KeyError: 'image'",
- False,
- ),
- # none of the silenced errors matches alert string
- (
- ["Authorization failed", "data refresh", "No unit codes"],
- "Error due to invalid selection criteria",
- True,
- ),
- ],
-)
-def test_send_alert_skips_when_silenced(silenced_errors, alert, should_send):
- mock_silenced_dags = {
- "silenced_dag_id": {
- "issue": "https://github.com/WordPress/openverse/issues/1",
- "errors": silenced_errors,
- }
- }
- with mock.patch("common.slack.send_message") as send_message_mock, mock.patch(
- "common.slack.Variable"
- ) as MockVariable:
- MockVariable.get.side_effect = [mock_silenced_dags]
- send_alert(alert, dag_id="silenced_dag_id")
- assert send_message_mock.called == should_send
-
-
@pytest.mark.parametrize(
"exception, environment, slack_message_override, call_expected",
[
@@ -432,7 +501,7 @@ def test_on_failure_callback(
env_vars = {
"environment": environment,
"slack_message_override": slack_message_override,
- "silenced_slack_alerts": [],
+ "silenced_slack_notifications": {},
}
# Mock env variables
diff --git a/tests/dags/data_refresh/test_record_reporting.py b/tests/dags/data_refresh/test_record_reporting.py
index b809609c8..aeba4e38f 100644
--- a/tests/dags/data_refresh/test_record_reporting.py
+++ b/tests/dags/data_refresh/test_record_reporting.py
@@ -12,7 +12,7 @@ from data_refresh.record_reporting import report_record_difference
],
)
def test_record_reporting(before, after, expected_in_message):
- actual = report_record_difference(before, after, "media")
+ actual = report_record_difference(before, after, "media", "dag_id")
assert isinstance(expected_in_message, list), (
"Value for 'expected_in_message' should be a list, "
"a string may give a false positive"
diff --git a/tests/dags/maintenance/test_check_silenced_dags.py b/tests/dags/maintenance/test_check_silenced_dags.py
index 56699621f..52eb95c30 100644
--- a/tests/dags/maintenance/test_check_silenced_dags.py
+++ b/tests/dags/maintenance/test_check_silenced_dags.py
@@ -2,7 +2,7 @@ from unittest import mock
import pytest
from airflow.exceptions import AirflowException, AirflowSkipException
-from maintenance.check_silenced_dags.check_silenced_dags import (
+from maintenance.check_silenced_dags import (
check_configuration,
get_dags_with_closed_issues,
get_issue_info,
@@ -24,37 +24,77 @@ from tests.factories.github import make_issue
# One DAG to reenable
(
{
- "dag_a_id": {
- "issue": "https://github.com/WordPress/openverse/issues/1",
- "errors": [
- "Test exception",
- ],
- }
+ "dag_a_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "Test exception",
+ }
+ ]
},
[
- ("dag_a_id", "https://github.com/WordPress/openverse/issues/1"),
+ (
+ "dag_a_id",
+ "https://github.com/WordPress/openverse/issues/1",
+ "Test exception",
+ ),
+ ],
+ True,
+ ),
+ # One DAG, multiple notifications to reenable
+ (
+ {
+ "dag_a_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "Test exception",
+ },
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "A different error",
+ },
+ ]
+ },
+ [
+ (
+ "dag_a_id",
+ "https://github.com/WordPress/openverse/issues/1",
+ "Test exception",
+ ),
+ (
+ "dag_a_id",
+ "https://github.com/WordPress/openverse/issues/2",
+ "A different error",
+ ),
],
True,
),
# Multiple DAGs to reenable
(
{
- "dag_a_id": {
- "issue": "https://github.com/WordPress/openverse/issues/1",
- "errors": [
- "Test exception",
- ],
- },
- "dag_b_id": {
- "issue": "https://github.com/WordPress/openverse/issues/2",
- "errors": [
- "A different error",
- ],
- },
+ "dag_a_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/1",
+ "predicate": "Test exception",
+ }
+ ],
+ "dag_b_id": [
+ {
+ "issue": "https://github.com/WordPress/openverse/issues/2",
+ "predicate": "A different error",
+ }
+ ],
},
[
- ("dag_a_id", "https://github.com/WordPress/openverse/issues/1"),
- ("dag_b_id", "https://github.com/WordPress/openverse/issues/2"),
+ (
+ "dag_a_id",
+ "https://github.com/WordPress/openverse/issues/1",
+ "Test exception",
+ ),
+ (
+ "dag_b_id",
+ "https://github.com/WordPress/openverse/issues/2",
+ "A different error",
+ ),
],
True,
),
@@ -63,24 +103,22 @@ from tests.factories.github import make_issue
def test_check_configuration(silenced_dags, dags_to_reenable, should_send_alert):
with (
mock.patch(
- "maintenance.check_silenced_dags.check_silenced_dags.Variable",
+ "maintenance.check_silenced_dags.Variable",
return_value=silenced_dags,
),
mock.patch(
- "maintenance.check_silenced_dags.check_silenced_dags.get_dags_with_closed_issues",
+ "maintenance.check_silenced_dags.get_dags_with_closed_issues",
return_value=dags_to_reenable,
) as get_dags_with_closed_issues_mock,
- mock.patch(
- "maintenance.check_silenced_dags.check_silenced_dags.send_alert"
- ) as send_alert_mock,
+ mock.patch("maintenance.check_silenced_dags.send_alert") as send_alert_mock,
):
- message = check_configuration("not_set", "silenced_slack_alerts")
+ message = check_configuration("not_set")
assert send_alert_mock.called == should_send_alert
assert get_dags_with_closed_issues_mock.called_with("not_set", silenced_dags)
# Called with correct dag_ids
- for dag_id, issue_url in dags_to_reenable:
- assert f"<{issue_url}|{dag_id}>" in message
+ for dag_id, issue_url, predicate in dags_to_reenable:
+ assert f"<{issue_url}|{dag_id}: '{predicate}'>" in message
@pytest.mark.parametrize(
@@ -123,12 +161,12 @@ def test_get_dags_with_closed_issues(open_issues, closed_issues):
return make_issue("closed")
with mock.patch(
- "maintenance.check_silenced_dags.check_silenced_dags.GitHubAPI.get_issue",
+ "maintenance.check_silenced_dags.GitHubAPI.get_issue",
) as MockGetIssue:
MockGetIssue.side_effect = mock_get_issue
silenced_dags = {
- f"dag_{issue}": {"issue": issue, "errors": ["test"]}
+ f"dag_{issue}": [{"issue": issue, "predicate": "test"}]
for issue in open_issues + closed_issues
}
@@ -136,7 +174,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) in dags_to_reenable
+ assert (f"dag_{issue}", issue, "test") in dags_to_reenable
@pytest.mark.parametrize(