본문으로 건너뛰기

Alertmanager Webhook API

개요

Alertmanager Webhook API는 Prometheus Alertmanager에서 발생한 알람을 Webhook 형식으로 수신하여 Caffeine의 Alert 시스템으로 변환합니다.

기본 정보

항목
기본 경로/api/v1.0/alertmanager
인증불필요
버전v1.0

엔드포인트 요약

메서드경로설명
POST/api/v1.0/alertmanager/webhookAlertmanager Webhook 수신
GET/api/v1.0/alertmanager/healthHealth Check

상세 엔드포인트

POST /api/v1.0/alertmanager/webhook

Prometheus Alertmanager에서 전송된 Webhook Payload를 수신하여 Caffeine Alert 시스템으로 발행합니다.

요청 본문 (Prometheus Alertmanager Webhook 형식)

{
"version": "4",
"groupKey": "{}/{}:{alertname=\"HighMemoryUsage\"}",
"status": "firing",
"receiver": "caffeine-webhook",
"groupLabels": {
"alertname": "HighMemoryUsage"
},
"commonLabels": {
"alertname": "HighMemoryUsage",
"severity": "warning",
"instance": "localhost:9090"
},
"commonAnnotations": {
"description": "Memory usage is above 80%",
"summary": "High memory usage detected"
},
"externalURL": "http://localhost:9093",
"alerts": [
{
"status": "firing",
"labels": {
"alertname": "HighMemoryUsage",
"instance": "localhost:9090",
"job": "node-exporter",
"severity": "warning"
},
"annotations": {
"description": "Memory usage is above 80%",
"summary": "High memory usage detected"
},
"startsAt": "2026-02-09T10:30:00Z",
"endsAt": "0001-01-01T00:00:00Z",
"generatorURL": "http://localhost:9090/graph?g0.expr=..."
}
]
}

응답 (성공)

{
"success": true,
"processedCount": 1,
"failedCount": 0,
"message": "Processed 1/1 alerts"
}

응답 (부분 실패)

{
"success": true,
"processedCount": 2,
"failedCount": 1,
"message": "Processed 2/3 alerts"
}

응답 코드

코드설명
200Webhook 수신 성공 (부분 실패 포함)
400잘못된 Payload (Alert 목록 비어있음)
500서버 내부 오류

GET /api/v1.0/alertmanager/health

Alertmanager Webhook 엔드포인트의 Health Check를 수행합니다.

요청

파라미터 없음

응답

{
"status": "healthy",
"endpoint": "alertmanager webhook"
}

응답 코드

코드설명
200정상

DTO 정의

WebhookResponse

속성타입설명
successbool전체 처리 성공 여부
processedCountint성공적으로 처리된 Alert 개수
failedCountint처리 실패한 Alert 개수
messagestring처리 결과 메시지

PrometheusWebhookPayload

속성타입설명
versionstringAlertmanager Webhook 버전
statusstring전체 상태 (firing, resolved)
receiverstringWebhook 수신자 이름
alertsList<PrometheusAlert>Alert 목록

PrometheusAlert

속성타입설명
statusstringAlert 상태 (firing, resolved)
labelsDictionary<string, string>Alert 라벨
annotationsDictionary<string, string>Alert 주석
startsAtDateTime시작 시간 (UTC)
endsAtDateTime?종료 시간 (UTC, resolved 시에만)

Prometheus Alertmanager 설정

Caffeine Webhook 엔드포인트를 Alertmanager에 등록하려면 alertmanager.yml에 다음 설정을 추가하세요.

route:
receiver: 'caffeine-webhook'
group_wait: 10s
group_interval: 10s
repeat_interval: 1h

receivers:
- name: 'caffeine-webhook'
webhook_configs:
- url: 'https://caffeine.example.com/api/v1.0/alertmanager/webhook'
send_resolved: true
http_config:
follow_redirects: true

Severity 매핑

Prometheus Alert의 severity 라벨이 Caffeine의 AlertSeverity로 매핑됩니다:

