Skip to content

Commit b62cc23

Browse files
authored
feat(notify): Stop using the slack-notifier base (#33928)
1 parent 7c50b3f commit b62cc23

File tree

11 files changed

+117
-78
lines changed

11 files changed

+117
-78
lines changed

.gitlab/internal_kubernetes_deploy/internal_kubernetes_deploy.yml

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22
# internal_kubernetes_deploy stage
33
# Contains jobs to trigger a pipeline in our k8s-datadog-agent-ops repo
44

5-
include:
6-
- https://gitlab-templates.ddbuild.io/slack-notifier/v3-sdm/template.yml
7-
85
internal_kubernetes_deploy_experimental:
96
stage: internal_kubernetes_deploy
107
rules:
@@ -68,7 +65,7 @@ internal_kubernetes_deploy_experimental:
6865

6966
notify-slack:
7067
stage: internal_kubernetes_deploy
71-
extends: .slack-notifier-base
68+
image: registry.ddbuild.io/ci/datadog-agent-buildimages/deb_arm64$DATADOG_AGENT_BUILDIMAGES_SUFFIX:$DATADOG_AGENT_BUILDIMAGES
7269
rules:
7370
- if: $FORCE_K8S_DEPLOYMENT == "true"
7471
when: always
@@ -79,9 +76,10 @@ notify-slack:
7976
- if: $APPS !~ "/^datadog-agent/"
8077
when: never
8178
- !reference [.on_deploy]
82-
tags: ["arch:amd64"]
79+
tags: ["arch:arm64"]
8380
needs: ["internal_kubernetes_deploy_experimental"]
8481
script:
8582
- export SDM_JWT=$(vault read -field=token identity/oidc/token/sdm)
86-
- python3 -m pip install -r tasks/requirements.txt
83+
- python3 -m pip install -r tasks/requirements.txt -r tasks/libs/requirements-notifications.txt
84+
- SLACK_API_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $SLACK_AGENT token) || exit $?; export SLACK_API_TOKEN
8785
- inv pipeline.changelog ${CI_COMMIT_SHORT_SHA} || exit $?

.gitlab/notify/notify.yml

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,35 @@
22
# notify stage
33
# Contains jobs which send notifications depending on pipeline status.
44

5-
include:
6-
- https://gitlab-templates.ddbuild.io/slack-notifier/v3-sdm/template.yml
5+
.notify_setup:
6+
- SLACK_API_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $SLACK_AGENT token) || exit $?; export SLACK_API_TOKEN
7+
- GITLAB_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $GITLAB_TOKEN read_api) || exit $?; export GITLAB_TOKEN
8+
- DD_API_KEY=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $AGENT_API_KEY_ORG2 token) || exit $?; export DD_API_KEY
9+
- python3 -m pip install -r requirements.txt -r tasks/libs/requirements-notifications.txt
710

