Skip to content

GatsLee/aiops

Repository files navigation

AIOps Agent

ML+LLM 2계층 홈서버 이상 탐지 에이전트. Isolation Forest(다변량)와 EWMA(단변량)를 결합한 하이브리드 이상 탐지 + 로컬 LLM 근본 원인 분석 + Telegram 알림.

아키텍처

flowchart LR
    subgraph 수집["1. 수집 (1분)"]
        N[Nginx 로그] --> I[MetricsIngester]
        P[Prometheus] --> I
        D[Docker API] --> I
    end

    subgraph 탐지["2. 탐지 (5분)"]
        I --> |11개 feature| EWMA[EWMA 단변량]
        I --> |11개 feature| IF[Isolation Forest 다변량]
        EWMA --> H{하이브리드 판정}
        IF --> H
    end

    subgraph 분석["3. 분석"]
        H --> |CRITICAL/WARNING| LLM[Ollama LLM]
        LLM --> |root_cause JSON| DB[(SQLite)]
    end

    subgraph 알림["4. 알림"]
        H --> |CRITICAL 즉시| TG[Telegram]
        H --> |WARNING 15분 배치| TG
        H --> |매일 9시| TG
    end

    H --> |이벤트| Redis[Redis Streams]
Loading

디렉터리 구조

01-aiops/
├── src/                # FastAPI 앱, 설정, DB, LLM, 이벤트 버스
│   └── agents/         # 수집 · 탐지 · 분석 · 알림 에이전트
├── prompts/            # LLM 프롬프트 템플릿
├── data/models/        # 학습된 IF 모델 + EWMA 상태
├── tests/              # 단위 테스트
└── docs/               # ML/AI 알고리즘 심층 문서

Feature Vector (11차원)

Feature 소스 설명
request_rate Nginx 로그 초당 요청 수
error_rate_4xx Nginx 로그 4xx 에러 비율
error_rate_5xx Nginx 로그 5xx 에러 비율
unique_ips_per_min Nginx 로그 분당 고유 클라이언트 IP 수
avg_response_size Nginx 로그 평균 응답 크기 (bytes)
cpu_percent Prometheus 호스트 CPU 사용률
memory_percent Prometheus 호스트 메모리 사용률
disk_io Prometheus 디스크 I/O 사용률
network_rx Prometheus 네트워크 수신 bytes/sec
network_tx Prometheus 네트워크 송신 bytes/sec
container_count_unhealthy Docker API 비정상 컨테이너 수

탐지 알고리즘

EWMA (단변량): feature별 이동평균/분산을 추적하고, 현재 값이 3σ를 초과하면 이상으로 판정. 학습 불필요, 즉시 배포 가능.

Isolation Forest (다변량): 11개 feature를 동시에 고려하는 앙상블 모델. 7일치 데이터로 매주 재학습. contamination=5%로 임계값 자동 캘리브레이션.

하이브리드 판정:

조건 판정
IF가 CRITICAL CRITICAL
IF가 WARNING 또는 EWMA 이상 2개 이상 WARNING
EWMA 이상 1개만 로그만 (저장 안 함)
없음 정상

자세한 알고리즘 설명은 docs/ 참조.

스케줄

작업 주기 설명
collect_metrics 1분 메트릭 수집 → SQLite 저장
detect_anomalies 5분 이상 탐지 → 알림
flush_warnings 15분 WARNING 배치 알림 전송
retrain_model 일요일 03:00 IF 모델 7일치 데이터로 재학습
daily_summary 매일 09:00 KST 일간 요약 Telegram 전송
health_ping 5분 Redis health 이벤트 발행

API 엔드포인트

경로 메서드 설명
/health GET 상태 확인 (uptime, model_loaded)
/status GET 전체 에이전트 상태
/metrics GET Prometheus 스크랩 엔드포인트
/run POST 즉시 수집 + 탐지 실행
/anomalies GET 이상 목록 조회 (?hours=24)
/anomalies/{id}/acknowledge POST 이상 확인 처리
/train POST 모델 수동 재학습

설정 (.env)

# LLM
AGENT_OLLAMA_BASE_URL=http://host.docker.internal:11434
AGENT_OLLAMA_MODEL=qwen2.5:7b

# Telegram
AGENT_TELEGRAM_BOT_TOKEN=your-bot-token
AGENT_TELEGRAM_CHAT_ID=your-chat-id

# ML 임계값
AGENT_ANOMALY_CONTAMINATION=0.05      # IF 오염 비율
AGENT_EWMA_LAMBDA=0.2                 # EWMA 평활 계수
AGENT_EWMA_SIGMA=3.0                  # 이상 판정 σ 배수

# 스케줄
AGENT_COLLECT_INTERVAL_MINUTES=1
AGENT_DETECT_INTERVAL_MINUTES=5

전체 설정은 .env.example 참조.

실행

docker compose up -d

로그 확인:

docker compose logs -f aiops

수동 탐지 실행:

curl -X POST http://localhost:8100/run

기술 스택

영역 기술
ML scikit-learn (Isolation Forest), numpy, pandas
LLM Ollama (qwen2.5:7b)
API FastAPI + uvicorn
DB SQLite (aiosqlite)
스케줄링 APScheduler
이벤트 버스 Redis Streams
알림 python-telegram-bot
모니터링 prometheus-client
로깅 structlog

About

ML+LLM home server anomaly detection agent — IsolationForest + EWMA + Ollama

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors