在PostgreSQL 15原生分区场景,如何为history_uint创建按月分区并设置自动attach?

解读

Zabbix 5.0/6.0 LTS 在国内落地时,官方仍推荐用housekeeper做历史数据轮转,但单表10亿+行后vacuum与IO抖动明显。PostgreSQL 15原生分区(声明式分区)已支持attach/detach的元数据锁粒度下降,且分区表可在线调整,正好用来替代housekeeper,实现“按月分区+自动attach”的轻量级生命周期管理。面试官想确认三件事:

  1. 你是否理解Zabbix表结构(history_uint以clock为时间轴,itemid+clock为主键);
  2. 能否用PG15原生语法把老表无损迁移到分区表;
  3. 能否用最小权限、最小锁粒度完成“未来分区”的自动创建与attach,避免凌晨告警风暴。

知识点

  1. PG15声明式分区:PARTITION BY RANGE (clock) 使用UNIX时间戳整数;
  2. 默认分区(default partition)陷阱:必须提前创建,否则attach时全表锁;
  3. 排它约束(partition constraint)与CHECK约束:PG15已自动推导,无需手工加CHECK;
  4. 附件化锁:attach partition only需“ShareUpdateExclusiveLock”,与DML不冲突;
  5. 权限:zbx_monitor用户只需CREATE、ALTER TABLE,不需SUPERUSER;
  6. 调度:国内机房常用crontab或systemd timer,也可放到Zabbix外部检查脚本里,由Zabbix Agent采集“分区缺失”告警触发;
  7. 回退方案:如attach失败,必须保证default partition能接住新数据,否则Zabbix Server INSERT会报“no partition”导致数据丢失。

答案

步骤一:评估与锁窗口

  1. 在业务低峰(凌晨02:00-03:00)执行,确保Zabbix Server已配置CacheSize足够大,短时只读不影响前端。
  2. 查询当前最大clock:
    SELECT max(clock) FROM history_uint;
    确认未来30天数据量,预估单分区<2亿行,符合PG15分区表B+树深度≤4。

步骤二:创建分区父表
BEGIN;
ALTER TABLE history_uint RENAME TO history_uint_old;
CREATE TABLE history_uint (LIKE history_uint_old INCLUDING ALL)
PARTITION BY RANGE (clock);
-- 必须一次性建立default partition,否则后续attach会锁全表
CREATE TABLE history_uint_default PARTITION OF history_uint DEFAULT;
COMMIT;

步骤三:迁移历史数据(在线)
使用pg_partman的“非阻塞迁移”思路,但不用pg_partman,而是手工循环:
DO DECLARE r record; BEGIN FOR r IN SELECT date_trunc('month', to_timestamp(clock)) AS mon, min(clock) AS min_c, max(clock) AS max_c FROM history_uint_old GROUP BY 1 LOOP EXECUTE format($f$ CREATE TABLE IF NOT EXISTS history_uint_y%sm%s PARTITION OF history_uint FOR VALUES FROM (%s) TO (%s); $f$, to_char(r.mon,'YYYY'), to_char(r.mon,'MM'), r.min_c, r.max_c + 86400); -- 多留1天防边界 END LOOP; END;
-- 然后并行INSERT INTO history_uint SELECT * FROM history_uint_old;
-- 迁移完验证行数一致后,DROP history_uint_old。

步骤四:自动attach函数(PL/pgSQL)
CREATE OR REPLACE FUNCTION auto_attach_partition()
RETURNS void
LANGUAGE plpgsql
AS DECLAREstarttsint:=datepart(′epoch′,datetrunc(′month′,currentdate+interval′1month′));endtsint:=datepart(′epoch′,datetrunc(′month′,currentdate+interval′2months′));partnametext:=′historyuinty′∣∣tochar(totimestamp(startts),′YYYYmMM′);BEGIN−−若分区已存在则跳过IFtoregclass(partname)ISNOTNULLTHENRETURN;ENDIF;EXECUTEformat(′CREATETABLEIFNOTEXISTSEXECUTEformat(′ALTERTABLEhistoryuintATTACHPARTITIONpartname,startts,endts);−−更新统计信息,避免新分区无统计导致计划走错EXECUTEformat(′ANALYZEEND DECLARE start_ts int := date_part('epoch', date_trunc('month', current_date + interval '1 month')); end_ts int := date_part('epoch', date_trunc('month', current_date + interval '2 months')); part_name text := 'history_uint_y' || to_char(to_timestamp(start_ts), 'YYYYmMM'); BEGIN -- 若分区已存在则跳过 IF to_regclass(part_name) IS NOT NULL THEN RETURN; END IF; EXECUTE format('CREATE TABLE IF NOT EXISTS %I (LIKE history_uint INCLUDING ALL)', part_name); EXECUTE format('ALTER TABLE history_uint ATTACH PARTITION %I FOR VALUES FROM (%s) TO (%s)', part_name, start_ts, end_ts); -- 更新统计信息,避免新分区无统计导致计划走错 EXECUTE format('ANALYZE %I', part_name); END;

步骤五:调度与监控

  1. 在/etc/cron.d/zabbix-partition中加入:
    0 1 25 * * postgres psql -d zabbix -c "SELECT auto_attach_partition();"
    每月25号预建下月分区,保证“提前存在”。
  2. 在Zabbix里新增Item:
    key: pg.partition.missing[<pgsql>,history_uint]
    脚本逻辑:查询pg_partition_tree,若未来30天分区缺失则返回1,触发告警。
  3. 权限最小化:
    GRANT CREATE ON SCHEMA public TO zbx_monitor;
    函数SECURITY DEFINER OWNER TO postgres,zbx_monitor仅拥有EXECUTE权限。

步骤六:清理旧分区
不再用housekeeper,改用detach+drop:
ALTER TABLE history_uint DETACH PARTITION history_uint_y2023m05;
DROP TABLE history_uint_y2023m05;
可封装成另一个函数,由保留策略(如90天)调用。

拓展思考

  1. 如果Zabbix版本升级到6.4,官方已内建TimescaleDB支持,是否还坚持原生分区?
    答:国内金融、运营商合规环境限制第三方插件,原生分区仍是“零外部依赖”的最稳方案;TimescaleDB的压缩chunk虽香,但需额外维护license与版本对齐。
  2. 分区键能否改为itemid+clock的哈希分区?
    答:Zabbix查询模式以clock范围为主,哈希分区会导致分区剪枝失效,IO反而放大。
  3. 若出现attach失败,如何做到“可观测”?
    答:把函数包在BEGIN/EXCEPTION块,捕获SQLSTATE '42P16'(分区重叠)写入专用日志表,Zabbix通过log[]监控项实时告警,实现“分区生命周期”可观测。