본문 바로가기
IT & Tech 정보

AI/ML 기반 AIOps 파이프라인 구축

by 지식과 지혜의 나무 2025. 5. 29.
반응형


Elastic ML 이상 탐지 → Prometheus Alertmanager → Kubernetes 자동 복구 & GitOps 기록화

이 글에서는 로그·메트릭 데이터를 실시간으로 학습·분석해 이상 징후를 포착하고, 감지 즉시 **자가 치유(healing loop)**를 돌아 장애를 자동 복구하며, 모든 복구 이력을 GitOps 방식으로 기록·추적하는 AIOps 파이프라인을 단계별로 살펴봅니다.



1. 전체 아키텍처

┌───────────────────────┐
│  Application / K8s    │
│ ┌───────────────────┐ │
│ │  Metricbeat,      │ │
│ │  Filebeat         │ │
│ └───────────────────┘ │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│  Elasticsearch +      │
│   Elastic ML Jobs     │  ← 이상치(anomaly) 모델 학습 및 예측
└──────────┬────────────┘
           │ anomaly_score
           ▼
┌───────────────────────┐    scrape    ┌───────────────────────────┐
│  Elastic Exporter     │─────────────▶│    Prometheus Server      │
└──────────┬────────────┘              └───────────────────────────┘
           │ custom metrics                        │
           ▼                                       ▼
┌───────────────────────┐                   ┌────────────────────────┐
│ Alertmanager (Webhook)│◀──────────────────│  Prometheus Rule       │
└──────────┬────────────┘                   └────────────────────────┘
           │ Webhook                          │ CR 생성
           ▼                                  ▼
┌───────────────────────┐                   ┌─────────────────────────┐
│ Custom Remediation    │                   │  GitHub Actions / CLI   │
│   Operator (K8s)      │                   │  (GitOps 커밋 자동화)    │
└──────────┬───────┬────┘                   └─────────────────────────┘
           │       │                          
    rollout restart  │                          
           │       ▼                          
           ▼    ┌────────────────────────┐    
┌──────────────────│  Kubernetes Cluster   │    
│  Git 커밋:       │  (자가 Healing Loop)  │    
│  auto-remediate  └────────────────────────┘    
└──────────────────▶ Argo CD Sync & Self-Heal │    
                     (변경 기록·검증)         │    
                     └────────────────────────┘    




2. Elastic ML 이상 탐지 설정
1. Metricbeat/Filebeat
• 애플리케이션 로그·메트릭을 Elasticsearch 인덱스(metrics-*, logs-*)로 전송
2. Elastic ML Job

POST _ml/anomaly_detectors/webapp_response_time_job
{
  "description": "WebApp resp_time anomaly detection",
  "analysis_config": {
    "bucket_span": "1m",
    "detectors": [
      { "function": "high_mean", "field_name": "response_time" }
    ]
  },
  "data_description": { "time_field": "@timestamp" }
}

• 1분 단위(bucket_span)로 평균 응답 시간 이상치 탐지
• 학습 완료 후, job_id로 실시간 점수 조회

3. 실시간 예측

GET _ml/anomaly_detectors/webapp_response_time_job/results/latest

• 반환된 anomaly_score를 외부 시스템(Elastic Exporter)으로 전송



3. Elastic Exporter → Prometheus
1. Elastic Exporter 설정 (elastic-exporter.yaml)

scrape_configs:
  - job_name: 'elastic_ml'
    metrics_path: /metrics
    static_configs:
      - targets: ['elastic-exporter:9111']


2. Exporter 내부 로직 (Go/Python)
• Elastic ML API 호출 → latest 점수 취득
• Prometheus 형식으로 노출

# HELP elastic_anomaly_score latest anomaly score from Elastic ML
# TYPE elastic_anomaly_score gauge
elastic_anomaly_score{job="webapp"} 85.3





4. Prometheus 알림 룰

