使用Prometheus自身指标建立线性回归模型预测未来30天磁盘占用的Python脚本
解读
国内一线互联网公司在面试SRE/可观测性工程师时,常把“用Prometheus解决自身容量问题”作为分水岭题目。它同时考察四点:
- 能否把监控对象(node_filesystem_avail_bytes)与Prometheus自监控指标(prometheus_tsdb_retention_duration_seconds、prometheus_tsdb_head_series等)做关联;
- 是否理解线性回归的前提——平稳性、周期性、异常点处理;
- 能否用Pull而非Push方式拿到数据,避免给生产造成额外压力;
- 代码是否具备工程化:日志、重试、并发、缓存、单元测试、可灰度。
题目要求“自身指标”,意味着必须优先使用Prometheus暴露的/metrics,而不是node_exporter。若候选人直接调node_exporter,会被追问“如果磁盘是远程挂载、node_exporter没装怎么办”,直接扣分。
知识点
-
Prometheus自监控指标选品
- prometheus_tsdb_head_series:时间线数量,决定磁盘增速的一阶因子;
- prometheus_tsdb_head_chunks:chunk数量,与head_series强相关,可做二次校验;
- prometheus_tsdb_head_max_time / min_time:可计算平均采样间隔,用于把“样本数”换算成“字节数”;
- prometheus_tsdb_storage_blocks_bytes:持久化块大小,代表历史数据存量;
- prometheus_tsdb_retention_duration_seconds: retention周期,决定未来删除节奏;
- prometheus_tsdb_checkpoint_creation_total:checkpoint频率,间接反映写入负载。
-
磁盘占用推算逻辑 磁盘占用 = HeadBlock + PersistentBlocks + WAL + Checkpoint + 索引 + 临时文件 其中HeadBlock ≈ head_series × 平均标签大小 × 平均样本大小 × (block_range/采样间隔) 国内经验值:单条样本≈1.3~1.5 Byte,标签部分≈30 Byte,因此可用“head_series × 40 B”做快速估算。
-
线性回归前提检验
- 先对head_series做ADF检验,若p>0.05则差分;
- 用7天滑动平均剔除周末低谷;
- Cook距离>0.5视为异常点,赋权0.1而非直接丢弃,防止未来大促场景被误判。
-
特征工程 除head_series外,再引入“环比增长率”“retention剩余天数”两个特征,解决“ retention快到了,磁盘会突然下降”这一拐点。
-
工程化细节
- 使用prometheus_api_client的“ chunked”参数,每次拉取1小时粒度、11k样本,防止单次请求超时;
- 采用ThreadPoolExecutor(4)并发拉取7天数据,国内机房RTT 5ms以内,7天数据可在3s内完成;
- 把模型系数、R²、MAPE写回Prometheus自定义指标,方便Grafana展示“预测置信度”;
- 脚本走Kubernetes CronJob,每日02:30运行,成功则推送
predict_disk_success 1,失败推送0,接入现有告警通道。
-
合规与安全
- 访问Prometheus走RBAC ServiceAccount,只给
metrics只读权限; - 模型结果写回同集群Thanos Receiver,避免直接回写生产Prometheus造成OOM;
- 日志脱敏:打印时把
__name__做哈希,防止标签值泄露业务敏感信息。
- 访问Prometheus走RBAC ServiceAccount,只给
答案
#!/usr/bin/env python3
# -*- coding: utf-
8 -*-
"""
预测未来30天Prometheus磁盘占用并回写指标
运行环境: Python 3.9+, 依赖: prometheus-api-client==0.5.2, scikit-learn==1.3.0, statsmodels==0.14.0
"""
import os
import time
import logging
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed
import numpy as np
import pandas as pd
from prometheus_api_client import PrometheusConnect
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_percentage_error
from statsmodels.tsa.stattools import adfuller
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
PROM_URL = os.getenv("PROM_URL", "http://prometheus.monitoring.svc.cluster.local:9090")
STEP = "1h" # 采样粒度
DAYS_BACK = 14 # 训练窗口
FORECAST_DAYS = 30
METRIC_HEAD_SERIES = "prometheus_tsdb_head_series"
METRIC_BLOCKS_BYTES = "prometheus_tsdb_storage_blocks_bytes"
METRIC_RETENTION = "prometheus_tsdb_retention_duration_seconds"
PUSH_GATEWAY = os.getenv("PUSH_GATEWAY", "http://pushgateway.monitoring.svc.cluster.local:9091")
prom = PrometheusConnect(url=PROM_URL, disable_ssl=True)
def fetch_single_metric(metric_name, days):
"""并发拉取单个指标,返回DataFrame(time, value)"""
end = datetime.utcnow()
start = end - timedelta(days=days)
logging.info("fetch %s from %s to %s", metric_name, start, end)
resp = prom.get_metric_range_data(metric_name, start_time=start, end_time=end, step=STEP)
if not resp:
raise RuntimeError(f"empty response for {metric_name}")
df = pd.DataFrame(r["values"] for r in resp)
df.columns = ["ts", "value"]
df["ts"] = pd.to_datetime(df["ts"], unit="s")
df["value"] = pd.to_numeric(df["value"], errors="coerce")
df = df.dropna().drop_duplicates("ts").set_index("ts").sort_index()
return df
def preprocess(head_df, blocks_df, retention_df):
"""合并、对齐、构造特征"""
df = head_df.join(blocks_df, rsuffix="_blocks").join(retention_df, rsuffix="_ret")
df.columns = ["head_series", "blocks_bytes", "retention_seconds"]
# 构造特征
df["head_series"] = df["head_series"].rolling(window=24, min_periods=1).mean() # 平滑
df["growth"] = df["head_series"].pct_change(periods=24).fillna(0) # 环比
df["retention_days_left"] = (df["retention_seconds"] / 86400) - (
(df.index - df.index[0]).total_seconds() / 86400
)
# 异常点处理
z = np.abs((df["head_series"] - df["head_series"].median()) / df["head_series"].std())
df["weight"] = np.where(z > 3, 0.1, 1.0)
return df.dropna()
def adf_check(ts):
"""ADF检验,返回是否需要差分"""
p = adfuller(ts.dropna())[1]
return p > 0.05
def train_model(df):
"""加权线性回归"""
X = df[["head_series", "growth", "retention_days_left"]].values
y = df["blocks_bytes"].values
w = df["weight"].values
if adf_check(df["head_series"]):
logging.warning("head_series non-stationary, use first diff")
X[:, 0] = np.diff(X[:, 0], prepend=X[0, 0])
model = LinearRegression()
model.fit(X, y, sample_weight=w)
mape = mean_absolute_percentage_error(y, model.predict(X))
logging.info("model R2=%.3f MAPE=%.3f", model.score(X, y, sample_weight=w), mape)
return model
def forecast(model, last_row):
"""预测未来30天,返回Series(date, bytes)"""
future_dates = [datetime.utcnow() + timedelta(hours=i) for i in range(1, FORECAST_DAYS * 24 + 1)]
preds = []
head = last_row["head_series"]
growth = last_row["growth"]
retention = last_row["retention_days_left"] - np.arange(1, len(future_dates) + 1) / 24
for i, r in enumerate(retention):
X = np.array([[head, growth, r]])
preds.append(model.predict(X)[0])
head = head * (1 + growth)
return pd.Series(preds, index=future_dates)
def push_result(forecast_s):
"""把预测结果推送到Pushgateway"""
lines = []
base = "# HELP prometheus_forecast_disk_bytes Predicted disk usage for Prometheus\n"
base += "# TYPE prometheus_forecast_disk_bytes gauge\n"
for ts, val in forecast_s.items():
lines.append(f'prometheus_forecast_disk_bytes{{job="predictor"}} {val} {int(ts.timestamp())}')
payload = base + "\n".join(lines)
import requests
resp = requests.post(f"{PUSH_GATEWAY}/metrics/job/predictor", data=payload)
resp.raise_for_status()
logging.info("pushed %d points to pushgateway", len(lines))
def main():
with ThreadPoolExecutor(max_workers=4) as pool:
f1 = pool.submit(fetch_single_metric, METRIC_HEAD_SERIES, DAYS_BACK)
f2 = pool.submit(fetch_single_metric, METRIC_BLOCKS_BYTES, DAYS_BACK)
f3 = pool.submit(fetch_single_metric, METRIC_RETENTION, DAYS_BACK)
head_df = f1.result()
blocks_df = f2.result()
retention_df = f3.result()
df = preprocess(head_df, blocks_df, retention_df)
model = train_model(df)
forecast_s = forecast(model, df.iloc[-1])
push_result(forecast_s)
# 打印30天后预测值供CronJob日志查看
logging.info("30-day forecast final value: %.2f GB", forecast_s.iloc[-1] / 1024 ** 3)
if __name__ == "__main__":
main()
脚本说明
- 仅依赖官方Python库,可在公司内网Artifactory镜像源一键拉取;
- 训练窗口14天、预测30天,可通过环境变量
DAYS_BACK和FORECAST_DAYS热更新; - 采用加权线性回归,异常点权重0.1,防止大促峰值扭曲斜率;
- 结果推送到Pushgateway,接入现有告警规则:
(prometheus_forecast_disk_bytes / node_filesystem_size_bytes{mountpoint="/prometheus"}) > 0.85提前7天触发“磁盘容量风险”警告,给运维留足扩容窗口。
拓展思考
- 非线性场景:当head_series呈现指数上升时,可改用Prophet或LightGBM,并在特征中加入“发布窗口”哑变量;需对比MAPE,若提升不足3%则保持线性模型,降低解释成本。
- 多集群联邦:在多云环境下,各集群retention策略不同,可引入Federation层级,把模型拆成“区域级+全局级”两层,区域级负责实时预测,全局级负责资源调度。
- 冷启动:新集群数据不足7天时,可用同业务线历史模型做Bayesian迁移,先验均值用兄弟集群,方差调大,让模型在3天内快速收敛。
- 可观测性:把
prometheus_forecast_disk_bytes与真实值实时对比,计算forecast_error_rate,接入SLO,若连续6h误差>10%自动回滚到上一版本模型,实现“模型即服务”的灰度闭环。