-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook_server.py
More file actions
453 lines (335 loc) · 12.9 KB
/
webhook_server.py
File metadata and controls
453 lines (335 loc) · 12.9 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
"""
Webhook server to receive alerts from monitoring tools.
Supports Datadog, PagerDuty, Grafana, and generic webhooks.
"""
import json
import logging
from datetime import datetime
from typing import Optional
from flask import Flask, request, jsonify
from config import settings
from orchestrator import Orchestrator
from integrations_config import integrations
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__)
# Global orchestrator instance
orchestrator = Orchestrator(verbose=True, parallel=True)
def parse_datadog_alert(payload: dict) -> str:
"""Parses Datadog webhook payload into alert string."""
event_type = payload.get("event_type", "alert")
title = payload.get("title", "Unknown Alert")
body = payload.get("body", "")
tags = payload.get("tags", [])
# Extract service from tags
service = "unknown"
for tag in tags:
if tag.startswith("service:"):
service = tag.split(":")[1]
break
alert = f"""
[{event_type.upper()}] {title}
Service: {service}
Start: {datetime.now().strftime("%H:%M %Z")}
Environment: production
Details:
{body}
Tags: {', '.join(tags)}
"""
return alert.strip()
def parse_pagerduty_alert(payload: dict) -> str:
"""Parses PagerDuty webhook payload into alert string."""
messages = payload.get("messages", [])
if not messages:
return "Unknown PagerDuty alert"
incident = messages[0].get("incident", {})
title = incident.get("title", "Unknown Incident")
urgency = incident.get("urgency", "high")
service = incident.get("service", {}).get("name", "unknown")
description = incident.get("description", "")
alert = f"""
[{urgency.upper()}] {title}
Service: {service}
Start: {datetime.now().strftime("%H:%M %Z")}
Environment: production
Description:
{description}
"""
return alert.strip()
def parse_grafana_alert(payload: dict) -> str:
"""Parses Grafana webhook payload into alert string."""
state = payload.get("state", "alerting")
title = payload.get("title", "Unknown Alert")
message = payload.get("message", "")
rule_name = payload.get("ruleName", "")
# Extract tags/labels
tags = payload.get("tags", {})
service = tags.get("service", "unknown")
alert = f"""
[{state.upper()}] {title}
Rule: {rule_name}
Service: {service}
Start: {datetime.now().strftime("%H:%M %Z")}
Environment: production
Message:
{message}
"""
return alert.strip()
def parse_opsgenie_alert(payload: dict) -> str:
"""Parses OpsGenie webhook payload into alert string."""
alert_data = payload.get("alert", {})
message = alert_data.get("message", "Unknown Alert")
priority = alert_data.get("priority", "P1")
source = alert_data.get("source", "unknown")
description = alert_data.get("description", "")
# Extract tags
tags = alert_data.get("tags", [])
service = "unknown"
for tag in tags:
if tag.startswith("service:"):
service = tag.split(":")[1]
break
alert = f"""
[{priority}] {message}
Service: {service}
Source: {source}
Start: {datetime.now().strftime("%H:%M %Z")}
Environment: production
Description:
{description}
"""
return alert.strip()
def parse_sentry_alert(payload: dict) -> str:
"""Parses Sentry webhook payload into alert string."""
# Sentry sends different event types
action = payload.get("action", "created")
data = payload.get("data", {})
# Handle issue alerts
if "issue" in data:
issue = data.get("issue", {})
event = data.get("event", {})
title = issue.get("title", "Unknown Error")
culprit = issue.get("culprit", "")
level = issue.get("level", "error")
count = issue.get("count", 1)
project = issue.get("project", {}).get("name", "unknown")
# Extract stack trace info
stack_info = ""
if event:
entries = event.get("entries", [])
for entry in entries:
if entry.get("type") == "exception":
exceptions = entry.get("data", {}).get("values", [])
if exceptions:
exc = exceptions[0]
exc_type = exc.get("type", "")
exc_value = exc.get("value", "")
frames = exc.get("stacktrace", {}).get("frames", [])
if frames:
last_frame = frames[-1]
filename = last_frame.get("filename", "")
line_no = last_frame.get("lineNo", "")
function = last_frame.get("function", "")
stack_info = f"""
Exception: {exc_type}: {exc_value}
Location: {filename}:{line_no} in {function}
"""
# Extract release if available
release = event.get("release", "")
if isinstance(release, dict):
release = release.get("version", "")
# Extract tags
tags = issue.get("tags", [])
tag_str = ", ".join([f"{t['key']}:{t['value']}" for t in tags[:5]]) if tags else ""
alert = f"""
[{level.upper()}] {title}
Service: {project}
Culprit: {culprit}
Occurrences: {count}
Start: {datetime.now().strftime("%H:%M %Z")}
Environment: production
Release: {release}
{stack_info}
Tags: {tag_str}
"""
return alert.strip()
# Handle metric alerts
elif "metric_alert" in data:
metric_alert = data.get("metric_alert", {})
title = metric_alert.get("title", "Metric Alert")
alert = f"""
[METRIC ALERT] {title}
Start: {datetime.now().strftime("%H:%M %Z")}
Environment: production
"""
return alert.strip()
# Fallback for unknown format
return f"[SENTRY] Unknown alert format: {json.dumps(payload)[:200]}"
def parse_generic_alert(payload: dict) -> str:
"""Parses generic webhook payload into alert string."""
# Try common fields
title = payload.get("title") or payload.get("name") or payload.get("message") or "Unknown Alert"
service = payload.get("service") or payload.get("source") or "unknown"
severity = payload.get("severity") or payload.get("priority") or payload.get("level") or "alert"
description = payload.get("description") or payload.get("body") or payload.get("text") or ""
alert = f"""
[{severity.upper()}] {title}
Service: {service}
Start: {datetime.now().strftime("%H:%M %Z")}
Environment: production
Description:
{description}
"""
return alert.strip()
@app.route("/health", methods=["GET"])
def health():
"""Health check endpoint."""
return jsonify({
"status": "healthy",
"timestamp": datetime.now().isoformat()
})
@app.route("/webhook/datadog", methods=["POST"])
def webhook_datadog():
"""Receives webhooks from Datadog."""
try:
payload = request.json
logger.info(f"Received Datadog webhook: {json.dumps(payload)[:200]}")
alert = parse_datadog_alert(payload)
# Run investigation
report = orchestrator.investigate(alert)
return jsonify({
"status": "processed",
"alert_source": "datadog",
"report_preview": report[:500]
})
except Exception as e:
logger.error(f"Error processing Datadog webhook: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/webhook/pagerduty", methods=["POST"])
def webhook_pagerduty():
"""Receives webhooks from PagerDuty."""
try:
payload = request.json
logger.info(f"Received PagerDuty webhook: {json.dumps(payload)[:200]}")
alert = parse_pagerduty_alert(payload)
# Run investigation
report = orchestrator.investigate(alert)
return jsonify({
"status": "processed",
"alert_source": "pagerduty",
"report_preview": report[:500]
})
except Exception as e:
logger.error(f"Error processing PagerDuty webhook: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/webhook/grafana", methods=["POST"])
def webhook_grafana():
"""Receives webhooks from Grafana."""
try:
payload = request.json
logger.info(f"Received Grafana webhook: {json.dumps(payload)[:200]}")
alert = parse_grafana_alert(payload)
# Run investigation
report = orchestrator.investigate(alert)
return jsonify({
"status": "processed",
"alert_source": "grafana",
"report_preview": report[:500]
})
except Exception as e:
logger.error(f"Error processing Grafana webhook: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/webhook/opsgenie", methods=["POST"])
def webhook_opsgenie():
"""Receives webhooks from OpsGenie."""
try:
payload = request.json
logger.info(f"Received OpsGenie webhook: {json.dumps(payload)[:200]}")
alert = parse_opsgenie_alert(payload)
# Run investigation
report = orchestrator.investigate(alert)
return jsonify({
"status": "processed",
"alert_source": "opsgenie",
"report_preview": report[:500]
})
except Exception as e:
logger.error(f"Error processing OpsGenie webhook: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/webhook/sentry", methods=["POST"])
def webhook_sentry():
"""Receives webhooks from Sentry."""
try:
payload = request.json
logger.info(f"Received Sentry webhook: {json.dumps(payload)[:200]}")
# Sentry sends a verification request on setup
if payload.get("action") == "verification":
return jsonify({"status": "ok"})
alert = parse_sentry_alert(payload)
# Run investigation
report = orchestrator.investigate(alert)
return jsonify({
"status": "processed",
"alert_source": "sentry",
"report_preview": report[:500]
})
except Exception as e:
logger.error(f"Error processing Sentry webhook: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/webhook", methods=["POST"])
def webhook_generic():
"""Receives generic webhooks."""
try:
payload = request.json
logger.info(f"Received generic webhook: {json.dumps(payload)[:200]}")
alert = parse_generic_alert(payload)
# Run investigation
report = orchestrator.investigate(alert)
return jsonify({
"status": "processed",
"alert_source": "generic",
"report_preview": report[:500]
})
except Exception as e:
logger.error(f"Error processing generic webhook: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/analyze", methods=["POST"])
def analyze_manual():
"""Manual analysis endpoint - accepts raw alert text."""
try:
payload = request.json
alert = payload.get("alert", "")
if not alert:
return jsonify({"error": "Missing 'alert' field"}), 400
logger.info(f"Manual analysis requested: {alert[:100]}")
# Run investigation
report = orchestrator.investigate(alert)
return jsonify({
"status": "processed",
"report": report
})
except Exception as e:
logger.error(f"Error in manual analysis: {e}")
return jsonify({"error": str(e)}), 500
def run_server(host: str = "0.0.0.0", port: int = 8080, debug: bool = False):
"""Runs the webhook server."""
logger.info(f"Starting webhook server on {host}:{port}")
logger.info("Available endpoints:")
logger.info(" GET /health - Health check")
logger.info(" POST /webhook/sentry - Sentry webhooks")
logger.info(" POST /webhook/datadog - Datadog webhooks")
logger.info(" POST /webhook/pagerduty - PagerDuty webhooks")
logger.info(" POST /webhook/grafana - Grafana webhooks")
logger.info(" POST /webhook/opsgenie - OpsGenie webhooks")
logger.info(" POST /webhook - Generic webhooks")
logger.info(" POST /analyze - Manual analysis")
app.run(host=host, port=port, debug=debug)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Anomaly Analysis Webhook Server")
parser.add_argument("--host", default="0.0.0.0", help="Host to bind")
parser.add_argument("--port", type=int, default=8080, help="Port to bind")
parser.add_argument("--debug", action="store_true", help="Enable debug mode")
args = parser.parse_args()
run_server(host=args.host, port=args.port, debug=args.debug)