811
notify-on-tagged-success:
9-
extends: .slack-notifier-base
1012
stage: notify
13+
image: registry.ddbuild.io/ci/datadog-agent-buildimages/deb_arm64$DATADOG_AGENT_BUILDIMAGES_SUFFIX:$DATADOG_AGENT_BUILDIMAGES
1114
rules: !reference [.on_deploy_stable_or_beta_repo_branch]
1215
dependencies: []
13-
tags: ["arch:amd64"]
16+
tags: ["arch:arm64"]
1417
script: |
1518
MESSAGE_TEXT=":host-green: Tagged build <$CI_PIPELINE_URL|$CI_PIPELINE_ID> succeeded.
1619
*$CI_COMMIT_REF_NAME* is available in the staging repositories."
17-
postmessage "#agent-release-sync" "$MESSAGE_TEXT"
20+
python3 -m pip install -r requirements.txt -r tasks/libs/requirements-notifications.txt
21+
SLACK_API_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $SLACK_AGENT token) || exit $?; export SLACK_API_TOKEN
22+
invoke notify.post-message -c "#agent-release-sync" -m "$MESSAGE_TEXT"
1823
1924
notify:
20-
extends: .slack-notifier-base
2125
stage: notify
26+
image: registry.ddbuild.io/ci/datadog-agent-buildimages/deb_arm64$DATADOG_AGENT_BUILDIMAGES_SUFFIX:$DATADOG_AGENT_BUILDIMAGES
2227
rules: !reference [.on_main_or_release_branch_or_deploy_always]
2328
dependencies: []
24-
tags: ["arch:amd64"]
29+
tags: ["arch:arm64"]
2530
resource_group: notification
2631
timeout: 15 minutes # Added to prevent a stuck job blocking the resource_group defined above
2732
script:
28-
- GITLAB_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $GITLAB_TOKEN read_api) || exit $?; export GITLAB_TOKEN
29-
- DD_API_KEY=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $AGENT_API_KEY_ORG2 token) || exit $?; export DD_API_KEY
30-
- python3 -m pip install -r requirements.txt -r tasks/libs/requirements-notifications.txt
33+
- !reference [.notify_setup]
3134
- invoke -e notify.send-message -p $CI_PIPELINE_ID
3235
- invoke -e notify.check-consistent-failures -p $CI_PIPELINE_ID
3336

@@ -38,8 +41,7 @@ send_pipeline_stats:
3841
when: always
3942
dependencies: []
4043
script:
41-
- GITLAB_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $GITLAB_TOKEN read_api) || exit $?; export GITLAB_TOKEN
42-
- DD_API_KEY=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $AGENT_API_KEY_ORG2 token) || exit $?; export DD_API_KEY
44+
- !reference [.notify_setup]
4345
- invoke -e notify.send-stats
4446

4547
notify_github:
@@ -105,11 +107,6 @@ notify_gitlab_ci_changes:
105107
resource_group: notification
106108
timeout: 15 minutes # Added to prevent a stuck job blocking the resource_group defined above
107109

108-
.failure_summary_setup:
109-
- SLACK_API_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $SLACK_AGENT token) || exit $?; export SLACK_API_TOKEN
110-
- GITLAB_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $GITLAB_TOKEN read_api) || exit $?; export GITLAB_TOKEN
111-
- DD_API_KEY=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $AGENT_API_KEY_ORG2 token) || exit $?; export DD_API_KEY
112-
- python3 -m pip install -r requirements.txt -r tasks/libs/requirements-notifications.txt
113110

114111
# Upload failure summary data to S3 at the end of each main pipeline
115112
notify_failure_summary_on_pipeline:
@@ -119,7 +116,7 @@ notify_failure_summary_on_pipeline:
119116
when: never
120117
- !reference [.on_main_always]
121118
script:
122-
- !reference [.failure_summary_setup]
119+
- !reference [.notify_setup]
123120
- inv -e notify.failure-summary-upload-pipeline-data
124121

125122
# Send failure summary notifications daily and weekly
@@ -130,7 +127,7 @@ notify_failure_summary_daily:
130127
when: never
131128
- !reference [.on_deploy_nightly_repo_branch_always]
132129
script:
133-
- !reference [.failure_summary_setup]
130+
- !reference [.notify_setup]
134131
- weekday="$(date --utc '+%A')"
135132
- |
136133
if [ "$weekday" = "Sunday" ] || [ "$weekday" = "Monday" ]; then

.gitlab/trigger_release/trigger_release.yml

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,6 @@ trigger_manual_prod_release_on_failure:
7777
when: never
7878
- !reference [.on_deploy_stable_on_failure]
7979

