Hệ thống giám sát dịch vụ suy luận âm thanh trong môi trường sản xuất AcousticSense AI sử dụng Prometheus + Grafana

1. Bối cảnh dự án và yêu cầu giám sát

AcousticSense AI là hệ thống nhận diện thể loại âm nhạc thông minh dựa trên phân tích tín hiệu âm thanh. Hệ thống này chuyển đổi tín hiệu âm thanh thành biểu đồ phổ Mel rồi sử dụng mô hình Vision Transformer để phân loại 16 thể loại âm nhạc. Trong môi trường sản xuất, việc đảm bảo tính ổn định và hiệu suất của hệ thống là rất quan trọng. Khi lượng người dùng tăng lên, chúng tôi cần theo dõi các chỉ số quan trọng sau:
  • Thời gian phản hồi và tốc độ xử lý của dịch vụ suy luận
  • Tỷ lệ sử dụng CPU và GPU
  • Sử dụng bộ nhớ và phát hiện rò rỉ
  • Hiệu suất các giai đoạn xử lý âm thanh
  • Tỷ lệ lỗi và phát hiện bất thường
Giải pháp giám sát truyền thống dựa trên nhật ký không còn đủ hiệu quả. Vì vậy, chúng tôi triển khai bảng điều khiển giám sát dựa trên Prometheus + Grafana.

2. Thiết kế kiến trúc giám sát

2.1 Kiến trúc giám sát tổng thể

Kiến trúc giám sát bao gồm 4 lớp chính:
Dịch vụ suy luận âm thanh → Prometheus thu thập chỉ số → Grafana trực quan hóa → Thông báo cảnh báo
Các thành phần cốt lõi:
  • Prometheus: CSDL thời gian, chịu trách nhiệm thu thập và lưu trữ chỉ số
  • Grafana: Nền tảng trực quan hóa dữ liệu, cung cấp nhiều bảng điều khiển giám sát
  • Node Exporter: Công cụ thu thập chỉ số hệ thống
  • cAdvisor: Công cụ giám sát container
  • Exporter chỉ số tùy chỉnh: Thu thập chỉ số cụ thể cho nghiệp vụ

2.2 Chỉ số giám sát quan trọng

Chúng tôi định nghĩa các loại chỉ số giám sát sau:

Tầng hệ thống:

  • Tỷ lệ sử dụng CPU, bộ nhớ, I/O đĩa, lưu lượng mạng
  • Tỷ lệ sử dụng GPU, bộ nhớ GPU, nhiệt độ

Tầng dịch vụ:

  • Tốc độ xử lý yêu cầu (QPS), thời gian phản hồi (P99, P95, P50)
  • Tỷ lệ lỗi, tỷ lệ timeout, số lần thử lại

Tầng nghiệp vụ:

  • Thời gian xử lý âm thanh, thời gian tạo phổ, thời gian suy luận
  • Phân bố thể loại âm nhạc, thống kê độ tin cậy

3. Cấu hình và triển khai Prometheus

3.1 Cài đặt Prometheus

Lệnh cài đặt Prometheus:
# Tải xuống Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-2.37.0.linux-amd64

# Tạo file cấu hình
cat > prometheus.yml << EOF
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'acousticsense-api'
    static_configs:
      - targets: ['localhost:8000']
    
  - job_name: 'node-exporter'
    static_configs:
      - targets: ['localhost:9100']
    
  - job_name: 'cadvisor'
    static_configs:
      - targets: ['localhost:8080']
    
  - job_name: 'custom-metrics'
    static_configs:
      - targets: ['localhost:9000']
EOF

# Khởi động Prometheus
./prometheus --config.file=prometheus.yml &

3.2 Triển khai exporter chỉ số

Lệnh cài đặt exporter hệ thống:
# Cài đặt Node Exporter (chỉ số hệ thống)
wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz
tar xvfz node_exporter-*.tar.gz
cd node_exporter-1.3.1.linux-amd64
./node_exporter &

# Cài đặt cAdvisor (giám sát container)
docker run \
  --volume=/:/rootfs:ro \
  --volume=/var/run:/var/run:ro \
  --volume=/sys:/sys:ro \
  --volume=/var/lib/docker/:/var/lib/docker:ro \
  --volume=/dev/disk/:/dev/disk:ro \
  --publish=8080:8080 \
  --detach=true \
  --name=cadvisor \
  gcr.io/cadvisor/cadvisor:v0.47.0

4. Giám sát chỉ số nghiệp vụ tùy chỉnh

4.1 Exporter chỉ số dịch vụ âm thanh

Tạo exporter chỉ số cho AcousticSense AI:
# metrics_exporter.py
from prometheus_client import start_http_server, Summary, Counter, Gauge, Histogram
import time
import requests
import psutil
import GPUtil

