Skip to content

Commit 7fec657

Browse files
committed
feat: implemented AI for log analysis for alert and recommendation
1 parent 981901a commit 7fec657

22 files changed

+4113
-199
lines changed

β€Ž.dockerignoreβ€Ž

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ ENV/
3030
*~
3131

3232
# Environment
33-
.env
34-
.env.local
33+
# .env
34+
# .env.local
3535

3636
# Documentation
3737
*.md

β€Ž.env.exampleβ€Ž

Lines changed: 17 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,85 +1,35 @@
11
# Application Settings
2-
APP_NAME=log-analysis-service
3-
APP_VERSION=1.0.0
42
ENVIRONMENT=development
5-
DEBUG=True
3+
DEBUG=true
64
LOG_LEVEL=INFO
75

8-
# Server Configuration
9-
HOST=0.0.0.0
10-
PORT=8000
11-
WORKERS=4
12-
13-
# Database Configuration
6+
# Database
147
DATABASE_URL=postgresql+asyncpg://postgres:password@localhost:5432/log_analysis_db
15-
DATABASE_POOL_SIZE=20
16-
DATABASE_MAX_OVERFLOW=10
17-
DATABASE_POOL_TIMEOUT=30
18-
DATABASE_POOL_RECYCLE=3600
198
POSTGRES_USER=postgres
209
POSTGRES_PASSWORD=password
2110
POSTGRES_DB=log_analysis_db
22-
POSTGRES_HOST=localhost
23-
POSTGRES_PORT=5432
24-
2511

26-
# RabbitMQ Configuration
12+
# RabbitMQ
2713
RABBITMQ_HOST=localhost
2814
RABBITMQ_PORT=5672
2915
RABBITMQ_USER=guest
3016
RABBITMQ_PASSWORD=guest
3117
RABBITMQ_VHOST=/
32-
RABBITMQ_PREFETCH_COUNT=10
33-
RABBITMQ_RECONNECT_DELAY=5
34-
RABBITMQ_ERLANG_COOKIE=your-secret-cookie-change-this
35-
36-
# Queue Names
37-
LOG_ANALYSIS_QUEUE=log_analysis_queue
38-
RECOMMENDATION_QUEUE=recommendation_queue
39-
ALERTS_QUEUE=alerts_queue
18+
RABBITMQ_ERLANG_COOKIE=secret_cookie_change_me
4019

41-
# JWT Authentication
20+
# Security
4221
JWT_SECRET_KEY=your-super-secret-jwt-key-change-this-in-production
4322
JWT_ALGORITHM=HS256
44-
JWT_EXPIRATION_MINUTES=60
45-
API_GATEWAY_PUBLIC_KEY=
46-
47-
# Processing Configuration
48-
BATCH_SIZE=100
49-
PROCESSING_INTERVAL_SECONDS=5
50-
MAX_CONCURRENT_BATCHES=5
51-
52-
# Anomaly Detection Thresholds
53-
ERROR_RATE_THRESHOLD=10.0
54-
ANOMALY_SCORE_THRESHOLD=0.85
55-
MIN_PATTERN_FREQUENCY=5
56-
57-
# Metrics & Monitoring
58-
PROMETHEUS_PORT=9090
59-
ENABLE_METRICS=True
60-
METRICS_PATH=/metrics
61-
62-
# Rate Limiting
63-
RATE_LIMIT_ENABLED=True
64-
RATE_LIMIT_REQUESTS=100
65-
RATE_LIMIT_PERIOD=60
66-
67-
# CORS Settings
68-
CORS_ENABLED=True
69-
CORS_ORIGINS=["http://localhost:3000", "http://localhost:8080"]
70-
CORS_METHODS=["GET", "POST", "PUT", "DELETE", "OPTIONS"]
71-
CORS_HEADERS=["*"]
72-
73-
# Security
74-
ALLOWED_HOSTS=["localhost", "127.0.0.1"]
75-
TRUSTED_PROXIES=[]
76-
77-
# Retry Configuration
78-
MAX_RETRY_ATTEMPTS=3
79-
RETRY_BACKOFF_FACTOR=2
80-
RETRY_MAX_DELAY_SECONDS=60
8123

