-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_webhook_flow.py
More file actions
executable file
·276 lines (219 loc) · 8.33 KB
/
debug_webhook_flow.py
File metadata and controls
executable file
·276 lines (219 loc) · 8.33 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
#!/usr/bin/env python3
"""
Interactive webhook flow debugging script.
This script helps you debug the webhook integration system step-by-step.
Run with: python debug_webhook_flow.py
"""
import asyncio
import logging
import sys
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
# Configure detailed logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s | %(name)s | %(levelname)s | %(message)s",
)
from config import get_config
from src.agents.nodes.detect import detect_node
from src.agents.schemas import IncidentMetrics, create_initial_state
from src.app.webhooks.events import (
EventTypes,
WebhookEvent,
dispatch_event,
get_registered_handlers,
register_handler,
)
LOGGER = logging.getLogger("debug_webhook")
# -----------------------------------------------------------------------------
# Debug Handlers
# -----------------------------------------------------------------------------
async def debug_handler(event: WebhookEvent):
"""Debug handler that prints event details."""
print("\n" + "=" * 70)
print(f"🔔 WEBHOOK EVENT RECEIVED")
print("=" * 70)
print(f"Event Type: {event.event_type.value}")
print(f"Incident ID: {event.incident_id}")
print(f"Timestamp: {event.timestamp}")
print(f"\nPayload:")
for key, value in event.payload.items():
if isinstance(value, list) and len(value) > 3:
print(f" {key}: [{len(value)} items]")
else:
print(f" {key}: {value}")
print(f"\nMetadata:")
for key, value in event.metadata.items():
print(f" {key}: {value}")
print("=" * 70 + "\n")
# -----------------------------------------------------------------------------
# Debug Functions
# -----------------------------------------------------------------------------
def debug_step_1_config():
"""Step 1: Check configuration."""
print("\n" + "=" * 70)
print("STEP 1: Checking Configuration")
print("=" * 70)
config = get_config()
webhook_config = config.webhooks
print(f"✅ Webhook system enabled: {webhook_config.enabled}")
print(f"✅ Slack enabled: {webhook_config.slack.enabled}")
print(f"✅ Slack URL configured: {bool(webhook_config.slack.webhook_url)}")
print(f"✅ PagerDuty enabled: {webhook_config.pagerduty.enabled}")
print(
f"✅ PagerDuty key configured: {bool(webhook_config.pagerduty.integration_key)}"
)
if not webhook_config.enabled:
print("⚠️ WARNING: Webhook system is disabled!")
return config
def debug_step_2_handler_registration():
"""Step 2: Register handlers and check registration."""
print("\n" + "=" * 70)
print("STEP 2: Handler Registration")
print("=" * 70)
# Register debug handler for all event types
for event_type in EventTypes:
register_handler(event_type, debug_handler)
handlers = get_registered_handlers()
print(f"✅ Registered handlers for {len(handlers)} event types:")
for event_type, count in handlers.items():
print(f" - {event_type}: {count} handler(s)")
return handlers
async def debug_step_3_event_creation():
"""Step 3: Create and dispatch test event."""
print("\n" + "=" * 70)
print("STEP 3: Event Creation & Dispatch")
print("=" * 70)
# Create test event
event_type = EventTypes.INCIDENT_DETECTED
incident_id = "debug-test-incident-1"
payload = {
"is_anomaly": True,
"confidence": 0.95,
"detection_method": "z_score",
"metrics": [
{
"metric_name": "cpu_usage_percent",
"current_value": 95.0,
"baseline_value": 70.0,
"deviation_score": 4.0,
}
],
}
metadata = {
"source": "debug-script",
"priority": "high",
}
print(f"📤 Creating event:")
print(f" Type: {event_type.value}")
print(f" Incident ID: {incident_id}")
print(f" Payload keys: {list(payload.keys())}")
# Dispatch event
print(f"\n📨 Dispatching event...")
await dispatch_event(event_type, incident_id, payload, metadata)
# Wait for handlers to complete
print(f"⏳ Waiting for handlers to complete...")
await asyncio.sleep(2)
print(f"✅ Event dispatched and handlers called")
async def debug_step_4_agent_integration():
"""Step 4: Test event dispatch from agent node."""
print("\n" + "=" * 70)
print("STEP 4: Agent Node Integration")
print("=" * 70)
# Create incident state
metrics = [
IncidentMetrics(
metric_name="memory_usage_percent",
current_value=92.0,
baseline_value=60.0,
deviation_score=5.0,
labels={"service": "test-service"},
)
]
state = create_initial_state("debug-agent-incident-1", metrics)
print(f"📊 Created incident state:")
print(f" Incident ID: {state['incident_id']}")
print(f" Metrics count: {len(state['metrics'])}")
# Run detection (this should trigger event dispatch)
print(f"\n🔍 Running detection node...")
try:
result_state = await detect_node(state)
detection_result = result_state.get("detection_result")
if detection_result:
print(f"✅ Detection complete:")
print(f" Is Anomaly: {detection_result.is_anomaly}")
print(f" Confidence: {detection_result.confidence}")
print(f" Method: {detection_result.detection_method}")
if detection_result.is_anomaly:
print(f"\n⏳ Waiting for webhook events...")
await asyncio.sleep(2)
print(
f"✅ If webhooks are configured, events should have been dispatched"
)
else:
print(f"⚠️ No detection result in state")
except Exception as e:
print(f"❌ Error in detection: {e}")
import traceback
traceback.print_exc()
def debug_step_5_metrics():
"""Step 5: Check metrics."""
print("\n" + "=" * 70)
print("STEP 5: Metrics Check")
print("=" * 70)
try:
from src.app.webhooks.metrics import (
WEBHOOK_DELIVERY_DURATION,
WEBHOOK_DELIVERY_FAILURES,
WEBHOOK_EVENTS_DISPATCHED,
)
print("✅ Metrics available:")
print(f" - WEBHOOK_EVENTS_DISPATCHED")
print(f" - WEBHOOK_DELIVERY_DURATION")
print(f" - WEBHOOK_DELIVERY_FAILURES")
print(f"\n💡 To view metrics, start Prometheus and query:")
print(f" sentinel_webhook_events_dispatched_total")
except Exception as e:
print(f"⚠️ Could not import metrics: {e}")
# -----------------------------------------------------------------------------
# Main
# -----------------------------------------------------------------------------
async def main():
"""Run all debug steps."""
print("\n" + "=" * 70)
print("🛠️ WEBHOOK FLOW DEBUGGING SCRIPT")
print("=" * 70)
print("\nThis script will walk through the webhook integration step-by-step.")
print("Press Enter after each step to continue...\n")
input("Press Enter to start Step 1 (Configuration Check)...")
config = debug_step_1_config()
input("\nPress Enter to start Step 2 (Handler Registration)...")
handlers = debug_step_2_handler_registration()
input("\nPress Enter to start Step 3 (Event Creation & Dispatch)...")
await debug_step_3_event_creation()
input("\nPress Enter to start Step 4 (Agent Node Integration)...")
await debug_step_4_agent_integration()
input("\nPress Enter to start Step 5 (Metrics Check)...")
debug_step_5_metrics()
print("\n" + "=" * 70)
print("✅ DEBUGGING COMPLETE")
print("=" * 70)
print("\nNext steps:")
print("1. Review the output above for any errors or warnings")
print("2. Check webhook delivery (Slack channel or PagerDuty)")
print("3. Review Prometheus metrics if available")
print("4. Check application logs for detailed information")
print("\n")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n\n⚠️ Debugging interrupted by user")
sys.exit(0)
except Exception as e:
print(f"\n\n❌ Error during debugging: {e}")
import traceback
traceback.print_exc()
sys.exit(1)