Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Slack alerting utilities (#279)
Madison Swain-Bowden14c2d6d7d164
diff --git a/docker/airflow/Dockerfile b/docker/airflow/Dockerfileindex 0c04d8aea..6eaf625c5 100644--- a/docker/airflow/Dockerfile+++ b/docker/airflow/Dockerfile@@ -39,11 +39,12 @@ USER airflowWORKDIR ${AIRFLOW_HOME}# Always add the prod req because the dev reqs depend on it for deduplication-COPY ${REQUIREMENTS_FILE} requirements_prod.txt docker/airflow/wait_for_db.py ${AIRFLOW_HOME}/+COPY ${REQUIREMENTS_FILE} requirements_prod.txt ${AIRFLOW_HOME}/+COPY docker/airflow/wait_for_db.py /opt/airflow/RUN pip install --user -r ${REQUIREMENTS_FILE} -c ${CONSTRAINTS_FILE}-COPY docker/airflow/entrypoint.sh entrypoint.sh+COPY docker/airflow/entrypoint.sh /opt/airflow/entrypoint.sh-ENTRYPOINT ["./entrypoint.sh"]+ENTRYPOINT ["/opt/airflow/entrypoint.sh"]CMD ["server"]diff --git a/docker/airflow/entrypoint.sh b/docker/airflow/entrypoint.shindex 8b29acb9b..5db865626 100755--- a/docker/airflow/entrypoint.sh+++ b/docker/airflow/entrypoint.sh@@ -36,7 +36,7 @@ sleep 0.1; # The $COLUMNS variable takes a moment to populate# Wait for postgresheader "WAITING FOR POSTGRES"-python wait_for_db.py+python /opt/airflow/wait_for_db.py# Upgrade the database -- command is idempotent.header "MIGRATING DATABASE"airflow db upgradediff --git a/env.template b/env.templateindex 0e5f65ac3..fd4fb775a 100644--- a/env.template+++ b/env.template@@ -42,6 +42,9 @@ AIRFLOW_CONN_AWS_DEFAULT=aws://test_key:test_secret@?region_name=us-east-1&host=# Change the following line in prod to use the appropriate DBAIRFLOW_CONN_POSTGRES_OPENLEDGER_UPSTREAM=postgres://deploy:deploy@postgres:5432/openledgerAIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING=postgres://deploy:deploy@postgres:5432/openledger+# Slack notification webhook connection info (this must be URL encoded, with a+# pre-pended https://, e.g. "https://https%3A%2F%2Fhooks.slack.com%2Fservices%2everythingelse")+AIRFLOW_CONN_SLACK=https://slackOPENLEDGER_CONN_ID=postgres_openledger_upstreamTEST_CONN_ID=postgres_openledger_testingdiff --git a/justfile b/justfileindex 356e7ce53..a06f7c32d 100644--- a/justfile+++ b/justfile@@ -73,9 +73,14 @@ test *pytestargs:shell: updocker-compose {{ DOCKER_FILES }} exec {{ SERVICE }} /bin/bash-# Launch an IPython REPL within the webserver container-ipython: up- docker-compose {{ DOCKER_FILES }} exec -w /usr/local/airflow/openverse_catalog/dags {{ SERVICE }} /usr/local/airflow/.local/bin/ipython+# Launch an IPython REPL using the webserver image+ipython: (up "postgres s3")+ docker-compose {{ DOCKER_FILES }} run \+ --rm \+ -w /usr/local/airflow/openverse_catalog/dags \+ -v {{ justfile_directory() }}/.ipython:/usr/local/airflow/.ipython:z \+ {{ SERVICE }} \+ /usr/local/airflow/.local/bin/ipython# Run a given command using the webserver imagerun *args: (up "postgres s3")diff --git a/openverse_catalog/dags/common/slack.py b/openverse_catalog/dags/common/slack.pynew file mode 100644index 000000000..d695fcc12--- /dev/null+++ b/openverse_catalog/dags/common/slack.py@@ -0,0 +1,215 @@+"""+# Slack Block Message Builder++TODO:+ - track number of characters, raise error after 4k+ - attach text, fields++This class is intended to be used with a channel-specific slack webhook.+More information can be found here: https://app.slack.com/block-kit-builder.++## Send multiple messages - payload is reset after sending++>>> slack = SlackMessage(username="Multi-message Test")++>>> slack.add_text("message 1")+>>> slack.send()++>>> slack.add_text("message 2")+>>> slack.send()++## Embed images, plus context++>>> slack = SlackMessage(username="Blocks - Referenced Images")++>>> slack.add_context(":pika-love: context stuff *here*")++>>> msg = "Example message with new method of embedding images and divider below."++>>> slack.add_text(msg)+>>> slack.add_divider()+>>> slack.add_image(url1, title=img1_title, alt_text="img #1")+>>> slack.add_image(url2, title=img2_title, alt_text="img #2")+>>> slack.send()++## Dev Tools+>>> # prints current payload+>>> slack.display()++>>> # get payload dict+>>> payload = slack.payload++"""++import json+from os.path import basename+from typing import Any, Callable, Optional++from airflow.providers.http.hooks.http import HttpHook+from requests import Response+++SLACK_CONN_ID = "slack"+JsonDict = dict[str, Any]+++class SlackMessage:+ """Slack Block Message Builder"""++ def __init__(+ self,+ username: str = "Airflow",+ icon_emoji: str = ":airflow:",+ unfurl_links: bool = True,+ unfurl_media: bool = True,+ http_conn_id: str = SLACK_CONN_ID,+ ):++ self.http = HttpHook(method="POST", http_conn_id=http_conn_id)+ self.blocks = []+ self._context = {}+ self._payload: dict[str, Any] = {+ "username": username,+ "unfurl_links": unfurl_links,+ "unfurl_media": unfurl_media,+ }++ if icon_emoji:+ self._payload["icon_emoji"] = icon_emoji++ self._base_payload = self._payload.copy()++ @staticmethod+ def _text_block(message: str, plain_text: bool) -> JsonDict:+ text_type = "plain_text" if plain_text else "mrkdwn"+ return {"type": text_type, "text": message}++ @staticmethod+ def _image_block(+ url: str, title: Optional[str] = None, alt_text: Optional[str] = None+ ) -> JsonDict:+ img = {"type": "image", "image_url": url}+ if title:+ img.update({"title": {"type": "plain_text", "text": title}})+ if alt_text:+ img["alt_text"] = alt_text+ else:+ img["alt_text"] = basename(url)+ return img++ def clear(self) -> None:+ """Clear all stored data to prime the instance for a new message."""+ self.blocks = []+ self._context = {}+ self._payload = self._base_payload.copy()++ def display(self) -> None:+ """Prints current payload, intended for local development only."""+ if self._context:+ self._append_context()+ self._payload.update({"blocks": self.blocks})+ print(json.dumps(self._payload, indent=4))++ @property+ def payload(self) -> JsonDict:+ payload = self._payload.copy()+ payload.update({"blocks": self.blocks})+ return payload++ ####################################################################################+ # Context+ ####################################################################################++ def _append_context(self) -> None:+ self.blocks.append(self._context.copy())+ self._context = {}++ def _add_context(+ self, body_generator: Callable, main_text: str, **options: Any+ ) -> None:+ if not self._context:+ self._context = {"type": "context", "elements": []}+ body = body_generator(main_text, **options)+ if len(self._context["elements"]) < 10:+ self._context["elements"].append(body)+ else:+ raise ValueError("Unable to include more than 10 context elements")++ def add_context(self, message: str, plain_text: bool = False) -> None:+ """Display context above or below a text block"""+ self._add_context(+ self._text_block,+ message,+ plain_text=plain_text,+ )++ def add_context_image(self, url: str, alt_text: Optional[str] = None) -> None:+ """Display context image inline within a text block"""+ self._add_context(self._image_block, url, alt_text=alt_text)++ ####################################################################################+ # Blocks+ ####################################################################################++ def _add_block(self, block: JsonDict) -> None:+ if self._context:+ self._append_context()+ self.blocks.append(block)++ def add_divider(self) -> None:+ """Add a divider between blocks."""+ self._add_block({"type": "divider"})++ def add_text(self, message: str, plain_text: bool = False) -> None:+ """Add a text block, using markdown or plain text."""+ text = self._text_block(message, plain_text)+ self._add_block({"type": "section", "text": text})++ def add_image(+ self, url, title: Optional[str] = None, alt_text: Optional[str] = None+ ) -> None:+ """Add an image block, with optional title and alt text."""+ self._add_block(self._image_block(url, title, alt_text))++ ####################################################################################+ # Send+ ####################################################################################++ def send(self, notification_text: str = "Airflow notification") -> Response:+ """+ Sends message payload to the channel configured by the webhook.++ Any notification text provided will only show up as the content within+ the notification pushed to various devices.+ """+ if not self._context and not self.blocks:+ raise ValueError("Nothing to send!")++ if self._context:+ self._append_context()+ self._payload.update({"blocks": self.blocks})+ self._payload["text"] = notification_text++ response = self.http.run(+ endpoint=None,+ data=json.dumps(self._payload),+ headers={"Content-type": "application/json"},+ extra_options={"verify": True},+ )++ self.clear()+ response.raise_for_status()+ return response+++def send_message(+ text: str,+ username: str = "Airflow",+ icon_emoji: str = ":airflow:",+ markdown: bool = True,+ http_conn_id: str = SLACK_CONN_ID,+) -> None:+ """Send a simple slack message, convenience message for short/simple messages."""+ s = SlackMessage(username, icon_emoji, http_conn_id=http_conn_id)+ s.add_text(text, plain_text=not markdown)+ s.send(text)diff --git a/requirements_prod.txt b/requirements_prod.txtindex cdcd555e4..434f0bbdb 100644--- a/requirements_prod.txt+++ b/requirements_prod.txt@@ -1,6 +1,4 @@-apache-airflow-providers-amazon-apache-airflow-providers-postgres-apache-airflow[amazon,postgres]==2.1.2+apache-airflow[amazon,postgres,http]==2.1.2lxml==4.6.3psycopg2-binaryrequests-file==1.5.1diff --git a/tests/dags/common/test_slack.py b/tests/dags/common/test_slack.pynew file mode 100644index 000000000..b5d69834d--- /dev/null+++ b/tests/dags/common/test_slack.py@@ -0,0 +1,288 @@+from unittest import mock++import pytest+from common.slack import SlackMessage, send_message+++_FAKE_IMAGE = "http://image.com/img.jpg"++[email protected](autouse=True)+def http_hook_mock():+ with mock.patch("common.slack.HttpHook") as HttpHookMock:+ yield HttpHookMock+++ "plain_text, expected",+ [+ (+ False,+ {"type": "mrkdwn", "text": "test message"},+ ),+ (+ True,+ {"type": "plain_text", "text": "test message"},+ ),+ ],+)+def test_text_section(plain_text, expected):+ actual = SlackMessage._text_block("test message", plain_text)+ assert actual == expected+++ "url, title, alt_text, expected",+ [+ (+ _FAKE_IMAGE,+ None,+ None,+ {"type": "image", "image_url": _FAKE_IMAGE, "alt_text": "img.jpg"},+ ),+ (+ _FAKE_IMAGE,+ "Sample title",+ None,+ {+ "type": "image",+ "image_url": _FAKE_IMAGE,+ "title": {"type": "plain_text", "text": "Sample title"},+ "alt_text": "img.jpg",+ },+ ),+ (+ _FAKE_IMAGE,+ None,+ "Sample alternative text",+ {+ "type": "image",+ "image_url": _FAKE_IMAGE,+ "alt_text": "Sample alternative text",+ },+ ),+ (+ _FAKE_IMAGE,+ "Both title",+ "And alt text",+ {+ "type": "image",+ "image_url": _FAKE_IMAGE,+ "title": {"type": "plain_text", "text": "Both title"},+ "alt_text": "And alt text",+ },+ ),+ ],+)+def test_image_section(url, title, alt_text, expected):+ actual = SlackMessage._image_block(url, title, alt_text)+ assert actual == expected+++def test_clear():+ s = SlackMessage()+ s.blocks = [{"text": "fake"}, {"text": "fake2"}]+ s._context = {"fake-context": "value"}+ s._payload = {"fake-payload": "value"}+ s.clear()+ assert s.blocks == []+ assert s._context == {}+ assert s._payload == s._base_payload+++def test_payload_property():+ s = SlackMessage()+ s.blocks = [{"text": "fake"}, {"text": "fake2"}]+ assert s.payload == {+ "blocks": [{"text": "fake"}, {"text": "fake2"}],+ "icon_emoji": ":airflow:",+ "unfurl_links": True,+ "unfurl_media": True,+ "username": "Airflow",+ }+++def test_add_context_no_initial_context():+ s = SlackMessage()+ assert s._context == {}+ s.add_context("Sample context")+ assert s._context == {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": "Sample context"}],+ }+++def test_add_context_multiple():+ s = SlackMessage()+ s.add_context("Sample context")+ s.add_context("Additional context")+ assert s._context == {+ "type": "context",+ "elements": [+ {"type": "mrkdwn", "text": "Sample context"},+ {"type": "mrkdwn", "text": "Additional context"},+ ],+ }+++def test_add_context_too_many():+ s = SlackMessage()+ with pytest.raises(+ ValueError, match="Unable to include more than 10 context elements"+ ):+ for idx in range(20):+ s.add_context(f"Sample context {idx}")+++def test_add_context_image_no_initial_context():+ s = SlackMessage()+ assert s._context == {}+ s.add_context_image(_FAKE_IMAGE, alt_text="fake alt")+ assert s._context == {+ "type": "context",+ "elements": [+ {+ "alt_text": "fake alt",+ "image_url": "http://image.com/img.jpg",+ "type": "image",+ }+ ],+ }+++def test_add_context_image_multiple():+ s = SlackMessage()+ s.add_context_image(_FAKE_IMAGE, alt_text="fake alt")+ s.add_context_image(_FAKE_IMAGE, alt_text="other alt")+ assert s._context == {+ "type": "context",+ "elements": [+ {+ "alt_text": "fake alt",+ "image_url": "http://image.com/img.jpg",+ "type": "image",+ },+ {+ "alt_text": "other alt",+ "image_url": "http://image.com/img.jpg",+ "type": "image",+ },+ ],+ }+++def test_add_context_image_too_many():+ s = SlackMessage()+ with pytest.raises(+ ValueError, match="Unable to include more than 10 context elements"+ ):+ for idx in range(20):+ s.add_context_image(_FAKE_IMAGE, alt_text=f"Alt: {idx}")+++def test_add_block():+ s = SlackMessage()+ s._add_block({"fake": "value"})+ assert s._context == {}+ assert s.blocks == [{"fake": "value"}]+++def test_add_block_with_context():+ s = SlackMessage()+ s.add_context("Additional context")+ s._add_block({"fake": "value"})+ assert s._context == {}+ assert s.blocks == [+ {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": "Additional context"}],+ },+ {"fake": "value"},+ ]+++def test_add_divider():+ s = SlackMessage()+ s.add_divider()+ assert s.blocks == [{"type": "divider"}]+++def test_add_text():+ s = SlackMessage()+ s.add_text("Fake message")+ assert s.blocks == [+ {"type": "section", "text": {"type": "mrkdwn", "text": "Fake message"}}+ ]+++def test_add_image():+ s = SlackMessage()+ s.add_image(_FAKE_IMAGE)+ assert s.blocks == [+ {+ "type": "image",+ "image_url": "http://image.com/img.jpg",+ "alt_text": "img.jpg",+ }+ ]+++def test_send_no_message():+ s = SlackMessage()+ with pytest.raises(ValueError, match="Nothing to send!"):+ s.send()+++def test_send_no_context(http_hook_mock):+ s = SlackMessage()+ s.blocks = [1, 2, 3]+ s.send()+ http_hook_mock.return_value.run.assert_called_with(+ endpoint=None,+ data='{"username": "Airflow", "unfurl_links": true, "unfurl_media": true, '+ '"icon_emoji": ":airflow:", "blocks": [1, 2, 3], '+ '"text": "Airflow notification"}',+ headers={"Content-type": "application/json"},+ extra_options={"verify": True},+ )+ assert s._payload == s._base_payload+++def test_send_with_context(http_hook_mock):+ s = SlackMessage()+ s.blocks = [1, 2, 3]+ s.add_context("Sample context")+ s.send()+ http_hook_mock.return_value.run.assert_called_with(+ endpoint=None,+ data='{"username": "Airflow", "unfurl_links": true, "unfurl_media": true, '+ '"icon_emoji": ":airflow:", "blocks": [1, 2, 3, {"type": "context", '+ '"elements": [{"type": "mrkdwn", "text": "Sample context"}]}], '+ '"text": "Airflow notification"}',+ headers={"Content-type": "application/json"},+ extra_options={"verify": True},+ )+ assert s._payload == s._base_payload+++def test_send_fails(http_hook_mock):+ s = SlackMessage()+ # Cause an exception within the raise_for_status call+ http_hook_mock.return_value.run.return_value.raise_for_status.side_effect = (+ Exception("HTTP Error 666")+ )+ s.add_text("Sample message")+ with pytest.raises(Exception, match="HTTP Error 666"):+ s.send()+++def test_send_message(http_hook_mock):+ send_message("Sample text", username="DifferentUser")+ http_hook_mock.return_value.run.assert_called_with(+ endpoint=None,+ data='{"username": "DifferentUser", "unfurl_links": true, "unfurl_media": true,'+ ' "icon_emoji": ":airflow:", "blocks": [{"type": "section", "text": '+ '{"type": "mrkdwn", "text": "Sample text"}}], "text": "Sample text"}',+ headers={"Content-type": "application/json"},+ extra_options={"verify": True},+ )