82-
# Feature Flags
83-
ENABLE_REAL_TIME_PROCESSING=True
84-
ENABLE_PATTERN_CLUSTERING=True
85-
ENABLE_ML_ANOMALY_DETECTION=True
24+
# AI Services (Optional)
25+
ENABLE_OPENAI_ANALYSIS=false
26+
OPENAI_API_KEY=sk-your-api-key-here
27+
OPENAI_MODEL=gpt-4-turbo-preview
28+
AI_ANALYSIS_MIN_SEVERITY=ERROR
29+
30+
# Groq AI Configuration (Recommended - Fast & Affordable)
31+
ENABLE_GROQ_ANALYSIS=false
32+
GROQ_API_KEY=gsk_your_api_key_here
33+
GROQ_MODEL=llama-3.1-70b-versatile
34+
GROQ_TEMPERATURE=0.3
35+
GROQ_MAX_TOKENS=1000

β€Ž.gitignoreβ€Ž

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,3 +205,5 @@ cython_debug/
205205
marimo/_static/
206206
marimo/_lsp/
207207
__marimo__/
208+
209+
*.md

β€ŽDockerfileβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Multi-stage build for smaller image size
22

3-
FROM python:3.11-slim as builder
3+
FROM python:3.11-slim AS builder
44

55
WORKDIR /build
66

β€ŽMakefileβ€Ž

Lines changed: 206 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,219 @@
1-
.PHONY: help install dev test lint format clean docker-build docker-up docker-down migrate
1+
# Log Analysis Service - Makefile
22

3+
.PHONY: help start stop restart test clean logs status
4+
5+
# Default target
36
help:
4-
@echo "Log Analysis Service - Available commands:"
5-
@echo " install - Install dependencies"
6-
@echo " dev - Run development server"
7-
@echo " test - Run tests"
8-
@echo " lint - Run linters"
9-
@echo " format - Format code"
10-
@echo " clean - Clean generated files"
11-
@echo " docker-build - Build Docker image"
12-
@echo " docker-up - Start Docker services"
13-
@echo " docker-down - Stop Docker services"
14-
@echo " migrate - Run database migrations"
15-
16-
install:
17-
pip install -r requirements.txt
7+
@echo "Log Analysis Service - Available Commands:"
8+
@echo ""
9+
@echo "πŸš€ Service Management:"
10+
@echo " start - Start all services with Docker Compose"
11+
@echo " stop - Stop all services"
12+
@echo " restart - Restart all services"
13+
@echo " logs - View application logs"
14+
@echo " status - Check service status"
15+
@echo " clean - Clean up containers and volumes"
16+
@echo ""
17+
@echo "πŸ”‘ Authentication:"
18+
@echo " get-token - Generate admin authentication token"
19+
@echo " get-token-user - Generate user authentication token"
20+
@echo " get-token-admin- Generate admin authentication token"
21+
@echo ""
22+
@echo "βš™οΈ Configuration:"
23+
@echo " get-config - Show application configuration"
24+
@echo ""
25+
@echo "πŸ§ͺ Testing:"
26+
@echo " test-logs - Run comprehensive log processing tests"
27+
@echo " test-critical - Test critical error scenarios"
28+
@echo " test-pattern - Test pattern detection"
29+
@echo " test-anomaly - Test anomaly detection"
30+
@echo " test-api-status - Test AI status endpoint"
31+
@echo " test-api-logs - Test logs endpoint"
32+
@echo " test-api-stats - Test stats endpoint"
33+
@echo ""
34+
@echo "πŸ“Š Monitoring:"
35+
@echo " check-logs-db - View recent logs in database"
36+
@echo " check-patterns - View detected patterns"
37+
@echo " check-queues - View RabbitMQ queue status"
38+
@echo " metrics - View Prometheus metrics"
39+
@echo ""
1840

19-
dev:
20-
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
41+
# Start all services
42+
start:
43+
@echo "πŸš€ Starting Log Analysis Service..."
44+
docker compose up -d
45+
@echo "⏳ Waiting for services to be ready..."
46+
@sleep 10
47+
@echo "βœ… Services started! Check status with 'make status'"
48+
49+
# Stop all services
50+
stop:
51+
@echo "πŸ›‘ Stopping services..."
52+
docker compose down
53+
54+
# Restart services
55+
restart:
56+
@echo "πŸ”„ Restarting services..."
57+
docker compose restart
2158

22-
test:
23-
pytest tests/ -v --cov=app --cov-report=html --cov-report=term
59+
restart-build:
60+
@echo "πŸ”„ Restarting services..."
61+
docker compose up -d --build
62+
2463

