Quay lại danh sách
Tự động hóa kiểm tra sức khỏe proxy với Prometheus và RoProxy

Tự động hóa kiểm tra sức khỏe proxy với Prometheus và RoProxy

18 tháng 8, 2026

Giới thiệu

Khi vận hành một proxy pool quy mô lớn (hàng trăm đến hàng nghìn IP), việc biết được proxy nào vẫn khỏe, proxy nào bị chậm hoặc bị block là yếu tố quyết định thành bại của các tác vụ scraping, test API hay giám sát SEO. Nếu không có cơ chế health-check tự động, bạn sẽ phải thủ công kiểm tra, dẫn đến lãng phí tài nguyên và rủi ro dữ liệu không chính xác.

Bài viết này trình bày quy trình xây dựng một hệ thống health-check tự động sử dụng Prometheus để thu thập metric, Grafana để trực quan hóa và Alertmanager để cảnh báo, đồng thời tận dụng RoProxy API để bật/tắt hoặc xoá proxy không đạt yêu cầu. Toàn bộ quy trình được viết dưới dạng infrastructure-as-code để dễ dàng triển khai trên Kubernetes, Docker Compose hay VM đơn lẻ.

Kiến trúc hệ thống health-check

+----------------+      +----------------+      +----------------+      +----------------+
|  Proxy Exporter| ---> |   Prometheus   | ---> |    Grafana     | ---> |  Alertmanager  |
+----------------+      +----------------+      +----------------+      +----------------+
        |                       ^                        ^                |
        |                       |                        |                |
        v                       |                        |                v
+----------------+      +----------------+      +----------------+  +----------------+
|  RoProxy API   | <--- |  Remediation   | <--- |  Alert Rules   |  |  Notification  |
+----------------+      +----------------+      +----------------+  +----------------+
  • Proxy Exporter: dịch vụ nhẹ (Python/Go) định kỳ gọi endpoint của RoProxy để đo latency, tỷ lệ thành công, mã trạng thái HTTP.
  • Prometheus: scrape metric từ exporter theo chu kỳ cấu hình (mặc định 30s).
  • Grafana: dashboard hiển thị latency trung bình, error rate, số lượng proxy active/inactive.
  • Alertmanager: nhận cảnh báo từ Prometheus, kích hoạt script remediation gọi RoProxy API để disable/remove proxy xấu.

Bước 1: Triển khai Proxy Exporter