80-
include:
81-
- https://gitlab-templates.ddbuild.io/slack-notifier/v3-sdm/template.yml
82-
8380
.setup_github_app_agent_platform_auto_pr:
8481
# GitHub App rate-limits are per-app. Since we are rarely calling the job, we are only using the instance 2
8582
- |
@@ -90,9 +87,9 @@ include:
9087
9188
generate_windows_gitlab_runner_bump_pr:
9289
stage: trigger_release
93-
extends: .slack-notifier-base
90+
image: registry.ddbuild.io/ci/datadog-agent-buildimages/deb_arm64$DATADOG_AGENT_BUILDIMAGES_SUFFIX:$DATADOG_AGENT_BUILDIMAGES
9491
needs: ["trigger_auto_staging_release"]
95-
tags: ["arch:amd64"]
92+
tags: ["arch:arm64"]
9693
rules:
9794
- if: $DDR_WORKFLOW_ID != null
9895
when: never
@@ -105,14 +102,15 @@ generate_windows_gitlab_runner_bump_pr:
105102
- !reference [.setup_github_app_agent_platform_auto_pr]
106103
- python3 -m pip install -r requirements.txt -r tasks/libs/requirements-notifications.txt
107104
- $S3_CP_CMD $S3_ARTIFACTS_URI/agent-version.cache .
105+
- SLACK_API_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $SLACK_AGENT token) || exit $?; export SLACK_API_TOKEN
108106
- inv -e github.update-windows-runner-version
109107

110108
# Manual job to generate the gitlab bump pr on buildenv if trigger_auto_staging_release fails
111109
generate_windows_gitlab_runner_bump_pr_manual:
112110
stage: trigger_release
113-
extends: .slack-notifier-base
111+
image: registry.ddbuild.io/ci/datadog-agent-buildimages/deb_arm64$DATADOG_AGENT_BUILDIMAGES_SUFFIX:$DATADOG_AGENT_BUILDIMAGES
114112
needs: ["trigger_auto_staging_release"]
115-
tags: ["arch:amd64"]
113+
tags: ["arch:arm64"]
116114
rules:
117115
- if: $DDR_WORKFLOW_ID != null
118116
when: never
@@ -125,4 +123,5 @@ generate_windows_gitlab_runner_bump_pr_manual:
125123
- !reference [.setup_github_app_agent_platform_auto_pr]
126124
- python3 -m pip install -r requirements.txt -r tasks/libs/requirements-notifications.txt
127125
- $S3_CP_CMD $S3_ARTIFACTS_URI/agent-version.cache .
126+
- SLACK_API_TOKEN=$($CI_PROJECT_DIR/tools/ci/fetch_secret.sh $SLACK_AGENT token) || exit $?; export SLACK_API_TOKEN
128127
- inv -e github.update-windows-runner-version

tasks/github_tasks.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
from tasks.libs.common.datadog_api import create_gauge, send_event, send_metrics
2626
from tasks.libs.common.git import get_default_branch
2727
from tasks.libs.common.utils import get_git_pretty_ref
28-
from tasks.libs.notify.pipeline_status import send_slack_message
2928
from tasks.libs.owners.linter import codeowner_has_orphans, directory_has_packages_without_owner
3029
from tasks.libs.owners.parsing import read_owners
3130
from tasks.libs.pipeline.notifications import GITHUB_SLACK_MAP
@@ -143,7 +142,10 @@ def _update_windows_runner_version(new_version=None, buildenv_ref="master"):
143142

144143
message = f":robobits: A new windows-runner bump PR to {new_version} has been generated. Please take a look :frog-review:\n:pr: {PR_URL} :ty:"
145144

146-
send_slack_message("ci-infra-support", message)
145+
from slack_sdk import WebClient
146+
147+
client = WebClient(token=os.environ["SLACK_API_TOKEN"])
148+
client.chat_postMessage(channel="ci-infra-support", text=message)
147149
return workflow_conclusion
148150

149151

tasks/libs/notify/alerts.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
from tasks.libs.pipeline.data import get_failed_jobs
2020
from tasks.libs.pipeline.notifications import (
2121
get_pr_from_commit,
22-
send_slack_message,
2322
)
2423
from tasks.owners import channel_owners, make_partition
2524

