Prometheus 监控查询
从 Prometheus 查询指标、警报和集群状态。
两种访问模式
当 Prometheus 可以通过网络访问(云服务、远程服务器等)时使用:
# 使用远程 Prometheus URL
python scripts/query_prometheus.py \
--prom-url "https://prometheus.example.com" \
--query "up"
# 查询警报
python scripts/query_prometheus.py \
--prom-url "https://prometheus.example.com" \
--alerts
当 Prometheus 只能通过 kubectl 访问时使用:
# 终端 1:端口转发 Prometheus
kubectl port-forward -n prometheus svc/prometheus 9090:9090
# 终端 2:查询指标
python scripts/query_prometheus.py \
--prom-url "http://localhost:9090" \
--query "up"
查询脚本
使用 scripts/query_prometheus.py 查询指标:
# 查询特定指标(默认:http://localhost:9090)
python scripts/query_prometheus.py --query "up"
# 显式 URL
python scripts/query_prometheus.py \
--prom-url "http://localhost:9090" \
--query "rate(http_requests_total[5m])"
# 查询警报
python scripts/query_prometheus.py --alerts
默认:如果 --prom-url 未指定,则使用 http://localhost:9090。
常见查询类型
警报
# 所有触发警报
ALERTS{alertstate="firing"}
# 待处理警报
ALERTS{alertstate="pending"}
集群状态
# 节点状态
kube_node_status_condition{condition="Ready"}
# Pod 状态
kube_pod_status_phase{phase="Running"}
kube_pod_status_phase{phase="Failed"}
# Namespace Pod 数量统计
count by (namespace) (kube_pod_info)
Nginx 指标
# 请求率
rate(nginx_http_requests_total[5m])
# 连接状态
nginx_connections_active
nginx_connections_reading
nginx_connections_writing
nginx_connections_waiting
# 请求持续时间(p99)
histogram_quantile(0.99, rate(nginx_http_request_duration_seconds_bucket[5m]))
自定义指标
将 替换为实际指标:
# 当前值
# 5 分钟内的速率
rate([5m])
# 1 小时内的平均值
avg([1h])
参数
prom-url:Prometheus URL(默认:http://localhost:9090)
query:PromQL 查询字符串
alerts:查询所有警报的标志
time:评估时间戳(ISO 8601)
start:范围查询的开始时间
end:范围查询的结束时间
step:查询分辨率步骤(用于范围查询)
timeout:查询超时时间(秒,默认:30)
输出
返回格式化的指标结果。对于即时查询,返回当前值。对于警报,返回警报名称、状态(触发/待处理)和标签。
示例
检查集群健康状况
# 所有触发警报
python scripts/query_prometheus.py --alerts
# 节点状态
python scripts/query_prometheus.py --query "kube_node_status_condition{condition='Ready'}"
Nginx 负载
# 请求率
python scripts/query_prometheus.py --query "rate(nginx_http_requests_total[5m])"
# 活动连接
python scripts/query_prometheus.py --query "nginx_connections_active"
自定义指标
python scripts/query_prometheus.py --query "my_custom_metric"
python scripts/query_prometheus.py --query "rate(my_custom_metric[5m])"