forked from conbench/conbench
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
benchalerts: Add slack pipeline steps (conbench#1555)
* Add slack pipeline steps * lint * pass comment details through too
- Loading branch information
Austin Dickey
authored
Dec 19, 2023
1 parent
3dc8f02
commit c3acf82
Showing
10 changed files
with
461 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
import os | ||
|
||
from benchclients.http import RetryingHTTPClient | ||
from benchclients.logging import fatal_and_log | ||
|
||
|
||
class SlackClient(RetryingHTTPClient): | ||
"""A client to interact with Slack. | ||
This uses the token-based authentication method, not the Incoming Webhooks method. | ||
Notes | ||
----- | ||
Environment variables | ||
~~~~~~~~~~~~~~~~~~~~~ | ||
``SLACK_TOKEN`` | ||
A Slack token; see https://api.slack.com/authentication/token-types. Tokens look | ||
like ``xoxb-...`` if they're bot tokens. | ||
""" | ||
|
||
default_retry_for_seconds = 60 | ||
timeout_long_running_requests = (3.5, 10) | ||
|
||
def __init__(self) -> None: | ||
token = os.getenv("SLACK_TOKEN", "") | ||
if not token: | ||
fatal_and_log("Environment variable SLACK_TOKEN not found.") | ||
|
||
super().__init__() | ||
self.session.headers.update({"Authorization": f"Bearer {token}"}) | ||
|
||
@property | ||
def _base_url(self) -> str: | ||
return "https://slack.com/api" | ||
|
||
def _login_or_raise(self) -> None: | ||
pass | ||
|
||
def post_message(self, channel_id: str, message: str) -> dict: | ||
"""Post a message to a Slack channel. | ||
Parameters | ||
---------- | ||
channel_id | ||
The ID of the channel to post to. | ||
message | ||
The message text. | ||
Returns | ||
------- | ||
dict | ||
The response body from the Slack HTTP API as a dict. | ||
""" | ||
resp_dict = self._make_request( | ||
"POST", | ||
self._abs_url_from_path("/chat.postMessage"), | ||
200, | ||
json={"channel": channel_id, "text": message}, | ||
).json() | ||
|
||
if not resp_dict.get("ok"): | ||
fatal_and_log( | ||
f"Failed to send message to Slack. Deserialized response body: {resp_dict}", | ||
) | ||
|
||
return resp_dict |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
"""Pipeline steps to talk to Slack.""" | ||
|
||
from typing import Any, Dict, Optional | ||
|
||
from benchclients.logging import log | ||
|
||
from ..alert_pipeline import AlertPipelineErrorHandler, AlertPipelineStep | ||
from ..integrations.github import CheckStatus | ||
from ..integrations.slack import SlackClient | ||
from ..message_formatting import Alerter | ||
|
||
|
||
class SlackMessageAboutBadCheckStep(AlertPipelineStep): | ||
"""An ``AlertPipeline`` step to post to Slack about a failing GitHub Check that was | ||
created by a previously-run ``GitHubCheckStep``. This is useful if you're running | ||
benchmarks on a merge-commit, and no one is necessarily monitoring the Checks on the | ||
default branch. | ||
Parameters | ||
---------- | ||
channel_id | ||
The ID of the Slack channel to post to. | ||
slack_client | ||
A SlackClient instance. If not provided, will default to ``SlackClient()``. | ||
check_step_name | ||
The name of the ``GitHubCheckStep`` that ran earlier in the pipeline. Defaults | ||
to "GitHubCheckStep" (which was the default if no name was given to that step). | ||
pr_comment_step_name | ||
[Optional] The name of the ``GitHubPRCommentStep`` that ran earlier in the | ||
pipeline. If provided, will include a link to the comment in the Slack message. | ||
step_name | ||
The name for this step. If not given, will default to this class's name. | ||
alerter | ||
Advanced usage; should not be necessary in most cases. An optional Alerter | ||
instance to use to format the message. If not provided, will default to | ||
``Alerter()``. | ||
Returns | ||
------- | ||
dict | ||
The response body from the Slack HTTP API as a dict, or None if no message was | ||
posted (e.g. if the check was successful). | ||
Notes | ||
----- | ||
Environment variables | ||
~~~~~~~~~~~~~~~~~~~~~ | ||
``SLACK_TOKEN`` | ||
A Slack token; see https://api.slack.com/authentication/token-types. Tokens look | ||
like ``xoxb-...`` if they're bot tokens. Only required if ``slack_client`` is | ||
not provided. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
channel_id: str, | ||
slack_client: Optional[SlackClient] = None, | ||
check_step_name: str = "GitHubCheckStep", | ||
pr_comment_step_name: Optional[str] = None, | ||
step_name: Optional[str] = None, | ||
alerter: Optional[Alerter] = None, | ||
) -> None: | ||
super().__init__(step_name=step_name) | ||
self.channel_id = channel_id | ||
self.slack_client = slack_client or SlackClient() | ||
self.check_step_name = check_step_name | ||
self.pr_comment_step_name = pr_comment_step_name | ||
self.alerter = alerter or Alerter() | ||
|
||
def run_step(self, previous_outputs: Dict[str, Any]) -> Optional[dict]: | ||
check_details, full_comparison = previous_outputs[self.check_step_name] | ||
if self.pr_comment_step_name: | ||
comment_details = previous_outputs[self.pr_comment_step_name] | ||
else: | ||
comment_details = None | ||
|
||
if self.alerter.github_check_status(full_comparison) == CheckStatus.SUCCESS: | ||
log.info("GitHub Check was successful; not posting to Slack.") | ||
return None | ||
|
||
res = self.slack_client.post_message( | ||
message=self.alerter.slack_message( | ||
full_comparison=full_comparison, | ||
check_details=check_details, | ||
comment_details=comment_details, | ||
), | ||
channel_id=self.channel_id, | ||
) | ||
return res | ||
|
||
|
||
class SlackErrorHandler(AlertPipelineErrorHandler): | ||
"""Handle errors in a pipeline by posting a Slack message. | ||
Parameters | ||
---------- | ||
channel_id | ||
The ID of the Slack channel to post to. | ||
slack_client | ||
A SlackClient instance. If not provided, will default to ``SlackClient()``. | ||
build_url | ||
An optional build URL to include in the message. | ||
Notes | ||
----- | ||
Environment variables | ||
~~~~~~~~~~~~~~~~~~~~~ | ||
``SLACK_TOKEN`` | ||
A Slack token; see https://api.slack.com/authentication/token-types. Tokens look | ||
like ``xoxb-...`` if they're bot tokens. Only required if ``slack_client`` is | ||
not provided. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
channel_id: str, | ||
slack_client: Optional[SlackClient] = None, | ||
build_url: Optional[str] = None, | ||
) -> None: | ||
self.channel_id = channel_id | ||
self.slack_client = slack_client or SlackClient() | ||
self.build_url = build_url | ||
|
||
def handle_error(self, exc: BaseException, traceback: str) -> None: | ||
res = self.slack_client.post_message( | ||
channel_id=self.channel_id, | ||
message=f"Error in benchalerts pipeline. {self.build_url=}", | ||
) | ||
log.debug(res) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
benchalerts/tests/unit_tests/mocked_responses/POST_slack_chat_postMessage_123.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
{ | ||
"data": { | ||
"channel": "123", | ||
"message": { | ||
"app_id": "123", | ||
"blocks": [ | ||
{ | ||
"block_id": "yxoJ", | ||
"elements": [ | ||
{ | ||
"elements": [ | ||
{ | ||
"text": "hello", | ||
"type": "text" | ||
} | ||
], | ||
"type": "rich_text_section" | ||
} | ||
], | ||
"type": "rich_text" | ||
} | ||
], | ||
"bot_id": "123", | ||
"bot_profile": { | ||
"app_id": "123", | ||
"deleted": false, | ||
"icons": { | ||
"image_36": "https://avatars.slack-edge.com/", | ||
"image_48": "https://avatars.slack-edge.com/", | ||
"image_72": "https://avatars.slack-edge.com/" | ||
}, | ||
"id": "123", | ||
"name": "abc", | ||
"team_id": "123", | ||
"updated": 1657225466 | ||
}, | ||
"team": "123", | ||
"text": "hello", | ||
"ts": "1702579355.753289", | ||
"type": "message", | ||
"user": "123" | ||
}, | ||
"ok": true, | ||
"response_metadata": { | ||
"warnings": [ | ||
"missing_charset" | ||
] | ||
}, | ||
"ts": "1702579355.753289", | ||
"warning": "missing_charset" | ||
}, | ||
"status_code": 200 | ||
} |
13 changes: 13 additions & 0 deletions
13
benchalerts/tests/unit_tests/mocked_responses/POST_slack_chat_postMessage_fail.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{ | ||
"data": { | ||
"error": "channel_not_found", | ||
"ok": false, | ||
"response_metadata": { | ||
"warnings": [ | ||
"missing_charset" | ||
] | ||
}, | ||
"warning": "missing_charset" | ||
}, | ||
"status_code": 200 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.