25-
lint:
26-
flake8 app/ tests/
27-
mypy app/
64+
# View logs
65+
logs:
66+
@echo "πŸ“‹ Viewing application logs..."
67+
docker compose logs -f log_analysis_service
2868

29-
format:
30-
black app/ tests/
31-
isort app/ tests/
69+
# Check service status
70+
status:
71+
@echo "πŸ“Š Service Status:"
72+
@echo ""
73+
@echo "Docker Services:"
74+
@docker compose ps
75+
@echo ""
76+
@echo "Health Check:"
77+
@curl -s http://localhost:8000/health | jq . || echo "❌ Health check failed"
78+
@echo ""
79+
@echo "Readiness Check:"
80+
@curl -s http://localhost:8000/health/ready | jq . || echo "❌ Readiness check failed"
3281

82+
# Clean up
3383
clean:
34-
find . -type d -name "__pycache__" -exec rm -rf {} +
35-
find . -type f -name "*.pyc" -delete
36-
find . -type f -name "*.pyo" -delete
37-
find . -type d -name "*.egg-info" -exec rm -rf {} +
38-
rm -rf .pytest_cache .mypy_cache .coverage htmlcov/
84+
@echo "🧹 Cleaning up..."
85+
docker compose down -v
86+
docker system prune -f
87+
88+
# Local development
89+
dev:
90+
@echo "πŸ”§ Starting for local development..."
91+
python start_app.py
92+
93+
# Initial setup
94+
setup:
95+
@echo "βš™οΈ Setting up Log Analysis Service..."
96+
@echo "1. Creating .env file..."
97+
@if [ ! -f .env ]; then cp .env.example .env; echo "βœ… .env file created"; else echo "βœ… .env file already exists"; fi
98+
@echo "2. Starting services..."
99+
docker compose up -d
100+
@echo "3. Waiting for services to be ready..."
101+
@sleep 15
102+
@echo "4. Running initial tests..."
103+
python test_all_endpoints.py
104+
@echo "βœ… Setup complete! Service is ready to use."
105+
106+
# Quick test
107+
quick-test:
108+
@echo "⚑ Quick API test..."
109+
@curl -s http://localhost:8000/health | jq . && echo "βœ… Health check passed" || echo "❌ Health check failed"
110+
@curl -s http://localhost:8000/health/ready | jq . && echo "βœ… Readiness check passed" || echo "❌ Readiness check failed"
111+
112+
# AI toggle commands
113+
ai-on:
114+
@echo "πŸ€– Enabling AI processing..."
115+
@curl -s -X POST -H "Authorization: Bearer test-token" "http://localhost:8000/api/v1/ai/toggle?enable_ai=true" | jq .
116+
117+
ai-off:
118+
@echo "πŸ”„ Disabling AI processing..."
119+
@curl -s -X POST -H "Authorization: Bearer test-token" "http://localhost:8000/api/v1/ai/toggle?enable_ai=false" | jq .
120+
121+
ai-status:
122+
@echo "πŸ“Š AI Status:"
123+
@curl -s -H "Authorization: Bearer test-token" "http://localhost:8000/api/v1/ai/status" | jq .
124+
125+
# Test AI with custom message
126+
test-ai:
127+
@echo "πŸ§ͺ Testing AI with custom message..."
128+
@curl -s -X POST -H "Authorization: Bearer test-token" "http://localhost:8000/api/v1/ai/test?test_message=Database connection timeout&service_name=test-service" | jq .
129+
130+
# View all logs
131+
logs-all:
132+
@echo "πŸ“‹ Viewing all service logs..."
133+
docker compose logs -f
134+
135+
# Database commands
136+
db-shell:
137+
@echo "πŸ—„οΈ Opening database shell..."
138+
docker compose exec postgres psql -U postgres -d log_analysis_db
139+
140+
db-tables:
141+
@echo "πŸ“Š Database tables:"
142+
docker compose exec postgres psql -U postgres -d log_analysis_db -c "\dt"
143+
144+
# Metrics
145+
metrics:
146+
@echo "πŸ“ˆ Prometheus metrics:"
147+
@curl -s http://localhost:8000/metrics | head -20
148+
149+
# Authentication
150+
get-token:
151+
@echo "πŸ”‘ Generating authentication token..."
152+
@docker compose exec -T log_analysis_service python -c "from app.core.auth_external import create_test_token; print('Token:', create_test_token('test-user', ['admin']))"
153+
154+
get-token-user:
155+
@echo "πŸ”‘ Generating user token..."
156+
@docker compose exec -T log_analysis_service python -c "from app.core.auth_external import create_test_token; print('Token:', create_test_token('user-123', ['user']))"
157+
158+
get-token-admin:
159+
@echo "πŸ”‘ Generating admin token..."
160+
@docker compose exec -T log_analysis_service python -c "from app.core.auth_external import create_test_token; print('Token:', create_test_token('admin-456', ['admin', 'user']))"
161+
162+
# Configuration
163+
get-config:
164+
@echo "βš™οΈ Application Configuration:"
165+
@docker compose exec -T log_analysis_service python -c "from app.core.config import get_settings; s = get_settings(); print(f'Database URL: {s.database_url}'); print(f'RabbitMQ URL: {s.rabbitmq_url}'); print(f'Server: {s.host}:{s.port}')"
166+
167+
# Testing
168+
test-logs:
169+
@echo "πŸ§ͺ Running comprehensive log tests..."
170+
docker compose exec -T log_analysis_service python /app/test_send_log.py --scenario all
171+
172+
test-critical:
173+
@echo "🚨 Testing critical errors..."
174+
docker compose exec -T log_analysis_service python /app/test_send_log.py --scenario critical
175+
176+
test-pattern:
177+
@echo "πŸ’‘ Testing pattern detection..."
178+
docker compose exec -T log_analysis_service python /app/test_send_log.py --scenario pattern
179+
180+
test-anomaly:
181+
@echo "⚠️ Testing anomaly detection..."
182+
docker compose exec -T log_analysis_service python /app/test_send_log.py --scenario anomaly
183+
184+
test-normal:
185+
@echo "βœ… Testing normal logs..."
186+
docker compose exec -T log_analysis_service python /app/test_send_log.py --scenario normal
187+
188+
test-mixed:
189+
@echo "🎯 Testing mixed scenario..."
190+
docker compose exec -T log_analysis_service python /app/test_send_log.py --scenario mixed
191+
192+
# API Testing (requires token)
193+
test-api-status:
194+
@echo "🌐 Testing AI status endpoint..."
195+
@TOKEN=$$(docker compose exec -T log_analysis_service python -c "from app.core.auth_external import create_test_token; print(create_test_token('test-user', ['admin']))"); \
196+
curl -H "Authorization: Bearer $$TOKEN" http://localhost:8000/api/v1/ai/status
39197

