-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitoring_engine.py
More file actions
2876 lines (2644 loc) · 113 KB
/
monitoring_engine.py
File metadata and controls
2876 lines (2644 loc) · 113 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import logging
from pathlib import Path
from typing import List, Dict, Any
from fastapi import FastAPI, BackgroundTasks, HTTPException, Query, Depends, Body
from fastapi.responses import JSONResponse
from pydantic import BaseModel, EmailStr
import httpx
import time
import re
import os
import json
import hashlib
import jwt
from contextlib import asynccontextmanager
from datetime import datetime, timedelta
from fastapi.middleware.cors import CORSMiddleware
import psutil
from dateutil import parser as dateutil_parser
from collections import defaultdict, OrderedDict # Add this import at the top if not present
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pymongo import MongoClient
import pymongo
from passlib.hash import bcrypt
from urllib.parse import urlparse
import pytz # Add this import at the top if not present
# Optional: pip install ollama
try:
import ollama
except ImportError:
ollama = None
# --- Email Alerting (SendGrid) ---
try:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
except ImportError:
SendGridAPIClient = None
Mail = None
# Add imports for PostgreSQL and MySQL
try:
import psycopg2
except ImportError:
psycopg2 = None
try:
import mysql.connector
except ImportError:
mysql = None
LOG_PATH = Path("/app/logs/metrics.log")
PROMETHEUS_URL = os.getenv("PROMETHEUS_URL", "http://prometheus:9090")
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://host.docker.internal:11434")
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "llama3")
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
GROQ_MODEL = os.getenv("GROQ_MODEL", "llama3-8b-8192")
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
ALERT_EMAIL_FROM = os.getenv("ALERT_EMAIL_FROM")
ALERT_EMAIL_TO = os.getenv("ALERT_EMAIL_TO")
user_service_metrics = {} # {service_name: {metrics, status, last_scraped, error}}
async def background_user_service_metrics_scraper():
"""Periodically scrape /metrics from user-registered services and cache results."""
global user_service_metrics, service_uptime_tracker
while True:
try:
# Get all registered services from all users
all_services = list(services_collection.find({}))
for svc in all_services:
name = svc["name"]
url = svc["url"].rstrip("/")
owner = svc["owner"]
metrics_url = f"{url}/metrics"
current_time = time.time()
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.get(metrics_url)
if resp.status_code == 200:
# Parse Prometheus metrics text format
metrics = parse_prometheus_metrics(resp.text)
# Track uptime internally
if name not in service_uptime_tracker:
service_uptime_tracker[name] = {
"first_seen": current_time,
"last_healthy": current_time
}
else:
service_uptime_tracker[name]["last_healthy"] = current_time
# Calculate uptime from Prometheus process_start_time_seconds
uptime = None
if "process_start_time_seconds" in metrics:
process_start_time = metrics["process_start_time_seconds"]
if process_start_time > 0:
uptime = (current_time - process_start_time) / 60 # in minutes
# Store historical metrics for load forecasting
save_metrics_history(name, metrics, current_time)
user_service_metrics[name] = {
"metrics": metrics,
"status": "healthy",
"last_scraped": current_time,
"error": None,
"owner": owner,
"url": url,
"uptime": uptime
}
else:
user_service_metrics[name] = {
"metrics": {},
"status": "unhealthy",
"last_scraped": current_time,
"error": f"Status {resp.status_code}",
"owner": owner,
"url": url
}
except Exception as e:
user_service_metrics[name] = {
"metrics": {},
"status": "unhealthy",
"last_scraped": current_time,
"error": str(e),
"owner": owner,
"url": url
}
except Exception as e:
print(f"[User Service Metrics Scraper] Error: {e}")
# Save uptime tracker periodically (every 10 minutes)
if int(time.time()) % 600 == 0: # Every 10 minutes
save_uptime_tracker()
# Clean up old metrics data periodically (every 6 hours)
if int(time.time()) % 21600 == 0: # Every 6 hours
cleanup_old_metrics_history(days_to_keep=30)
await asyncio.sleep(30) # Scrape every 30 seconds
# Add a new function to scrape metrics for a specific user
async def scrape_metrics_for_user(user_email: str):
"""Scrape metrics for a specific user's services."""
global service_uptime_tracker
services = get_registered_services_for_user(user_email)
for svc in services:
name = svc["name"]
url = svc["url"].rstrip("/")
metrics_url = f"{url}/metrics"
current_time = time.time()
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.get(metrics_url)
if resp.status_code == 200:
metrics = parse_prometheus_metrics(resp.text)
# Track uptime internally
if name not in service_uptime_tracker:
service_uptime_tracker[name] = {
"first_seen": current_time,
"last_healthy": current_time
}
else:
service_uptime_tracker[name]["last_healthy"] = current_time
# Calculate uptime from Prometheus process_start_time_seconds
uptime = None
if "process_start_time_seconds" in metrics:
process_start_time = metrics["process_start_time_seconds"]
if process_start_time > 0:
uptime = (current_time - process_start_time) / 60 # in minutes
# Store historical metrics for load forecasting
save_metrics_history(name, metrics, current_time)
user_service_metrics[name] = {
"metrics": metrics,
"status": "healthy",
"last_scraped": current_time,
"error": None,
"owner": user_email,
"url": url,
"uptime": uptime
}
else:
user_service_metrics[name] = {
"metrics": {},
"status": "unhealthy",
"last_scraped": current_time,
"error": f"Status {resp.status_code}",
"owner": user_email,
"url": url
}
except Exception as e:
user_service_metrics[name] = {
"metrics": {},
"status": "unhealthy",
"last_scraped": current_time,
"error": str(e),
"owner": user_email,
"url": url
}
def parse_prometheus_metrics(metrics_text):
"""Parse Prometheus text format into a dict of metric_name: value."""
metrics = {}
# Track metrics that need to be summed (like http_requests_total with different labels)
summable_metrics = {}
for line in metrics_text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
try:
parts = line.split()
if len(parts) == 2:
key, value = parts
# Check if this is a metric with labels
if "{" in key:
# Extract the base metric name (without labels)
base_key = key.split("{")[0]
# For metrics that should be summed across all labels
if base_key in ["http_requests_total", "errors_total"]:
if base_key not in summable_metrics:
summable_metrics[base_key] = 0
summable_metrics[base_key] += float(value)
else:
# For other metrics with labels, keep the last value (existing behavior)
metrics[base_key] = float(value)
else:
# No labels, store directly
metrics[key] = float(value)
except Exception:
continue
# Add the summed metrics to the result
for metric_name, total_value in summable_metrics.items():
metrics[metric_name] = total_value
# --- Compute average latency (seconds) ---
avg_latency = None
for prefix in ["http_request_duration_seconds", "total_response_ms"]:
sum_key = f"{prefix}_sum"
count_key = f"{prefix}_count"
if sum_key in metrics and count_key in metrics and metrics[count_key] > 0:
avg = metrics[sum_key] / metrics[count_key]
# If using ms, convert to seconds for consistency
if prefix == "total_response_ms":
avg = avg / 1000.0
avg_latency = avg
break
if avg_latency is not None:
metrics["avg_latency"] = avg_latency
return metrics
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load uptime tracking data on startup
load_uptime_tracker()
task1 = asyncio.create_task(background_log_scanner())
task2 = asyncio.create_task(background_user_service_metrics_scraper())
task3 = asyncio.create_task(background_db_health_checker())
yield
task1.cancel()
task2.cancel()
task3.cancel()
# Save uptime tracking data on shutdown
save_uptime_tracker()
app = FastAPI(lifespan=lifespan)
# Add this after creating the app
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins for development
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# In-memory store for parsed log data and detected anomalies
parsed_logs: List[Dict[str, Any]] = []
metrics_summary: Dict[str, Any] = {}
anomaly_cache: List[str] = []
prometheus_metrics: Dict[str, Any] = {}
# --- In-memory cache for root cause analysis ---
root_cause_cache = {}
CACHE_TTL_SECONDS = 120 # 2 minutes
# Track sent anomalies to avoid duplicate emails (in-memory, resets on restart)
sent_anomalies = set()
# --- Service uptime tracking (AppVital internal) ---
service_uptime_tracker = {} # {service_name: {"first_seen": timestamp, "last_healthy": timestamp}}
def load_uptime_tracker():
"""Load uptime tracking data from file"""
global service_uptime_tracker
try:
uptime_file = Path("/app/data/service_uptime.json")
if uptime_file.exists():
with open(uptime_file, "r") as f:
service_uptime_tracker = json.load(f)
print(f"Loaded uptime tracking data for {len(service_uptime_tracker)} services")
except Exception as e:
print(f"Error loading uptime tracker: {e}")
service_uptime_tracker = {}
def save_uptime_tracker():
"""Save uptime tracking data to file"""
try:
uptime_file = Path("/app/data/service_uptime.json")
uptime_file.parent.mkdir(exist_ok=True)
with open(uptime_file, "w") as f:
json.dump(service_uptime_tracker, f, indent=2)
except Exception as e:
print(f"Error saving uptime tracker: {e}")
# --- Authentication Models and Functions ---
class RegisterModel(BaseModel):
email: EmailStr
password: str
class LoginModel(BaseModel):
email: EmailStr
password: str
# In-memory user storage (in production, use a database)
users_db = {}
def hash_password(password: str) -> str:
"""Hash a password using SHA-256"""
return hashlib.sha256(password.encode()).hexdigest()
def verify_password(password: str, hashed: str) -> bool:
"""Verify a password against its hash"""
return hash_password(password) == hashed
def create_access_token(data: dict) -> str:
"""Create a JWT access token"""
secret = os.getenv("JWT_SECRET", "mysecretkey")
payload = data.copy()
payload.update({"exp": datetime.utcnow() + timedelta(hours=24)})
return jwt.encode(payload, secret, algorithm="HS256")
def send_email_alert(subject, content):
if not (SENDGRID_API_KEY and ALERT_EMAIL_FROM and ALERT_EMAIL_TO):
print("[Email Alert] Missing SENDGRID_API_KEY, ALERT_EMAIL_FROM, or ALERT_EMAIL_TO env vars.")
return
if not SendGridAPIClient or not Mail:
print("[Email Alert] SendGrid not installed.")
return
message = Mail(
from_email=ALERT_EMAIL_FROM,
to_emails=ALERT_EMAIL_TO,
subject=subject,
plain_text_content=content,
html_content=f"<pre>{content}</pre>"
)
try:
sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.send(message)
print(f"[Email Alert] Sent: {subject} (status {response.status_code})")
except Exception as e:
print(f"[Email Alert] Failed: {e}")
# --- Enhanced Log Parsing ---
def parse_log_line(line: str) -> Dict[str, Any]:
"""Parse structured and unstructured log lines, normalize level and service, always set message."""
try:
if line.strip().startswith('{'):
data = json.loads(line)
# Normalize level and service
if 'level' in data:
data['level'] = data['level'].upper()
# Try to infer service if missing or unknown
if 'service' not in data or not data['service'] or data['service'].lower() == 'unknown':
msg = data.get('message', '')
path = data.get('path', '')
event = data.get('event', '')
# Improved service inference
if 'auth_service' in msg or 'auth_service' in event or '/auth' in path or 'auth' in msg.lower():
data['service'] = 'auth_service'
elif 'order_service' in msg or 'order_service' in event or '/order' in path or 'order' in msg.lower():
data['service'] = 'order_service'
elif 'catalog_service' in msg or 'catalog_service' in event or '/catalog' in path or 'catalog' in msg.lower() or 'product' in msg.lower():
data['service'] = 'catalog_service'
elif 'controller' in msg.lower() or 'controller' in event.lower():
data['service'] = 'controller'
else:
data['service'] = 'unknown'
# Always ensure message field exists
if 'message' not in data or not data['message']:
# Try to use event or raw
data['message'] = data.get('event', '') or str(data)
return data
except json.JSONDecodeError:
pass
# Fallback to regex parsing for unstructured logs
log_pattern = re.compile(r"(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d+) \[(?P<level>\w+)\] (?P<message>.*)")
match = log_pattern.match(line)
if match:
data = match.groupdict()
data['level'] = data.get('level', '').upper()
msg = data.get('message', '')
# Improved service inference
if 'auth_service' in msg or '/auth' in msg or 'auth' in msg.lower():
data['service'] = 'auth_service'
elif 'order_service' in msg or '/order' in msg or 'order' in msg.lower():
data['service'] = 'order_service'
elif 'catalog_service' in msg or '/catalog' in msg or 'catalog' in msg.lower() or 'product' in msg.lower():
data['service'] = 'catalog_service'
elif 'controller' in msg.lower():
data['service'] = 'controller'
else:
data['service'] = 'unknown'
# Always ensure message field exists
if 'message' not in data or not data['message']:
data['message'] = str(data)
return data
# Always set message for raw logs
return {"raw": line, "timestamp": datetime.now().isoformat(), "level": "INFO", "service": "unknown", "message": line}
def load_logs() -> List[Dict[str, Any]]:
"""Load and parse logs from all service log files"""
log_files = [
Path("/app/logs/metrics.log"), # Main log file (controller)
Path("/app/logs/auth_service.log"), # Auth service logs
Path("/app/logs/catalog_service.log"), # Catalog service logs
Path("/app/logs/order_service.log"), # Order service logs
]
logs = []
for log_file in log_files:
if not log_file.exists():
continue
try:
# Try different encodings
encodings = ['utf-8', 'utf-16', 'latin-1']
file_content = None
for encoding in encodings:
try:
with log_file.open("r", encoding=encoding) as f:
file_content = f.read()
break
except UnicodeDecodeError:
continue
if file_content is None:
print(f"Could not read {log_file} with any encoding")
continue
for line in file_content.split('\n'):
line = line.strip()
if line:
parsed = parse_log_line(line)
if parsed:
logs.append(parsed)
except Exception as e:
print(f"Error loading logs from {log_file}: {e}")
return logs
# --- Enhanced Metrics Analysis ---
def analyze_logs(logs: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Comprehensive log analysis with industry-standard metrics"""
stats = {
"total": len(logs),
"errors": 0,
"auth_failures": 0,
"http_500": 0,
"order_404": 0,
"latencies": [],
"last_10_errors": [],
"error_types": {},
"response_codes": {},
"services": {},
"time_series": {},
"performance_metrics": {
"avg_latency_ms": None,
"min_latency_ms": None,
"max_latency_ms": None,
"p95_latency_ms": None,
"p99_latency_ms": None,
"error_rate": 0.0,
"success_rate": 0.0
}
}
# Time-based analysis (fix: each window is exclusive, not cumulative)
current_time = datetime.now()
time_windows = {
"last_1h": current_time - timedelta(hours=1),
"last_15m": current_time - timedelta(minutes=15),
"last_5m": current_time - timedelta(minutes=5)
}
# Prepare time series buckets
for window_name in time_windows:
stats["time_series"][window_name] = {"total": 0, "errors": 0}
for log in logs:
msg = log.get("message", "")
level = log.get("level", "")
service = log.get("service", "unknown")
status_code = log.get("status_code")
latency = log.get("latency_ms")
if latency is None:
latency = log.get("duration_ms")
timestamp_str = log.get("timestamp", "")
# Service tracking
if service not in stats["services"]:
stats["services"][service] = {
"total_requests": 0,
"errors": 0,
"avg_latency": 0,
"latencies": []
}
stats["services"][service]["total_requests"] += 1
# Count errors
if "error" in msg.lower() or level == "ERROR":
stats["errors"] += 1
stats["services"][service]["errors"] += 1
if len(stats["last_10_errors"]) < 10:
stats["last_10_errors"].append(log)
# Count specific error types
if "401" in msg or "authentication failed" in msg.lower():
stats["auth_failures"] += 1
stats["error_types"]["auth_failure"] = stats["error_types"].get("auth_failure", 0) + 1
if "500" in msg or (status_code and status_code == 500):
stats["http_500"] += 1
stats["error_types"]["http_500"] = stats["error_types"].get("http_500", 0) + 1
if "404" in msg and "order" in msg.lower():
stats["order_404"] += 1
stats["error_types"]["order_404"] = stats["error_types"].get("order_404", 0) + 1
# Latency analysis
if latency is not None:
stats["latencies"].append(latency)
stats["services"][service]["latencies"].append(latency)
# Response code analysis
if status_code:
stats["response_codes"][str(status_code)] = stats["response_codes"].get(str(status_code), 0) + 1
# Time series analysis (fix: each window is exclusive)
try:
if timestamp_str:
log_time = dateutil_parser.parse(timestamp_str)
for window_name, window_start in time_windows.items():
# Only count logs within this window (not cumulative)
if log_time >= window_start and log_time <= current_time:
# For each window, check if log_time is within window's range only
# For last_5m: >= now-5m and <= now
# For last_15m: >= now-15m and < now-5m
# For last_1h: >= now-1h and < now-15m
if window_name == "last_5m":
if log_time >= current_time - timedelta(minutes=5):
stats["time_series"][window_name]["total"] += 1
if "error" in msg.lower() or level == "ERROR":
stats["time_series"][window_name]["errors"] += 1
elif window_name == "last_15m":
if current_time - timedelta(minutes=15) <= log_time < current_time - timedelta(minutes=5):
stats["time_series"][window_name]["total"] += 1
if "error" in msg.lower() or level == "ERROR":
stats["time_series"][window_name]["errors"] += 1
elif window_name == "last_1h":
if current_time - timedelta(hours=1) <= log_time < current_time - timedelta(minutes=15):
stats["time_series"][window_name]["total"] += 1
if "error" in msg.lower() or level == "ERROR":
stats["time_series"][window_name]["errors"] += 1
except Exception:
pass
# Calculate performance metrics
if stats["latencies"]:
latencies = sorted(stats["latencies"])
stats["performance_metrics"].update({
"avg_latency_ms": sum(latencies) / len(latencies),
"min_latency_ms": min(latencies),
"max_latency_ms": max(latencies),
"p95_latency_ms": latencies[int(len(latencies) * 0.95)],
"p99_latency_ms": latencies[int(len(latencies) * 0.99)]
})
# Calculate rates
if stats["total"] > 0:
stats["performance_metrics"]["error_rate"] = (stats["errors"] / stats["total"]) * 100
stats["performance_metrics"]["success_rate"] = 100 - stats["performance_metrics"]["error_rate"]
# Calculate service-specific metrics
for service in stats["services"]:
service_data = stats["services"][service]
if service_data["latencies"]:
service_data["avg_latency"] = sum(service_data["latencies"]) / len(service_data["latencies"])
return stats
async def scrape_prometheus() -> Dict[str, Any]:
"""Enhanced Prometheus metrics scraping with industry-standard queries"""
metrics = {}
queries = {
"up": "up",
"http_requests_total": "http_requests_total",
"http_request_duration_seconds": "http_request_duration_seconds",
"response_time_ms": "response_time_ms",
"cpu_percent": "cpu_percent",
"memory_used_mb": "memory_used_mb",
"auth_attempts_total": "auth_attempts_total",
"jwt_tokens_issued_total": "jwt_tokens_issued_total",
"db_operations_total": "db_operations_total",
"errors_total": "errors_total",
"process_start_time_seconds": "process_start_time_seconds"
}
try:
async with httpx.AsyncClient() as client:
# Scrape individual metrics
for metric_name, query in queries.items():
try:
resp = await client.get(
f"{PROMETHEUS_URL}/api/v1/query",
params={"query": query},
timeout=5
)
if resp.status_code == 200:
data = resp.json()
metrics[metric_name] = data.get("data", {}).get("result", [])
else:
metrics[f"{metric_name}_error"] = resp.text
except Exception as e:
metrics[f"{metric_name}_error"] = str(e)
# Get service health status
resp = await client.get(f"{PROMETHEUS_URL}/api/v1/targets", timeout=5)
if resp.status_code == 200:
targets_data = resp.json()
metrics["targets"] = targets_data.get("data", {}).get("activeTargets", [])
# Get metric metadata
resp = await client.get(f"{PROMETHEUS_URL}/api/v1/label/__name__/values", timeout=5)
if resp.status_code == 200:
metadata = resp.json()
metrics["available_metrics"] = metadata.get("data", [])
except Exception as e:
metrics["prometheus_error"] = str(e)
return metrics
# --- Enhanced Anomaly Detection ---
def detect_anomalies(logs: List[Dict[str, Any]]) -> List[str]:
"""Advanced anomaly detection with multiple algorithms"""
anomalies = []
# Check last 100 logs for anomalies
recent_logs = logs[-100:] if len(logs) > 100 else logs
# 1. Error rate anomaly
error_count = sum(1 for log in recent_logs if log.get("level") == "ERROR")
if error_count > 10:
anomalies.append(f"High error rate detected: {error_count} errors in last 100 logs")
# 2. HTTP 500 anomaly
http_500_count = sum(1 for log in recent_logs if "500" in log.get("message", ""))
if http_500_count > 5:
anomalies.append(f"Spike in HTTP 500 errors: {http_500_count} in last 100 logs")
# 3. Authentication failures anomaly
auth_failures = sum(1 for log in recent_logs if "401" in log.get("message", ""))
if auth_failures > 5:
anomalies.append(f"Spike in authentication failures: {auth_failures} in last 100 logs")
# 4. Latency anomaly detection
latencies = []
for log in recent_logs:
latency = log.get("latency_ms")
if latency:
latencies.append(latency)
if latencies:
avg_latency = sum(latencies) / len(latencies)
if avg_latency > 1000: # More than 1 second average
anomalies.append(f"High average latency detected: {avg_latency:.2f}ms")
# Detect latency spikes (values > 2x average)
threshold = avg_latency * 2
spikes = [l for l in latencies if l > threshold]
if len(spikes) > 3:
anomalies.append(f"Latency spikes detected: {len(spikes)} requests > {threshold:.2f}ms")
# 5. Service-specific anomalies
service_errors = {}
for log in recent_logs:
service = log.get("service", "unknown")
if "error" in log.get("message", "").lower() or log.get("level") == "ERROR":
service_errors[service] = service_errors.get(service, 0) + 1
for service, error_count in service_errors.items():
if error_count > 3:
anomalies.append(f"Service {service} has high error rate: {error_count} errors")
# --- Email alert for new anomalies ---
for anomaly in anomalies:
if anomaly not in sent_anomalies:
send_email_alert(
subject=f"[Health Monitor] Anomaly Detected",
content=f"Anomaly detected:\n{anomaly}\n\nSee dashboard for details."
)
sent_anomalies.add(anomaly)
return anomalies
# --- Enhanced Ollama Integration with better error handling
async def ask_ollama_for_root_cause_httpx(prompt: str) -> str:
"""Direct HTTP call to Ollama API with comprehensive error handling"""
url = OLLAMA_URL.rstrip('/') # Remove trailing slash
data = {
"model": OLLAMA_MODEL,
"prompt": prompt,
"stream": False,
"options": {
"temperature": 0.1,
"top_p": 0.9,
"max_tokens": 500
}
}
try:
print(f"Attempting to connect to Ollama at: {url}/api/generate")
print(f"Using model: {OLLAMA_MODEL}")
async with httpx.AsyncClient(timeout=httpx.Timeout(120.0)) as client:
# Health check
try:
health_resp = await client.get(f"{url}/api/tags", timeout=5.0)
print(f"Ollama health check status: {health_resp.status_code}")
if health_resp.status_code != 200:
return f"Ollama is not responding properly. Status: {health_resp.status_code}"
except Exception as e:
return f"Cannot reach Ollama server at {url}. Error: {str(e)}"
# Generation request
resp = await client.post(
f"{url}/api/generate",
json=data,
headers={"Content-Type": "application/json"}
)
print(f"Ollama generate response status: {resp.status_code}")
if resp.status_code == 200:
result = resp.json()
response_text = result.get("response", "")
if response_text:
return response_text
else:
return f"Ollama returned empty response. Full response: {result}"
else:
error_text = resp.text
return f"Ollama API error (HTTP {resp.status_code}): {error_text}"
except httpx.TimeoutException:
return f"Timeout connecting to Ollama at {url}. The model might be loading or the server is slow."
except httpx.ConnectError:
return f"Connection failed to Ollama at {url}. Check if Ollama is running and accessible from the container."
except Exception as e:
return f"Unexpected error calling Ollama: {str(e)}"
def get_groq_headers():
return {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
async def ask_llm_groq(prompt: str) -> str:
if not GROQ_API_KEY:
return "Error: GROQ_API_KEY not configured. Please set the GROQ_API_KEY environment variable."
url = "https://api.groq.com/openai/v1/chat/completions"
headers = get_groq_headers()
data = {
"model": GROQ_MODEL,
"messages": [
{"role": "user", "content": prompt}
]
}
try:
print(f"Calling Groq API with model: {GROQ_MODEL}")
async with httpx.AsyncClient(timeout=60.0) as client:
resp = await client.post(url, headers=headers, json=data)
print(f"Groq API response status: {resp.status_code}")
if resp.status_code != 200:
error_text = resp.text
print(f"Groq API error response: {error_text}")
return f"Groq API error (HTTP {resp.status_code}): {error_text}"
result = resp.json()
print(f"Groq API response: {result}")
if "choices" in result and len(result["choices"]) > 0:
content = result["choices"][0]["message"]["content"]
print(f"Groq API content length: {len(content)}")
return content
else:
print(f"Unexpected Groq API response format: {result}")
return f"Unexpected Groq API response format: {result}"
except httpx.TimeoutException:
return "Error: Groq API request timed out after 60 seconds."
except httpx.ConnectError:
return "Error: Cannot connect to Groq API. Check your internet connection."
except Exception as e:
print(f"Groq API exception: {str(e)}")
return f"Groq API error: {str(e)}"
# --- Focused log selection for root cause analysis ---
def select_focused_logs_for_anomaly(logs, anomaly_text=None, window=10, max_logs=20):
# If anomaly_text is provided, try to find the log index with matching message
if anomaly_text:
for i, log in enumerate(reversed(logs)):
if anomaly_text.lower() in json.dumps(log, default=str).lower():
# Found anomaly log, select window around it
start = max(0, len(logs) - i - window)
end = min(len(logs), len(logs) - i + window)
return logs[start:end]
# If no anomaly or not found, fallback to last N error logs
error_logs = [log for log in logs if log.get("level") == "ERROR" or "error" in log.get("message", "").lower()]
if error_logs:
return error_logs[-max_logs:]
# Fallback: last N logs
return logs[-max_logs:]
async def ai_incident_analysis(anomaly, logs, metrics, dependencies=None, cache_key=None):
# --- Caching logic ---
now = time.time()
if cache_key and cache_key in root_cause_cache:
cached = root_cause_cache[cache_key]
if now - cached["timestamp"] < CACHE_TTL_SECONDS:
return cached["result"]
# --- Flexible log selection ---
if anomaly and anomaly != "No anomalies detected, manual analysis":
focused_logs = select_focused_logs_for_anomaly(logs, anomaly_text=anomaly)
prompt_type = "incident"
else:
# No anomaly: use last N error logs, or last N logs if no errors
error_logs = [log for log in logs if log.get("level") == "ERROR" or "error" in log.get("message", "").lower()]
focused_logs = error_logs[-20:] if error_logs else logs[-20:]
prompt_type = "general"
recent_logs = focused_logs[-20:]
if not recent_logs:
recent_logs = [{"message": "No recent logs available."}]
if not metrics:
metrics = {"total": 0, "errors": 0, "performance_metrics": {"error_rate": 0}}
# --- Updated prompt for strict JSON output ---
if prompt_type == "incident":
prompt = f"""You are an SRE analyzing a system incident. Please provide a concise analysis.
INCIDENT DETAILS:\nAnomaly: {anomaly}
RECENT LOGS (last {len(recent_logs)}):\n{chr(10).join([json.dumps(log, default=str)[:200] + '...' if len(json.dumps(log, default=str)) > 200 else json.dumps(log, default=str) for log in recent_logs])}
METRICS SUMMARY:\n- Total requests: {metrics.get('total', 0)}\n- Error count: {metrics.get('errors', 0)}\n- Error rate: {metrics.get('performance_metrics', {}).get('error_rate', 0):.2f}%
SERVICE DEPENDENCIES: {dependencies or 'N/A'}
Respond ONLY with valid JSON. Do NOT include any explanation, markdown, or comments. Your entire response must be a single valid JSON object, with no text before or after.
{{
\"summary\": \"...\",
\"root_cause\": \"...\",
\"actions\": [\"...\", \"...\"],
\"prevention\": [\"...\", \"...\"],
\"confidence\": \"...\",
\"evidence\": [\"...\", \"...\"]
}}
"""
else:
prompt = f"""You are an SRE reviewing system logs. No explicit anomaly was detected, but please review the following logs and metrics for any issues, unusual patterns, or potential risks.\n\nLOG SAMPLE (last {len(recent_logs)}):\n{chr(10).join([json.dumps(log, default=str)[:200] + '...' if len(json.dumps(log, default=str)) > 200 else json.dumps(log, default=str) for log in recent_logs])}\n\nMETRICS SUMMARY:\n- Total requests: {metrics.get('total', 0)}\n- Error count: {metrics.get('errors', 0)}\n- Error rate: {metrics.get('performance_metrics', {}).get('error_rate', 0):.2f}%\n\nSERVICE DEPENDENCIES: {dependencies or 'N/A'}\n\nRespond ONLY with valid JSON. Do NOT include any explanation, markdown, or comments. Your entire response must be a single valid JSON object, with no text before or after.\n{{\n \"summary\": \"...\",\n \"root_cause\": \"...\",\n \"actions\": [\"...\", \"...\"],\n \"prevention\": [\"...\", \"...\"],\n \"confidence\": \"...\",\n \"evidence\": [\"...\", \"...\"]\n}}\n"""
ai_result = await ask_llm_groq(prompt)
# --- Try to parse as JSON, removing comment lines ---
parsed_result = None
if isinstance(ai_result, str):
try:
# Extract JSON block
start = ai_result.find('{')
end = ai_result.rfind('}')
if start != -1 and end != -1:
json_str = ai_result[start:end+1]
# Remove lines starting with // (comments)
json_str = '\n'.join(line for line in json_str.splitlines() if not line.strip().startswith('//'))
parsed_result = json.loads(json_str)
except Exception as e:
parsed_result = None
# If parsing failed, fallback to string in a single field
if not parsed_result:
parsed_result = {
"summary": None,
"root_cause": ai_result if isinstance(ai_result, str) else str(ai_result),
"actions": [],
"prevention": [],
"confidence": None,
"evidence": []
}
result = {
"anomalies": anomaly_cache,
"root_cause": parsed_result
}
# Cache the result
if cache_key:
root_cause_cache[cache_key] = {"timestamp": now, "result": result}
return result
async def ai_log_summary(logs, metrics, dependencies=None):
# Limit to last 20 logs, and truncate each log string
max_logs = 30
recent_logs = logs[-max_logs:]
if not recent_logs:
recent_logs = [{"message": "No recent logs available."}]
if not metrics:
metrics = {"total": 0, "errors": 0, "performance_metrics": {"error_rate": 0}}
prompt = f"""You are an SRE reviewing system logs. Please provide a concise summary of the last {len(recent_logs)} logs.
LOG SAMPLE (last {len(recent_logs)}):
{chr(10).join([json.dumps(log, default=str)[:200] + "..." if len(json.dumps(log, default=str)) > 200 else json.dumps(log, default=str) for log in recent_logs])}
METRICS SUMMARY:
- Total requests: {metrics.get('total', 0)}
- Error count: {metrics.get('errors', 0)}
- Error rate: {metrics.get('performance_metrics', {}).get('error_rate', 0):.2f}%
SERVICE DEPENDENCIES: {dependencies or 'N/A'}
Please provide:
1. OVERALL SUMMARY (2-3 sentences)
2. NOTABLE TRENDS OR PATTERNS (1-2 sentences)
3. ANY RECOMMENDATIONS (1-2 bullet points)
Keep response under 300 words.
"""
ai_result = await ask_llm_groq(prompt)
return {
"summary": ai_result
}
# --- Background Task ---
async def background_log_scanner():
"""Enhanced background log scanner with Prometheus integration"""
global parsed_logs, metrics_summary, anomaly_cache, prometheus_metrics
last_size = 0
while True:
try:
# Load and parse logs
logs = load_logs()
if len(logs) != last_size:
parsed_logs = logs
metrics_summary = analyze_logs(logs)
anomaly_cache = detect_anomalies(logs)
last_size = len(logs)
# Scrape Prometheus metrics
prometheus_metrics = await scrape_prometheus()
except Exception as e:
print(f"Error in background scanner: {e}")
await asyncio.sleep(30) # Update every 30 seconds
# --- Authentication Endpoints ---
@app.post("/register")
async def register_user(data: RegisterModel):
"""Register a new user (persistent, MongoDB)"""
existing = users_collection.find_one({"email": data.email})
if existing:
return {"status": "error", "msg": "Email already registered"}
hashed_pw = bcrypt.hash(data.password)
user_doc = {
"email": data.email,
"passwordHash": hashed_pw,
"createdAt": datetime.utcnow(),
"lastLoginAt": None,
"sessionCount": 0
}
users_collection.insert_one(user_doc)
return {"status": "success", "msg": "User registered successfully"}
@app.post("/login")
async def login_user(data: LoginModel):
"""Login a user (persistent, MongoDB)"""
user = users_collection.find_one({"email": data.email})