groups:
- name: webapp-anomaly
  rules:
  - alert: WebAppHighAnomalyScore
    expr: max_over_time(elastic_anomaly_score{job="webapp"}[5m]) > 80
    for: 2m
    labels:
      severity: critical
    annotations:
      summary: "WebApp 응답 이상치 감지"
      description: "5분간 anomaly_score > 80 ({{ $value }})"




5. Alertmanager Webhook → Custom CRD
1. Alertmanager 설정

receivers:
  - name: 'k8s-remediation'
    webhook_configs:
      - url: 'http://remediator-svc.default.svc.cluster.local/remediate'
route:
  receiver: 'k8s-remediation'
  group_wait: 10s
  group_interval: 1m
  repeat_interval: 1h


2. RemediationRequest CRD

apiVersion: remediation.example.com/v1alpha1
kind: RemediationRequest
metadata:
  generateName: rr-webapp-
spec:
  target:
    kind: Deployment
    name: webapp
  action: restart
  reason: "High anomaly score detected"


3. Webhook 핸들러 (Python Flask 예)

@app.route('/remediate', methods=['POST'])
def remediate():
    alert = request.json['alerts'][0]
    rr = {
        "apiVersion": "remediation.example.com/v1alpha1",
        "kind": "RemediationRequest",
        "metadata": {"generateName": "rr-webapp-"},
        "spec": {"target": {"kind": "Deployment", "name": "webapp"}, "action": "restart"}
    }
    k8s_api.create_namespaced_custom_object(
        group="remediation.example.com", version="v1alpha1",
        namespace="default", plural="remediationrequests", body=rr)
    return '', 200





6. Operator를 통한 자동 복구
1. Operator 로직 (Go, Kubebuilder)
• RemediationRequest 수신 시 spec.action에 따라 복구 실행

if req.Spec.Action == "restart" {
    client.AppsV1().Deployments(ns).Restart(ctx, name, metav1.RestartOptions{})
}

• 실행 후 CR 상태(status.phase)를 Succeeded 또는 Failed로 업데이트

2. 롤링 재시작 명령

kubectl rollout restart deployment/webapp -n default





7. GitOps 기록화 & Argo CD
1. GitHub Actions 워크플로우 (.github/workflows/record-remediation.yml)

on:
  repository_dispatch:
    types: [remediation-requested]
jobs:
  record:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: |
          git config user.name "a10ps-bot"
          git config user.email "bot@example.com"
          timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
          echo "- action: restart\n  target: webapp\n  at: ${timestamp}" >> remediation-log.yaml
          git add remediation-log.yaml
          git commit -m "auto-remediate: restart webapp at ${timestamp}"
          git push

• Operator가 Kubernetes 이벤트 발생 시 repository_dispatch 호출

2. Argo CD

spec:
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
  syncOptions:
    - Validate=true

• Git 커밋마다 클러스터 상태와 Git 상태를 동기화·검증



8. 결과 및 확장 포인트
• 실시간 이상 탐지: Elastic ML이 알려지지 않은 이슈까지 자동 학습·발견
• 무인 자가 치유: 평균 1–2분 내에 장애 자동 복구
• 투명한 운영 이력: 모든 복구가 Git 히스토리에 기록되어 추적·감사 용이
• SRE 생산성 극대화: 반복적 모니터링·긴급 대응에서 해방

확장
• Istio Envoy 메트릭·분산 추적 연동
• 자동 백포트 패치 → Operator가 kubectl rollout restart 대신 helm upgrade 실행
• Event-driven serverless[AWS Lambda, Knative] 트리거 추가
• Slack/PagerDuty 수동 승인 옵션



“AI가 시스템을 스스로 학습·판단하고, 코드로 기록하며, 스스로 치유하는 AIOps.”
이 파이프라인은 무중단 서비스 안정성과 개발 생산성을 동시에 달성하는 차세대 SRE 운영 모델입니다.

반응형