@@ -232,7 +231,10 @@ def send_alert(channel, consecutive: ConsecutiveJobAlert, cumulative: Cumulative
232231
message = message.strip()
233232

234233
if message:
235-
send_slack_message(channel, message)
234+
from slack_sdk import WebClient
235+
236+
client = WebClient(token=os.environ["SLACK_API_TOKEN"])
237+
client.chat_postMessage(channel=channel, text=message)
236238

237239
# Create metrics for consecutive and cumulative alerts
238240
return [

tasks/libs/notify/pipeline_status.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1+
import os
12
import re
3+
import sys
24

35
from tasks.libs.ciproviders.gitlab_api import get_commit, get_pipeline
46
from tasks.libs.common.git import get_default_branch
7+
from tasks.libs.common.utils import Color, color_message
58
from tasks.libs.notify.utils import DEPLOY_PIPELINES_CHANNEL, PIPELINES_CHANNEL, PROJECT_NAME, get_pipeline_type
69
from tasks.libs.pipeline.data import get_failed_jobs
710
from tasks.libs.pipeline.notifications import (
811
base_message,
9-
email_to_slackid,
1012
get_failed_tests,
11-
send_slack_message,
1213
)
1314
from tasks.libs.types.types import SlackMessage
1415

@@ -58,16 +59,26 @@ def send_message(ctx, pipeline_id, dry_run):
5859
for test in get_failed_tests(PROJECT_NAME, job):
5960
message.add_test_failure(test, job)
6061

61-
# Send messages
62+
# Send message
63+
from slack_sdk import WebClient
64+
from slack_sdk.errors import SlackApiError
65+
66+
client = WebClient(token=os.environ["SLACK_API_TOKEN"])
6267
if dry_run:
6368
print(f"Would send to {slack_channel}:\n{str(message)}")
6469
else:
65-
send_slack_message(slack_channel, str(message))
70+
client.chat_postMessage(channel=slack_channel, text=str(message))
6671

6772
if should_send_message_to_author(pipeline.ref, get_default_branch()):
6873
author_email = commit.author_email
6974
if dry_run:
7075
print(f"Would send to {author_email}:\n{str(message)}")
7176
else:
72-
recipient = email_to_slackid(ctx, author_email)
73-
send_slack_message(recipient, str(message))
77+
try:
78+
recipient = client.users_lookupByEmail(email=author_email)
79+
client.chat_postMessage(channel=recipient.data['user']['id'], text=str(message))
80+
except SlackApiError as e:
81+
print(
82+
f"[{color_message('ERROR', Color.RED)}] Failed to send message to {author_email}: {e.response['error']}",
83+
file=sys.stderr,
84+
)

tasks/libs/pipeline/notifications.py

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,12 @@
44
import os
55
import pathlib
66
import re
7-
import subprocess
87
from collections import defaultdict
98
from datetime import datetime, timezone
109

1110
import gitlab
1211
import yaml
1312
from gitlab.v4.objects import ProjectCommit, ProjectJob, ProjectPipeline
14-
from invoke.context import Context
1513

1614
from tasks.libs.ciproviders.gitlab_api import get_gitlab_repo
1715
from tasks.libs.owners.parsing import read_owners
@@ -157,6 +155,9 @@ def base_message(project_name: str, pipeline: ProjectPipeline, commit: ProjectCo
157155
commit_url_github = f"{GITHUB_BASE_URL}/{project_name}/commit/{commit.id}"
158156
commit_short_sha = commit.id[-8:]
159157
author = commit.author_name
158+
finish = datetime.fromisoformat(pipeline.finished_at) if pipeline.finished_at else datetime.now(timezone.utc)
159+
delta = finish - datetime.fromisoformat(pipeline.started_at)
160+
duration = f"[:hourglass: {int(delta.total_seconds() / 60)} min]"
160161

161162
# Try to find a PR id (e.g #12345) in the commit title and add a link to it in the message if found.
162163
pr_info = get_pr_from_commit(commit_title, project_name)
@@ -165,22 +166,10 @@ def base_message(project_name: str, pipeline: ProjectPipeline, commit: ProjectCo
165166
parsed_pr_id, pr_url_github = pr_info
166167
enhanced_commit_title = enhanced_commit_title.replace(f"#{parsed_pr_id}", f"<{pr_url_github}|#{parsed_pr_id}>")
167168

168-
return f"""{header} pipeline <{pipeline_url}|{pipeline_id}> for {commit_ref_name} {state}.
169+
return f"""{header} pipeline <{pipeline_url}|{pipeline_id}> for {commit_ref_name} {state} {duration}.
169170
{enhanced_commit_title} (<{commit_url_gitlab}|{commit_short_sha}>)(:github: <{commit_url_github}|link>) by {author}"""
170171

171172

172-
def send_slack_message(recipient, message):
173-
subprocess.run(["postmessage", recipient, message], check=True)
174-
175-
176-
def email_to_slackid(ctx: Context, email: str) -> str:
177-
slackid = ctx.run(f"echo '{email}' | email2slackid", hide=True, warn=True).stdout.strip()
178-
179-
assert slackid != '', 'Email not found'
180-
181-
return slackid
182-
183-
184173
def warn_new_commits(release_managers, team, branch, next_rc):
185174
from slack_sdk import WebClient
186175

tasks/notify.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,3 +277,14 @@ def close_failing_tests_stale_issues(_, dry_run=False):
277277
print(f'Error closing issue {issue["key"]}: {e}', file=sys.stderr)
278278

279279
print(f'Closed {n_closed} issues without failing tests')
280+
281+
282+
@task
283+
def post_message(_: Context, channel: str, message: str):
284+
"""
285+
Post a message to a slack channel
286+
"""
287+
from slack_sdk import WebClient
288+
289+
client = WebClient(token=os.environ['SLACK_API_TOKEN'])
290+
client.chat_postMessage(channel=channel, text=message)

tasks/pipeline.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
is_allowed_repo_branch,
2727
)
2828
from tasks.libs.owners.parsing import read_owners
29-
from tasks.libs.pipeline.notifications import send_slack_message
3029
from tasks.libs.pipeline.tools import (
3130
FilteredOutException,
3231
cancel_pipelines_with_confirmation,
@@ -475,6 +474,9 @@ def is_system_probe(owners, files):
475474

476475
@task
477476
def changelog(ctx, new_commit_sha):
477+
from slack_sdk import WebClient
478+
479+
client = WebClient(token=os.environ["SLACK_API_TOKEN"])
478480
# Environment variable to deal with both local and CI environments
479481
if "CI_PROJECT_DIR" in os.environ:
480482
parent_dir = os.environ["CI_PROJECT_DIR"]
@@ -502,7 +504,7 @@ def changelog(ctx, new_commit_sha):
502504
if old_commit_sha == new_commit_sha:
503505
print("No new commits found, exiting")
504506
slack_message += no_commits_msg
505-
send_slack_message("system-probe-ops", slack_message)
507+
client.chat_postMessage(channel="system-probe-ops", text=slack_message)
506508
return
507509

508510
print(f"Generating changelog for commit range {old_commit_sha} to {new_commit_sha}")
@@ -543,7 +545,7 @@ def changelog(ctx, new_commit_sha):
543545
slack_message += empty_changelog_msg
544546

545547
print(f"Posting message to slack: \n {slack_message}")
546-
send_slack_message("system-probe-ops", slack_message)
548+
client.chat_postMessage(channel="system-probe-ops", text=slack_message)
547549
print(f"Writing new commit sha: {new_commit_sha} to SSM")
548550
res = ctx.run(
549551
f"aws ssm put-parameter --name ci.datadog-agent.gitlab_changelog_commit_sha --value {new_commit_sha} "

0 commit comments

Comments
 (0)