# Định nghĩa chỉ số giám sát
THOI_GIAN_YEU_CAU = Histogram('thoi_gian_yeu_cau_seconds', 'Thời gian xử lý yêu cầu âm thanh')
SO_LUONG_YEU_CAU = Counter('so_luong_yeu_cau_total', 'Tổng số yêu cầu')
SO_LUONG_LOI = Counter('so_luong_loi_total', 'Số yêu cầu lỗi')
SU_DUNG_GPU = Gauge('su_dung_gpu_percent', 'Tỷ lệ sử dụng GPU')
SU_DUNG_BO_NHO = Gauge('su_dung_bo_nho_mb', 'Sử dụng bộ nhớ (MB)')
THOI_GIAN_XU_LY = Histogram('thoi_gian_xu_ly_seconds', 'Thời gian xử lý các giai đoạn âm thanh', ['giai_doan'])

class AudioMetricsExporter:
    def __init__(self, port=9000):
        self.port = port
    
    def start(self):
        start_http_server(self.port)
        print(f"Exporter chỉ số khởi động trên cổng {self.port}")
        
        # Khởi động thu thập chỉ số hệ thống
        self.collect_system_metrics()
    
    def collect_system_metrics(self):
        while True:
            # Thu thập chỉ số GPU
            gpus = GPUtil.getGPUs()
            if gpus:
                SU_DUNG_GPU.set(gpus[0].load * 100)
            
            # Thu thập chỉ số bộ nhớ
            memory = psutil.virtual_memory()
            SU_DUNG_BO_NHO.set(memory.used / 1024 / 1024)
            
            time.sleep(5)
    
    def record_request(self, duration, success=True):
        THOI_GIAN_YEU_CAU.observe(duration)
        SO_LUONG_YEU_CAU.inc()
        if not success:
            SO_LUONG_LOI.inc()
    
    def record_processing_stage(self, stage, duration):
        THOI_GIAN_XU_LY.labels(giai_doan=stage).observe(duration)

# Tích hợp vào dịch vụ chính
metrics_exporter = AudioMetricsExporter()
metrics_exporter.start()

4.2 Tích hợp vào dịch vụ suy luận âm thanh

Sửa đổi dịch vụ xử lý âm thanh chính để thêm thu thập chỉ số:
# Trong app_gradio.py thêm tích hợp giám sát
import time
from metrics_exporter import metrics_exporter

def analyze_audio(audio_file):
    start_time = time.time()
    
    try:
        # Giai đoạn tải âm thanh
        load_start = time.time()
        audio_data, sr = librosa.load(audio_file)
        metrics_exporter.record_processing_stage('tai_am_thanh', time.time() - load_start)
        
        # Giai đoạn tạo phổ
        spec_start = time.time()
        mel_spectrogram = create_mel_spectrogram(audio_data, sr)
        metrics_exporter.record_processing_stage('tao_pho', time.time() - spec_start)
        
        # Giai đoạn suy luận mô hình
        inference_start = time.time()
        predictions = model.predict(mel_spectrogram)
        metrics_exporter.record_processing_stage('suy_luan_mo_hinh', time.time() - inference_start)
        
        total_time = time.time() - start_time
        metrics_exporter.record_request(total_time, success=True)
        
        return predictions
        
    except Exception as e:
        total_time = time.time() - start_time
        metrics_exporter.record_request(total_time, success=False)
        raise e

5. Cấu hình bảng điều khiển Grafana

5.1 Cài đặt và cấu hình Grafana

Lệnh cài đặt Grafana:
# Cài đặt Grafana
wget https://dl.grafana.com/oss/release/grafana-9.0.0.linux-amd64.tar.gz
tar -zxvf grafana-9.0.0.linux-amd64.tar.gz
cd grafana-9.0.0

# Khởi động Grafana
./bin/grafana-server web &
Truy cập giao diện Grafana (cổng 3000) và cấu hình nguồn dữ liệu Prometheus:
  1. Đăng nhập Grafana (tài khoản mặc định: admin/admin)
  2. Thêm nguồn dữ liệu → Prometheus
  3. Đặt URL: http://localhost:9090
  4. Lưu và kiểm tra kết nối

5.2 Tạo bảng điều khiển giám sát dịch vụ âm thanh

5.2.1 Bảng điều khiển tài nguyên hệ thống