Dưới đây là một exporter Python đơn giản sử dụng requestsprometheus_client. Nó đọc danh sách proxy từ RoProxy (hoặc file config), gửi request test đến một target an toàn (ví dụ https://httpbin.org/ip) và xuất metric.

# proxy_exporter.py
import os
import time
import requests
from prometheus_client import start_http_server, Gauge, CollectorRegistry

ROPROXY_API = os.getenv("ROPROXY_API", "https://api.roproxy.com/v1/proxies")
API_KEY = os.getenv("ROPROXY_API_KEY")
TARGET_URL = os.getenv("TARGET_URL", "https://httpbin.org/ip")
SCRAPE_INTERVAL = int(os.getenv("SCRAPE_INTERVAL", "30"))

registry = CollectorRegistry()
latency = Gauge('proxy_latency_seconds', 'Latency of proxy request', ['proxy_id', 'proxy_ip'], registry=registry)
success = Gauge('proxy_success', '1 if request succeeded else 0', ['proxy_id', 'proxy_ip'], registry=registry)

def fetch_proxies():
    headers = {"Authorization": f"Bearer {API_KEY}"}
    resp = requests.get(ROPROXY_API, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()  # list of {id, ip, port, type}

def check_proxy(proxy):
    proxy_url = f"http://{proxy['ip']}:{proxy['port']}"
    proxies = {"http": proxy_url, "https": proxy_url}
    start = time.time()
    try:
        r = requests.get(TARGET_URL, proxies=proxies, timeout=10)
        elapsed = time.time() - start
        ok = 1 if r.status_code == 200 else 0
    except Exception:
        elapsed = time.time() - start
        ok = 0
    latency.labels(proxy_id=proxy['id'], proxy_ip=proxy['ip']).set(elapsed)
    success.labels(proxy_id=proxy['id'], proxy_ip=proxy['ip']).set(ok)

def main():
    start_http_server(9100, registry=registry)
    while True:
        proxies = fetch_proxies()
        for p in proxies:
            check_proxy(p)
        time.sleep(SCRAPE_INTERVAL)

if __name__ == "__main__":
    main()

Giải thích nhanh:

  • Exporter expose metric trên cổng 9100 (/metrics).
  • Biến môi trường giúp cấu hình linh hoạt cho các môi trường dev/staging/prod.
  • Có thể đóng gói thành Docker image và chạy như sidecar hoặc deployment riêng.

Bước 2: Cấu hình Prometheus scrape

Thêm job scrape vào prometheus.yml:

scrape_configs:
  - job_name: 'proxy-exporter'
    static_configs:
      - targets: ['proxy-exporter:9100']
    metrics_path: /metrics
    scrape_interval: 30s

Nếu exporter chạy trên nhiều replica, hãy dùng service discovery (Consul, Kubernetes SD) để tự động phát hiện target.

Bước 3: Tạo dashboard Grafana

  1. Tạo dashboard mới → Add panel.
  2. Chọn metric proxy_latency_secondsLegend {{proxy_ip}}Visualization Time series.
  3. Thêm panel thứ hai cho proxy_successStat hiển thị tỷ lệ thành công trung bình.
  4. Panel bảng (Table) liệt kê proxy có proxy_success == 0 trong 5 phút gần nhất.

Để tái sử dụng, xuất dashboard thành JSON và commit vào repo. Ví dụ snippet panel latency:

{
  "title": "Proxy Latency (seconds)",
  "type": "graph",
  "targets": [
    {
      "expr": "proxy_latency_seconds",
      "legendFormat": "{{proxy_ip}}",
      "refId": "A"
    }
  ],
  "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 }
}

Bước 4: Cảnh báo tự động với Alertmanager

Tạo file alert.rules.yml cho Prometheus:

groups:
- name: proxy-health
  rules:
  - alert: ProxyHighLatency
    expr: proxy_latency_seconds > 5
    for: 2m
    labels:
      severity: warning
    annotations:
      summary: "Proxy {{ $labels.proxy_ip }} latency > 5s"
      description: "Latency đã vượt ngưỡng 5 giây trong 2 phút liên tiếp."
  - alert: ProxyHighErrorRate
    expr: avg_over_time(proxy_success[5m]) < 0.8
    for: 3m
    labels:
      severity: critical
    annotations:
      summary: "Proxy {{ $labels.proxy_ip }} error rate > 20%"
      description: "Tỷ lệ thành công dưới 80% trong 5 phút."

Cấu hình Alertmanager để gửi webhook đến script remediation:

route:
  receiver: 'remediation-webhook'
receivers:
- name: 'remediation-webhook'
  webhook_configs:
  - url: 'http://remediation-service:8080/alert'

Bước 5: Tích hợp tự động loại bỏ proxy xấu (Remediation)

Service remediation nhận payload từ Alertmanager, trích xuất proxy_ip và gọi RoProxy API để disable hoặc delete proxy.

# remediation.py (Flask)
from flask import Flask, request, jsonify
import os
import requests

app = Flask(__name__)
ROPROXY_API = os.getenv("ROPROXY_API", "https://api.roproxy.com/v1/proxies")
API_KEY = os.getenv("ROPROXY_API_KEY")
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

@app.route('/alert', methods=['POST'])
def alert():
    data = request.json
    for alert in data.get('alerts', []):
        labels = alert.get('labels', {})
        proxy_ip = labels.get('proxy_ip')
        if not proxy_ip:
            continue
        # Tìm proxy_id từ IP (có thể cache mapping)
        proxy_id = get_proxy_id_by_ip(proxy_ip)
        if proxy_id:
            # Disable proxy thay vì xóa để có thể bật lại sau
            requests.patch(f"{ROPROXY_API}/{proxy_id}", headers=HEADERS, json={"status": "disabled"})
    return jsonify({"status": "ok"})

def get_proxy_id_by_ip(ip):
    # Giả sử có endpoint list proxies, thực tế nên cache Redis
    resp = requests.get(ROPROXY_API, headers=HEADERS)
    for p in resp.json():
        if p['ip'] == ip:
            return p['id']
    return None

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

Triển khai remediation cùng namespace với Alertmanager, đảm bảo network policy cho phép inbound từ Alertmanager.

Ví dụ thực tế: Giám sát pool 500 IP

  1. Khởi tạo: Tạo 500 proxy residential qua RoProxy dashboard, ghi nhận ID/IP.
  2. Deploy exporter với SCRAPE_INTERVAL=30 → Prometheus thu thập ~10k metric/phút.
  3. Dashboard hiển thị latency trung bình 1.2s, success rate 96%.
  4. Cảnh báo kích hoạt khi 3 proxy latency >5s → remediation disable 3 IP.
  5. Kết quả: Sau 24h, pool ổn định ở 497 active proxy, không còn request thất bại do proxy chết.

Mẹo tối ưu hoá

  • Sampling interval: 30s đủ cho hầu hết use-case; giảm xuống 10s nếu cần phát hiện nhanh nhưng tăng load Prometheus.
  • Label enrichment: Thêm label region, type (residential/datacenter) tại exporter để lọc dashboard theo khu vực.
  • Retention: Cấu hình Prometheus --storage.tsdb.retention.time=30d để giữ lịch sử phân tích xu hướng.
  • Cache mapping IP→ID: Dùng Redis TTL 1h để tránh gọi RoProxy API lặp lại trong remediation.
  • Canary test: Trước khi disable vĩnh viễn, chạy 3 request test thêm để tránh false positive do network blip.

Kết luận

Việc tự động hóa health-check proxy không chỉ giúp duy trì chất lượng pool mà còn giảm thiểu can thiệp thủ công, cho phép team tập trung vào logic scraping hay test chính. Kết hợp Prometheus, Grafana, AlertmanagerRoProxy API tạo thành một vòng lặp quan sát – cảnh báo – khắc phục hoàn toàn tự động, có thể mở rộng cho hàng chục nghìn IP. Hãy bắt đầu với exporter nhỏ, sau đó mở rộng dashboard và alert rule phù hợp với SLA của dự án bạn.


Lưu ý: Các đoạn code trên là minh hoạ cốt lõi; khi đưa vào production hãy thêm logging, retry, circuit-breaker và bảo mật API key (Vault/SealedSecrets).