通过Prophet预测磁盘使用率并写回Prometheus作为新指标的脚本
解读
这道题把“时间序列预测”与“Prometheus 生态闭环”两个高频考点揉在一起,既考察候选人对 Facebook Prophet 的建模能力,也考察对 Prometheus 数据模型、Exporter 机制、服务发现以及可观测性治理的理解。国内一线互联网公司在做容量预算、磁盘水位提前预警时,普遍采用“离线训练+在线推理”的混合架构,因此脚本必须满足:
- 能跑在 K8s CronJob 或物理机 crontab 里,轻量无状态;
- 输出符合 Prometheus 文本格式的 /metrics 接口,方便被 Prometheus Server Pull;
- 标签体系与 node_exporter 原生指标保持一致,避免标签冲突;
- 支持多盘、多实例横向扩展,且对 Prophet 参数可热更新;
- 代码可灰度、可回滚,日志与指标自身可观测。
知识点
- Prometheus 数据模型:指标名、标签集、时间戳、值四元组;文本暴露格式规范。
- Pull vs Push:Prophet 预测结果是“未来点”,必须用 Pushgateway 或自定义 Exporter 方式回写;要理解 Pushgateway 的持久化语义及“指标消失”问题。
- Prophet 建模要点:季节性、节假日、变点、容量上限 cap、数据缺失填充、采样频率对齐。
- PromQL 采样:rate/irate/increase 仅适用于 Counter,磁盘使用率是 Gauge,直接取值即可;预测值也是 Gauge。
- 标签一致性:原始指标 node_filesystem_avail_bytes / node_filesystem_size_bytes 的标签为 {device, fstype, mountpoint, instance, job},预测脚本必须复用同一套标签,否则 Grafana 仪表盘无法 join。
- 安全与性能:脚本内存占用 <200 MB、单次运行 <30 s;避免在 Prophet 里一次性加载 30 天原始数据导致 OOM;预测步长一般 24 h 即可,更新频率 1 h。
- 可观测性:脚本自身暴露 python_prophet_disk_prediction_duration_seconds、python_prophet_disk_prediction_errors_total,方便 SRE 监控脚本健康度。
答案
给出一套可直接落地的 Python3 脚本(单文件、无外部依赖除 prophet 与 prometheus_client),逻辑拆成四步:采数 → 建模 → 预测 → 回写。假设运行在 K8s CronJob,每小时执行一次,预测未来 24 h 磁盘使用率,并通过 NodePort 方式的自定义 Exporter 暴露 /metrics,供 Prometheus 拉取。
#!/usr/bin/env python3
# disk_prophet_exporter.py
import os, time, logging, json
from datetime import datetime, timedelta
import requests
import pandas as pd
from prophet import Prophet
from prometheus_client import start_http_server, Gauge, REGISTRY
# 1. 参数通过环境变量注入,方便 K8s ConfigMap 热更新
PROMETHEUS_URL = os.getenv("PROM_URL", "http://prometheus:9090")
QUERY_STEP = os.getenv("QUERY_STEP", "60s") # 原始采样精度
FORECAST_HORIZON = int(os.getenv("FC_HORIZON", "24")) # 预测小时数
LISTEN_PORT = int(os.getenv("METRICS_PORT", "9826"))
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
# 2. 日志格式统一,方便 Filebeat 采集
logging.basicConfig(
level=LOG_LEVEL,
format="%(asctime)s | %(levelname)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
# 3. 定义输出指标,标签与 node_exporter 保持一致
g_forecast = Gauge(
"node_filesystem_usage_ratio_forecast_1h",
"Prophet 预测 1 小时后的磁盘使用率,0-1 之间",
["device", "fstype", "mountpoint", "instance", "job"]
)
g_forecast_24h = Gauge(
"node_filesystem_usage_ratio_forecast_24h",
"Prophet 预测 24 小时后的磁盘使用率,0-1 之间",
["device", "fstype", "mountpoint", "instance", "job"]
)
g_script_duration = Gauge(
"python_prophet_disk_prediction_duration_seconds",
"脚本单次运行耗时"
)
g_script_errors = Gauge(
"python_prophet_disk_prediction_errors_total",
"脚本累计异常次数"
)
# 4. 工具:PromQL 查询封装
def prom_query(query: str) -> list:
"""返回 PromQL 瞬时查询结果列表,元素为 (timestamp, labels, value)"""
url = f"{PROMETHEUS_URL}/api/v1/query"
params = {"query": query}
try:
resp = requests.get(url, params=params, timeout=30)
resp.raise_for_status()
data = resp.json()
if data["status"] != "success":
raise RuntimeError("Prometheus API 返回非 success")
result = []
for item in data["data"]["result"]:
labels = item["metric"]
ts, val = item["value"]
result.append((int(ts), labels, float(val)))
return result
except Exception as e:
logging.exception("prom_query 失败: %s", e)
g_script_errors.inc()
return []
# 5. 工具:获取某标签组合 7 天历史时序
def get_ts_7d(labels: dict) -> pd.DataFrame:
"""返回 DataFrame: ds, y"""
query_labels = ",".join([f'{k}="{v}"' for k, v in labels.items()])
query = f"""
(1 - node_filesystem_avail_bytes{{{query_labels}}}
/ node_filesystem_size_bytes{{{query_labels}}})
"""
url = f"{PROMETHEUS_URL}/api/v1/query_range"
end = datetime.utcnow()
start = end - timedelta(days=7)
params = {
"query": query,
"start": start.timestamp(),
"end": end.timestamp(),
"step": QUERY_STEP
}
resp = requests.get(url, params=params, timeout=60)
resp.raise_for_status()
data = resp.json()
if data["status"] != "success" or not data["data"]["result"]:
return pd.DataFrame(columns=["ds", "y"])
values = data["data"]["result"][0]["values"]
df = pd.DataFrame(values, columns=["ts", "y"])
df["ds"] = pd.to_datetime(df["ts"], unit="s")
df["y"] = df["y"].astype(float)
return df[["ds", "y"]]
# 6. Prophet 建模+预测
def forecast(df: pd.DataFrame, periods: int) -> pd.DataFrame:
if df.empty or len(df) < 48:
logging.warning("样本点不足,跳过建模")
return pd.DataFrame(columns=["ds", "yhat", "yhat_lower", "yhat_upper"])
m = Prophet(
daily_seasonality=True,
weekly_seasonality=True,
yearly_seasonality=False,
interval_width=0.85,
changepoint_prior_scale=0.05,
seasonality_prior_scale=10
)
m.fit(df)
future = m.make_future_dataframe(periods=periods, freq="H")
# 磁盘使用率有上限 1,做逻辑封顶
future["cap"] = 1.0
forecast_df = m.predict(future)
return forecast_df
# 7. 主流程
def run():
start_at = time.time()
# 7.1 先拿到当前时刻所有挂载点列表
query = "node_filesystem_size_bytes"
current_list = prom_query(query)
if not current_list:
logging.error("无法获取当前磁盘列表")
return
# 7.2 遍历每个挂载点
for ts, labels, _ in current_list:
try:
# 只预测 ext4/xfs 数据盘,跳过 docker/overlay
if labels.get("fstype") not in {"ext4", "xfs"}:
continue
df = get_ts_7d(labels)
fc_df = forecast(df, FORECAST_HORIZON)
if fc_df.empty:
continue
# 取 1h 与 24h 后的预测值
now = datetime.utcnow()
target_1h = now + timedelta(hours=1)
target_24h = now + timedelta(hours=24)
val_1h = fc_df[fc_df["ds"] >= target_1h]["yhat"].iloc[0]
val_24h = fc_df[fc_df["ds"] >= target_24h]["yhat"].iloc[0]
# 写回 Prometheus 指标
label_values = [
labels.get("device", ""),
labels.get("fstype", ""),
labels.get("mountpoint", ""),
labels.get("instance", ""),
labels.get("job", "")
]
g_forecast.labels(*label_values).set(max(0.0, min(1.0, val_1h)))
g_forecast_24h.labels(*label_values).set(max(0.0, min(1.0, val_24h)))
except Exception as e:
logging.exception("处理 %s 失败: %s", labels, e)
g_script_errors.inc()
# 7.3 记录自身耗时
g_script_duration.set(time.time() - start_at)
if __name__ == "__main__":
# 启动 HTTP Server,暴露 /metrics
start_http_server(LISTEN_PORT)
logging.info("Exporter 启动,监听 %s", LISTEN_PORT)
# 立即执行一次,随后由外部 CronJob 控制频率
run()
# 阻塞,保持 /metrics 可访问
while True:
time.sleep(3600)
部署要点:
- 打包镜像
python:3.11-slim + prophet + prometheus_client,大小 <200 MB。 - K8s CronJob 每小时拉起一次,资源限制 CPU 200 m / Memory 256 Mi;成功退出码 0,失败重试 3 次。
- Prometheus 增加 scrape_config,job_name 设为
disk_prophet,静态配置 CronPod IP 或 Service。 - Grafana 侧复用原有 Node Exporter 仪表盘,新增两条折线:
node_filesystem_usage_ratio_forecast_1h与node_filesystem_usage_ratio_forecast_24h,颜色用橙色虚线,提示“预测线”。
拓展思考
- 在线 vs 离线:如果预测任务很重(如上万挂载点),可把 Prophet 训练放到离线 Spark + pandas UDF,每小时产出“未来 24 h 系数表”,在线脚本只负责查表插值,耗时从 30 s 降到 1 s。
- 多步滚动预测:Prophet 默认一次性预测多步,误差随步长放大;可改用 ARIMA/LSTM/DeepAR,并通过 Prometheus Remote Write 把预测误差写回,做在线模型漂移监控。
- 告警策略:不要直接对预测值告警,而是使用
predict(node_filesystem_usage_ratio_forecast_24h > 0.9) and (node_filesystem_usage_ratio < 0.75),即“未来快满但当前还不满”,提前 24 h 通知运维扩容,避免误报。 - 标签高基数:若挂载点动态变化(如 K8s 本地 CSI 卷),需定期清理 REGISTRY 中的失效标签,否则内存泄漏;可在脚本退出前调用
REGISTRY.clear()并重建 Gauge。 - 合规与审计:国内金融、政企场景要求预测脚本可审计,需把每次 Prophet 参数、输入样本 MD5、预测结果落盘到 S3/OSS,保留 30 天,方便监管回溯。