40-
docker-build:
41-
docker-compose build
198+
test-api-logs:
199+
@echo "πŸ“‹ Testing logs endpoint..."
200+
@TOKEN=$$(docker compose exec -T log_analysis_service python -c "from app.core.auth_external import create_test_token; print(create_test_token('test-user', ['admin']))"); \
201+
curl -H "Authorization: Bearer $$TOKEN" http://localhost:8000/api/v1/logs
42202

43-
docker-up:
44-
docker-compose up -d
203+
test-api-stats:
204+
@echo "πŸ“Š Testing stats endpoint..."
205+
@TOKEN=$$(docker compose exec -T log_analysis_service python -c "from app.core.auth_external import create_test_token; print(create_test_token('test-user', ['admin']))"); \
206+
curl -H "Authorization: Bearer $$TOKEN" http://localhost:8000/api/v1/stats
45207

46-
docker-down:
47-
docker-compose down
208+
# View results
209+
check-logs-db:
210+
@echo "πŸ“Š Recent logs in database:"
211+
docker compose exec postgres psql -U postgres -d log_analysis_db -c "SELECT id, service_name, log_level, LEFT(message, 50) as message, timestamp FROM log_entries ORDER BY timestamp DESC LIMIT 10;"
48212

49-
migrate:
50-
alembic upgrade head
213+
check-patterns:
214+
@echo "πŸ” Detected patterns:"
215+
docker compose exec postgres psql -U postgres -d log_analysis_db -c "SELECT pattern_id, LEFT(template, 40) as template, occurrence_count, service_name FROM patterns WHERE is_active = true ORDER BY occurrence_count DESC LIMIT 10;"
51216

52-
migrate-create:
53-
@read -p "Enter migration message: " msg; \
54-
alembic revision --autogenerate -m "$$msg"
217+
check-queues:
218+
@echo "πŸ“¬ RabbitMQ queues:"
219+
docker compose exec rabbitmq rabbitmqctl list_queues name messages

0 commit comments

Comments
Β (0)