forked from segmentio/topicctl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_and_notify.py
More file actions
executable file
·303 lines (258 loc) · 9.2 KB
/
parse_and_notify.py
File metadata and controls
executable file
·303 lines (258 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import sys
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Any, Mapping, Sequence
from infra_event_notifier.datadog_notifier import DatadogNotifier
from infra_event_notifier.slack_notifier import SlackNotifier
class Destinations(Enum):
DATADOG = "datadog"
SLACK = "slack"
# DD event max length is 4000 chars,
# slack msg max length is 3000 chars,
# we check 100 lower to leave room for titles
DATADOG_MAX_LENGTH = 3900
SLACK_MAX_LENGTH = 2900
SENTRY_REGION = os.getenv("SENTRY_REGION", "unknown")
def make_table(
headers: Sequence[str],
content: Sequence[Sequence[str | int | None]],
error_message: str | None,
destination: str,
) -> str:
"""
Formats an ASCII table for slack message since slack's
markdown support is lacking
"""
if not headers and not content:
return ""
def make_row(
row: Sequence[str | int | None], max_width: Sequence[int]
) -> str:
content = "|".join(
(
" " + str(col).ljust(max_width[i]) + " "
for i, col in enumerate(row)
)
)
return f"|{content}|\n"
assert all(
len(row) == len(headers) for row in content
), "Invalid table format."
# get max width of columns
num_cols = len(headers)
max_width = [len(h) for h in headers]
for i in range(num_cols):
for row in content:
max_width[i] = max(max_width[i], len(str(row[i])))
line = ["-" * (width) for width in max_width]
rows = [make_row(r, max_width) for r in content]
# only create table body if changes actually occurred
# (if no changes then `content` = [["Topic Name", {name}]], hence len > 1)
table = (
(
f"{make_row(headers, max_width)}"
+ f"{make_row(line, max_width)}"
+ f"{''.join(rows)}"
)
if len(content) > 1
else ""
)
if destination == Destinations.SLACK and table:
table = f"```\n{table}```"
if error_message is not None:
error_header = (
"ERROR - the following error occurred while processing this topic:"
)
error_footer = (
"The following changes were still made:"
if len(content) > 1
else "No changes were made."
)
if destination == Destinations.DATADOG:
error_header = f"# {error_header}\n"
error_footer = f"# {error_footer}\n"
elif destination == Destinations.SLACK:
error_header = f":warning: *{error_header}*\n"
error_footer = f":warning: *{error_footer}*\n"
table = error_header + f"{error_message}\n\n" + error_footer + table
if destination == Destinations.DATADOG:
table = f"%%%\n{table}%%%"
return table
@dataclass(frozen=True)
class Topic(ABC):
name: str
@abstractmethod
def render_table(self) -> str:
raise NotImplementedError
@dataclass(frozen=True)
class NewTopic(Topic):
change_set: Sequence[Sequence[str | int | None]]
dry_run: bool
error_message: str | None
name: str
def render_table(self, destination: str) -> str:
return make_table(
headers=["Parameter", "Value"],
content=[["Topic Name", self.name], *self.change_set],
error_message=self.error_message,
destination=destination,
)
@classmethod
def build(cls, raw_content: Mapping[str, Any]) -> NewTopic:
change_set = [["Action (create/update)", "create"]]
if raw_content["numPartitions"]:
change_set.extend(
[["Partition Count", raw_content["numPartitions"]]]
)
if raw_content["replicationFactor"]:
change_set.extend(
[["Replication Factor", raw_content["replicationFactor"]]]
)
change_set += [
[str(entry["name"]), str(entry["value"])]
for entry in raw_content["configEntries"]
]
# if nothing changed, report no changes
if len(change_set) == 1:
change_set = []
return NewTopic(
name=raw_content["topic"],
dry_run=raw_content["dryRun"],
error_message=raw_content["errorMessage"],
change_set=change_set,
)
@dataclass(frozen=True)
class UpdatedTopic(Topic):
change_set: Sequence[Sequence[str | int | None]]
dry_run: bool
error_message: str | None
name: str
def render_table(self, destination: str) -> str:
return make_table(
headers=["Parameter", "Old Value", "New Value"],
content=self.change_set,
error_message=self.error_message,
destination=destination,
)
@classmethod
def build(cls, raw_content: Mapping[str, Any]) -> UpdatedTopic:
change_set = [["Action (create/update)", "update", ""]]
if (
raw_content["numPartitions"]
and raw_content["numPartitions"]["current"]
and raw_content["numPartitions"]["updated"]
):
change_set.extend(
[
[
"Partition Count",
raw_content["numPartitions"]["current"],
raw_content["numPartitions"]["updated"],
]
]
)
if raw_content["newConfigEntries"]:
change_set.extend(
[
[str(entry["name"]), "", str(entry["value"])]
for entry in raw_content["newConfigEntries"] or []
]
)
if raw_content["updatedConfigEntries"]:
change_set.extend(
[
[
str(entry["name"]),
str(entry["current"]),
str(entry["updated"]),
]
for entry in raw_content["updatedConfigEntries"]
]
)
if raw_content["missingKeys"]:
change_set.extend(
[
[str(entry), "", "REMOVED"]
for entry in raw_content["missingKeys"] or []
]
)
if raw_content["replicaAssignments"]:
assignments = raw_content["replicaAssignments"]
change_set.extend(
[
[
f"Partition {p['partition']} assignments",
str(p["currentReplicas"]),
str(p["updatedReplicas"]),
]
for p in assignments
]
)
if len(change_set) == 1:
change_set = []
return UpdatedTopic(
name=raw_content["topic"],
dry_run=raw_content["dryRun"],
error_message=raw_content["errorMessage"],
change_set=change_set,
)
def main():
dd_token = os.getenv("DATADOG_API_KEY")
slack_secret = os.getenv("TOPICCTL_WEBHOOK_SECRET")
slack_url = os.getenv("ENG_PIPES_URL")
assert dd_token is not None, "No Datadog token in DATADOG_API_KEY env var"
assert (
slack_secret is not None
), "No HMAC secret in TOPICCTL_WEBHOOK_SECRET env var"
dd_notifier = DatadogNotifier(datadog_api_key=dd_token)
slack_notifier = SlackNotifier(
eng_pipes_key=slack_secret, eng_pipes_url=slack_url
)
for line in sys.stdin:
try:
topic = json.loads(line)
except json.JSONDecodeError as e:
title = f"Topicctl failed to apply in region {SENTRY_REGION}"
slack_notifier.send(
title=title, body=f"Topicctl produced invalid JSON: {e}"
)
raise
if "error" in topic:
title = f"Topicctl failed to apply in region {SENTRY_REGION}"
slack_notifier.send(title=title, body=topic["error"])
print(f"Error: {topic['error']}", file=sys.stderr)
exit(-1)
action = topic["action"]
topic_content = (
NewTopic.build(topic)
if action == "create"
else UpdatedTopic.build(topic)
)
tags = {
"source": "topicctl",
"source_tool": "topicctl",
"source_category": "infra-tools",
"sentry_region": SENTRY_REGION,
}
dry_run = "Dry run: " if topic_content.dry_run else ""
title = (
f"{dry_run}Topicctl ran apply on topic {topic_content.name} "
f"in region {SENTRY_REGION}"
)
dd_table = topic_content.render_table(Destinations.DATADOG)
slack_table = topic_content.render_table(Destinations.SLACK)
if len(dd_table) > DATADOG_MAX_LENGTH:
dd_table = dd_table[:(DATADOG_MAX_LENGTH)] + "\n..."
if len(slack_table) > SLACK_MAX_LENGTH:
slack_table = slack_table[:(SLACK_MAX_LENGTH)] + "\n..."
tags["topicctl_topic"] = topic_content.name
dd_notifier.send(title=title, body=dd_table, tags=tags, alert_type="")
slack_notifier.send(title=title, body=slack_table)
print(f"{title}", file=sys.stderr)
if __name__ == "__main__":
main()