Triển khai Prometheus và Grafana vào Kubernetes Cluster
Chúng ta cần triển khai Prometheus để thu thập metrics từ OpenFaaS, Kubernetes Nodes và các Pod, sau đó dùng Grafana để trực quan hóa dữ liệu này. Sử dụng Helm là cách nhanh nhất và chuẩn nhất để deploy các component này.
Tại sao: Prometheus là tiêu chuẩn de facto cho monitoring trong Kubernetes, hỗ trợ native integration với OpenFaaS. Grafana cung cấp dashboard linh hoạt để xem biểu đồ.
Kết quả mong đợi: Pod Prometheus và Grafana chạy trạng thái Running, cổng 9090 và 3000 mở, dữ liệu metrics bắt đầu được thu thập.
Bước 1: Cài đặt Prometheus qua Helm chart.
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm install prometheus prometheus-community/kube-prometheus-stack -n monitoring --create-namespace
Command này tạo namespace monitoring, cài đặt Prometheus, Alertmanager và Grafana từ chart chính thức.
Bước 2: Cấu hình để Prometheus thu thập metrics từ OpenFaaS Gateway.
Chúng ta cần thêm config file để Prometheus biết scrape endpoint của OpenFaaS Gateway.
cat
Config này chỉ định Prometheus scrape port 8080 của OpenFaaS Gateway. Lưu ý service name phải khớp với deployment thực tế của bạn.
Bước 3: Khởi động lại Prometheus để load config mới.
kubectl rollout restart deployment prometheus-kube-prometheus-prometheus -n monitoring
Restart deployment để Prometheus đọc lại ConfigMap và bắt đầu thu thập metrics từ OpenFaaS.
Verify: Kiểm tra target trong Prometheus UI.
kubectl port-forward svc/prometheus-kube-prometheus-prometheus -n monitoring 9090:9090
Mở trình duyệt truy cập http://localhost:9090/targets. Bạn phải thấy job "openfaas-gateway" có trạng thái "UP".
Cấu hình OpenFaaS và Cloudflare để xuất logs sang ELK Stack
Để tập trung logs, chúng ta sẽ đẩy logs từ OpenFaaS (Kubernetes) và Cloudflare Workers về một ELK Stack (Elasticsearch, Logstash, Kibana) đã chạy sẵn hoặc triển khai mới.
Tại sao: Logs rời rạc khó debug. ELK Stack cho phép tìm kiếm, lọc và phân tích logs theo thời gian thực trên toàn hệ thống hybrid.
Kết quả mong đợi: Logs từ OpenFaaS functions và Cloudflare Workers xuất hiện trong Kibana với timestamp và trace ID nhất quán.
Bước 1: Triển khai ELK Stack vào Kubernetes (sử dụng Helm cho Elasticsearch và Kibana).
helm repo add elastic https://helm.elastic.co
helm install elasticsearch elastic/elasticsearch -n logging --create-namespace --set replicas=1 --set volumeClaimTemplate.storageClassName=standard
helm install kibana elastic/kibana -n logging --set elasticsearchHosts=http://elasticsearch-master.logging:9200
Deploy 1 node Elasticsearch và 1 Kibana. Đảm bảo cluster có đủ tài nguyên storage.
Bước 2: Cấu hình Fluentd (hoặc Fluent Bit) để ship logs từ OpenFaaS sang Elasticsearch.
OpenFaaS chạy trên K8s, logs nằm trong stdout. Chúng ta dùng Fluent Bit để gather và ship.
cat
Config này đọc logs container, enrich với metadata Kubernetes (namespace, pod name), và đẩy vào Elasticsearch.
Bước 3: Deploy Fluent Bit DaemonSet.
helm install fluent-bit fluent/fluent-bit -n logging --set extraVolumes[0].name=fluentbit-config --set extraVolumes[0].configMap.name=fluentbit-config --set extraVolumeMounts[0].name=fluentbit-config --set extraVolumeMounts[0].mountPath=/fluentbit/etc/config --set configMap.enabled=false
Deploy Fluent Bit với config custom ở trên. Lưu ý thay bằng password thực tế của user elastic.
Bước 4: Cấu hình Cloudflare Workers để ship logs.
Cloudflare Workers không có stdout log như K8s. Chúng ta dùng Logpush API để đẩy logs về một endpoint (webhook) hoặc trực tiếp vào S3/GCS, sau đó dùng Logstash để parse vào ELK. Ở đây giả sử ta dùng webhook đến Logstash running trong K8s.
curl -X PUT "https://api.cloudflare.com/client/v4/zones//logpush/jobs" \
-H "Authorization: Bearer " \
-H "Content-Type: application/json" \
--data '{"enabled":true,"destination_conf":"https://logstash.logging:9600","logpull_options":"fields=EdgeRequest.ID,EdgeRequest.Source,EdgeRequest.Method,EdgeRequest.Duration,EdgeRequest.Status,EdgeRequest.Request.Headers","sampling":1.0,"name":"workers-to-elk"}'
Command này tạo một Logpush job trên Cloudflare Dashboard để gửi logs về Logstash endpoint.
Bước 5: Cấu hình Logstash pipeline để nhận logs từ Cloudflare và viết vào Elasticsearch.
cat "/"
}
}
filter {
if [EdgeRequest] {
mutate {
add_field => { "source" => "cloudflare-worker" }
}
json {
source => "message"
target => "cf_data"
}
}
}
output {
elasticsearch {
hosts => ["http://elasticsearch-master.logging:9200"]
user => "elastic"
password => ""
index => "cloudflare-logs-%{+YYYY.MM.dd}"
}
}
EOF
Pipeline này nhận JSON từ Cloudflare, thêm field source, và viết vào index riêng.
Bước 6: Deploy Logstash.
helm install logstash elastic/logstash -n logging --set elasticsearchHosts=http://elasticsearch-master.logging:9200 --set configmap.enabled=true --set configmap.name=logstash-pipeline --set httpPort=9600
Deploy Logstash để xử lý logs từ Cloudflare.
Verify: Truy cập Kibana.
kubectl port-forward svc/kibana-kibana -n logging 5601:5601
Mở http://localhost:5601, vào Discovery tab, tìm index pattern "openfaas-logs" và "cloudflare-logs". Bạn sẽ thấy logs từ cả hai nguồn.
Thiết lập Distributed Tracing (Jaeger) để theo dõi request xuyên hệ thống
Để debug request đi từ Client -> Cloudflare Worker -> OpenFaaS Gateway -> Function, chúng ta cần Distributed Tracing. Jaeger là công cụ open-source phù hợp nhất cho môi trường Kubernetes và Edge.
Tại sao: Logs chỉ cho biết "gì xảy ra", Trace cho biết "tại sao và như thế nào" thông qua luồng thực thi. Quan trọng trong môi trường hybrid nơi latency phát sinh ở nhiều điểm.
Kết quả mong đợi: Một trace ID duy nhất đi xuyên suốt Cloudflare Worker và OpenFaaS Function, hiển thị timeline chi tiết trong Jaeger UI.
Bước 1: Triển khai Jaeger vào Kubernetes.
helm repo add jaegertracing https://jaegertracing.github.io/helm-charts
helm install jaeger jaegertracing/jaeger -n tracing --create-namespace
Deploy Jaeger Collector, Agent và Query UI.
Bước 2: Cấu hình OpenFaaS để inject Trace ID.
OpenFaaS Gateway cần được cấu hình để tạo và truyền Trace Context. Chúng ta chỉnh sửa deployment của OpenFaaS Gateway để thêm env variables và sidecar (hoặc proxy) hỗ trợ OpenTelemetry.
cat
Config này chứa endpoint của Jaeger Collector trong cluster.
Bước 3: Cập nhật OpenFaaS Gateway deployment để sử dụng config trên.
Giả sử bạn đang dùng Helm cho OpenFaaS, ta dùng --set để inject env variables.
helm upgrade openfaas openfaas/openfaas -n openfaas \
--set gateway.envValues.jaeger_endpoint="http://jaeger-collector.tracing:14268" \
--set gateway.envValues.service_name="openfaas-gateway" \
--set gateway.image.tag="latest"
Update deployment để Gateway gửi traces về Jaeger.
Bước 4: Cấu hình Cloudflare Workers để truyền Trace ID.
Cloudflare Workers sử dụng OpenTelemetry SDK. Trong code Worker, ta cần init tracer và gửi spans về Jaeger.
File: src/worker.js
import { Tracer } from '@opentelemetry/api';
import { JaegerExporter } from '@opentelemetry/exporter-jaeger';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
const sdk = new NodeSDK({
traceExporter: new JaegerExporter({
host: 'jaeger-collector.tracing', // Cần expose service này hoặc dùng public endpoint
port: 14268,
}),
});
sdk.start();
export default {
async fetch(request, env, ctx) {
const tracer = sdk.getTracer('cloudflare-worker');
return tracer.startActiveSpan('worker-request', async (span) => {
try {
// Extract context từ request header (traceparent)
// Logic xử lý business
const response = await fetch('https://openfaas-gateway.openfaas:8080/function/my-function', {
headers: {
...request.headers,
'X-Trace-ID': span.spanContext().traceId, // Pass trace ID
}
});
span.setStatus({ code: response.status === 200 ? 'OK' : 'ERROR' });
return response;
} catch (error) {
span.recordException(error);
span.setStatus({ code: 'ERROR' });
throw error;
} finally {
span.end();
}
});
}
};
Code này khởi tạo tracer, tạo span cho request, và truyền trace ID qua header đến OpenFaaS.
Bước 5: Expose Jaeger Query UI.
kubectl port-forward svc/jaeger-query -n tracing 16686:16686
Mở http://localhost:16686 để xem traces.
Verify: Gõ request vào Worker và xem Trace.
curl http://localhost:8080/function/my-function
Truy cập Jaeger UI, tìm service "cloudflare-worker" hoặc "openfaas-gateway". Bạn sẽ thấy một trace duy nhất bao gồm span từ Worker và span từ Function.
Tạo Dashboard tổng hợp hiệu năng của Edge và Serverless
Dashboard này sẽ gộp metrics từ Prometheus (OpenFaaS, K8s) và Logs/Traces (Jaeger, ELK) để có cái nhìn toàn cảnh.
Tại sao: Quản trị viên cần một màn hình duy nhất để thấy độ trễ (latency), lỗi (errors), và throughput của toàn bộ hệ thống hybrid.
Kết quả mong đợi: Dashboard Grafana hiển thị biểu đồ Request Rate, Latency P95, Error Rate cho cả Edge và Serverless.
Bước 1: Import Dashboard từ thư viện Grafana.
Chúng ta dùng dashboard có sẵn cho OpenFaaS và Kubernetes, sau đó custom thêm panel cho Cloudflare.
kubectl exec -it -n monitoring prometheus-kube-prometheus-grafana -- grafana-cli dashboard import 13110
Dashboard ID 13110 là "Kubernetes / Compute Resources / Nodes". Ta cần thêm panel mới cho OpenFaaS.
Bước 2: Tạo Dashboard custom trong Grafana.
Truy cập Grafana (port-forward ở phần 1), tạo Dashboard mới "Hybrid System Overview".
Panel 1: OpenFaaS Request Rate.
# PromQL Query
rate(openfaas_request_duration_seconds_count[1m])
Biểu đồ hiển thị số request/giây vào OpenFaaS Gateway.
Panel 2: Cloudflare Worker Latency (P95).
Vì Cloudflare không export metrics trực tiếp vào Prometheus, ta cần dùng một middleware (như Prometheus Blackbox Exporter) hoặc parse logs từ ELK sang Prometheus. Ở đây giả sử ta đã có metrics từ Cloudflare Logpush vào Prometheus (qua Logstash -> Prometheus exporter).
# PromQL Query (Giả định metric tên: cloudflare_worker_duration_seconds)
histogram_quantile(0.95, rate(cloudflare_worker_duration_seconds_bucket[5m]))
Biểu đồ hiển thị độ trễ P95 của Worker.
Panel 3: End-to-End Trace Latency.
Panel này dùng Data Source là Jaeger (cần install plugin Jaeger trong Grafana).
# Query trong Jaeger Data Source
service: cloudflare-worker OR service: openfaas-gateway
Hiển thị timeline của các trace gần đây có lỗi hoặc độ trễ cao.
Bước 4: Cấu hình Alerting Rules.
Đi vào Alerting tab trong Grafana, tạo rule.
Rule 1: High Latency.
# Condition
IF (rate(openfaas_request_duration_seconds_sum[1m] / rate(openfaas_request_duration_seconds_count[1m])) > 0.5)
THEN alert for 1m
Trigger khi độ trễ trung bình vượt quá 500ms trong 1 phút.
Rule 2: High Error Rate.
# Condition
IF (rate(openfaas_request_duration_seconds_count{status="500"}[1m]) / rate(openfaas_request_duration_seconds_count[1m]) > 0.05)
THEN alert for 1m
Trigger khi tỷ lệ lỗi 5xx vượt quá 5%.
Verify: Mở Dashboard Grafana.
Tạo request load giả (sử dụng wrk hoặc hey) để kích hoạt các biểu đồ và alert. Kiểm tra xem các panel có update theo thời gian thực không.
Cấu hình Alerting để cảnh báo sự cố thời gian thực
Sau khi có metrics và dashboard, chúng ta cần gửi cảnh báo đến Slack, PagerDuty hoặc Email khi có sự cố.
Tại sao: Giám sát bị động là không đủ. Cần hệ thống chủ động báo động để team on-call xử lý ngay lập tức.
Kết quả mong đợi: Khi có lỗi hoặc độ trễ cao, tin nhắn cảnh báo được gửi vào kênh Slack/PagerDuty đã cấu hình.
Bước 1: Cấu hình Alertmanager.
Alertmanager đi kèm với Prometheus Stack. Ta cần chỉnh sửa config để định tuyến alerts.
cat
Config này định tuyến alerts severity critical về PagerDuty, warning về Slack.
Bước 2: Tạo PrometheusRule để định nghĩa alerts chi tiết.
cat 0.05
for: 1m
labels:
severity: critical
annotations:
summary: "High error rate in OpenFaaS"
description: "Error rate is above 5% for {{ \$labels.job }}."
- alert: CloudflareWorkerDown
expr: absent(cloudflare_worker_duration_seconds_sum)
for: 2m
labels:
severity: critical
annotations:
summary: "Cloudflare Worker is not responding"
description: "No metrics received from Cloudflare Worker in the last 2 minutes."
EOF
Rule này định nghĩa 3 alert: độ trễ OpenFaaS, lỗi OpenFaaS, và Worker bị down. Labels severity quyết định route nào được dùng trong Alertmanager.
Bước 3: Khởi động lại Prometheus để load rules mới.
kubectl rollout restart deployment prometheus-kube-prometheus-prometheus -n monitoring
Prometheus cần restart để nhận PrometheusRule mới và áp dụng vào Alertmanager.
Verify: Kích hoạt cảnh báo thử nghiệm.
curl -X POST http://prometheus-kube-prometheus-prometheus.monitoring:9090/api/v1/admin/rules/reload
Tiếp tục tạo traffic lỗi hoặc làm chậm response để kích hoạt rule. Kiểm tra kênh Slack hoặc email để xác nhận tin nhắn đã nhận.
Điều hướng series:
Mục lục: Series: Series: Xây dựng nền tảng Serverless và Edge Computing an toàn với OpenFaaS, Cloudflare Workers và Wasm trên hạ tầng Kubernetes
« Phần 7: Bảo mật: Xác thực, mã hóa và bảo vệ API
Phần 9: Tự động hóa CI/CD cho pipeline Serverless và Edge »