Prometheus SeverityCaffeine AlertSeverity
criticalCritical
warningWarning
info, page, 기타Info

라벨에 severity가 없으면 기본값 Info가 사용됩니다.

사용 예제

Prometheus Alert Rule 정의

# prometheus/rules.yml
groups:
- name: caffeine-alerts
interval: 30s
rules:
- alert: HighMemoryUsage
expr: (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes > 0.8
for: 5m
labels:
severity: warning
service: caffeine-engine
annotations:
summary: "High memory usage detected"
description: "Memory usage is above 80% for more than 5 minutes"

- alert: DiskSpaceLow
expr: node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} < 0.1
for: 5m
labels:
severity: critical
service: caffeine-engine
annotations:
summary: "Disk space is critically low"
description: "Less than 10% disk space remaining"

C# (HttpClient로 수동 Webhook 전송)

using System.Net.Http.Json;

var client = new HttpClient { BaseAddress = new Uri("https://localhost:5001") };

// Prometheus Webhook 형식으로 수동 전송 (테스트용)
var payload = new
{
version = "4",
status = "firing",
receiver = "caffeine-webhook",
alerts = new[]
{
new
{
status = "firing",
labels = new Dictionary<string, string>
{
{ "alertname", "TestAlert" },
{ "severity", "warning" },
{ "instance", "localhost:9090" }
},
annotations = new Dictionary<string, string>
{
{ "summary", "Test alert from C# client" },
{ "description", "This is a test alert" }
},
startsAt = DateTime.UtcNow,
endsAt = DateTime.MinValue
}
}
};

var response = await client.PostAsJsonAsync("/api/v1.0/alertmanager/webhook", payload);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<WebhookResponse>();
Console.WriteLine($"Processed: {result.ProcessedCount}, Failed: {result.FailedCount}");
}

curl

# Health Check
curl -X GET "https://localhost:5001/api/v1.0/alertmanager/health"

# Webhook 전송 (테스트)
curl -X POST "https://localhost:5001/api/v1.0/alertmanager/webhook" \
-H "Content-Type: application/json" \
-d '{
"version": "4",
"status": "firing",
"receiver": "caffeine-webhook",
"alerts": [
{
"status": "firing",
"labels": {
"alertname": "TestAlert",
"severity": "warning"
},
"annotations": {
"summary": "Test alert"
},
"startsAt": "2026-02-09T10:30:00Z"
}
]
}'

Alert 처리 흐름

로그 출력

Webhook 수신 시 다음과 같은 로그가 출력됩니다:

[Information] Alertmanager Webhook 수신: 3개 알람 (Status: firing, Receiver: caffeine-webhook)
[Information] Prometheus 알람 발행 성공: HighMemoryUsage (Severity: Warning)
[Warning] Prometheus 알람 발행 실패: FailedAlert
[Error] Prometheus 알람 처리 중 오류: ErrorAlert

주의사항

  • Alertmanager의 send_resolved: true 설정을 활성화하면 Alert가 해결되었을 때도 Webhook이 전송됩니다.
  • startsAtendsAt는 UTC 시간대로 전달됩니다.
  • Caffeine은 개별 Alert 처리 실패 시에도 전체 Webhook 요청은 200 OK를 반환합니다 (부분 실패 허용).
  • Alert 목록이 비어있으면 400 Bad Request가 반환됩니다.

보안 고려사항

프로덕션 환경에서는 다음 보안 조치를 권장합니다:

  1. HTTPS 사용: Webhook URL에 HTTPS 적용
  2. API Gateway 인증: Alertmanager → Caffeine 사이에 API Gateway를 두고 인증 토큰 검증
  3. 방화벽 규칙: Alertmanager IP만 Webhook 엔드포인트 접근 허용
# alertmanager.yml (인증 토큰 추가)
receivers:
- name: 'caffeine-webhook'
webhook_configs:
- url: 'https://caffeine.example.com/api/v1.0/alertmanager/webhook'
http_config:
bearer_token: 'YOUR_SECRET_TOKEN'

관련 API

참고 자료