Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Omit DAGs that are known to fail from alerts (#643)
Staci Cooper9fea6554e32c
diff --git a/openverse_catalog/dags/common/github.py b/openverse_catalog/dags/common/github.pyindex abd08d15d..83612b271 100644--- a/openverse_catalog/dags/common/github.py+++ b/openverse_catalog/dags/common/github.py@@ -16,6 +16,9 @@ class GitHubAPI:response.raise_for_status()return response.json()+ def get_issue(self, repo: str, issue_number: int, owner: str = "WordPress"):+ return self._make_request("GET", f"repos/{owner}/{repo}/issues/{issue_number}")+def get_open_prs(self, repo: str, owner: str = "WordPress"):return self._make_request("GET",diff --git a/openverse_catalog/dags/common/loader/reporting.py b/openverse_catalog/dags/common/loader/reporting.pyindex 49199dd4f..600717313 100644--- a/openverse_catalog/dags/common/loader/reporting.py+++ b/openverse_catalog/dags/common/loader/reporting.py@@ -110,5 +110,4 @@ def report_completion(*Number of records upserted per media type*:{media_type_reports}"""send_message(message, username="Airflow DAG Load Data Complete")- logger.info(message)return messagediff --git a/openverse_catalog/dags/common/slack.py b/openverse_catalog/dags/common/slack.pyindex ee9e9a18f..e953e14c2 100644--- a/openverse_catalog/dags/common/slack.py+++ b/openverse_catalog/dags/common/slack.py@@ -219,15 +219,22 @@ def send_message(username: str = "Airflow",icon_emoji: str = ":airflow:",markdown: bool = True,+ unfurl_links: bool = True,+ unfurl_media: bool = True,http_conn_id: str = SLACK_NOTIFICATIONS_CONN_ID,) -> None:"""Send a simple slack message, convenience message for short/simple messages."""+ log.info(text)if not should_send_message(http_conn_id):returnenvironment = Variable.get("environment", default_var="dev")s = SlackMessage(- f"{username} | {environment}", icon_emoji, http_conn_id=http_conn_id+ f"{username} | {environment}",+ icon_emoji,+ unfurl_links,+ unfurl_media,+ http_conn_id=http_conn_id,)s.add_text(text, plain_text=not markdown)s.send(text)@@ -255,16 +262,33 @@ def should_send_message(http_conn_id=SLACK_NOTIFICATIONS_CONN_ID):def send_alert(text: str,+ dag_id: str | None = None,username: str = "Airflow Alert",icon_emoji: str = ":airflow:",markdown: bool = True,+ unfurl_links: bool = True,+ unfurl_media: bool = True,):"""Wrapper for send_message that allows sending a message to the configured alertschannel instead of the default notification channel."""++ known_failures = Variable.get(+ "silenced_slack_alerts", default_var={}, deserialize_json=True+ )+ if dag_id in known_failures:+ log.info(f"Skipping Slack alert for {dag_id}: {text}")+ return+send_message(- text, username, icon_emoji, markdown, http_conn_id=SLACK_ALERTS_CONN_ID+ text,+ username,+ icon_emoji,+ markdown,+ unfurl_links,+ unfurl_media,+ http_conn_id=SLACK_ALERTS_CONN_ID,)@@ -274,6 +298,7 @@ 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"]execution_date = context["execution_date"]exception: Optional[Exception] = context.get("exception")@@ -296,6 +321,4 @@ def on_failure_callback(context: dict) -> None:*Log*: {ti.log_url}{exception_message}"""- send_message(- message, username="Airflow DAG Failure", http_conn_id=SLACK_ALERTS_CONN_ID- )+ send_alert(message, dag_id=dag.dag_id, username="Airflow DAG Failure")diff --git a/openverse_catalog/dags/database/report_pending_reported_media.py b/openverse_catalog/dags/database/report_pending_reported_media.pyindex 45c6487aa..8ee4f1910 100644--- a/openverse_catalog/dags/database/report_pending_reported_media.py+++ b/openverse_catalog/dags/database/report_pending_reported_media.py@@ -127,7 +127,6 @@ The following media have been reported and require manual review:{media_type_reports}"""- logger.info(message)slack.send_alert(message, username="Reported Media Requires Review")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.pynew file mode 100644index 000000000..decca2b2e--- /dev/null+++ b/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags.py@@ -0,0 +1,56 @@+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, issue_url in silenced_dags.items():+ 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 messagediff --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.pynew file mode 100644index 000000000..61654c6e7--- /dev/null+++ b/openverse_catalog/dags/maintenance/check_silenced_dags/check_silenced_dags_dag.py@@ -0,0 +1,60 @@+"""+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/test_slack.py b/tests/dags/common/test_slack.pyindex 62882ef81..eca6240fc 100644--- a/tests/dags/common/test_slack.py+++ b/tests/dags/common/test_slack.py@@ -338,10 +338,24 @@ def test_send_alert():"DifferentUser",":airflow:",True,+ True,+ True,http_conn_id=SLACK_ALERTS_CONN_ID,)+def test_send_alert_skips_when_silenced():+ mock_silenced_dags = {+ "silenced_dag_id": "https://github.com/WordPress/openverse/issues/1"+ }+ 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("Sample text", dag_id="silenced_dag_id")+ send_message_mock.assert_not_called()++@pytest.mark.parametrize("exception, environment, slack_message_override, call_expected",[@@ -369,10 +383,12 @@ def test_on_failure_callback("task_instance": mock.Mock(),"execution_date": datetime.now(),"exception": exception,+ "dag": mock.Mock(),}env_vars = {"environment": environment,"slack_message_override": slack_message_override,+ "silenced_slack_alerts": [],}# Mock env variablesdiff --git a/tests/dags/maintenance/test_check_silenced_dags.py b/tests/dags/maintenance/test_check_silenced_dags.pynew file mode 100644index 000000000..dc29cda63--- /dev/null+++ b/tests/dags/maintenance/test_check_silenced_dags.py@@ -0,0 +1,145 @@+from unittest import mock++import pytest+from airflow.exceptions import AirflowException, AirflowSkipException+from maintenance.check_silenced_dags.check_silenced_dags import (+ check_configuration,+ get_dags_with_closed_issues,+ get_issue_info,+)++from tests.factories.github import make_issue+++ "silenced_dags, dags_to_reenable, should_send_alert",+ (+ # No Dags to reenable, task should skip+ pytest.param(+ {},+ [],+ False,+ marks=pytest.mark.raises(exception=AirflowSkipException),+ ),+ # One DAG to reenable+ (+ {"dag_a_id": "https://github.com/WordPress/openverse/issues/1"},+ [+ ("dag_a_id", "https://github.com/WordPress/openverse/issues/1"),+ ],+ True,+ ),+ # Multiple DAGs to reenable+ (+ {+ "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"),+ ("dag_b_id", "https://github.com/WordPress/openverse/issues/2"),+ ],+ True,+ ),+ ),+)+def test_check_configuration(silenced_dags, dags_to_reenable, should_send_alert):+ with (+ mock.patch(+ "maintenance.check_silenced_dags.check_silenced_dags.Variable",+ return_value=silenced_dags,+ ),+ mock.patch(+ "maintenance.check_silenced_dags.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,+ ):+ message = check_configuration("not_set", "silenced_slack_alerts")+ 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+++ "open_issues, closed_issues",+ (+ # No issues+ ([], []),+ # Only open issues+ (+ [+ "https://github.com/WordPress/openverse/issues/1",+ ],+ [],+ ),+ # Some closed issues, some open+ (+ [+ "https://github.com/WordPress/openverse/issues/1",+ ],+ [+ "https://github.com/WordPress/openverse/issues/2",+ ],+ ),+ # Multiple closed issues+ (+ [],+ [+ "https://github.com/WordPress/openverse/issues/1",+ "https://github.com/WordPress/openverse/issues/2",+ ],+ ),+ ),+)+def test_get_dags_with_closed_issues(open_issues, closed_issues):+ # Mock get_issue+ def mock_get_issue(repo, issue_number, owner):+ url = f"https://github.com/WordPress/openverse/issues/{issue_number}"+ if url in open_issues:+ return make_issue("open")+ return make_issue("closed")++ with mock.patch(+ "maintenance.check_silenced_dags.check_silenced_dags.GitHubAPI.get_issue",+ ) as MockGetIssue:+ MockGetIssue.side_effect = mock_get_issue++ silenced_dags = {f"dag_{issue}": issue for issue in open_issues + closed_issues}++ dags_to_reenable = get_dags_with_closed_issues("not_set", silenced_dags)++ assert len(dags_to_reenable) == len(closed_issues)+ for issue in closed_issues:+ assert (f"dag_{issue}", issue) in dags_to_reenable+++ "url, expected_result",+ (+ (+ "https://github.com/WordPress/openverse/issues/10",+ ("WordPress", "openverse", "10"),+ ),+ (+ "WordPress/openverse-catalog/issues/100",+ ("WordPress", "openverse-catalog", "100"),+ ),+ pytest.param(+ "openverse/issues/10",+ None,+ marks=pytest.mark.raises(+ exception=AirflowException,+ match="Issue url openverse/issues/10 could not be parsed.",+ ),+ ),+ ),+)+def test_get_issue_info(url, expected_result):+ result = get_issue_info(url)+ assert result == expected_resultdiff --git a/tests/factories/github/__init__.py b/tests/factories/github/__init__.pyindex 75b7af3b5..530305ce9 100644--- a/tests/factories/github/__init__.py+++ b/tests/factories/github/__init__.py@@ -91,3 +91,11 @@ def make_pr_comment(is_reminder: bool) -> dict:)return comment+++def make_issue(state: str) -> dict:+ issue = _read_fixture("issue")++ issue["state"] = state++ return issuediff --git a/tests/factories/github/issue.json b/tests/factories/github/issue.jsonnew file mode 100644index 000000000..0c492d5cc--- /dev/null+++ b/tests/factories/github/issue.json@@ -0,0 +1,157 @@+{+ "active_lock_reason": "too heated",+ "assignee": {+ "avatar_url": "https://github.com/images/error/octocat_happy.gif",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "gravatar_id": "",+ "html_url": "https://github.com/octocat",+ "id": 1,+ "login": "octocat",+ "node_id": "MDQ6VXNlcjE=",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "site_admin": false,+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "type": "User",+ "url": "https://api.github.com/users/octocat"+ },+ "assignees": [+ {+ "avatar_url": "https://github.com/images/error/octocat_happy.gif",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "gravatar_id": "",+ "html_url": "https://github.com/octocat",+ "id": 1,+ "login": "octocat",+ "node_id": "MDQ6VXNlcjE=",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "site_admin": false,+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "type": "User",+ "url": "https://api.github.com/users/octocat"+ }+ ],+ "author_association": "COLLABORATOR",+ "body": "I'm having a problem with this.",+ "closed_at": null,+ "closed_by": {+ "avatar_url": "https://github.com/images/error/octocat_happy.gif",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "gravatar_id": "",+ "html_url": "https://github.com/octocat",+ "id": 1,+ "login": "octocat",+ "node_id": "MDQ6VXNlcjE=",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "site_admin": false,+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "type": "User",+ "url": "https://api.github.com/users/octocat"+ },+ "comments": 0,+ "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments",+ "created_at": "2011-04-22T13:33:48Z",+ "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events",+ "html_url": "https://github.com/octocat/Hello-World/issues/1347",+ "id": 1,+ "labels": [+ {+ "color": "f29513",+ "default": true,+ "description": "Something isn't working",+ "id": 208045946,+ "name": "bug",+ "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=",+ "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug"+ }+ ],+ "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}",+ "locked": true,+ "milestone": {+ "closed_at": "2013-02-12T13:22:01Z",+ "closed_issues": 8,+ "created_at": "2011-04-10T20:09:31Z",+ "creator": {+ "avatar_url": "https://github.com/images/error/octocat_happy.gif",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "gravatar_id": "",+ "html_url": "https://github.com/octocat",+ "id": 1,+ "login": "octocat",+ "node_id": "MDQ6VXNlcjE=",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "site_admin": false,+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "type": "User",+ "url": "https://api.github.com/users/octocat"+ },+ "description": "Tracking milestone for version 1.0",+ "due_on": "2012-10-09T23:39:01Z",+ "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0",+ "id": 1002604,+ "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels",+ "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==",+ "number": 1,+ "open_issues": 4,+ "state": "open",+ "title": "v1.0",+ "updated_at": "2014-03-03T18:58:10Z",+ "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1"+ },+ "node_id": "MDU6SXNzdWUx",+ "number": 1347,+ "pull_request": {+ "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff",+ "html_url": "https://github.com/octocat/Hello-World/pull/1347",+ "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch",+ "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347"+ },+ "repository_url": "https://api.github.com/repos/octocat/Hello-World",+ "state": "open",+ "title": "Found a bug",+ "updated_at": "2011-04-22T13:33:48Z",+ "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347",+ "user": {+ "avatar_url": "https://github.com/images/error/octocat_happy.gif",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "gravatar_id": "",+ "html_url": "https://github.com/octocat",+ "id": 1,+ "login": "octocat",+ "node_id": "MDQ6VXNlcjE=",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "site_admin": false,+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "type": "User",+ "url": "https://api.github.com/users/octocat"+ }+}