CPU và tỷ lệ sử dụng bộ nhớ:
# Tỷ lệ sử dụng CPU
100 - (avg by(instance)(irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

# Bộ nhớ sử dụng
node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes
Giám sát GPU:
# Tỷ lệ sử dụng GPU
su_dung_gpu_percent

# Bộ nhớ GPU sử dụng
node_memory_GPU_bytes

5.2.2 Bảng điều khiển hiệu suất dịch vụ

Tốc độ xử lý và độ trễ:
# QPS (số yêu cầu/giây)
rate(so_luong_yeu_cau_total[5m])

# Độ trễ P99
histogram_quantile(0.99, rate(thoi_gian_yeu_cau_seconds_bucket[5m]))

# Tỷ lệ lỗi
rate(so_luong_loi_total[5m]) / rate(so_luong_yeu_cau_total[5m])
Thời gian xử lý các giai đoạn âm thanh:
# Thời gian trung bình các giai đoạn
avg by(giai_doan)(rate(thoi_gian_xu_ly_seconds_sum[5m])) / avg by(giai_doan)(rate(thoi_gian_xu_ly_seconds_count[5m]))

5.2.3 Bảng điều khiển chỉ số nghiệp vụ

Phân bố thể loại âm nhạc:
# Thể loại âm nhạc được nhận diện nhiều nhất
topk(5, rate(genre_classification_total[24h]))
Thống kê độ tin cậy:
# Độ tin cậy trung bình
avg(genre_confidence)

# Tỷ lệ yêu cầu độ tin cậy cao
sum(genre_confidence > 0.8) / count(genre_confidence)

6. Cấu hình quy tắc cảnh báo

6.1 Quy tắc cảnh báo Prometheus

Tạo file quy tắc cảnh báo:
# alerts.yml
groups:
- name: acousticsense-alerts
  rules:
  - alert: TỷLệLỗiCao
    expr: rate(so_luong_loi_total[5m]) / rate(so_luong_yeu_cau_total[5m]) > 0.05
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "Cảnh báo tỷ lệ lỗi cao"
      description: "Tỷ lệ lỗi dịch vụ âm thanh vượt quá 5%, giá trị hiện tại là {{ $value }}"
  
  - alert: ĐộTrễCao
    expr: histogram_quantile(0.99, rate(thoi_gian_yeu_cau_seconds_bucket[5m])) > 5
    for: 10m
    labels:
      severity: warning
    annotations:
      summary: "Cảnh báo độ trễ cao"
      description: "Độ trễ P99 vượt quá 5 giây, giá trị hiện tại là {{ $value }}"
  
  - alert: DịchVụNgưngHoạtĐộng
    expr: up{job="acousticsense-api"} == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "Cảnh báo dịch vụ ngưng hoạt động"
      description: "Dịch vụ suy luận âm thanh không khả dụng"
  
  - alert: SửDụngGPUCao
    expr: su_dung_gpu_percent > 90
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "Cảnh báo sử dụng GPU cao"
      description: "Tỷ lệ sử dụng GPU vượt quá 90%, giá trị hiện tại là {{ $value }}%"

6.2 Cấu hình thông báo cảnh báo

Cấu hình kênh thông báo Grafana:
  • Thông báo qua email: Cấu hình SMTP, thiết lập email nhận cảnh báo
  • Tích hợp Slack: Gửi cảnh báo đến kênh Slack
  • Thông báo Webhook: Tích hợp với hệ thống giám sát hiện có
  • PagerDuty: Cấu hình thông báo khẩn cấp

7. Gợi ý triển khai môi trường sản xuất

7.1 Triển khai hệ thống giám sát có tính sẵn sàng cao

Phiên bản docker-compose có tính sẵn sàng cao:
version: '3.8'

services:
  prometheus:
    image: prom/prometheus
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - prom_data:/prometheus
    deploy:
      replicas: 2
  
  grafana:
    image: grafana/grafana
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=securepassword
    volumes:
      - grafana_data:/var/lib/grafana
    depends_on:
      - prometheus
  
  node-exporter:
    image: prom/node-exporter
    ports:
      - "9100:9100"
  
  cadvisor:
    image: gcr.io/cadvisor/cadvisor
    ports:
      - "8080:8080"
    volumes:
      - /:/rootfs:ro
      - /var/run:/var/run:ro
      - /sys:/sys:ro
      - /var/lib/docker/:/var/lib/docker:ro

volumes:
  prom_data:
  grafana_data:

7.2 Chính sách lưu trữ dữ liệu giám sát

Cấu hình chính sách lưu trữ:
# prometheus.yml cấu hình lưu trữ
global:
  scrape_interval: 15s
  evaluation_interval: 15s
  # Giữ lại dữ liệu gốc trong 15 ngày
  retention: 15d

# Cấu hình ghi dữ liệu tới lưu trữ đối tượng
remote_write:
  - url: http://thanos:10908/api/v1/write
    queue_config:
      capacity: 10000
      max_shards: 200
      min_shards: 100

# Cấu hình nén
storage:
  tsdb:
    retention: 15d
    min-block-duration: 2h
    max-block-duration: 24h

Thẻ: prometheus Grafana xử lý âm thanh Giám sát Hệ thống Node Exporter

Đăng vào ngày 17 tháng 7 lúc 06:24