这是本节的多页打印视图。
点击此处打印 .
返回本页常规视图 .
Pigsty 中文文档 v4.0 (WIP) “P ostgreSQL I n G reat STY le”: P ostgres, I nfras, G raphics, S ervice, T oolbox, it’s all Y ours.
—— 开箱即用、本地优先的 PostgreSQL 发行版,开源 RDS 替代
仓库 | 演示 | 博客 | 论坛 | GPTs | 微信公众号 | EN Docs
快速上手 最新版本的 Pigsty:curl -fsSL https://repo.pigsty.cc/get | bash
入门 : 安装部署 | 离线安装 | 资源准备 | 声明配置 | 执行剧本 | 置备机器 | 安全考量 | FAQ
模块 :PGSQL | INFRA | NODE | ETCD | MINIO | REDIS | FERRET | DOCKER | APP
关于 :功能特性 | 历史沿革 | 活动新闻 | 加入社区 | 隐私政策 | 开源协议 | 赞助我们 | 服务订阅
概念 : 架构概览 | 集群模型 | 监控系统 | 本地CA | IaC | HA | PITR | 服务接入 | 认证鉴权
参考 : 操作系统 | 扩展列表 | 文件结构 | 同类产品 | 成本参考
1 - PIGSTY 2 - 关于 了解 Pigsty 项目本身的方方面面:功能特性、历史发展,开源协议,隐私政策,社区活动与新闻。
2.1 - 亮点特性 Pigsty 的价值主张与亮点功能特性。
“P ostgreSQL I n G reat STY le”: P ostgres, I nfras, G raphics, S ervice, T oolbox, it’s all Y ours.
—— 开箱即用、本地优先的 PostgreSQL 发行版,开源 RDS 替代
价值主张
总览 Pigsty 是一个更好的本地开源 RDS for PostgreSQL 替代:
开箱即用的RDS :从内核到RDS发行版,在 EL/Debian/Ubuntu 下提供 13-18 版本的生产级 PG 数据库服务。丰富的扩展插件 :提供无可比拟的 440+ 扩展,提供开箱即用的分布式的时序地理空间图文向量多模态数据库能力。灵活的模块架构 :灵活组合,自由扩展:Redis/Etcd/MinIO/Mongo;可独立使用,监控现有RDS/主机/数据库。惊艳的观测能力 :基于现代可观测性技术栈 Prometheus/Grafana,提供令人惊艳,无可比拟的数据库观测能力。验证过的可靠性 :故障自愈的高可用架构:硬件故障自动切换,流量无缝衔接。并提供自动配置的 PITR 兜底删库!简单易用可维护 :声明式API,GitOps就位,傻瓜式操作,Database/Infra-as-Code 以及管理SOP封装管理复杂度!扎实的安全实践 :加密备份一应俱全,自带基础ACL最佳实践。只要硬件与密钥安全,您无需操心数据库的安全性!广泛的应用场景 :低代码数据应用开发,或使用预置的 Docker Compose 模板,一键拉起使用PostgreSQL的海量软件!开源的自由软件 :以云数据库1/10不到的成本拥有与更好的数据库服务!帮您真正“拥有”自己的数据,实现自主可控!PostgreSQL 整合了生态中的工具与最佳实践:
开箱即用的 PostgreSQL 发行版,深度整合地理、时序、分布式、图、向量、搜索、AI等 440 余个扩展插件 ! 运行于裸操作系统之上,无需容器支持,支持主流操作系统: EL 8/9/10, Ubuntu 22.04/24.04 以及 Debian 12/13。 基于 patroni , haproxy , 与etcd ,打造故障自愈的高可用架构:硬件故障自动切换,流量无缝衔接。 基于 pgBackRest 与可选的 MinIO 集群提供开箱即用的 PITR 时间点恢复,为软件缺陷与人为删库兜底。 基于 Ansible 提供声明式的 API 对复杂度进行抽象,以 Database-as-Code 的方式极大简化了日常运维管理操作。 Pigsty用途广泛,可用作完整应用运行时,开发演示数据/可视化应用,大量使用 PG 的软件可用 Docker 模板一键拉起。 提供基于 Vagrant 的本地开发测试沙箱环境,与基于 Terraform 的云端自动部署方案,开发测试生产保持环境一致。 部署并监控专用的 Redis (主从,哨兵,集群),MinIO,Etcd,Haproxy,MongoDB (FerretDB ) 集群 开箱即用的RDS 让您立刻在本地拥有生产级的PostgreSQL数据库服务!
PostgreSQL 是一个足够完美的数据库内核,但它需要更多工具与系统的配合才能成为一个足够好的数据库服务(RDS),Pigsty 帮助 PostgreSQL 完成这一步飞跃。
Pigsty 为您解决使用 PostgreSQL 中会遇到的各种难题:内核扩展安装,连接池,负载均衡,服务接入,高可用 / 自动故障切换,日志收集,指标监控,告警,备份恢复,PITR,访问控制,参数调优,安全加密,证书签发,NTP,DNS,参数调优,配置管理,CMDB,管理预案… 您无需再为这些细节烦心劳神!
Pigsty 支持 PostgreSQL 13 ~ 18 主干内核与其他兼容分支,可运行于 EL / Debian / Ubuntu 以及 兼容操作系统发行版 上,在 x86_64 与 ARM64 芯片架构上可用,且无需容器支持。
除了数据库内核与大量开箱即用的扩展插件以外,Pigsty 还提供了数据库服务所需的完整基础设施与运行时,以及本地沙箱 / 生产环境 / 云 IaaS 自动部署方案。
Pigsty 可以一键从裸机开始拉起整套环境,触达软件交付的最后一公里。普通研发运维均可快速上手并兼职进行数据库管理,无需数据库专家即可自建企业级RDS服务!
丰富的扩展插件 超融合多模态,一切皆用 PostgreSQL,一个PG替换所有数据库!
PostgreSQL 的灵魂在于其丰富的 扩展生态 ,而 Pigsty 独一无二地深度整合了 PostgreSQL 生态中的 440+ 扩展 ,为您提供开箱即用的超融合多模态数据库!
插件间可以产生协同效应 ,产生 1+1 远大于 2 的效果。
您可以使用 PostGIS 处理地理空间数据,使用 TimescaleDB 分析时序/事件流数据,并使用 Citus 将其原地升级为分布式地理时空数据库;
您可以用 PGVector 存储并搜索AI嵌入,用 ParadeDB 实现 ES级全文检索,并同时使用精准的 SQL,全文检索,与模糊向量进行混合检索。
您还可以通过 Hydra 、 duckdb_fdw 、pg_analytics 、pg_duckdb 等分析扩展,实现专用 OLAP 数据库/数据湖仓的分析表现。
使用 PostgreSQL 单一组件替代 MySQL,Kafka,ElasticSearch,MongoDB,以及大数据分析技术栈已经成为一种最佳实践 —— 单一数据库选型能够显著降低系统复杂度,极大提高研发效能与敏捷性,实现程度惊人的软硬件,研发/运维人力降本增效。
灵活的模块架构 灵活组合,自由扩展,多数据库支持,监控现有RDS/主机/数据库
Pigsty 中的组件被抽象可独立部署的 模块 ,并可自由组合以应对多变的需求场景。INFRA 模块带有完整的现代监控技术栈,而 NODE 模块则将节点调谐至指定状态并纳管。
在多个节点上安装 PGSQL 模块会自动组建出基于主从复制的高可用数据库集群,而同样的 ETCD 模块则为数据库高可用提供共识与元数据存储。
除了上述四个 核心模块 之外,Pigsty 还提供一系列选装功能模块:MINIO 模块可以提供本地对象存储能力,并作为集中式数据库备份仓库。
REDIS 模块能以独立主从,哨兵,原生集群的方式为数据库提供辅助。DOCKER 模块可用于拉起无状态的应用软件。
此外,Pigsty 还提供 PG 兼容 / 衍生内核的支持,您可以使用 Babelfish 提供 MS SQL Server 兼容性,使用 IvorySQL 提供 Oracle 兼容性,
使用 OpenHaloDB 提供 MySQL 兼容性,使用 OrioleDB 提供极致的 OLTP 性能。
不仅如此,你还可以使用 FerretDB 提供 MongoDB 兼容性,使用 Supabase 提供 Firebase 兼容,并使用 PolarDB 满足国产化合规要求。
更多专业版/试点模块将不断引入 Pigsty,如 GPSQL ,KAFKA ,DUCKDB ,VICTORIA ,TIGERBEETLE ,KUBERNETES ,CONSUL ,JUPYTER ,GREENPLUM ,CLOUDBERRY ,MYSQL , …
惊艳的观测能力 使用现代开源可观测性技术栈,提供无与伦比的监控最佳实践!
Pigsty 提供了基于开源的 Grafana / Prometheus 现代可观测性技术栈做 监控 的最佳实践:,Grafana 负责可视化呈现,VictoriaMetrics 用于收集监控指标,VictoriaLogs 用于日志收集与查询,Alertmanager 用于告警通知。Blackbox Exporter 负责检查服务可用性。整套系统同样被设计为一键拉起,开箱即用的 INFRA 模块。
Pigsty 所管理的任何组件都会被自动纳入监控之中,包括主机节点,负载均衡 HAProxy,数据库 Postgres,连接池 Pgbouncer,元数据库 ETCD,KV缓存 Redis,对象存储 MinIO,……,以及整套监控基础设施本身。大量的 Grafana 监控面板与预置告警规则会让你的系统观测能力有质的提升,当然,这套系统也可以被复用于您的应用监控基础设施,或者监控已有的数据库实例或 RDS。
无论是故障分析还是慢查询优化、无论是水位评估还是资源规划,Pigsty 为您提供全面的数据支撑,真正做到数据驱动。在 Pigsty 中,超过三千类监控指标被用于描述整个系统的方方面面,并被进一步加工、聚合、处理、分析、提炼并以符合直觉的可视化模式呈现在您的面前。从全局大盘总览,到某个数据库实例中单个对象(表,索引,函数)的增删改查详情都能一览无余。您可以随意上卷下钻横向跳转,浏览系统现状与历史趋势,并预测未来的演变。
此外,Pigsty的监控系统模块部分还可以 独立使用 ——用它来监控现有的主机节点与数据库实例,或者是云上的 RDS 服务。只需要一个连接串一行命令,您就可以获得极致的 PostgreSQL 可观测性体验。
访问 截图画廊 与 在线演示 获取更多详情。
久经考验的可靠性 开箱即用的高可用与时间点恢复能力,确保你的数据库坚如磐石!
对于软件缺陷或人为误操作造成的删表删库,Pigsty 提供了开箱即用的 PITR 时间点恢复能力,无需额外配置即默认启用。只要存储空间管够,基于 pgBackRest 的基础备份与 WAL 归档让您拥有快速回到过去任意时间点的能力。您可以使用本地目录/磁盘,亦或专用的 MinIO 集群或 S3 对象存储服务保留更长的回溯期限,丰俭由人。
更重要的是,Pigsty 让高可用与故障自愈成为 PostgreSQL 集群的标配,基于 patroni, etcd, 与 haproxy 打造的 高可用故障自愈架构 ,让您在面对硬件故障时游刃有余:主库故障自动切换的 RTO < 30s(可配置),一致性优先模式下确保数据零损失 RPO = 0。只要集群中有任意实例存活,集群就可以对外提供完整的服务,而客户端只要连接至集群中的任意节点,即可获得完整的服务。
Pigsty 内置了 HAProxy 负载均衡器用于自动流量切换,提供 DNS/VIP/LVS 等多种接入方式供客户端选用。故障切换与主动切换对业务侧除零星闪断外几乎无感知,应用不需要修改连接串重启。极小的维护窗口需求带来了极大的灵活便利:您完全可以在无需应用配合的情况下滚动维护升级整个集群。硬件故障可以等到第二天再抽空善后处置的特性,让研发,运维与 DBA 都能安心睡个好觉。
许多大型组织与核心机构已经在生产环境中长时间使用 Pigsty ,最大的部署有 25K CPU 核心与 200+ PostgreSQL 超大规格实例;在这一部署案例中,六七年内经历了数十次硬件故障与各类事故,DBA 换了几茬,但依然可以保持比 99.999% 更高的可用性战绩。
简单易用可维护 Infra as Code, 数据库即代码,声明式的API将数据库管理的复杂度来封装。
Pigsty 使用声明式的接口对外提供服务,将系统的可控制性拔高到一个全新水平:用户通过配置清单告诉 Pigsty “我想要什么样的数据库集群”,而不用去操心到底需要怎样去做。从效果上讲,这类似于 K8S 中的 CRD 与 Operator,但 Pigsty 可用于任何节点上的数据库与基础设施:不论是容器,虚拟机,还是物理机。
无论是创建/销毁集群,添加/移除从库,还是新增数据库/用户/服务/扩展/黑白名单规则,您只需要修改配置清单并运行 Pigsty 提供的幂等剧本,而 Pigsty 负责将系统调整到您期望的状态。
用户无需操心配置的细节,Pigsty将自动根据机器的硬件配置进行调优,您只需要关心诸如集群叫什么名字,有几个实例放在哪几台机器上,使用什么配置模版:事务/分析/核心/微型,这些基础信息,研发也可以自助服务。但如果您愿意跳入兔子洞中,Pigsty 也提供了丰富且精细的控制参数,满足最龟毛 DBA 的苛刻定制需求。
除此之外,Pigsty 本身的安装部署也是一键傻瓜式的,所有依赖被预先打包,在安装时可以无需互联网访问。而安装所需的机器资源,也可以通过 Vagrant 或 Terraform 模板自动获取,让您在十几分钟内就可以从零在本地笔记本或云端虚拟机上拉起一套完整的 Pigsty 部署。本地沙箱环境可以跑在1核2G的微型虚拟机中,提供与生产环境完全一致的功能模拟,可以用于开发、测试、演示与学习。
扎实的安全实践 加密备份一应俱全,只要硬件与密钥安全,您无需操心数据库的安全性。
Pigsty 针对高标准,严要求的企业级场景设计 ,采用业界领先的 安全最佳实践 保护您的数据安全(机密性/完整性/可用性),默认配置下的安全性便足以满足绝大多数场景下的合规要求。
Pigsty 会创建自签名的 CA (或使用您提供的 CA)签发证书,加密网络通信。需要保护的敏感管理页面与API端点都受到密码保护。
数据库备份使用 AES 算法加密,数据库密码使用 scram-sha-256 算法加密,并提供插件强制执行密码强度策略。
Pigsty 提供了一套开箱即用,简单易用,便于扩展的 ACL 模型,提供读/写/管理/ETL 的权限区分,并带有遵循最小权限原则的 HBA 规则集,通过多重防护确保系统机密性。
Pigsty 默认启用数据库校验和避免静默数据腐坏,通过从库副本提供坏块兜底。提供 CRIT 数据零丢失配置模板,使用 watchdog 确保为高可用 Fencing 兜底。
您可以通过 audit 插件审计数据库操作,系统与数据库日志全部收集备查,以满足合规要求。
Pigsty 正确配置 SELinux 与防火墙配置,并遵循最小权限原则设计操作系统用户组与文件权限,确保系统安全基线符合合规要求。
而且在 Etcd,MinIO 等附属可选组件上的安全上也毫不妥协,etcd 与 minio 均使用 RBAC 模型与 TLS 加密通信,确保系统整体安全性。
合理配置的系统通过等保三级毫无问题,只要您遵循安全性最佳实践,内网部署并合理配置安全组与防火墙,数据库安全性将不再是您的痛点。
广泛的应用场景 使用预置的Docker模板,一键拉起使用PostgreSQL的海量软件!
在各类数据密集型应用中,数据库往往是最为棘手的部分。例如 Gitlab 企业版与社区版的核心区别就是底层 PostgreSQL 数据库的监控与高可用,如果您已经有了足够好的本地 PG RDS,完全可以拒绝为软件自带的土法手造数据库组件买单。
Pigsty 提供了 Docker 模块与大量开箱即用的 Compose 模板。您可以使用 Pigsty 管理的高可用 PostgreSQL (以及 Redis 与 MinIO )作为后端存储,以无状态的模式一键拉起这些软件:
Gitlab、Gitea、Wiki.js、NocoDB、Odoo、Jira、Confluence、Habour、Mastodon、Discourse、KeyCloak 等等。如果您的应用需要一个靠谱的 PostgreSQL 数据库, Pigsty 也许是最简单的获取方案。
Pigsty 也提供了与 PostgreSQL 紧密联系的应用开发工具集:PGAdmin4、PGWeb、ByteBase、PostgREST、Kong、以及 EdgeDB、FerretDB、Supabase 这些使用 PostgreSQL 作为存储的"上层数据库"。
更奇妙的是,您完全可以基于 Pigsty 内置了的 Grafana 与 Postgres ,以低代码的方式快速搭建起一个交互式的数据应用来,甚至还可以使用 Pigsty 内置的 ECharts 面板创造更有表现力的交互可视化作品。
Pigsty 为您的 AI 应用提供了一个功能强大的运行时,您的 Agent 可以在这个环境中利用 PostgreSQL 与可观测性世界的强大能力,快速构建起一个数据驱动的智能体。
开源的自由软件 Pigsty是基于 Apache-2.0 开源的自由软件,由热爱 PostgreSQL 的社区成员用热情浇灌
Pigsty 是完全 开源免费 的自由软件,它允许您在缺乏数据库专家的情况下,用几乎接近纯硬件的成本来运行企业级的 PostgreSQL 数据库服务。
作为对比,数据库厂商的“企业级数据库服务”与公有云厂商提供的 RDS 会收取底层硬件资源几倍到十几倍不等的 溢价 作为 “服务费”。
很多用户选择上云,正是因为自己搞不定数据库;很多用户使用 RDS,是因为别无他选。
我们将打破云厂商的垄断,为用户提供一个云中立的,更好的 RDS 开源替代:
Pigsty 紧跟 PostgreSQL 上游主干,不会有供应商锁定,不会有恼人的 “授权费”,不会有节点数量限制,不会收集您的任何数据。您的所有的核心资产 —— 数据,都能"自主可控",掌握在自己手中。
Pigsty 本身旨在用数据库自动驾驶软件,替代大量无趣的人肉数据库运维工作,但再好的软件也没法解决所有的问题。
总会有一些的冷门低频疑难杂症需要专家介入处理。这也是为什么我们也提供专业的 订阅服务 ,来为有需要的企业级用户使用 PostgreSQL 提供兜底。
几万块的订阅咨询费不到顶尖 DBA 每年工资的几十分之一,让您彻底免除后顾之忧,把成本真正花在刀刃上。对于社区用户,我们亦用爱发电 ,提供免费的支持与日常答疑。
2.2 - 发展规划 未来功能的规划,新功能的发布节奏,待办事项列表。
版本发布策略 Pigsty 使用语义化版本号,<主版本>.<次版本>.<修订号>。Alpha / Beta / RC 版本会在版本号后添加后缀,如 -a1,-b1,-c1。
主版本更新意味着不兼容的基础性变化与重大新特性;次版本更新通常表示普通功能特性更新,较小的API变动;修订版本更新意味着 Bug 修复与软件包版本更新。
Pigsty 计划每年发布一次主版本更新,次版本更新通常跟随 PostgreSQL 小版本更新节奏,在 PostgreSQL 新版本发布后最迟一个月内跟进。
Pigsty 通常每年计划 4 - 6 个小版本,完整发布历史请参考 发行注记 。
使用具体的版本号进行部署
Pigsty 使用 main 主干分支进行开发,请始终使用带有版本号的 Release 。
除非您清楚知道自己在做什么,否则请勿使用 GitHub 的 main 分支,总是检出特定版本使用。
列入考虑的新特性 这里是我们的 活跃议题 与 路线图 。
扩展插件与软件包 关于扩展支持的路线图,可以在这里找到:https://pgext.cloud/e/roadmap
考虑纳入 暂不考虑 2.3 - 历史沿革 Pigsty 项目的由来与动机,过去发展的历史,未来的目标与愿景。
历史起源 Pigsty 项目始于 2018 ~ 2019 年,起源于 探探 。
探探是一个互联网交友 App —— 中国的 Tinder,现已被陌陌收购。
探探这家公司是一个北欧 Style 的创业公司,有着一个瑞典工程师初创团队。
探探在技术上极有品味,使用 PostgreSQL 与 Go 作为核心技术栈。
探探整个系统架构参照了 Instagram ,一切围绕 PostgreSQL 数据库设计。
直到几百万日活,几百万 TPS,几百 TB 数据的量级下,数据组件 只用了 PostgreSQL 。
几乎所有的业务逻辑都使用 PG 存储过程实现 —— 甚至包括 100ms 的推荐算法!
探探这种深度使用 PostgreSQL 特性的非典型研发模式,对工程师与DBA的水平提出了极高的要求。
而 Pigsty ,就是我们用这种真实世界的大规模,高标准数据库集群场景打磨出的开源项目 ——
沉淀着我们作为顶尖 PostgreSQL 专家的经验与最佳实践。
发展过程 在最开始,Pigsty 并没有现在这样的愿景、目标与版图。而是旨在提供一个供我们自己使用的 PostgreSQL 监控系统。
我们调研了市面上所有的方案,开源的、商业的、云的,datadog, pgwatch,…… ,没有一个能满足我们对于可观测性的需求。
因此我们决定亲自动手,基于 Grafana 与 Prometheus 自己动手打造一个,这就是 Pigsty 的前身与雏形。
Pigsty 作为监控系统的效果相当惊艳,帮助我们解决了无数管理问题。
随后,研发人员希望在本地的开发机上也有这样的监控系统,于是我们使用 Ansible 编写了置备剧本,将这套系统从一次性建设任务转变为了可重复使用,可复制的软件。
新的功能允许用户使用 Vagrant 和 Terraform,用 Infra as Code 的方式快速拉起本地 DevBox 开发机,或生产环境服务器,并自动完成 PostgreSQL 与监控系统的部署。
接下来,我们重新设计了生产环境的 PostgreSQL 架构,引入了 Patroni 与 pgBackRest 解决了数据库的 高可用 与 时间点恢复 问题。
开发了基于逻辑复制的不停机 迁移 方案,通过蓝绿部署将生产环境两百套数据库集群滚动升级至最新大版本。并将这些能力引入 Pigsty 中。
Pigsty 是我们做给自己使用的软件,我们自己作为甲方用户,非常清楚自己需要什么,也不会在自己的需求上偷懒。
“Eat dog food”最大的好处就是,我们自己既是开发者也更是用户 —— 因此非常了解自己需要什么,也不会在自己的需求上偷懒。
我们解决了一个又一个的问题,并将解决方案沉淀到 Pigsty 里。Pigsty 的定位,也从一个监控系统,逐渐发展成为一个开箱即用的 PostgreSQL 数据库发行版。
因此在这一阶段,我们决定将 Pigsty 对外开源,并开始了一系列的技术分享与宣传,也开始有各行各业的外部用户使用起 Pigsty 并提出反馈意见。
全职创业 在 2022 年,Pigsty 项目获得了由陆奇博士发起的奇绩创坛的种子轮投资,我得以全职出来做这件事情。
作为一个开源项目,Pigsty 的发展相当不赖,在全职创业这两年里,Pigsty 在 Github 上的 Star 数从的 几百翻了几番到了 3700;上了 HN 头条推荐,增长开始滚起雪球;
在 OSSRank 开源榜单 中,Pigsty 在 PostgreSQL 生态项目中排名第 22 名,在中国人主导的项目里是最靠前的。
从前 Pigsty 只能跑在 CentOS 7 上,现今已经基本覆盖了所有主流 Linux 发行版 (EL, Debian, Ubuntu)。支持的 PG 大版本覆盖 12 - 17,维护,收录整合了PG生态中的 390+ 扩展插件。
其中,我本人维护了这里超过一半的扩展插件,并提供开箱即用的 RPM/DEB 包,算上 Pigsty 本身,“基于开源,回馈开源”,算是为 PG 生态做一些贡献。
Pigsty 的定位,也在不断发展的过程中,从一个 PostgreSQL 数据库发行版,进一步扩展到了 开源云数据库替代 。它真正对标的是云厂商的整个云数据库品牌。
公有云的反叛者 AWS、Azure、GCP、Aliyun 等公有云厂商为初创企业提供了许多便利,但它们是闭源的,并迫使用户以高额费用租赁基础资源。
我们认为,优秀的数据库服务,应该和优秀的数据库内核一样,普及到每一个用户手中,而不是必须花费高昂的代价去向赛博领主租赁。
云计算的敏捷与弹性都很好,但它应该是自由、开源、普惠、本地优先的 ——
我们认为云计算宇宙中需要一个代表开源价值观的解决方案,在不牺牲云带来好处的前提下,将基础设施的控制权交还给用户。
因此,我们也在引领着一场 下云的运动与战役 ,作为公有云的反叛者,来重塑这个行业的价值观。
我们的愿景 我希望,未来的世界人人都有自由使用优秀服务的事实权利,而不是只能被圈养在几个赛博领主公有云巨头厂商的地盘上当赛博佃户甚至赛博农奴。
这正是 Pigsty要做的事 —— 一个更好的,开源免费的RDS替代 。让用户能够在任何地方(包括云服务器)上,一键拉起有比云RDS更好的数据库服务。
Pigsty 是是对 PostgreSQL 的彻底补完,更是对云数据库的辛辣嘲讽 。它本意是“猪圈”,但更是 Postgres In Great STYle 的缩写,即“全盛状态下的 PostgreSQL ”。
Pigsty 本身是一款完全开源免费的软件,我们纯粹靠提供 咨询与服务 来维持运营
建设良好的系统也许跑个几年都不会遇到需要 ”兜底“ 的问题,但数据库的问题一但出现就不是小问题。
很多时候,专家的经验更是能够一言化腐朽为神奇,而我们为有需求的客户提供这样的服务 —— 我们认为这是一种更加公正、合理、可持续的模式。
关于团队 我是冯若航,Pigsty 的作者,Pigsty 绝大部分的代码由我 一人开发 ,个别特性由社区贡献。
软件领域依然存在个人英雄主义,独一无二的个体才能够创造出独一无二的作品来 —— 我希望 Pigsty 能够成为这样的作品。
如果您对我感兴趣,这里是我的个人主页:https://vonng.com/
《墨天轮风云人物访谈录 —— 冯若航 》
《90后,辞职创业,说要卷死云数据库 》
2.4 - 活动新闻 与 Pigsty 和 PostgreSQL 相关的活动事件与新闻,以及最新活动预告!
最近新闻 Pigsty 3.2.2 发布!
Pigsty 3.2.1 发布!
Pigsty 3.2.0 发布!
PostgreSQL 包管理器 pig 发布!
Pigsty 3.1.0 发布,提供完整的 PostgreSQL 17.2 扩展支持
Pigsty 3.0.4 发布! 提供扩展目录与仓库,编译 PG17扩展,自建Supabase流程优化
Pigsty 3.0.3 发布! 提供正式的 PostgreSQL 17 支持,优化 Etcd 运维与监控
Pigsty 3.0.2 发布! 精简安装模式,PolarDB 15 支持,例行问题修复(2024-09-07)
Pigsty 3.0.1 发布!Oracle 兼容性,Patroni 4 支持,例行问题修复 (2024-08-31)
Pigsty 3.0.0 发布!333 个扩展,可替换内核,完整RDS服务!
新闻:Pigsty提供的Yum/APT补充软件仓库,提供254个额外的开箱即用的二进制RPM/DEB扩展!
PGCon.Dev 2024 参会记!
Pigsty v2.7 发布!
Pigsty v2.6 发布!
The name of this project always makes me grin: PIGSTY is actually an acronym, standing for Postgres In Great STYle! It’s a Postgres distribution that includes lots of components and tools out of the box in areas like availability, deployment, and observability. The latest release pushes everything up to Postgres 16.2 standards and introduces new ParadeDB and DuckDB FDW extensions.
这个项目的名字总能让我笑开花:PIGSTY 实际上是一个首字母缩略词,代表 Postgres In Great STYle!它是一个 Postgres 发行版,包括了大量的组件和工具,涵盖了可用性、部署和可观测性等领域。最新版本将所有内容推进到了 Postgres 16.2,并引入了新的 ParadeDB 和 DuckDB FDW 扩展。
版本发布 Pigsty 发布注记
版本 发布时间 摘要 地址 v3.2.2 2025-01-23 390扩展,Omnigres支持,Mooncake,Citus13与PG17支持 v3.2.2 v3.2.1 2025-01-12 350扩展,Ivory4,Citus强化,Odoo模板 v3.2.1 v3.2.0 2024-12-24 扩展管理 CLI ,Grafana 强化,ARM64 扩展补完 v3.2.0 v3.1.0 2024-11-22 PG 17 作为默认大版本,配置简化,Ubuntu 24 与 ARM 支持,MinIO 改进 v3.1.0 v3.0.4 2024-10-30 PG 17 扩展,OLAP 全家桶,pg_duckdb v3.0.4 v3.0.3 2024-09-27 PostgreSQL 17,Etcd 运维优化,IvorySQL 3.4,PostGIS 3.5 v3.0.3 v3.0.2 2024-09-07 精简安装模式,PolarDB 15支持,监控视图更新 v3.0.2 v3.0.1 2024-08-31 例行问题修复,Patroni 4支持,Oracle兼容性改进 v3.0.1 v3.0.0 2024-08-25 333个扩展插件,可插拔内核,MSSQL,Oracle,PolarDB 兼容性 v3.0.0 v2.7.0 2024-05-20 扩展大爆炸,新增20+强力扩展插件,与多款Docker应用 v2.7.0 v2.6.0 2024-02-28 PG 16 作为默认大版本,引入 ParadeDB 与 DuckDB 等扩展 v2.6.0 v2.5.1 2023-12-01 例行小版本更新,PG16重要扩展支持 v2.5.1 v2.5.0 2023-09-24 Ubuntu/Debian支持:bullseye, bookworm, jammy, focal v2.5.0 v2.4.1 2023-09-24 Supabase/PostgresML支持与各种新扩展:graphql, jwt, pg_net, vault v2.4.1 v2.4.0 2023-09-14 PG16,监控RDS,服务咨询支持,新扩展:中文分词全文检索/图/HTTP/嵌入等 v2.4.0 v2.3.1 2023-09-01 带HNSW的PGVector,PG 16 RC1, 文档翻新,中文文档,例行问题修复 v2.3.1 v2.3.0 2023-08-20 主机VIP, ferretdb, nocodb, MySQL存根, CVE修复 v2.3.0 v2.2.0 2023-08-04 仪表盘 & 置备重做,UOS 兼容性 v2.2.0 v2.1.0 2023-06-10 支持 PostgreSQL 12 ~ 16beta v2.1.0 v2.0.2 2023-03-31 新增 pgvector 支持,修复 MinIO CVE v2.0.2 v2.0.1 2023-03-21 v2 错误修复,安全增强,升级 Grafana 版本 v2.0.1 v2.0.0 2023-02-28 架构大升级,兼容性、安全性、可维护性显著增强 v2.0.0 v1.5.1 2022-06-18 Grafana 安全性修复 v1.5.1 v1.5.0 2022-05-31 Docker 应用程序支持 v1.5.0 v1.4.1 2022-04-20 错误修复 & 英文文档完整翻译 v1.4.1 v1.4.0 2022-03-31 MatrixDB 支持,分离 INFRA/NODES/PGSQL/REDIS模块 v1.4.0 v1.3.0 2021-11-30 PGCAT 重整 & PGSQL 增强 & Redis Beta支持 v1.3.0 v1.2.0 2021-11-03 默认 PGSQL 版本升级至 14 v1.2.0 v1.1.0 2021-10-12 主页, JupyterLab, PGWEB, Pev2 & pgbadger v1.1.0 v1.0.0 2021-07-26 v1 正式版, 监控系统重整 v1.0.0 v0.9.0 2021-04-04 Pigsty 图形界面, 命令行界面, 日志集成 v0.9.0 v0.8.0 2021-03-28 服务置备,定制对外暴露的数据库服务 v0.8.0 v0.7.0 2021-03-01 仅监控部署,监控现有 PostgreSQL 实例 v0.7.0 v0.6.0 2021-02-19 架构增强,将PG与Consul解耦 v0.6.0 v0.5.0 2021-01-07 支持在配置中定义业务数据库/用户 v0.5.0 v0.4.0 2020-12-14 支持 PostgreSQL 13,添加官方文档 v0.4.0 v0.3.0 2020-10-22 虚拟机置备方案正式定稿 v0.3.0 v0.2.0 2020-07-10 PG监控系统第六版正式发布 v0.2.0 v0.1.0 2020-06-20 在生产仿真测试环境中验证通过 v0.1.0 v0.0.5 2020-08-19 离线安装模式:无需互联网访问即可交付 v0.0.5 v0.0.4 2020-07-27 将 Ansible 剧本重构为 Role Refactor playbooks into ansible roles v0.0.4 v0.0.3 2020-06-22 接口设计改进 v0.0.3 v0.0.2 2020-04-30 首次提交 v0.0.2 v0.0.1 2019-05-15 概念原型 v0.0.1
会议与演讲 日期 类型 活动 主题 2023-12-20 直播辩论 开源漫谈第七期 上云 or 下云,割韭菜还是降本增效? 2023-11-24 技术大会 大模型时代的向量数据库 圆桌讨论:大模型时代向量数据库新未来 2023-09-08 人物专访 墨天轮风云人物访谈 冯若航:不想当段子手的技术狂,不是一位好的开源创始人 2023-08-16 技术大会 DTCC 2023 DBA之夜:PostgreSQL vs MySQL的开源协议问题 2023-08-09 直播辩论 开源漫谈第一期 MySQL vs PostgreSQL,谁是世界第一? 2023-07-01 技术大会 SACC 2023 专题研讨会8:FinOps实践:云成本管理与优化 2023-05-12 线下活动 PostgreSQL中国社区 温州站线下沙龙 PG With DB4AI: 向量数据库 PGVECTOR & AI4DB: 数据库自动驾驶 Pigsty 2023-04-08 技术大会 数据库嘉年华 2023 更好的开源RDS替代:Pigsty 2023-04-01 技术大会 PostgreSQL中国社区 西安站线下沙龙 PG高可用与容灾最佳实践 2023-03-23 公开直播 Bytebase x Pigsty 管理 PostgreSQL 的最佳实践: Bytebase x Pigsty 2023-03-04 技术大会 PostgreSQL中国技术大会 炮打 RDS,Pigsty v2.0 发布 2023-02-01 技术大会 DTCC 2022 开源 RDS 替代:开箱即用、自动驾驶的数据库发行版 Pigsty 2022-07-21 直播辩论 云吞噬开源,那开源有机会反击吗? 云吞噬开源,那开源有机会反击吗? 2022-07-04 人物专访 专题采访:创造者说 90 后,辞职创业,说要卷死云数据库 2022-06-28 公开直播 贝斯的圆桌趴 |DBA 福音 - SQL 审核最佳实践 2022-06-12 公开路演 奇绩创坛 S22 路演日 好用省钱的数据库发行版 Pigsty 2022-06-05 视频直播 PG中文社区直播分享 Pigstyv1.5快速上手新特性介绍与生产集群搭建
2.5 - 加入社区 Pigsty 是一个 Build in Public 的项目,我们在 GitHub 上非常活跃,中文区用户主要活跃于微信群组中。
GitHub 我们的 GitHub 仓库地址是:https://github.com/pgsty/pigsty ,欢迎点个 ⭐️ 关注 我们。
我们欢迎任何人 提交新 Issue 或创建 Pull Request ,提出功能建议并参与 Pigsty 贡献。
请注意,关于 Pigsty 文档的问题,请在 github.com/Vonng/pigsty.cc 仓库中提交 Issue 。
微信群组 中文区用户主要活跃于微信群组中,目前有七个活跃的群组,1群-4群已经满员,其他群需要添加小助手微信拉入。
加入微信社群,请用搜索 “Pigsty小助手”,(微信号 pigsty-cc) 备注或发送 “加群” ,小助手会将您拉入群组中。
海外社群 Telegram: https://t.me/joinchat/gV9zfZraNPM3YjFh
Discord: https://discord.gg/j5pG8qfKxU
您也可以通过邮件联系我: rh@vonng.com
社区求助 当您使用 Pigsty 遇到问题时,可以向社区求助,您提供的信息越丰富,就越有可能在社区得到帮助。
请参考 社区求助指南 ,尽可能提供足够的信息,以便社区成员帮助您解决问题。以下是求助提问的参考模板:
发生了什么事? (必选项 )
Pigsty版本号与操作系统版本 (必选项 )
$ grep version pigsty.yml
$ cat /etc/os-release
$ uname -a
一些云厂商对标准操作系统发行版进行了定制,您可以告诉我们使用的是哪一家云厂商的什么操作系统镜像。
如果您在安装操作系统后对环境进行了定制与修改,或者在您的局域网中有特定的安全规则与防火墙配置,也请在提问时告知我们。
Pigsty配置文件
请不要忘记抹掉任何敏感信息:密码,内部密钥,敏感配置等。
cat ~/pigsty/pigsty.yml
你期待发生什么?
请描述正常情况下应该发生什么事情,实际发生的情况与期待的情况有何偏离?
如何复现此问题?
请尽可能详细地告诉我们复现此问题的方法与步骤。
监控截图
如果你在使用 Pigsty 提供的监控系统,可以提供 相关 的截图。
错误日志
请尽可能提供与错误有关的日志。请不要粘贴类似 “Failed to start xxx service” 之类没有信息量的内容 。
您可以从 Grafana / Loki 中查询日志,或从以下位置获取日志:
Syslog: /var/log/messages (rhel) or /var/log/syslog (debian) Postgres: /pg/log/postgres/* Patroni: /pg/log/patroni/* Pgbouncer: /pg/log/pgbouncer/* Pgbackrest: /pg/log/pgbackrest/* journalctl -u patroni
journalctl -u <service name>
您已经搜索过 Issue/网站/FAQ了吗?
在 FAQ 中,我们提供了许多常见问题的解答,请在提问前检查
您也可以从 Github Issue 与 Discussion 中搜索相关问题:
有什么其他信息是我们需要知道的吗?
您提供的信息与上下文越丰富,我们越有可能帮助您解决问题。
2.6 - 隐私政策 Pigsty 软件与网站会收集哪些用户数据,以及我们将如何处理您的数据并保护您的隐私权?
Pigsty软件 当您安装 Pigsty 软件时,如果在网络隔离的环境中使用离线软件包安装,我们不会收到任何关于您的数据 。
如果您选择在线安装,那么在下载相关软件包时,我们的服务器或云供应商的服务器会自动在日志中记录来访机器的 IP 地址和/或主机名,和您下载的软件包名称。
除非法律要求,我们不会与其他组织共享这些信息。(实话说也是吃饱了撑着才会去看这些东西)
Pigsty 使用的主域名为:pigsty.io ,中国大陆请使用中文备案镜像站点 pigsty.cc 。
Pigsty网站 当您访问我们的网站时,我们的服务器会自动在 Nginx 日志中记录您的 IP 地址和/或主机名。
仅当您决定通过完成调查或在我们的某个网站上注册为用户来向我们发送此类信息时,我们才会存储您的电子邮件地址、姓名和地点等信息
我们收集这些信息是为了帮助我们改进网站内容、定制网页布局以及出于技术和支持目的联系人员。除非法律要求,我们不会与其他组织共享您的电子邮件地址。
本网站使用 Google Analytics,这是 Google, Inc.(“Google”)提供的一项网络分析服务。谷歌分析使用“cookies”,即放置在您计算机上的文本文件,帮助网站分析用户如何使用该网站。
cookie 生成的有关您使用网站的信息(包括您的 IP 地址)将被传输至 Google 位于美国的服务器并由其存储。谷歌将使用这些信息来评估您对网站的使用情况,为网站运营商编制网站活动报告,并提供与网站活动和互联网使用相关的其他服务。
如果法律要求,或者第三方代表 Google 处理信息,Google 还可能会将此信息传输给第三方。 Google 不会将您的 IP 地址与 Google 持有的任何其他数据关联起来。
您可以通过在浏览器上选择适当的设置来拒绝使用 cookie,但请注意,如果您这样做,您可能无法使用本网站的全部功能。使用本网站即表示您同意 Google 以上述方式和目的处理有关您的数据。
如果您对此政策有任何疑问或意见,或要求删除个人数据,您可以通过发送邮件至 rh@pigsty.io 与我们联系
2.7 - 开源协议 Pigsty 使用的开源协议 —— Apache-2.0,它授予您什么样的权利,又有哪些限制?
协议摘要 Pigsty 项目主体使用 Apache-2.0 开源许可证;个别可选模块使用 AGPLv3 许可证;Pigsty 文档网站使用 CC by 4.0 许可证。
项目协议地址:https://github.com/pgsty/pigsty/blob/main/LICENSE
Pigsty 开源项目 Pigsty 软件主体采用 Apache License 2.0 许可证。
这是一种宽松的开源许可证,允许您自由地使用、修改和分发本软件,包括用于商业目的,而无需公开您的源代码或使用相同许可证。
本协议授权您 本协议不提供 本协议的条件 商用 商标使用权 包含本许可证与版权声明 修改 责任与担保 声明对原始代码的修改 分发 专利授权 私人使用
Pigsty 特殊模块 Pigsty 的 INFRA 模块与 MINIO 模块受到 GNU Affero General Public License v3.0 (AGPLv3) 许可证的约束。
AGPLv3 不影响普通用户的使用:使用并不是一种“发布”,您无需操心使用 Pigsty 的业务代码是否需要开源。
当您将这些模块或者对这些模块的修改作为软件/服务的全部或一部分对外“再分发 ”时,您才需要考虑到 AGPLv3 的约束。
本协议授权您 本协议不提供 本协议的条件 商用 商标使用权 包含本许可证并显著声明 修改 责任与担保 不得修改其开源状态 分发 公开源代码 专利授权 通过网络使用属于分发的一种 私人使用 使用同样的协议开源
考虑到如果您选择使用该模块,那么已经使用了 AGPLv3 的 Grafana 与 MinIO,这并不是什么大问题。
这两个模块都是 可选项 ,您可以选择不使用它们以彻底规避 AGPLv3 的要求。
下列文件与目录使用 AGPL-3.0 授权 (Grafana, MinIO 相关组件):
Pigsty 文档网站 Pigsty 的文档与网站(包括但不限于:pigsty.cc ,pigsty.io ,pgsty.com )均使用 Creative Commons Attribution 4.0 International (CC BY 4.0) 许可证。
CC BY 4.0 是一种知识共享许可证,允许您自由地分享与演绎本站的内容,但是您必须给出 适当的署名 ,提供指向许可证的链接,并指出是否有对原始内容进行了修改 。
本协议授权您 本协议不提供 本协议的条件 商用 商标使用权 署名(注明原作者) 修改 责任与担保 标明修改内容 分发 专利授权 提供许可证链接 私人使用
SBOM 清单 以下为 Pigsty 项目所使用或相关的开源软件及其开源协议。
440 个 PostgreSQL 扩展插件的许可证请参考 PostgreSQL 扩展许可证清单 。
必要性等级说明:
必选 :提供 Pigsty 关键性核心能力,不提供关闭停用选项建议 :Pigsty 默认启用 的组件,可以通过配置选项停用可选 :Pigsty 默认支持但不启用的组件,可通过配置启用Apache-2.0 许可证原文
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (C) 2018-2026 Ruohang Feng, @Vonng (rh@vonng.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
AGPLv3 许可证原文 GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C) 2018-2026 Ruohang Feng, Author of Pigsty
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
2.8 - 赞助我们 Pigsty 的赞助者,投资人名单,感谢你们对本项目的支持!
赞助我们 Pigsty 是一个开源免费的自由软件,由 PostgreSQL 社区成员用热情浇灌而成,旨在整合 PostgreSQL 生态的力量,推广 PostgreSQL 的普及。
如果我们的工作帮到了您,请考虑赞助或者支持一下我们的项目:
直接打钱赞助我们,用最直接有力的鼓舞表达您的真挚支持! 考虑采购我们的技术支持服务 ,我们可以提供专业的 PostgreSQL 高可用集群部署与维护服务,让您的预算花得物有所值! 通过文章,讲座,视频分享您使用 Pigsty 的案例与经验。 允许我们在 “这些用户使用了Pigsty” 中提及您的组织。 向有需求的朋友,同事与客户提名/推荐我们的项目与服务。 关注我们的 微信公众号 并转发相关技术文章至群组与朋友圈。 天使投资人 Pigsty 是由 奇绩创坛 (原YC中国,MiraclePlus) S22 所投资的项目,感谢奇绩创坛与陆奇博士对本项目的支持!
2.9 - 行业案例 Pigsty 在各个领域与行业的客户/应用案例
根据 Google Analytics PV 与下载量,Pigsty 目前有约 10 万用户 ,一半来自中国大陆,一半来自全球其他地区。
遍布互联网、云计算、金融、自动驾驶、制造业、科技创新、ISV 与军工等多个行业。
如果您在 使用 Pigsty 并且愿意与我们分享您的案例与 Logo,欢迎联系我们,我们提供一次的免费咨询支持。
互联网 探探 :两百台+物理机,用于 PostgreSQL 与 Redis 服务
哔哩哔哩 :用于支持 PostgreSQL 创新业务
云厂商 Bitdeer :比特小鹿,提供 PG DBaaS
Oracle OCI :使用 Pigsty 交付 PostgreSQL 集群。
金融行业 AirWallex :监控 200+ GCP PostgreSQL 数据库
影视行业 影视飓风 :自建 PG RDS / Victoria Metrics
自动驾驶 Momenta :自动驾驶,管理自建 PostgreSQL 集群
制造业 华峰集团 :使用 Pigsty 交付 PostgreSQL 集群作为化工时序数据仓库
科技创新 北京领雾科技 :云上 PostgreSQL 下云自建
Motphys :自建 PostgreSQL 支持 Gitlab
赛陇生物科技 :自建 Supabase
杭州零码科技 :自建 PostgreSQL
ISV 内蒙古豪德天沐科技有限公司
上海元芳
DSG
军工 北京某部队
上海某部队
电科36所
机械工业研究所
航天一院
2.10 - 订阅服务 Pigsty 专业版/企业版订阅服务:当您遇到与 PostgreSQL 和 Pigsty 有关的疑难杂症时,订阅服务可以为您兜底。
Pigsty 旨在聚集PG生态的合力,并用自动驾驶的数据库管控软件帮助用户用好世界上 最流行 的数据库 PostgreSQL。
尽管 Pigsty 本身已经解决了 PG 使用中的诸多问题。但想真正达到企业级服务的质量,原厂提供的专家支持与兜底服务不可或缺。
我们深知专业的商业支持服务对于企业客户的重要性,因此,Pigsty 企业版在开源版本的基础上提供了一系列增值服务,帮助用户更好地用好 PostgreSQL 与 Pigsty,供有需求的客户按需选用。
如果您有下列需求,欢迎考虑 Pigsty 订阅服务:
在关键场景中运行数据库,需要严格 SLA 保障兜底。 希望对 Pigsty 与 PostgreSQL 相关疑难杂症提供兜底。 希望获取关于 PostgreSQL / Pigsty 生产环境最佳实践的指导。 希望有专家帮助解读监控图表,分析定位性能瓶颈与故障根因,给出意见。 希望根据现有资源与业务需求,规划满足安全/容灾/合规要求的数据库架构。 需要将其他数据库迁移至 PostgreSQL 数据库,或对历史遗留实例迁移与改造。 建设基于Prometheus / Grafana 技术栈的可观测性体系,数据大盘,可视化应用。 希望支持国产信创操作系统/国产信创 ARM 芯片架构,提供中文/本地化界面支持。 下云并寻求 RDS for PostgreSQL 的开源替代 —— 云中立,无供应商锁定的解决方案。 希望获取关于 Redis / ETCD / MinIO,以及 TimescaleDB / Citus 等扩展的专业支持。 希望规避 AGPL v3 协议对衍生作品强制使用同协议开源的的限制,进行二次开发与 OEM 贴牌。 希望将 Pigsty 作为 SaaS / PaaS / DBaaS 对外销售,或基于此发行版提供技术服务/咨询/云服务。 订阅计划 除了 开源版 之外,Pigsty 提供两种不同的订阅服务档位:专业版 与 企业版 ,您可以根据自身的实际情况与需求选购。
开源免费 无规模限制,无质保承诺
许可协议:AGPLv3
PG支持:17
架构支持:x86_64
OS支持:三系最新小版本
EL 9.4 Debian 12.7 Ubuntu 22.04.5 功能:核心模块
SLA:无 SLA 承诺
社区公益支持答疑:
支持:无人天支持选项
仓库:全球CF托管仓库
起售价:150,000 ¥ / 年 普通用户的默认之选
许可协议:商业许可证
PG支持:16, 17
架构支持:x86_64,Arm64
OS支持:五系大小版本
EL 8 / 9 兼容 Debian 12 Ubuntu 22 / 24 功能:所有模块 (信创除外)
SLA:工作日时效内响应
提供专家咨询服务:
支持:每年包含 1 人天
交付:标准离线软件包
仓库:中国大陆镜像站
起售价:400,000 ¥ / 年 严格 SLA 的关键场景
许可协议:商业许可证
PG支持:12 - 18+
架构支持:x86_64,Arm64
OS支持:按需定制
EL, Debian, Ubuntu 云上 Linux 操作系统 国产操作系统与ARM 功能:所有模块
SLA:7 x 24 (< 1h)
提供企业级专家咨询服务:
软件缺陷修复 疑难杂症分析 专家答疑解惑 备份合规建议 升级路径支持 性能瓶颈定位 年度架构评估 扩展插件收录 DBaaS & OEM 用例 支持:每年包含 2 人天
仓库:中国大陆镜像站
交付:定制离线软件包
信创:PolarDB-O 支持
Pigsty开源版 Pigsty 开源版使用 AGPLv3 许可证, 提供了完整核心功能,无需任何费用,但也不承诺任何质保服务。如果您发现了 Pigsty 的缺陷,我们非常欢迎您在 Github 上提出 Issue 。
如果您属于普通终端用户(即:公有云厂商,数据库厂商除外的用户),我们实际上执行更宽松的 Apache 2.0 许可证 —— 即使您对 Pigsty 进行二次开发,我们也不会对此进行追索。
针对开源版本,我们提供 PostgreSQL 17 在 EL 9.4,Debian 12.7,Ubuntu 22.04.5 三个精准操作系统发行版最新小版本上的预制标准离线软件包(作为对开源的支持,同时提供 Debian 12 的 Arm64 离线软件包)。
使用 Pigsty 开源版本,可以让初级研发工程师 / 运维工程师拥有专业 DBA 70%+ 的能力,在缺少数据库专家的情况下,也能够轻松搭建一个高可用,高性能,易维护,安全可靠的 PostgreSQL 数据库集群。
代号 操作系统发行版版本 x86_64Arm64PG17 PG16 PG15 PG14 PG13 EL9 RHEL 9 / Rocky9 / Alma9 el9.x86_64U22 Ubuntu 22.04 (jammy) u22.x86_64D12 Debian 12 (bookworm) d12.x86_64d12.aarch64
= 首要支持, = 选配支持
Pigsty专业版 专业版订阅: 起售价格 ¥ 150,000 / 年
Pigsty 专业版订阅提供了完整的功能模块,以及对于 Pigsty 本身的质保。关于 PostgreSQL 本身与扩展插件的缺陷,我们将尽最大努力通过 PostgreSQL 全球开发者社区进行反馈与修复。
Pigsty 专业版构建于开源版基础之上,完全兼容开源版本的所有功能,并提供额外的功能模块,与更为宽广的数据库 / 操作系统版本兼容选项:我们将针对五个主流操作系统发行版的 所有小版本 提供构建选项。
Pigsty 专业版包含了对 最近两个 PostgreSQL 大版本(17,16)的支持,提供两个大版本中的所有可用的扩展插件,确保您可以通过滚动升级的方式,平滑迁移到最新的 PostgreSQL 大版本上。
Pigsty 专业版订阅允许您使用中国大陆镜像站点软件仓库,无需翻墙代理即可访问;同时我们将针对您使用的精准操作系统大小版本定制离线软件安装包,确保在断网环境下也能正常安装交付,做到自主可控。
Pigsty 专业版订阅提供了标准的专家咨询服务,包括疑难杂症分析,DBA 答疑解惑,备份合规建议等,我们承诺在工作日(5x8)时效内响应您的问题,并且每年提供 1 人天支持,以及可选的人天加购选项。
Pigsty 专业版使用商业许可证,并提供书面合同承诺的 AGPLv3 开源义务豁免,即使您对 Pigsty 进行二次开发,并违反了 AGPLv3 协议没有开源,我们亦不会对此进行追索。
Pigsty 专业版的起售价格 ¥150,000 / 年 ,相当于 9 vCPU 的 AWS 高可用 RDS PG 年费, 或月薪 一万元 的初级运维工程师。
代号 操作系统发行版版本 x86_64Arm64PG17 PG16 PG15 PG14 PG13 EL9 RHEL 9 / Rocky9 / Alma9 el9.x86_64el9.aarch64EL8 RHEL 8 / Rocky8 / Alma8 / Anolis8 el8.x86_64el8.aarch64U24 Ubuntu 24.04 (noble) u24.x86_64u24.aarch64U22 Ubuntu 22.04 (jammy) u22.x86_64u22.aarch64D12 Debian 12 (bookworm) d12.x86_64d12.aarch64
Pigsty企业版 企业版订阅: 起售价格 ¥ 400,000 / 年
Pigsty 企业版订阅包含 Pigsty 专业版订阅提供的全部服务内容,和以下增值服务项:
Pigsty 企业版订阅提供最为广泛的数据库/操作系统版本支持范围,包括对过保操作系统(EL7, U20, D11),国产操作系统,云厂商操作系统,以及过保数据库大版本(从 PG 13 开始)的延长支持,以及对 Arm64 架构芯片的完整支持。
Pigsty 企业版订阅提供了信创,国产化解决方案,允许您在 Pigsty 中使用 PolarDB v2.0 (此内核许可需单独采购)内核替换原生 PostgreSQL 内核,以满足国产化合规要求。
Pigsty 企业版订阅提供了更高标准的企业级咨询服务,承诺 7x24 提供 (< 1h) 的响应时间 SLA,并可提供更多种类的咨询支持:版本升级,性能瓶颈定位,年度架构评估,扩展插件收录等。
Pigsty 企业版订阅每年自带 2 人天支持,以及可选的人天加购选项,用于解决各种更为棘手复杂耗时的问题。
Pigsty 企业版允许您将 Pigsty 用于 DBaaS 用途,建设云数据库服务对外出售。
Pigsty 企业版的起步价格为 ¥400,000 / 年 ,相当于 24 vCPU 的 AWS 高可用 RDS 年费,或月薪 三万元 的运维专家。
代号 操作系统发行版版本 x86_64PG17 PG16 PG15 PG14 PG13 PG12 Arm64PG17 PG16 PG15 PG14 PG13 PG12 EL9 RHEL 9 / Rocky9 / Alma9 el9.x86_64el9.arm64EL8 RHEL 8 / Rocky8 / Alma8 / Anolis8 el8.x86_64el8.arm64U24 Ubuntu 24.04 (noble) u24.x86_64u24.arm64U22 Ubuntu 22.04 (jammy) u22.x86_64u22.arm64D12 Debian 12 (bookworm) d12.x86_64d12.arm64D11 Debian 11 (bullseye) d12.x86_64d11.arm64U20 Ubuntu 20.04 (focal) d12.x86_64u20.arm64EL7 RHEL7 / CentOS7 / UOS … d12.x86_64el7.arm64
Pigsty订阅说明 功能差异
Pigsty 专业版/企业版相比开源版本,包含以下额外功能:
命令行管理工具 : 解锁 Pigsty 命令行工具( pig )的完整功能系统定制能力 :针对精确的主流Linux操作系统发行版大小版本提供预制的离线安装包离线安装能力 :在没有互联网访问的环境中(断网环境)实现 Pigsty 的完整安装PG内核多版本 :允许用户自由指定并安装 PostgreSQL 生命周期内大版本的内核(13 - 17)内核替换能力 :允许用户使用其他 PostgreSQL 系兼容内核,替换原生 PG 内核,以及离线安装这些内核的能力扩展支持能力 :针对 350 个可用 PG Extension,提供 PG 13-17+ 在主流操作系统上开箱即用的安装能力。完整功能模块 :提供所有功能模块:Supabase :可靠地自建生产级开源 FirebaseMinIO :企业PB级对象存储规划与自建DuckDB :提供完善的 DuckDB 支持,以及 PostgreSQL + DuckDB OLAP 扩展插件支持Kafka :提供高可用的 Kafka 集群部署与监控Kubernetes, VictoriaMetrics & VictoriaLogs 国产操作系统支持 :提供国产信创操作系统支持选项(仅限企业版订阅 )国产ARM架构支持 :提供国产 ARM64 架构支持选项(仅限企业版订阅 )中国大陆镜像仓库 :无需科学上网即可顺畅安装,提供境内 YUM/APT 仓库镜像与 DockerHub 访问代理。中文界面支持 :监控系统中文版界面支持(Beta)付费模式
Pigsty 订阅采用按年付费的模式,签订合同后,从合同约定日起计算一年的有效期。订阅合同到期前如果继续打款则视为自动续订。
连续订阅有折扣,第一次续签(第二年)享受 95 折优惠,第二次以及后续的续签享受订阅费用 9 折优惠,一次性订阅三年以上整体费用享受 85 折优惠。
在年度订阅合同终止后,您可以选择不续签订阅服务,Pigsty 将不再提供软件更新,技术支持,咨询服务,但您仍然可以继续使用已经安装版本的 Pigsty 专业版软件。
如果您订阅了 Pigsty 专业服务并选择不续订,在重新订阅时 无需 补齐中断期间的订阅费用,但所有折扣与优惠将重置。
Pigsty 的定价策略确保用户物有所值 —— 您可以立即获得顶尖 DBA 的数据库架构建设方案与管理最佳实践,并由其提供咨询答疑与服务支持兜底;
而付出的成本相比于全职雇佣数据库专家或使用云数据库极具竞争力。以下是市场上 企业级数据库专业服务市场定价参考 :
体面数据库专业服务的公允价格是 1 ~ 2 万元 / 年 ,计费单位为 vCPU ,即一个 CPU 线程(1 Intel 核 = 2 vCPU 线程)。
而 Pigsty 提供国内顶尖的 PostgreSQL 专家服务,并采用 按节点计费 的模式,在当下常见的高核数服务器节点上,能为用户带来无可比拟的 降本增效 体验。
Pigsty专家服务 除了 Pigsty 订阅,Pigsty 还提供按需采购的 Pigsty x PostgreSQL 专家服务 —— 业界顶级数据库专家坐堂问诊。
专家顾问:300,000 ¥ / 三年
在三年内,提供 10 次关于 PostgreSQL 与 Pigsty 的复杂案例处理,以及不限量答疑。
专家支持:30,000 ¥ / 人·天
业界顶级专家现场支持,可用于架构咨询,故障分析,问题排查,数据库体检,监控解读,迁移评估,教学培训,上下云参谋等连续耗时场景。
专家咨询:3000 ¥ / 例
咨询任何您想要了解的问题,关于 Pigsty, PostgreSQL,数据库,云计算,AI……
数据库老司机,云计算泥石流与您分享行业顶级洞察、认知与研判。
挂专家号:300 ¥ / 问题
给出一个关于 PostgreSQL / Pigsty / 数据库相关的问题的快速诊断意见与答复,不超过 5 分钟。
联系方式 请发送邮件至 rh@vonng.com 。中国大陆地区用户欢迎添加微信号 RuohangFeng。
2.11 - 常见问题 解答关于 Pigsty 项目本身的常见问题。
Pigsty 是什么,不是什么? Pigsty 是一个 PostgreSQL 数据库发行版,本地优先的开源 RDS 云数据库解决方案。
Pigsty 不是数据库管理系统(DBMS),而是管理 DBMS 的工具,发行版,解决方案,与最佳实践。
类比:数据库是车,那么 DBA 是司机,RDS 是出租车服务,Pigsty 则是自动驾驶软件。
Pigsty 解决什么问题? 用好数据库的能力 极为稀缺:要么高薪聘请数据库专家自建(雇司机),或从云厂商以天价租赁 RDS(打车),但现在你有新的选项:Pigsty(自动驾驶)。
Pigsty 帮用户用好数据库:让用户在没有 DBA 的情况下,以不到 RDS 1 / 10 的成本,自建质量效率更优的本地云数据库服务!
Pigsty 的目标用户是谁? Pigsty 有两类典型目标用户,基本盘是 中大型公司 超大规模自建企业级/生产级 PostgreSQL RDS / DBaaS 服务。
Pigsty 通过极致的可定制性,可以实现最苛刻场景的数据库管理需求,并提供企业级的支持与服务保障。
与此同时,Pigsty 也针对个人开发者,缺乏 DBA 中小企业以及开源社区提供 “开箱即用” 的 PG RDS 自建方案。
Pigsty 为什么能帮您用好数据库? Pigsty 沉淀了顶尖专家在最复杂,最大规模的甲方 PostgreSQL 场景中打磨得到的经验与最佳实践,产品化为可复制的软件:
一次性解决扩展安装,高可用,链接池,监控,备份恢复,参数优化,IaC 批量管理,一键安装,自动化运维等诸多问题。提前规避诸多陷阱,避免重复踩坑。
Pigsty 为何比 RDS 好用? Pigsty 提供远超 RDS 的特性集与基础设施支持,包括 400+ 扩展插件与 8+ 内核支持。
Pigsty 提供 PG 生态中独一无二的专业级监控系统,与久经复杂场景打磨考验的架构最佳实践,简单易用。
且用探探,苹果,阿里等顶级甲方场景打磨而成,用激情与热爱持续浇灌,深度与成熟度绝非 RDS 大锅饭可比。
Pigsty 为何比 RDS 省钱? Pigsty 允许您使用 10 ¥/核·月的纯硬件资源,运行 400¥-1400¥/核·月的 RDS 云数据库,并省去 DBA 的工资。通常,成规模的 Pigsty 部署总拥有成本(TCO)能比 RDS 低 90% 以上。
Pigsty 能够同时降低软件许可/服务/人力的开销,自建无需加人,让您将成本花在刀刃上。
Pigsty 对研发有什么帮助? Pigsty 整合了 PG 生态最全的扩展(400+),提供了 All in PG 解决方案:单一组件替代 Redis, Kafka, MySQL, ES, 向量数据库, OLAP / 大数据分析等专用组件。
极大提高研发效能与敏捷性的同时降低复杂度成本,而且研发能在 Pigsty 的加持下实现自助管理,自主 DevOps,无需 DBA。
Pigsty 对运维有什么帮助? Pigsty 故障自愈的高可用架构确保硬件故障无需当场处理,让运维与 DBA 睡个好觉;监控助力问题分析与性能优化;IaC 赋能超大规模集群自动化管理。
运维在 Pigsty 加持下能兼职 DBA ,而 DBA 则可以跳过系统建设阶段,节省大量工时并专注于高价值工作,或喝茶看报,学习PG。
Pigsty 的作者是谁? Pigsty 主体由冯若航一人开发,这是一位专注于 PostgreSQL 领域 10 年的开源贡献者,数据库专家与布道师,
曾任职于阿里,探探,苹果,全栈专家。现为一人公司创始人,提供专业咨询服务。
同时他也是技术 KOL,微信数据库个人公众号榜首 《非法加冯》 的主理人,全网粉丝六万+。
Pigsty 的生态位与影响力如何? Pigsty 全球 PostgreSQL 生态中最有影响力的中国开源项目,共有约十万用户,一半来自海外。
Pigsty 也是 PostgreSQL 生态最活跃的开源项目之一,目前在扩展分发与监控系统上占据碾压性优势。
PGEXT.Cloud 是由 Pigsty 维护的 PostgreSQL 扩展仓库,拥有全球最多的 PostgreSQL 扩展分发量。
目前已经成为多家国际 PostgreSQL 厂商的软件供应链上游。
Pigsty 目前是 PostgreSQL 生态的主要发行版之一,也是云厂商 RDS 的挑战者,目前已经广泛应用于军工,政企,医疗,互联网,金融,制造业等各个行业。
Pigsty 适合什么规模的客户? Pigsty 源于超大规模 PostgreSQL 自动化管理的需求,但已针对易用性进行深度优化,缺乏专业 DBA 能力的个人开发者与中小型企业也可以轻松上手使用。
最大规模部署为 25K vCPU,450万QPS,六年+,最小规模部署可完整运行于 1c1g 虚拟机上作为 Demo / Devbox 使用。
Pigsty 提供哪些能力? Pigsty 专注于整合 PostgreSQL 生态,提供 PostgreSQL 的最佳实践,但同时也支持一系列与 PostgreSQL 配合良好的开源软件。例如:
Etcd, Redis, MinIO, DuckDB, Prometheus FerretDB, Babelfish, IvorySQL, PolarDB, OrioleDB OpenHalo, Supabase, Greenplum, Dify, Odoo, … Pigsty 适用于哪些场景? 运行大规模 PostgreSQL 集群用于业务 自建 RDS,对象存储,缓存,数仓,Supabase, … 自建 Odoo,Dify,Wiki,GitLab 等企业级应用 运行监控基础设施,监控现有数据库与主机 同时组合使用多种 PG 扩展插件 大屏开发与交互式数据应用 Demo,数据可视化,Web 建站 Pigsty 开源免费吗? Pigsty 是 100% 的开源软件 + 自由软件,在遵循开源许可证的前提下,您可以将其免费地,自由的用于各种商业目的。
我们珍视软件自由,对于非 DBaaS / OEM 用例,我们执行更为宽松的等效 Apache 2.0 许可证。请参阅许可证以获取更多详细信息。
Pigsty 提供商业支持吗? Pigsty 软件本身开源免费,并提供丰俭由人的商业订阅,为 Pigsty & PostgreSQL 提供质保。
订阅提供更宽广的 OS/PG/芯片架构支持范围,以及专家咨询与支持。
Pigsty 商业订阅交付业界顶尖的管理/技术经验/解决方案,
帮助您节省宝贵的时间,替您扛雷,并为疑难杂症兜底。
Pigsty 支持国产信创吗? Pigsty 软件本身不属于数据库,不受信创名录限制,且已有多个部队用例。但 Pigsty 开源版不提供任何形式的信创支持。
商业版订阅提供与阿里云合作的国产信创解决方案,支持使用具有信创资质的 PolarDB-O(需单独采购)作为 RDS 内核,能够运行于信创操作系统/芯片环境。
Pigsty 可以作为多租户 DBaaS 运行吗? 如果您使用了 Pigsty Infra 模块,并将其作为公有云数据库服务(DBaaS)的一部分进行分发或运营,
您可以在遵循开源许可证的前提下将其用于此目的。
如果您使用了 AGPLv3 许可证的模块,则额外受此约束。
我们保留对 公有云/数据库厂商 违反 AGPLv3 许可证进行追责的权利。
如果您不希望开源衍生作品,建议您选购 Pigsty 企业版订阅计划,
提供对此用例的清晰授权以及对于 Pigsty 可选 AGPLv3 模块开源义务的豁免。
Pigsty 可以换 Logo 贴牌为自己的产品吗? 再分发 Pigsty 时,您必须保留原作品中的版权声明、专利声明、商标声明和归属声明,
并且需要在修改的文件中附上显著的变更说明,同时保留 LICENSE 文件的内容。
在此前提下,您可以更换 PIGSTY 的 Logo 与商标,但不得宣传为 “自己原创的作品”。
我们在企业版本中提供对 OEM 与贴牌的商业授权支持。
Pigsty 的服务主体 Pigsty 是奇绩创坛 S22 被投项目,原主体 磐吉云数(北京)科技有限责任公司 已经清算剥离 Pigsty 业务,与 Pigsty 无关。
Pigsty 目前由作者冯若航个人独资运营维护,商业主体为:
海南诸夏云数据有限公司 / 91460000MAE6L87B94 海口龙华辟技数据中心 / 92460000MAG0XJ569B 海口龙华越航科技中心 / 92460000MACCYGBQ1N PIGSTY® 与 PGSTY® 为海口龙华越航科技中心的注册商标。
2.12 - 同类对比 本文列出了与 Pigsty 生态位有重叠的产品与项目,并比较其在特性上的差异。
与 RDS 对比 Pigsty 是使用 Apache-2.0 开源的本地优先 RDS 替代,可以部署在您自己的物理机/虚拟机上,也可以部署在云服务器上。
因此,我们选择了全球份额第一的亚马逊云 AWS RDS for PostgreSQL ,以及中国市场份额第一的阿里云 RDS for PostgreSQL 作为参照对象。
阿里云 RDS 与 AWS RDS 均为闭源云数据库服务,通过租赁模式,仅在公有云上对外提供,以下对比基于最新的 PostgreSQL 16 主干版本进行,对比截止日期为 2024 年 2 月份。
功能特性 指标 Pigsty Aliyun RDS AWS RDS 大版本支持 13 - 18 13 - 18 13 - 18 只读从库 支持任意数量只读从库 备实例不对用户开放 备实例不对用户开放读写分离 支持端口区分读写流量 独立收费组件 独立收费组件快慢分离 支持离线 ETL 实例 未见相关特性 未见相关特性异地灾备 支持备份集群 支持多可用区部署 支持多可用区部署延迟从库 支持延迟实例 未见相关特性 未见相关特性负载均衡 HAProxy / LVS 独立收费组件 独立收费组件连接池 Pgbouncer 独立收费组件:RDS 独立收费组件:RDS Proxy高可用 Patroni / etcd 需高可用版提供支持 需高可用版提供支持时间点恢复 pgBackRest / MinIO 提供备份支持 提供备份支持指标监控 Prometheus / Exporter 免费基础版/收费进阶版 免费基础版/收费进阶版日志采集 Loki / Promtail 基础支持 基础支持可视化系统 Grafana / Echarts 提供基本监控 提供基本监控告警聚合通知 AlterManager 基础支持 基础支持
重要扩展 这里列出了一些重要扩展,对比基于最新的 PostgreSQL 16 主干版本进行,截止至 2024-02-28
扩展名称 Pigsty RDS / PGDG 官方仓库阿里云 RDS AWS RDS 加装扩展 自由加装 不允许 不允许地理空间 PostGIS 3.4.2 PostGIS 3.3.4 / Ganos 6.1 PostGIS 3.4.1雷达点云 PG PointCloud 1.2.5 Ganos PointCloud 6.1向量嵌入 PGVector 0.6.1 / Svector 0.5.6 pase 0.0.1 PGVector 0.6机器学习 PostgresML 2.8.1时序扩展 TimescaleDB 2.14.2水平分布式 Citus 12.1列存扩展 Hydra 1.1.1全文检索 pg_bm25 0.5.6图数据库 Apache AGE 1.5.0GraphQL PG GraphQL 1.5.0OLAP pg_analytics 0.5.6消息队列 pgq 3.5.0DuckDB duckdb_fdw 1.1模糊分词 zhparser 1.1 / pg_bigm 1.2 zhparser 1.0 / pg_jieba pg_bigm 1.2CDC抽取 wal2json 2.5.3 wal2json 2.5膨胀治理 pg_repack 1.5.0 pg_repack 1.4.8 pg_repack 1.5.0
AWS RDS PG 可用扩展 AWS RDS for PostgreSQL 16 可用扩展(已刨除PG自带扩展)
name pg16 pg15 pg14 pg13 pg12 pg11 pg10 amcheck 1.3 1.3 1.3 1.2 1.2 yes 1 auto_explain yes yes yes yes yes yes yes autoinc 1 1 1 1 null null null bloom 1 1 1 1 1 1 1 bool_plperl 1 1 1 1 null null null btree_gin 1.3 1.3 1.3 1.3 1.3 1.3 1.2 btree_gist 1.7 1.7 1.6 1.5 1.5 1.5 1.5 citext 1.6 1.6 1.6 1.6 1.6 1.5 1.4 cube 1.5 1.5 1.5 1.4 1.4 1.4 1.2 dblink 1.2 1.2 1.2 1.2 1.2 1.2 1.2 dict_int 1 1 1 1 1 1 1 dict_xsyn 1 1 1 1 1 1 1 earthdistance 1.1 1.1 1.1 1.1 1.1 1.1 1.1 fuzzystrmatch 1.2 1.1 1.1 1.1 1.1 1.1 1.1 hstore 1.8 1.8 1.8 1.7 1.6 1.5 1.4 hstore_plperl 1 1 1 1 1 1 1 insert_username 1 1 1 1 null null null intagg 1.1 1.1 1.1 1.1 1.1 1.1 1.1 intarray 1.5 1.5 1.5 1.3 1.2 1.2 1.2 isn 1.2 1.2 1.2 1.2 1.2 1.2 1.1 jsonb_plperl 1 1 1 1 1 null null lo 1.1 1.1 1.1 1.1 1.1 1.1 1.1 ltree 1.2 1.2 1.2 1.2 1.1 1.1 1.1 moddatetime 1 1 1 1 null null null old_snapshot 1 1 1 null null null null pageinspect 1.12 1.11 1.9 1.8 1.7 1.7 1.6 pg_buffercache 1.4 1.3 1.3 1.3 1.3 1.3 1.3 pg_freespacemap 1.2 1.2 1.2 1.2 1.2 1.2 1.2 pg_prewarm 1.2 1.2 1.2 1.2 1.2 1.2 1.1 pg_stat_statements 1.1 1.1 1.9 1.8 1.7 1.6 1.6 pg_trgm 1.6 1.6 1.6 1.5 1.4 1.4 1.3 pg_visibility 1.2 1.2 1.2 1.2 1.2 1.2 1.2 pg_walinspect 1.1 1 null null null null null pgcrypto 1.3 1.3 1.3 1.3 1.3 1.3 1.3 pgrowlocks 1.2 1.2 1.2 1.2 1.2 1.2 1.2 pgstattuple 1.5 1.5 1.5 1.5 1.5 1.5 1.5 plperl 1 1 1 1 1 1 1 plpgsql 1 1 1 1 1 1 1 pltcl 1 1 1 1 1 1 1 postgres_fdw 1.1 1.1 1.1 1 1 1 1 refint 1 1 1 1 null null null seg 1.4 1.4 1.4 1.3 1.3 1.3 1.1 sslinfo 1.2 1.2 1.2 1.2 1.2 1.2 1.2 tablefunc 1 1 1 1 1 1 1 tcn 1 1 1 1 1 1 1 tsm_system_rows 1 1 1 1 1 1 1.1 tsm_system_time 1 1 1 1 1 1 1.1 unaccent 1.1 1.1 1.1 1.1 1.1 1.1 1.1 uuid-ossp 1.1 1.1 1.1 1.1 1.1 1.1 1.1
Aliyun RDS PG 可用扩展 阿里云 RDS for PostgreSQL 16 可用扩展(已刨除PG自带扩展)
name pg16 pg15 pg14 pg13 pg12 pg11 pg10 ali_desc bloom 1 1 1 1 1 1 1 提供一种基于布鲁姆过滤器的索引访问方法。 btree_gin 1.3 1.3 1.3 1.3 1.3 1.3 1.2 提供一个为多种数据类型和所有enum类型实现B树等价行为的GIN操作符类示例。 btree_gist 1.7 1.7 1.6 1.5 1.5 1.5 1.5 提供一个为多种数据类型和所有enum类型实现B树等价行为的GiST操作符类示例。 citext 1.6 1.6 1.6 1.6 1.6 1.5 1.4 提供一种大小写不敏感的字符串类型。 cube 1.5 1.5 1.5 1.4 1.4 1.4 1.2 提供一种数据类型来表示多维立方体。 dblink 1.2 1.2 1.2 1.2 1.2 1.2 1.2 跨库操作表。 dict_int 1 1 1 1 1 1 1 附加全文搜索词典模板的示例。 earthdistance 1.1 1.1 1.1 1.1 1.1 1.1 1.1 提供两种不同的方法来计算地球表面的大圆距离。 fuzzystrmatch 1.2 1.1 1.1 1.1 1.1 1.1 1.1 判断字符串之间的相似性和距离。 hstore 1.8 1.8 1.8 1.7 1.6 1.5 1.4 在单一PostgreSQL值中存储键值对。 intagg 1.1 1.1 1.1 1.1 1.1 1.1 1.1 提供一个整数聚集器和一个枚举器。 intarray 1.5 1.5 1.5 1.3 1.2 1.2 1.2 提供一些有用的函数和操作符来操纵不含空值的整数数组。 isn 1.2 1.2 1.2 1.2 1.2 1.2 1.1 按照一个硬编码的前缀列表对输入进行验证,也被用来在输出时连接号码。 ltree 1.2 1.2 1.2 1.2 1.1 1.1 1.1 用于表示存储在一个层次树状结构中的数据的标签。 pg_buffercache 1.4 1.3 1.3 1.3 1.3 1.3 1.3 提供一种方法实时检查共享缓冲区。 pg_freespacemap 1.2 1.2 1.2 1.2 1.2 1.2 1.2 检查空闲空间映射(FSM)。 pg_prewarm 1.2 1.2 1.2 1.2 1.2 1.2 1.1 提供一种方便的方法把数据载入到操作系统缓冲区或者PostgreSQL缓冲区。 pg_stat_statements 1.1 1.1 1.9 1.8 1.7 1.6 1.6 提供一种方法追踪服务器执行的所有SQL语句的执行统计信息。 pg_trgm 1.6 1.6 1.6 1.5 1.4 1.4 1.3 提供字母数字文本相似度的函数和操作符,以及支持快速搜索相似字符串的索引操作符类。 pgcrypto 1.3 1.3 1.3 1.3 1.3 1.3 1.3 为PostgreSQL提供了密码函数。 pgrowlocks 1.2 1.2 1.2 1.2 1.2 1.2 1.2 提供一个函数来显示一个指定表的行锁定信息。 pgstattuple 1.5 1.5 1.5 1.5 1.5 1.5 1.5 提供多种函数来获得元组层的统计信息。 plperl 1 1 1 1 1 1 1 提供perl过程语言。 plpgsql 1 1 1 1 1 1 1 提供SQL过程语言。 pltcl 1 1 1 1 1 1 1 提供tcl过程语言。 postgres_fdw 1.1 1.1 1.1 1 1 1 1 跨库操作表。 sslinfo 1.2 1.2 1.2 1.2 1.2 1.2 1.2 提供当前客户端提供的 SSL 证书的有关信息。 tablefunc 1 1 1 1 1 1 1 包括多个返回表的函数。 tsm_system_rows 1 1 1 1 1 1 1 提供表采样方法SYSTEM_ROWS。 tsm_system_time 1 1 1 1 1 1 1 提供了表采样方法SYSTEM_TIME。 unaccent 1.1 1.1 1.1 1.1 1.1 1.1 1.1 文本搜索字典,它能从词位中移除重音(附加符号)。 uuid-ossp 1.1 1.1 1.1 1.1 1.1 1.1 1.1 提供函数使用几种标准算法之一产生通用唯一标识符(UUID)。 xml2 1.1 1.1 1.1 1.1 1.1 1.1 1.1 提供XPath查询和XSLT功能。
性能对比 指标 Pigsty Aliyun RDS AWS RDS 最佳性能 PGTPC on NVME SSD 评测 sysbench oltp_rwRDS PG 性能白皮书 sysbench oltp 场景 每核 QPS 4000 ~ 8000存储规格:最高档容量 32TB / NVME SSD 32 TB / ESSD PL3 64 TB / io2 EBS Block Express 存储规格:最高档IOPS 4K随机读:最大3M,随机写 2000~350K 4K随机读:最大 1M 16K随机IOPS: 256K 存储规格:最高档延迟 4K随机读:75µs,随机写 15µs 4K随机读:200µs 500µs / 推断为16K随机IO 存储规格:最高档可靠性 UBER < 1e-18,折合18个9 MTBF: 200万小时 5DWPD,持续三年 可靠性 9个9, 合 UBER 1e-9 存储与数据可靠性 持久性 :99.999%,5个9 (0.001% 年故障率) io2 说明 存储规格:最高档成本 31.5 ¥/TB·月 ( 5年质保均摊 / 3.2T / 企业级 / MLC ) 3200¥/TB·月 (原价 6400¥,包月4000¥) 3年预付整体打5折才有此价格 1900 ¥/TB·月 使用最大规格 65536GB / 256K IOPS 最大优惠
可观测性 Pigsty 提供了近 3000 类监控指标,提供了 50+ 监控面板,覆盖了数据库监控、主机监控、连接池监控、负载均衡监控等方方面面,为用户提供无与伦比的可观测性体验。
Pigsty 提供了 638 与 PostgreSQL 有关的监控指标,而 AWS RDS 只有 99 个,阿里云 RDS 更是只有个位数指标:
此外,也有一些项目提供了监控 PostgreSQL 的能力,但都相对比较简单初级:
可维护性 指标 Pigsty Aliyun RDS AWS RDS 系统易用性 简单 简单 简单 配置管理 配置文件 / CMDB 基于 Ansible Inventory 可使用 Terraform 可使用 Terraform 变更方式 幂等剧本 基于 Ansible Playbook 控制台点击操作 控制台点击操作 参数调优 自动根据节点适配 四种预置模板 OLTP, OLAP, TINY, CRIT Infra as Code 原生支持 可使用 Terraform 可使用 Terraform 可定制参数点 Pigsty Parameters 283 个服务与支持 提供商业订阅支持兜底 提供售后工单支持 提供售后工单支持 无互联网部署 可离线安装部署 N/A N/A 数据库迁移 提供从现有v10+ PG实例基于逻辑复制不停机迁移至Pigsty托管实例的剧本 提供上云辅助迁移 Aliyun RDS 数据同步
成本 经验上看,软硬件资源的部分 RDS 单位成本是自建的 5 ~ 15 倍,租售比通常在一个月。详情请参考 成本分析 。
要素 指标 Pigsty Aliyun RDS AWS RDS 成本 软件授权/服务费用 免费,硬件约 20 - 40 ¥/核·月 200 ~ 400 ¥/核·月 400 ~ 1300 ¥/核·月 服务支持费用 服务约 100 ¥/ 核·月 包含在 RDS 成本中
其他本地数据库管控软件 一些提供管理 PostgreSQL 能力的软件与供应商
其他 Kubernetes Operator Pigsty 拒绝在生产环境中使用 Kubernetes 管理数据库,因此与这些方案在生态位上存在差异。
PGO StackGres CloudNativePG TemboOperator PostgresOperator PerconaOperator Kubegres KubeDB KubeBlocks 更多信息请参阅:
2.12.1 - 成本对比 本文提供了一组成本数据,供您评估 Pigsty 自建,使用云数据库 RDS 所需的成本,以及常规的 DBA 薪酬参考。
总体概览 EC2 核·月 RDS 核·月 DHH 自建核月价格(192C 384G) 25.32 初级开源数据库DBA参考工资 15K/人·月 IDC自建机房(独占物理机: 64C384G) 19.53 中级开源数据库DBA参考工资 30K/人·月 IDC自建机房(容器,超卖500%) 7 高级开源数据库DBA参考工资 60K/人·月 UCloud 弹性虚拟机(8C16G,有超卖) 25 ORACLE 数据库授权 10000 阿里云 弹性服务器 2x内存(独占无超卖) 107 阿里云 RDS PG 2x内存(独占) 260 阿里云 弹性服务器 4x内存(独占无超卖) 138 阿里云 RDS PG 4x内存(独占) 320 阿里云 弹性服务器 8x内存(独占无超卖) 180 阿里云 RDS PG 8x内存(独占) 410 AWS C5D.METAL 96C 200G (按月无预付) 100 AWS RDS PostgreSQL db.T2 (2x) 440 AWS C5D.METAL 96C 200G (预付三年) 80 AWS RDS PostgreSQL db.M5 (4x) 611 AWS C7A.METAL 192C 384G (预付三年) 104.8 AWS RDS PostgreSQL db.R6G (8x) 786
RDS成本参考 付费模式 价格 折合每年(万¥) IDC自建(单物理机) ¥7.5w / 5年 1.5 IDC自建(2~3台组HA) ¥15w / 5年 3.0 ~ 4.5 阿里云 RDS 按需 ¥87.36/时 76.5 阿里云 RDS 月付(基准) ¥4.2w / 月 50 阿里云 RDS 年付(85折) ¥425095 / 年 42.5 阿里云 RDS 3年付(5折) ¥750168 / 3年 25 AWS 按需 $25,817 / 月 217 AWS 1年不预付 $22,827 / 月 191.7 AWS 3年全预付 12w$ + 17.5k$/月 175 AWS 中国/宁夏按需 ¥197,489 / 月 237 AWS 中国/宁夏1年不预付 ¥143,176 / 月 171 AWS 中国/宁夏3年全预付 ¥647k + 116k/月 160.6
我们可以对比一下自建与云数据库的成本差异:
方式 折合每年(万元) IDC托管服务器 64C / 384G / 3.2TB NVME SSD 660K IOPS (2~3台) 3.0 ~ 4.5 阿里云 RDS PG 高可用版 pg.x4m.8xlarge.2c, 64C / 256GB / 3.2TB ESSD PL3 25 ~ 50 AWS RDS PG 高可用版 db.m5.16xlarge, 64C / 256GB / 3.2TB io1 x 80k IOPS 160 ~ 217
ECS 成本参考 排除 NVMe SSD / ESSD PL3 后的纯算力价格对比 以阿里云为例,纯算力包月模式的价格是自建基准的 5 ~ 7 倍,预付五年的价格是自建的 2 倍
付费模式 单价(¥/核·月) 相对于标准价格 自建溢价倍率 按量付费(1.5倍) ¥ 202 160 % 9.2 ~ 11.2 包月(标准价格) ¥ 126 100 % 5.7 ~ 7.0 预付一年(65折) ¥ 83.7 66 % 3.8 ~ 4.7 预付二年(55折) ¥ 70.6 56 % 3.2 ~ 3.9 预付三年(44折) ¥ 55.1 44 % 2.5 ~ 3.1 预付四年(35折) ¥ 45 35 % 2.0 ~ 2.5 预付五年(30折) ¥ 38.5 30 % 1.8 ~ 2.1 DHH @ 2023 ¥ 22.0 探探 IDC 自建 ¥ 18.0
含 NVMe SSD / ESSD PL3 情况下的等效价格对比 包含常用规格后的 NVMe SSD 规格之后,纯算力包月模式的价格是自建基准的 11 ~ 14 倍,预付五年的价格是自建的 9 倍左右。
付费模式 单价(¥/核·月) + 40GB ESSD PL3 自建溢价比例 按量付费(1.5倍) ¥ 202 ¥ 362 14.3 ~ 18.6 包月(标准价格) ¥ 126 ¥ 286 11.3 ~ 14.7 预付一年(65折) ¥ 83.7 ¥ 244 9.6 ~ 12.5 预付二年(55折) ¥ 70.6 ¥ 230 9.1 ~ 11.8 预付三年(44折) ¥ 55.1 ¥ 215 8.5 ~ 11.0 预付四年(35折) ¥ 45 ¥ 205 8.1 ~ 10.5 预付五年(30折) ¥ 38.5 ¥ 199 7.9 ~ 10.2 DHH @ 2023 ¥ 25.3 探探 IDC 自建 ¥ 19.5
DHH案例:192核配12.8TB Gen4 SSD (1c:66);探探案例: 64核配3.2T Gen3 MLC SSD (1c:50)。
云上价格每核配比40GB ESSD PL3(1核:4x内存:40x磁盘)计算。
EBS成本参考 评估因素 本地 PCI-E NVME SSD Aliyun ESSD PL3 AWS io2 Block Express 容量 32TB 32 TB 64 TB IOPS 4K随机读:600K ~ 1.1M 4K随机写 200K ~ 350K 4K随机读:最大 1M 16K随机IOPS: 256K 延迟 4K随机读:75µs 4K随机写:15µs 4K 随机读: 200µs 随机IO:500µs 上下文推断为16K 可靠性 UBER < 1e-18,折合18个9 MTBF: 200万小时 5DWPD,持续三年 数据可靠性 9个9 存储与数据可靠性 持久性 :99.999%,5个9 (0.001% 年故障率) io2 说明 成本 **16 ¥/TB·**月 ( 5年均摊 / 3.2T MLC ) 5 年质保,¥3000 零售 **3200¥/TB·**月 (原价 6400¥,包月4000¥) 3年预付整体打5折才有此价格 **1900 ¥/TB·**月 使用最大规格 65536GB 256K IOPS 最优惠状态 SLA 5年质保 出问题直接换新 Aliyun RDS SLA 可用性 99.99%: 月费 15% 99%: 月费 30% 95%: 月费 100%Amazon RDS SLA 可用性 99.95%: 月费 15% 99%: 月费 25% 95%: 月费 100%
S3成本参考 Date $/GB·月 ¥/TB·5年 HDD ¥/TB SSD ¥/TB 2006 .030.150 63000 2800 2010 .110.140 58800 1680 2012 .120.095 39900 420 15400 2014 .040.030 12600 371 9051 2016 .120.023 9660 245 3766 2023 .120.023 9660 105 280 其他参考价 高性能存储 顶配底折价 与采购NVMe SSD 价格参考 S3 Express 0.160 67200 DHH 12T 1400 EBS io2 0.125 + IOPS 114000 Shannon 3.2T 900
下云合集 曾几何时,“上云 “近乎成为技术圈的政治正确,整整一代应用开发者的视野被云遮蔽。就让我们用实打实的数据分析与亲身经历,讲清楚公有云租赁模式的价值与陷阱 —— 在这个降本增效的时代中,供您借鉴与参考 —— 请看 《云计算泥石流:合订本 》
云基础资源篇
云商业模式篇
下云奥德赛篇
云故障复盘篇
RDS翻车篇
云厂商画像篇
2.13 - 发布注记 Pigsty 历史版本发布说明
Pigsty 当前的最新稳定版本为 v3.7.0 ,最新的测试版本为 v4.0.0-b3 。
版本 发布日期 摘要 发布页面 v4.0.0 2026-01-31 Infra 重构,安全加固,快速克隆,Agent 能力 v4.0.0 v3.7.0 2025-12-02 PG18 成为默认,437 个扩展,EL10 与 Debian13 支持,PGEXT.CLOUD v3.7.0 v3.6.1 2025-08-15 例行 PG 小版本更新,PGDG 中国区域镜像,EL9,D13 存根 v3.6.0 v3.6.0 2025-07-30 pgactive,MinIO / ETCD 改进,安装简化,配置梳理 v3.6.0 v3.5.0 2025-06-16 PG18 beta,421 扩展,监控升级,代码重构 v3.5.0 v3.4.1 2025-04-05 OpenHalo & OrioleDB,MySQL兼容,pgAdmin改进 v3.4.1 v3.4.0 2025-03-30 备份改进,自动证书,AGE,Ivory 全平台,本地化,架构与参数改进 v3.4.0 v3.3.0 2025-02-24 404 扩展,扩展目录,App 剧本,Nginx 定制,DocumentDB 支持 v3.3.0 v3.2.2 2025-01-23 390扩展,Omnigres支持,Mooncake,Citus13与PG17支持 v3.2.2 v3.2.1 2025-01-12 350扩展,Ivory4,Citus强化,Odoo模板 v3.2.1 v3.2.0 2024-12-24 扩展管理 CLI ,Grafana 强化,ARM64 扩展补完 v3.2.0 v3.1.0 2024-11-24 PG 17 升默认大版本,配置简化,Ubuntu24与ARM 支持,Supabase,MinIO 改进 v3.1.0 v3.0.4 2024-10-30 PG 17 扩展,OLAP 全家桶,pg_duckdb v3.0.4 v3.0.3 2024-09-27 PostgreSQL 17,Etcd 运维优化,IvorySQL 3.4,PostGIS 3.5 v3.0.3 v3.0.2 2024-09-07 精简安装模式,PolarDB 15支持,监控视图更新 v3.0.2 v3.0.1 2024-08-31 例行问题修复,Patroni 4支持,Oracle兼容性改进 v3.0.1 v3.0.0 2024-08-25 333个扩展插件,可插拔内核,MSSQL,Oracle,PolarDB 兼容性 v3.0.0 v2.7.0 2024-05-20 扩展大爆炸,新增20+强力扩展插件,与多款Docker应用 v2.7.0 v2.6.0 2024-02-28 PG 16 作为默认大版本,引入 ParadeDB 与 DuckDB 等扩展 v2.6.0 v2.5.1 2023-12-01 例行小版本更新,PG16重要扩展支持 v2.5.1 v2.5.0 2023-09-24 Ubuntu/Debian支持:bullseye, bookworm, jammy, focal v2.5.0 v2.4.1 2023-09-24 Supabase/PostgresML支持与各种新扩展:graphql, jwt, pg_net, vault v2.4.1 v2.4.0 2023-09-14 PG16,监控RDS,服务咨询支持,新扩展:中文分词全文检索/图/HTTP/嵌入等 v2.4.0 v2.3.1 2023-09-01 带HNSW的PGVector,PG 16 RC1, 文档翻新,中文文档,例行问题修复 v2.3.1 v2.3.0 2023-08-20 主机VIP, ferretdb, nocodb, MySQL存根, CVE修复 v2.3.0 v2.2.0 2023-08-04 仪表盘 & 置备重做,UOS 兼容性 v2.2.0 v2.1.0 2023-06-10 支持 PostgreSQL 12 ~ 16beta v2.1.0 v2.0.2 2023-03-31 新增 pgvector 支持,修复 MinIO CVE v2.0.2 v2.0.1 2023-03-21 v2 错误修复,安全增强,升级 Grafana 版本 v2.0.1 v2.0.0 2023-02-28 架构大升级,兼容性、安全性、可维护性显著增强 v2.0.0 v1.5.1 2022-06-18 Grafana 安全性修复 v1.5.1 v1.5.0 2022-05-31 Docker 应用程序支持 v1.5.0 v1.4.1 2022-04-20 错误修复 & 英文文档完整翻译 v1.4.1 v1.4.0 2022-03-31 MatrixDB 支持,分离 INFRA/NODES/PGSQL/REDIS模块 v1.4.0 v1.3.0 2021-11-30 PGCAT 重整 & PGSQL 增强 & Redis Beta支持 v1.3.0 v1.2.0 2021-11-03 默认 PGSQL 版本升级至 14 v1.2.0 v1.1.0 2021-10-12 主页, JupyterLab, PGWEB, Pev2 & pgbadger v1.1.0 v1.0.0 2021-07-26 v1 正式版, 监控系统重整 v1.0.0 v0.9.0 2021-04-04 Pigsty 图形界面, 命令行界面, 日志集成 v0.9.0 v0.8.0 2021-03-28 服务置备,定制对外暴露的数据库服务 v0.8.0 v0.7.0 2021-03-01 仅监控部署,监控现有 PostgreSQL 实例 v0.7.0 v0.6.0 2021-02-19 架构增强,将PG与Consul解耦 v0.6.0 v0.5.0 2021-01-07 支持在配置中定义业务数据库/用户 v0.5.0 v0.4.0 2020-12-14 支持 PostgreSQL 13,添加官方文档 v0.4.0 v0.3.0 2020-10-22 虚拟机置备方案正式定稿 v0.3.0 v0.2.0 2020-07-10 PG监控系统第六版正式发布 v0.2.0 v0.1.0 2020-06-20 在生产仿真测试环境中验证通过 v0.1.0 v0.0.5 2020-08-19 离线安装模式:无需互联网访问即可交付 v0.0.5 v0.0.4 2020-07-27 将 Ansible 剧本重构为 Role v0.0.4 v0.0.3 2020-06-22 接口设计改进 v0.0.3 v0.0.2 2020-04-30 首次提交 v0.0.2 v0.0.1 2019-05-15 概念原型 v0.0.1
v4.0.0-b3 (WIP) curl https://pigsty.cc/get | bash
GitHub Release: https://github.com/pgsty/pigsty/releases/tag/v4.0.0-b3
亮点
Infra 模块彻底翻新,Victoria 可观测性全家桶带来 10x 性能提升! 日志方案升级为 VictoriaLogs + Vector,性能、易用性史诗级加强! Pigsty UI 集成,带来浑然一体的 UI 使用体验。 全局安全性提升,防火墙 SELinux 权限加固 Docker 容器版本,可供快速评估试用 提供瞬间克隆数据库的能力 软件版本
基础设施软件包
其中 MinIO 开始使用 pgsty 自身维护打包的 RPM/DEB
grafana : 12.3.1 alertmanager : 0.30.0 victoria-metrics : 1.132.0 victoria-logs : 1.43.1 blackbox_exporter : 0.28.0 duckdb : 1.4.3 etcd : 3.6.7 rclone : 1.72.1 pev2 : 1.19.0 pg_exporter : 1.1.0 pgbackrest_exporter : 0.22.0 pig : 0.8.1 rclone : 1.72.1 vector : 0.52.0 genai-toolbox : 0.23.0 minio : 20251203120000 uv : 0.9.18 new package ccm (claude mgr) : 2.0.76 PG 扩展软件包
IvorySQL : 5.0 -> 5.1 pg_textsearch : 0.1.0 新扩展pg_clickhouse : 0.1.0 新扩展pg_ai_query : 0.1.1 新扩展timescaledb : 2.23.1 -> 2.24.0 pg_search : 0.20.0 -> 0.20.4 pg_duckdb : 1.1.0 -> 1.1.1 ,官方正式发布版本 pg_biscuit : 1.0 -> 2.0.1 ,仓库重命名 pg_convert : 0.0.4 -> 0.0.5 ,移除 PG 13 支持 pgdd : 0.6.0 -> 0.6.1 ,移除 PG 13 支持 pglinter : 1.0.0 -> 1.0.1 pg_session_jwt : 0.3.3 -> 0.4.0 pg_anon : 2.4.1 -> 2.5.1 pg_enigma : 0.4.0 -> 0.5.0 wrappers : 0.5.6 -> 0.5.7 pg_vectorize : 0.25.0 -> 0.26.0 vchord_bm25 : 0.2.2 -> 0.3.0 pg_timeseries : 0.1.7 -> 0.1.8 修复 PG 18 Deb 包:pg_vectorize ,pg_tiktoken ,pg_tzf ,pglite_fusion ,pgsmcrypto ,pgx_ulid ,plprql ,pg_summarize ,supautils
可观测性
使用全新的 VictoriaMetrics 替代 Prometheus,用几分之一的资源实现几倍的性能。 使用全新的日志收集方案:VictoriaLogs + Vector,取代 Promtail + Loki。 统一调整了所有组件的日志格式,PG 日志使用 UTC 时间戳(log_timezone) 调整了 PostgreSQL 日志的轮换方式,使用按周循环截断日志轮转模式 在 PG 日志中记录超过 1MB 的临时文件分配,在特定模版中启用 PG 17/18 日志新参数 新增了 Nginx Access & Error / Syslog / PG CSV / Pgbackrest 的 vector 日志解析配置 注册数据源现在会在所有 Infra 节点上进行,Victoria 数据源将自动注册入 Grafana 新增 grafana_pgurl 参数,允许指定 Grafana 使用 PG 作为后端存储元数据库 新增 grafana_view_pgpass 参数,指定 Grafana Meta 数据源使用的密码 pgbackrest_exporter 的默认选项现在将设置一个 120秒的内部缓存间隔(原本为 600s)。grafana_clean 参数的默认值现在由 true 改为 false,即默认不清除。新增指标收集器 pg_timeline,收集更实时的时间线指标 pg_timeline_id pg_exporter 更新至 1.1.0,修复大量历史遗留问题。接口改进
install.yml 剧本现在重命名为 deploy.yml 以更符合语义。pg_databases 数据库制备功能改进添加删库能力:可以使用 state 字段指定 create, absent, recreate 三种状态。 添加克隆能力:数据库定义中使用 strategy 参数指定克隆方法 支持较新版本引入的 locale 配置参数:locale_provider,icu_locale,icu_rules,builtin_locale 支持 is_tepmlate 参数,将数据库标记为模板数据库 添加了更多类型检查,避免了字符类参数的注入 允许在 extension 中指定 state: absent 以删除扩展 pg_users 用户制备功能改进,新增参数 admin,类似 roles,但是带有 ADMIN OPTION 权限可以转授。参数优化
pg_io_method 参数,auto, sync, worker, io_uring, 四种方式可选,默认 workeridle_replication_slot_timeout, 默认 7d, crit 模板 3dlog_lock_failures,oltp,crit 模版开启track_cost_delay_timing,olap,crit 模版开启log_connections,oltp/olap 开启认证日志,crit 开启全部日志。maintenance_io_concurrency 设置为 100,如果使用 SSDeffective_io_concurrency 从 1000 减小为 200file_copy_method 参数为 PG18 默认设置为 clone,提供瞬间克隆数据库的能力对于 PG17+,如果 pg_checksums 开关关闭,在 patroni 初始化集群时显式禁用校验和 修复了 duckdb.allow_community_extensions 总是生效的问题 允许通过 node_firewall_intranet 指定 HBA 信任的 “内网网段” 现在 pg_hba 与 pgbouncer_hba 支持 IPv6 的 localhost 访问 架构改进
在 Infra 节点上,设置固定的 /infra 软连接指向 Infra 数据目录 /data/infra。 现在 infra 的数据默认放置于 /data/infra 目录下,这使得在容器中使用更为便利。 本地软件仓库现在放置于 /data/nginx/pigsty, /www 现在作为软链接指向 /data/nginx 确保兼容。 DNS 解析记录现在放置于 /infra/hosts 目录下,解决了 Ansible SELinux 竞态问题 pg_remove/pg_pitr 移除 etcd 元数据的任务,现在不再依赖 admin_ip 管理节点,而在 etcd 集群上执行 36 节点仿真模板 simu 简化为 20 节点的版本。 适配上游变化,移除 PGDG sysupdate 仓库,移除 EL 系统上所有 llvmjit 的相关包 为 EPEL 10 / PGDG 9/10 仓库使用操作系统完整版本号(major.minor) 允许在仓库定义中指定 meta 参数,覆盖 yum 仓库的定义元数据 新增了 /pg/bin/pg-fork 脚本,用于快速创建 CoW 副本数据库实例 调整 /pg/bin/pg-pitr 脚本,现在可以用于实例级别的 PITR 恢复 确保 vagrant libvirt 模板默认带有 128GB 磁盘,以 xfs 挂载于 /data 。 确保 pgboucner 不再将 0.0.0.0 监听地址修改为 *。 安全改进
configure 现在会自动生成随机强密码,避免使用默认密码带来的安全隐患。移除 node_disable_firewall,新增 node_firewall_mode,支持 off, none, zone 三种模式。 移除 node_disable_selinux,新增 node_selinux_mode,支持 disabled, permissive, enforcing 三种模式。 新增 nginx basic auth 支持,可以为 Nginx Server 设置可选的 HTTP Basic Auth。 修复 ownca 证书有效期问题,确保了 Chrome 可以识别自签名证书。 更改了 MinIO 模块的默认密码,避免与众所周知的默认密码冲突- 启用了针对 etcd 的 RBAC,每个集群现在只能管理自己的 PostgreSQL 数据库集群。 etcd root 密码现在放置于 /etc/etcd/etcd.pass 文件中,仅对管理员可读 为 HAProxy,Nginx,DNSMasq,Redis 等组件配置了正确的 SELinux 上下文 收回了所有非 root 用户对可执行脚本的拥有权限 将 admin_ip 添加到 Patroni API 允许访问的 IP 列表白名单中 总是创建 admin 系统用户组,patronictl 配置收紧为仅限 admin 组用户访问 新增 node_admin_sudo 参数,允许指定/调整数据库管理员的 sudo 权限模式(all/nopass) 修复了若干 ansible copy content 字段为空时报错的问题。 修复了 pg_pitr 中遗留的一些问题,确保 patroni 集群恢复时没有竞态条件。 v3.7.0 亮点特性
PostgreSQL 18 深度支持,成为默认 PG 大版本,扩展已就位! 新增 EL10 / Debian 13 操作系统支持,总数达 14 个! 新增 PostgresQL 扩展数量,总数达到 437 个! 支持了 Ansible 2.19 破坏性重构以后的版本! Supabase,PolarDB, IvorySQL, Percona 内核更新至最新版本! 优化了 PG 默认参数的设置逻辑,更充分利用资源。 版本更新
PostgreSQL 18.1, 17.7, 16.11, 15.15, 14.20, 13.23 Patroni 4.1.0 Pgbouncer 1.25.0 pg_exporter 1.0.3 pgbackrest 2.57.0 Supabase 2025-11 PolarDB 15.15.5.0 FerretDB 2.7.0 DuckDB 1.4.2 Etcd 3.6.6 pig 0.7.4 更多软件版本更新信息,请参考:
API变化
为并行执行的相关参数设置了更合理的优化策略,详见 调参说明 在 rich 与 full 模板中,不再默认安装 citus 扩展,因为 citus 尚未支持 PG 18 PG 参数模板中,新增 duckdb 系列扩展存根。 为 min_wal_size, max_wal_size, max_slot_wal_keep_size 设置 200,2000,3000 GB 的封顶上限值。 为 temp_file_limit 设置 200 GB 的封顶上限,OLAP 设置为 2 TB。 适当增大连接池默认链接数量 新增 prometheus_port 参数,且默认值为 9058,避开与 EL10 RHEL Web Console 端口的冲突。 修改 alertmanager_port 参数的默认值为 9059,避开与 Kafka SSL 端口的潜在冲突。 新增 pg_pkg 的 pg_pre 子任务,在安装 PG 包前移除 el9+ 上导致 LLVM 冲突的 bpftool, python3-perf 在 Debian / Ubuntu 的默认仓库定义中新增 llvm 仓库模块 修复了 infra-rm.yml 移除软件包的逻辑 兼容性修复
修复了 Ubuntu/Debian 信任 CA 时 Warning 返回码错误的问题。 修复了 Ansible 2.19 引入的大量兼容性问题,确保在新老版本上正常运行。 为 seq 类变量添加了 int 类型转换,确保兼容 将大量 with_items 修改为 loop 语法,确保兼容 为密钥交换变量添加一层列表嵌套,避免在新版本下针对字符串进行字符迭代。 将 range 用例显式转换为 list 后使用 修改了 name,port 等标记保留的变量命名 将 play_hosts 修改为 ansible_play_hosts 为部分字符串类型添加了 string 强制类型转换,避免运行时错误。 EL10 逻辑适配: 修复了 EL10 缺少 ansible-collection-community-crypto 无法生成密钥的问题 修复了 EL10 缺少 ansible 逻辑包的问题 移除 modulemd_tools flamegraph timescaledb-tool 使用 java-21-openjdk 替代 java-17-openjdk aarch64 YUM 仓库名称问题 Debian 13 逻辑适配 使用 bind9-dnsutils 替代 dnsutils Ubuntu 24 修复 临时移除了上游依赖崩溃的 tcpdump 包 校验和
e00d0c2ac45e9eff1cc77927f9cd09df pigsty-v3.7.0.tgz
987529769d85a3a01776caefefa93ecb pigsty-pkg-v3.7.0.d12.aarch64.tgz
2d8272493784ae35abeac84568950623 pigsty-pkg-v3.7.0.d12.x86_64.tgz
090cc2531dcc25db3302f35cb3076dfa pigsty-pkg-v3.7.0.d13.x86_64.tgz
ddc54a9c4a585da323c60736b8560f55 pigsty-pkg-v3.7.0.el10.aarch64.tgz
d376e75c490e8f326ea0f0fbb4a8fd9b pigsty-pkg-v3.7.0.el10.x86_64.tgz
8c2deeba1e1d09ef3d46d77a99494e71 pigsty-pkg-v3.7.0.el8.aarch64.tgz
9795e059bd884b9d1b2208011abe43cd pigsty-pkg-v3.7.0.el8.x86_64.tgz
08b860155d6764ae817ed25f2fcf9e5b pigsty-pkg-v3.7.0.el9.aarch64.tgz
1ac430768e488a449d350ce245975baa pigsty-pkg-v3.7.0.el9.x86_64.tgz
e033aaf23690755848db255904ab3bcd pigsty-pkg-v3.7.0.u22.aarch64.tgz
cc022ea89181d89d271a9aaabca04165 pigsty-pkg-v3.7.0.u22.x86_64.tgz
0e978598796db3ce96caebd76c76e960 pigsty-pkg-v3.7.0.u24.aarch64.tgz
48223898ace8812cc4ea79cf3178476a pigsty-pkg-v3.7.0.u24.x86_64.tgz
v3.6.1 curl https://repo.pigsty.cc/get | bash -s v3.6.1
亮点特性
PostgreSQL 17.6, 16.10, 15.14, 14.19, 13.22, 以及 18 Beta 3 支持 在中国大陆地区使用 Pigsty 提供的 PGDG APT/YUM 镜像解决更新断供问题。 新的网站首页: https://pgsty.com 增加了 el10, debian 13 的实现存根,以及 el10 的 Terraform 镜像 基础设施软件包更新
Grafana 12.1.0 pg_exporter 1.0.2 pig 0.6.1 vector 0.49.0 redis_exporter 1.75.0 mongo_exporter 0.47.0 victoriametrics 1.123.0 victorialogs: 1.28.0 grafana-victoriametrics-ds 0.18.3 grafana-victorialogs-ds 0.19.3 grafana-infinity-ds 3.4.1 etcd 3.6.4 ferretdb 2.5.0 tigerbeetle 0.16.54 genai-toolbox 0.12.0 数据库软件包更新
API变更
从 node_kernel_modules 默认值中移除 br_filter 内核模块。 在添加 PGDG YUM 源时使用操作大版本号,不再使用小版本号。 校验和
045977aff647acbfa77f0df32d863739 pigsty-pkg-v3.6.1.d12.aarch64.tgz
636b15c2d87830f2353680732e1af9d2 pigsty-pkg-v3.6.1.d12.x86_64.tgz
700a9f6d0db9c686d371bf1c05b54221 pigsty-pkg-v3.6.1.el8.aarch64.tgz
2aff03f911dd7be363ba38a392b71a16 pigsty-pkg-v3.6.1.el8.x86_64.tgz
ce07261b02b02b36a307dab83e460437 pigsty-pkg-v3.6.1.el9.aarch64.tgz
d598d62a47bbba2e811059a53fe3b2b5 pigsty-pkg-v3.6.1.el9.x86_64.tgz
13fd68752e59f5fd2a9217e5bcad0acd pigsty-pkg-v3.6.1.u22.aarch64.tgz
c25ccfb98840c01eb7a6e18803de55bb pigsty-pkg-v3.6.1.u22.x86_64.tgz
0d71e58feebe5299df75610607bf428c pigsty-pkg-v3.6.1.u24.aarch64.tgz
4fbbab1f8465166f494110c5ec448937 pigsty-pkg-v3.6.1.u24.x86_64.tgz
083d8680fa48e9fec3c3fcf481d25d2f pigsty-v3.6.1.tgz
v3.6.0 curl https://repo.pigsty.cc/get | bash -s v3.6.0
亮点特性
全新文档站: https://doc.pgsty.com 新增 pgsql-pitr 剧本与备份/恢复教程,改善 PITR 体验, 新增内核支持:Percona PG TDE (PG17) 优化 Supabase 自建体验,更新至最新版本,并解决了一系列官方模板的问题 简化安装步骤,默认使用在线安装,更加高效简单,bootstrap 过程(安装ansible)嵌入安装脚本中 设计改进
改善了 Etcd 模块的实现,新增独立的 etcd-rm.yml 剧本与扩缩容 SOP 脚本。 改善了 MinIO 模块的实现,支持 HTTP 模式,创建不同属性的三个桶供开箱即用 重新调整梳理了所有配置模板,使用更为便利 针对中国大陆使用速度更快的 Docker Registry 镜像站 优化了 tuned 操作系统参数模板,针对现代硬件与 NVMe 磁盘优化 新增扩展 pgactive 用于多主复制与亚秒级故障切换 调整 pg_fs_main / pg_fs_backup 默认值,简化文件目录结构设计 问题修复
修复了 pgbouncer 配置文件的错误 by @housei-zzy 修复了 OrioleDB 在 Debian 平台上的问题 修复了 tuned shm 配置参数的问题 离线软件包直接使用 PGDG 源,避免使用断开同步的镜像站点 修复了 IvorySQL libxcrypt 依赖的问题 替换了破损与缓慢的 EPEL 软件仓库站点 修复了 haproxy_enabled 标记位的功能 基础设施软件包更新
新增 Victoria Metrics / Victoria Logs 相关包
genai-toolbox 0.9.0 (new) victoriametrics 1.120.0 -> 1.121.0 (重构) vmutils 1.121.0 (重命名 victoria-metrics-utils) grafana-victoriametrics-ds 0.15.1 -> 0.17.0 victorialogs 1.24.0 -> 1.25.1 (重构) vslogcli 1.24.0 -> 1.25.1 vlagent 1.25.1 (新增) grafana-victorialogs-ds 0.16.3 -> 0.18.1 prometheus 3.4.1 -> 3.5.0 grafana 12.0.0 -> 12.0.2 vector 0.47.0 -> 0.48.0 grafana-infinity-ds 3.2.1 -> 3.3.0 keepalived_exporter 1.7.0 blackbox_exporter 0.26.0 -> 0.27.0 redis_exporter 1.72.1 -> 1.77.0 rclone 1.69.3 -> 1.70.3 数据库软件包更新
PostgreSQL 18 Beta2 更新 pg_exporter 1.0.1,更新至最新依赖并提供 Docker 镜像 pig 0.6.0,更新了最新扩展与仓库列表,带有 pig install 子命令 vip-manager 3.0.0 -> 4.0.0 ferretdb 2.2.0 -> 2.3.1 dblab 0.32.0 -> 0.33.0 duckdb 1.3.1 -> 1.3.2 etcd 3.6.1 -> 3.6.3 ferretdb 2.2.0 -> 2.4.0 juicefs 1.2.3 -> 1.3.0 tigerbeetle 0.16.41 -> 0.16.50 pev2 1.15.0 -> 1.16.0 PG扩展包更新
OrioleDB 1.5 beta12 OriolePG 17.11 plv8 3.2.3 -> 3.2.4 postgresql_anonymizer 2.1.1 -> 2.3.0 pgvectorscale 0.7.1 -> 0.8.0 wrappers 0.5.0 -> 0.5.3 supautils 2.9.1 -> 2.10.0 citus 13.0.3 -> 13.1.0 timescaledb 2.20.0 -> 2.21.1 vchord 0.3.0 -> 0.4.3 pgactive 2.1.5 (new) documentdb 0.103.0 -> 0.105.0 pg_search 0.17.0 API变更
pg_fs_backup:重命名为 pg_fs_backup,默认值为 /data/backups。pg_rm_bkup:重命名为 pg_rm_backup,默认值为 true。pg_fs_main:现在默认值调整为 /data/postgres。nginx_cert_validity:新增参数,用于控制 Nginx 自签名证书的有效期,默认为 397d。minio_buckets:默认值调整为创建名为 pgsql、meta、data 的三个桶。minio_users:移除 dba 用户,新增 s3user_meta 和 s3user_data 用户,分别对应 meta 和 data 桶。minio_https:新增参数,允许配置 MinIO 使用 HTTP 模式。minio_provision:新增参数,允许跳过 MinIO 置备阶段(跳过桶和用户的创建)。minio_safeguard:新增参数,启用后会在执行 minio-rm.yml 时中止操作。minio_rm_data:新增参数,控制在执行 minio-rm.yml 时是否删除 minio 数据目录。minio_rm_pkg:新增参数,控制在执行 minio-rm.yml 时是否卸载 minio 软件包。etcd_learner:新增参数,允许 etcd 以学习者身份初始化。etcd_rm_data:新增参数,控制在执行 etcd-rm.yml 时是否删除 etcd 数据目录。etcd_rm_pkg:新增参数,控制在执行 etcd-rm.yml 时是否卸载 etcd 软件包。校验和
df64ac0c2b5aab39dd29698a640daf2e pigsty-v3.6.0.tgz
cea861e2b4ec7ff5318e1b3c30b470cb pigsty-pkg-v3.6.0.d12.aarch64.tgz
2f253af87e19550057c0e7fca876d37c pigsty-pkg-v3.6.0.d12.x86_64.tgz
0158145b9bbf0e4a120b8bfa8b44f857 pigsty-pkg-v3.6.0.el8.aarch64.tgz
07330d687d04d26e7d569c8755426c5a pigsty-pkg-v3.6.0.el8.x86_64.tgz
311df5a342b39e3288ebb8d14d81e0d1 pigsty-pkg-v3.6.0.el9.aarch64.tgz
92aad54cc1822b06d3e04a870ae14e29 pigsty-pkg-v3.6.0.el9.x86_64.tgz
c4fadf1645c8bbe3e83d5a01497fa9ca pigsty-pkg-v3.6.0.u22.aarch64.tgz
5477ed6be96f156a43acd740df8a9b9b pigsty-pkg-v3.6.0.u22.x86_64.tgz
196169afc1be02f93fcc599d42d005ca pigsty-pkg-v3.6.0.u24.aarch64.tgz
dbe5c1e8a242a62fe6f6e1f6e6b6c281 pigsty-pkg-v3.6.0.u24.x86_64.tgz
v3.5.0 亮点特性
支持 PG 18 (Beta),扩展更新,总数达到 421 个 OrioleDB 与 OpenHalo 内核在全平台上可用 可使用 pig do 子命令代替 bin 脚本 Supabase 自建加强,解决若干遗留问题,例如复制延迟与密钥分发 代码重构与架构优化,优化了 Postgres 与 Pgbouncer 默认参数 更新了 Grafana 12, pg_exporter 1.0 与相关插件,翻修面板 curl https://repo.pigsty.cc/get | bash -s v3.5.0
支持 PostgreSQL 18 通过 pg_exporter 1.0.0 支持 PG18 监控指标 通过 pig 0.4.1 支持 PG18 安装 Alias。 提供 pg18 配置模板 重构 pgsql 模块 PGSQL 重构,将 PG 监控抽离为单独的 pg_monitor 角色,移除 clean 逻辑 去除冗余重复的任务,合并同类项,精简配置。移除 dir/utils 任务块 所有扩展默认安装至 extensions 模式中(与 supabase 安全实践保持一致) 重命名模板文件,移除所有 .j2 后缀 为所有模板中的 monitor 函数添加 SET 命令清空 search_path,遵循 Supabase 安全最佳实践。 调整 pgbouncer 默认参数,增大默认链接池大小,设置链接池清理查询。 新增参数 pgbouncer_ignore_param ,允许配置 pgbouncer 忽略的参数列表 新增任务 pg_key 用于生成 pgsodium 所需的服务端密钥 针对 PG 17 默认启用 sync_replication_slots 重新调整了子任务标签,使其更符合配置小节的拆分逻辑 重构 pg_remove 模块 重命名参数:pg_rm_data, pg_rm_bkup, pg_rm_pkg 用于控制删除的内容 重新调整角色代码结构,使用更清楚的标签进行划分 新增 pg_monitor 模块 pgbouncer_exporter 现在不再和 pg_exporter 共享配置文件新增了 TimescaleDB, Citus,pg_wait_event 的监控指标。 使用 pg_exporter 1.0.0 ,更新了 PG16/17/18 相关监控指标。 使用更为紧凑,全新设计的指标收集器配置文件。 Supabase 加强 (感谢来自 @lawso017 的贡献!) 将 Supabase 容器镜像与数据库模式更新至最新版本 现在默认支持 pgsodium 服务端密钥加载 通过 supa-kick 定时任务解决 logflare 无法及时更新复制进度的问题 为 monitor 模式中的函数添加 set search_path 子句以遵循安全最佳实践 CLI 新增 pig do 命令,允许通过命令行工具替代 bin/ 中的 Shell 脚本 监控系统更新 更新 Grafana 大版本至 12.0.0,更新相关插件/数据源软件包 更新 Postgres 数据源 uid 命名方式(以适应新的 uid 长度限制与字符限制) 新增了 Static Datasource 更新了现有 Dashboard,修复若干遗留问题 基础设施软件包更新
pig 0.4.2 duckdb 1.3.0 etcd 3.6.0 vector 0.47.0 minio 20250422221226 mcli 20250416181326 pev 1.5.0 rclone 1.69.3 mtail 3.0.8 (new) 可观测性软件包更新
grafana 12.0.0 grafana-victorialogs-ds 0.16.3 grafana-victoriametrics-ds 0.15.1 grafana-infinity-ds 3.2.1 grafana_plugins 12.0.0 prometheus 3.4.0 pushgateway 1.11.1 nginx_exporter 1.4.2 pg_exporter 1.0.0 pgbackrest_exporter 0.20.0 redis_exporter 1.72.1 keepalived_exporter 1.6.2 victoriametrics 1.117.1 victoria_logs 1.22.2 数据库软件包更新
PostgreSQL 17.5, 16.9, 15.13, 14.18, 13.21 PostgreSQL 18beta1 支持 pgbouncer 1.24.1 pgbackrest 2.55 pgbadger 13.1 Postgres 扩展包更新
spat 0.1.0a4 新扩展 pgsentinel 1.1.0 新扩展 pgdd 0.6.0 (pgrx 0.14.1) 新扩展 convert 0.0.4 (pgrx 0.14.1) 新扩展 pg_tokenizer.rs 0.1.0 (pgrx 0.13.1) pg_render 0.1.2 (pgrx 0.12.8) pgx_ulid 0.2.0 (pgrx 0.12.7) pg_idkit 0.3.0 (pgrx 0.14.1) pg_ivm 1.11.0 orioledb 1.4.0 beta11 新增 debian/ubuntu 支持 openhalo 14.10 新增 debian/ubuntu 支持 omnigres 20250507 (在 d12/u22 编译最新版本失败) citus 12.0.3 timescaledb 2.20.0 (移除 PG14 支持) supautils 2.9.2 pg_envvar 1.0.1 pgcollection 1.0.0 aggs_for_vecs 1.4.0 pg_tracing 0.1.3 pgmq 1.5.1 tzf-pg 0.2.0 (pgrx 0.14.1) pg_search 0.15.18 (pgrx 0.14.1) anon 2.1.1 (pgrx 0.14.1) pg_parquet 0.4.0 (0.14.1) pg_cardano 1.0.5 (pgrx 0.12) -> 0.14.1 pglite_fusion 0.0.5 (pgrx 0.12.8) -> 14.1 vchord_bm25 0.2.1 (pgrx 0.13.1) vchord 0.3.0 (pgrx 0.13.1) pg_vectorize 0.22.1 (pgrx 0.13.1) wrappers 0.4.6 (pgrx 0.12.9) timescaledb-toolkit 1.21.0 (pgrx 0.12.9) pgvectorscale 0.7.1 (pgrx 0.12.9) pg_session_jwt 0.3.1 (pgrx 0.12.6) -> 0.12.9 pg_timetable 5.13.0 ferretdb 2.2.0 documentdb 0.103.0 (新增 aarch64支持) pgml 2.10.0 (pgrx 0.12.9) sqlite_fdw 2.5.0 (fix pg17 deb) tzf 0.2.2 0.14.1 (rename src) pg_vectorize 0.22.2 (pgrx 0.13.1) wrappers 0.5.0 (pgrx 0.12.9) 校验和
ab91bc05c54b88c455bf66533c1d8d43 pigsty-v3.6.0.tgz
4c9fabc2d1f0ed733145af2b6aff2f48 pigsty-pkg-v3.5.0.d12.x86_64.tgz
796d47de12673b2eb9882e527c3b6ba0 pigsty-pkg-v3.5.0.el8.x86_64.tgz
a53ef2cede1363f11e9faaaa43718fdc pigsty-pkg-v3.5.0.el9.x86_64.tgz
36da28f97a845fdc0b7bbde2d3812a67 pigsty-pkg-v3.5.0.u22.x86_64.tgz
8551b3e04b38af382163e6857778437d pigsty-pkg-v3.5.0.u24.x86_64.tgz
v3.4.1 GitHub 发布页面:v3.4.1
在 EL 系统上增加了对 MySQL 协议兼容 PostgreSQL 内核的支持:openHalo 在 EL 系统上增加了对 OLTP 增强 PostgreSQL 内核的支持:orioledb 优化了 pgAdmin 9.2 应用模板,具有自动服务器列表更新和 pgpass 密码填充功能 将 PG 默认最大连接数增加到 250、500、1000 从 EL8 中删除了有依赖错误的 mysql_fdw 扩展 基础设施更新
pig 0.3.4 etcd 3.5.21 restic 0.18.0 ferretdb 2.1.0 tigerbeetle 0.16.34 pg_exporter 0.8.1 node_exporter 1.9.1 grafana 11.6.0 zfs_exporter 3.8.1 mongodb_exporter 0.44.0 victoriametrics 1.114.0 minio 20250403145628 mcli 20250403170756 扩展更新
将 pg_search 升级到 0.15.13 将 citus 升级到 13.0.3 将 timescaledb 升级到 2.19.1 将 pgcollection RPM 升级到 1.0.0 将 pg_vectorize RPM 升级到 0.22.1 将 pglite_fusion RPM 升级到 0.0.4 将 aggs_for_vecs RPM 升级到 1.4.0 将 pg_tracing RPM 升级到 0.1.3 将 pgmq RPM 升级到 1.5.1 校验和
471c82e5f050510bd3cc04d61f098560 pigsty-v3.4.1.tgz
4ce17cc1b549cf8bd22686646b1c33d2 pigsty-pkg-v3.4.1.d12.aarch64.tgz
c80391c6f93c9f4cad8079698e910972 pigsty-pkg-v3.4.1.d12.x86_64.tgz
811bf89d1087512a4f8801242ca8bed5 pigsty-pkg-v3.4.1.el9.x86_64.tgzz
9fe2e6482b14a3e60863eeae64a78945 pigsty-pkg-v3.4.1.u22.x86_64.tgz
v3.4.0 GitHub 发布页面:v3.4.0
介绍博客:Pigsty v3.4 MySQL 兼容性和全面增强
新功能
增加了新的 pgBackRest 备份监控指标和仪表板 增强了 Nginx 服务器配置选项,支持自动 Certbot 签发 现在优先使用 PostgreSQL 内置的 C/C.UTF-8 区域设置 IvorySQL 4.4 现在在所有平台上完全支持(RPM/DEB 在 x86/ARM 上) 增加了新的软件包:Juicefs、Restic、TimescaleDB EventStreamer Apache AGE 图数据库扩展现在在 EL 上完全支持 PostgreSQL 13–17 改进了 app.yml playbook:无需额外配置即可启动标准 Docker 应用 升级 Supabase、Dify 和 Odoo 应用模板到最新版本 增加 electric 应用模板,本地优先的 PostgreSQL 同步引擎 基础设施包
+restic 0.17.3+juicefs 1.2.3+timescaledb-event-streamer 0.12.0Prometheus 3.2.1AlertManager 0.28.1blackbox_exporter 0.26.0node_exporter 1.9.0mysqld_exporter 0.17.2kafka_exporter 1.9.0redis_exporter 1.69.0pgbackrest_exporter 0.19.0-2DuckDB 1.2.1etcd 3.5.20FerretDB 2.0.0tigerbeetle 0.16.31vector 0.45.0VictoriaMetrics 1.113.0VictoriaLogs 1.17.0rclone 1.69.1pev2 1.14.0grafana-victorialogs-ds 0.16.0grafana-victoriametrics-ds 0.14.0grafana-infinity-ds 3.0.0PostgreSQL 相关
Patroni 4.0.5PolarDB 15.12.3.0-e1e6d85bIvorySQL 4.4pgbackrest 2.54.2pev2 1.14WiltonDB 13.17PostgreSQL 扩展
pgspider_ext 1.3.0(新扩展)apache age 13–17 el rpm (1.5.0)timescaledb 2.18.2 → 2.19.0citus 13.0.1 → 13.0.2documentdb 1.101-0 → 1.102-0pg_analytics 0.3.4 → 0.3.7pg_search 0.15.2 → 0.15.8pg_ivm 1.9 → 1.10emaj 4.4.0 → 4.6.0pgsql_tweaks 0.10.0 → 0.11.0pgvectorscale 0.4.0 → 0.6.0 (pgrx 0.12.5)pg_session_jwt 0.1.2 → 0.2.0 (pgrx 0.12.6)wrappers 0.4.4 → 0.4.5 (pgrx 0.12.9)pg_parquet 0.2.0 → 0.3.1 (pgrx 0.13.1)vchord 0.2.1 → 0.2.2 (pgrx 0.13.1)pg_tle 1.2.0 → 1.5.0supautils 2.5.0 → 2.6.0sslutils 1.3 → 1.4pg_profile 4.7 → 4.8pg_snakeoil 1.3 → 1.4pg_jsonschema 0.3.2 → 0.3.3pg_incremental 1.1.1 → 1.2.0pg_stat_monitor 2.1.0 → 2.1.1ddl_historization 0.7 → 0.0.7(错误修复)pg_sqlog 3.1.7 → 1.6(错误修复)pg_random 删除开发后缀(错误修复)asn1oid 1.5 → 1.6table_log 0.6.1 → 0.6.4接口变更
增加了新的 Docker 参数:docker_data 和 docker_storage_driver(#521 由 @waitingsong 提供) 增加了新的基础设施参数:alertmanager_port,让您指定 AlertManager 端口 增加了新的基础设施参数:certbot_sign,在 nginx 初始化期间申请证书?(默认为 false) 增加了新的基础设施参数:certbot_email,指定通过 Certbot 请求证书时使用的邮箱 增加了新的基础设施参数:certbot_options,指定 Certbot 的额外参数 更新 IvorySQL,从 IvorySQL 4.4 开始将其默认二进制文件放在 /usr/ivory-4 下 将 pg_lc_ctype 和其他区域相关参数的默认值从 en_US.UTF-8 更改为 C 对于 PostgreSQL 17,如果使用 UTF8 编码与 C 或 C.UTF-8 区域,PostgreSQL 的内置本地化规则现在优先 configure 自动检测 PG 版本和环境是否都支持 C.utf8,并相应调整区域相关选项将默认 IvorySQL 二进制路径设置为 /usr/ivory-4 更新 pg_packages 的默认值为 pgsql-main patroni pgbouncer pgbackrest pg_exporter pgbadger vip-manager 更新 repo_packages 的默认值为 [node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules] 从 /etc/profile.d/node.sh 中删除 LANG 和 LC_ALL 环境变量设置 现在使用 bento/rockylinux-8 和 bento/rockylinux-9 作为 EL 的 Vagrant box 镜像 增加了新别名 extra_modules,包含额外的可选模块 更新 PostgreSQL 别名:postgresql、pgsql-main、pgsql-core、pgsql-full GitLab 仓库现在包含在可用模块中 Docker 模块已合并到基础设施模块中 node.yml playbook 现在包含 node_pip 任务,在每个节点上配置 pip 镜像pgsql.yml playbook 现在包含 pgbackrest_exporter 任务,用于收集备份指标Makefile 现在允许使用 META/PKG 环境变量增加 /pg/spool 目录作为 pgBackRest 的临时存储 默认禁用 pgBackRest 的 link-all 选项 默认为 MinIO 仓库启用块级增量备份 错误修复
修复 pg-backup 中的退出状态码(#532 由 @waitingsong 提供) 在 pg-tune-hugepage 中,限制 PostgreSQL 仅使用大页面(#527 由 @waitingsong 提供) 修复 pg-role 任务中的逻辑错误 纠正大页面配置参数的类型转换 修复 slim 模板中 node_repo_modules 的默认值问题 校验和
768bea3bfc5d492f4c033cb019a81d3a pigsty-v3.4.0.tgz
7c3d47ef488a9c7961ca6579dc9543d6 pigsty-pkg-v3.4.0.d12.aarch64.tgz
b5d76aefb1e1caa7890b3a37f6a14ea5 pigsty-pkg-v3.4.0.d12.x86_64.tgz
42dacf2f544ca9a02148aeea91f3153a pigsty-pkg-v3.4.0.el8.aarch64.tgz
d0a694f6cd6a7f2111b0971a60c49ad0 pigsty-pkg-v3.4.0.el8.x86_64.tgz
7caa82254c1b0750e89f78a54bf065f8 pigsty-pkg-v3.4.0.el9.aarch64.tgz
8f817e5fad708b20ee217eb2e12b99cb pigsty-pkg-v3.4.0.el9.x86_64.tgz
8b2fcaa6ef6fd8d2726f6eafbb488aaf pigsty-pkg-v3.4.0.u22.aarch64.tgz
83291db7871557566ab6524beb792636 pigsty-pkg-v3.4.0.u22.x86_64.tgz
c927238f0343cde82a4a9ab230ecd2ac pigsty-pkg-v3.4.0.u24.aarch64.tgz
14cbcb90693ed5de8116648a1f2c3e34 pigsty-pkg-v3.4.0.u24.x86_64.tgz
v3.3.0 可用扩展总数增加到 404 ! PostgreSQL 二月小版本更新:17.4、16.8、15.12、14.17、13.20 新功能:app.yml 脚本,用于自动安装 Odoo、Supabase、Dify 等应用。 新功能:在 infra_portal 中进一步自定义 Nginx 配置。 新功能:增加 Certbot 支持,快速申请免费 HTTPS 证书。 新功能:pg_default_extensions 现在支持纯文本扩展列表。 新功能:默认仓库现在包含 mongo、redis、groonga、haproxy 等。 新参数:node_aliases,为节点添加命令别名。 修复:解决 Bootstrap 脚本中的默认 EPEL 仓库地址问题。 改进:为 Debian Security 仓库添加阿里云镜像。 改进:IvorySQL 内核的 pgBackRest 备份支持。 改进:PolarDB 的 ARM64 和 Debian/Ubuntu 支持。 pg_exporter 0.8.0 现在支持 pgbouncer 1.24 中的新指标。 新功能:git、docker、systemctl 等常用命令的自动补全 #506 #507 由 @waitingsong 提供。 改进:优化 pgbouncer 配置模板中的 ignore_startup_parameters #488 由 @waitingsong 提供。 新主页设计:Pigsty 的网站现在拥有全新的外观。 扩展目录:RPM/DEB 二进制包的详细信息和下载链接。 扩展构建:pig CLI 现在自动设置 PostgreSQL 扩展构建环境。 更多版本信息请参考 GitHub 发布页面 。
v3.2.2 变更内容
升级IvorySQL至4.2版本(基于PostgreSQL 17.2) 为PolarDB内核添加Arm64和Debian支持 在默认infra_packages中添加certbot和certbot-nginx 增加pgbouncer的max_prepared_statements参数至256 移除pgxxx-citus包别名 在pg_extensions中默认隐藏pgxxx-olap类别(因为存在两对扩展冲突) v3.2.1 亮点特性
PG扩展插件数量提升至350个,新增强力Rust扩展anon。 IvorySQL支持更新至PG17兼容的4.0版本 使用Pigsty编译的Citus,TimescaleDB与PGroonga。 添加Odoo一键自建模板与新app.yml剧本 新增 13 扩展插件:
新增 pg_anon 2.0.0 新增 omnisketch 1.0.2 新增 ddsketch 1.0.1 新增 pg_duration 1.0.1 新增 ddl_historization 0.0.7 新增 data_historization 1.1.0 新增 schedoc 0.0.1 新增 floatfile 1.3.1 新增 pg_upless 0.0.3 新增 pg_task 1.0.0 新增 pg_readme 0.7.0 新增 vasco 0.1.0 新增 pg_xxhash 0.0.1 更新扩展版本
lower_quantile 1.0.3 quantile 1.1.8 sequential_uuids 1.0.3 pgmq 1.5.0 (subdir) floatvec 1.1.1 pg_parquet 0.2.0 wrappers 0.4.4 pg_later 0.3.0 topn fix for deb.arm64 add age 17 on debian powa + pg17, 5.0.1 h3 + pg17 ogr_fdw + pg17 age + pg17 1.5 on debian pgtap + pg17 1.3.3 repmgr topn + pg17 pg_partman 5.2.4 credcheck 3.0 ogr_fdw 1.1.5 ddlx 0.29 postgis 3.5.1 tdigest 1.4.3 pg_repack 1.5.2 v3.2.0 亮点特性
Pigsty 命令行工具:pig 0.2.0,可用于管理扩展插件。 提供五大发行版上 390 个扩展 的 ARM64 扩展支持 Supabase 发布周最新版本更新,全发行版均可自建。 Grafana 更新至 11.4 ,新增 infinity 数据源。 软件包变化
新增扩展
更新扩展
pgvectorscale 0.4.0 -> 0.5.1 pg_parquet 0.1.0 -> 0.1.1 pg_polyline 0.0.1 pg_cardano 1.0.2 -> 1.0.3 pg_vectorize 0.20.0 pg_duckdb 0.1.0 -> 0.2.0 pg_search 0.13.0 -> 0.13.1 aggs_for_vecs 1.3.1 -> 1.3.2 pgoutput 被标记为新的 PostgreSQL Contrib 扩展基础设施
新增 promscale 0.17.0 新增 grafana-plugins 11.4 新增 grafana-infinity-plugins 新增 grafana-victoriametrics-ds 新增 grafana-victorialogs-ds vip-manager 2.8.0 -> 3.0.0 vector 0.42.0 -> 0.43.0 grafana 11.3 -> 11.4 prometheus 3.0.0 -> 3.0.1 (软件包名从 prometheus2 变更为 prometheus) nginx_exporter 1.3.0 -> 1.4.0 mongodb_exporter 0.41.2 -> 0.43.0 VictoriaMetrics 1.106.1 -> 1.107.0 VictoriaLogs 1.0.0 -> 1.3.2 pg_timetable 5.9.0 -> 5.10.0 tigerbeetle 0.16.13 -> 0.16.17 pg_export 0.7.0 -> 0.7.1 缺陷修复
el8.aarch64 添加 python3-cdiff 修复 patroni 依赖错漏问题 el9.aarch64 添加 timescaledb-tools ,修复官方仓库缺失问题 el9.aarch64 添加 pg_filedump ,修复官方仓库缺失问题 移除扩展
pg_mooncake 因为与 pg_duckdb 冲突而被移除。pg_top 因为出现太多版本出现缺失,因质量问题而淘汰。hunspell_pt_pt 因为与 PG 官方字典文件冲突而被淘汰。pg_timeit 因为无法在 AARCH64 架构上使用而被淘汰。pgdd 因为缺乏维护,PG 17 与 pgrx 版本老旧而被标记为弃用。old_snapshot 与 adminpack 被标记为 PG 17 不可用。pgml 被设置为默认不下载不安装。API变化
repo_url_packages 参数现在默认值为空数组,因为所有软件包现在都通过操作系统包管理器进行安装。grafana_plugin_cache 参数弃用,现在 Grafana 插件通过操作系统包管理器进行安装grafana_plugin_list 参数弃用,现在 Grafana 插件通过操作系统包管理器进行安装原名为 prod 的 36 节点仿真模板现在重命名为 simu。 原本在 node_id/vars 针对每个发行版代码生成的配置,现在同样针对 aarch64 生成。 infra_packages 中默认添加命令行管理工具 pigconfigure 命令同样会修改自动生成配置文件中 pgsql-xxx 别名的版本号。adminpack 在 PG 17 中被移除,因此从 Pigsty 默认扩展中被移除。问题修复
软件包校验和
8fdc6a60820909b0a2464b0e2b90a3a6 pigsty-v3.2.0.tgz
d2b85676235c9b9f2f8a0ad96c5b15fd pigsty-pkg-v3.2.0.el9.aarch64.tgz
649f79e1d94ec1845931c73f663ae545 pigsty-pkg-v3.2.0.el9.x86_64.tgz
c42da231067f25104b71a065b4a50e68 pigsty-pkg-v3.2.0.d12.aarch64.tgz
ebb818f98f058f932b57d093d310f5c2 pigsty-pkg-v3.2.0.d12.x86_64.tgz
24c0be1d8436f3c64627c12f82665a17 pigsty-pkg-v3.2.0.u22.aarch64.tgz
0b9be0e137661e440cd4f171226d321d pigsty-pkg-v3.2.0.u22.x86_64.tgz
v3.1.0 亮点特性
PostgreSQL 17 现已成为默认使用的主要版本 (17.2) Ubuntu 24.04 系统支持 arm 架构支持:EL9, Debian12, Ubuntu 22.04 Supabase 一键自建,新的剧本 supabase.yml MinIO 最佳实践改进,配置模板与 Vagrant 模板 提供了一系列开箱即用的配置模板与文档说明。 允许在 configure 过程中使用 -v|--version 指定使用的 PG 大版本。 调整 PG 默认插件策略:默认安装 pg_repack, wal2json 以及 pgvector 三个关键扩展。 大幅简化 repo_packages 本地软件源构建逻辑,允许在 repo_packages 中使用软件包组别名 提供了 WiltonDB,IvorySQL,PolarDB 的软件源镜像,简化三者的安装。 默认启用数据库校验和。 修复 ETCD 与 MINIO 日志面板 软件升级
PostgreSQL 17.2, 16.6, 15.10, 14.15, 13.18, 12.22 PostgreSQL 扩展版本变动请参考:https://pgext.cloud Patroni 4.0.4 MinIO 20241107 / MCLI 20241117 Rclone 1.68.2 Prometheus: 2.54.0 -> 3.0.0 VictoriaMetrics 1.102.1 -> 1.106.1 VictoriaLogs v0.28.0 -> 1.0.0 vslogcli 1.0.0 MySQL Exporter 0.15.1 -> 0.16.0 Redis Exporter 1.62.0 -> 1.66.0 MongoDB Exporter 0.41.2 -> 0.42.0 Keepalived Exporter 1.3.3 -> 1.4.0 DuckDB 1.1.2 -> 1.1.3 etcd 3.5.16 -> 3.5.17 tigerbeetle 16.8 -> 0.16.13 API变更
repo_upstream: 针对每个具体的操作系统发行版生成默认值:roles/node_id/varsrepo_packages: 允许使用 package_map 中定义的别名。repo_extra_packages: 新增未指定时的默认值,允许使用 package_map 中定义的别名。pg_checksum: 默认值修改为 true,默认打开。pg_packages: 默认值修改为:postgresql, wal2json pg_repack pgvector, patroni pgbouncer pgbackrest pg_exporter pgbadger vip-managerpg_extensions: 默认值修改为空数组 []。infra_portal: 允许为 home 服务器指定 path,替代默认的本地仓库路径 nginx_home (/www)校验和
e62f9ce9f89a58958609da7b234bf2f2 pigsty-v3.1.0.tgz
v3.0.4 特性
针对 PostgreSQL 17 编译了所有支持的 Pigsty 扩展插件 提供了全新的 OLAP 扩展支持:pg_duckdb 与 pg_parquet 简化并优化了最新版本 Supabase 自建的流程 新增参数 docker_image,允许在 Docker 安装后自动拉取镜像。 扩展
欢迎查阅我们最新的 PostgreSQL 扩展目录: https://pgext.cloud
统计项 总计 PGDG PIGSTY MISC MISS PG17 PG16 PG15 PG14 PG13 PG12 EL系统扩展 338 134 130 4 7 298 334 336 328 319 310 Deb系统扩展 326 109 143 74 19 290 322 324 316 307 300 RPM 软件包 313 122 129 4 6 275 309 311 303 294 285 DEB 软件包 298 93 142 64 19 264 294 296 288 279 272
版本升级
新的PGSQL扩展
升级与跟进PG扩展
pg_search 0.11.0 pg_analytics 0.2.0 plv8 3.2.3 supautils 2.5.0 icu_ext 1.9.0 redis_fdw 17 pg_failover_slots 1.1.0 pg_later 0.1.3 plprql 1.0.0 pg_vectorize 0.18.3 unit 7.7 -> 7.9 log_fdw 1.4 pg_duckdb 0.1.0 pg_graphql 1.5.9 (+17) pg_jsonschema 0.3.2 (+17) pgvectorscale 0.4.0 (+17) wrappers 0.4.3 +pg17 pg_ivm 1.9 pg_timeseries 0.1.6 pgmq 1.4.4 pg_protobuf 16 17 pg_uuidv7 1.6 pg_readonly pgddl 0.28 pg_safeupdate pg_stat_monitor 2.1 pg_profile 4.7 system_stats 3.2 pg_auth_mon 3.0 login_hook 1.6 logerrors 2.1.3 pg-orphaned pgnodemx 1.7 sslutils 1.4 (deb+pg16,17) timestamp9 (deb) 修复不支持PG16/17的扩展
pg_mon pg_uri agg_for_vecs quantile lower_quantile pg_protobuf acl pg_emailaddr pg_zstd smlar geohash pgsmcrypto (+17) pg_tiktoken (+17) pg_idkit (+17) 基础设施软件包
Grafana 11.3 duckdb 1.1.2 etcd 3.5.16 ferretdb 1.24.0 minio 20241013133411 mcli 2024101313411 pushgateway 1.10 tigerbeetle 0.16.8 mongodb_exporter 0.41.2 redis_exporter 1.64.1 vector 0.41.1 vip-manager 2.7 sealos 5.0.1 v3.0.3 特性
提供对最新发布的 PostgreSQL 17 支持。 优化了 etcd 配置,监控,与告警规则 (Oracle兼容的)IvorySQL 3.4 支持,与 PostgreSQL 16.4 同步 版本升级
PostGIS 3.5 Grafana 11.2 duckdb 1.1 pg_search 0.10.2 pg_analytics 0.1.4 v3.0.2 特性
精简安装模式 :使用 slim.yml 进行最精简的 HA PGSQL 部署。PolarDB PG 15 的原生支持。优化 monitor.pg_table_bloat 与 monitor.pg_index_bloat,使用安全定义包装函数规避 PolarDB 统计视图权限问题。 在各模块的监控注册阶段,尊重 prometheus_enabled 与 grafana_enabled 配置选项,关闭时不再注册。 在 /etc/profile.d/pgsql.sh 中添加 PGDATABASE 与 PGPORT 环境变量,设置为 pg_primary_db(默认postgres) 变更
在 Pigsty PGSQL 仓库中移除 PolarDB 11 与 CloudberryDB 1.5.4 的 RPM/APT 包。 使用专用的仓库分发 PolarDB 15 与 CloudberryDB 1.6.0 的 RPM/APT 包。 问题修复
修复 Redis 的 /etc/tmp.files.d 文件名错误。 在管理 pgbouncer 用户时,设置 PGHOST 与 PGPORT 环境变量。 临时移除 pg_snakeoil 扩展支持,因为 EL8 上游源 clamv 出现依赖缺失问题。 移除 pgsql 角色的 Notify / Handler,以兼容更老的 Ansible 2.9 版本。 v3.0.1 特性改进
PolarDB Oracle 兼容性模式支持(需要第三方商业闭源内核) 使用 Oracle 兼容的 SQL 语法改写监控视图与相关 SQL 语句 Patroni 4 支持与适配 新增扩展 pg_analytics,通过 duckdb 为 PG 加装分析能力 添加新扩展:odbc_fdw 与 jdbc_fdw,提供通用的外部数据源连接能力 仓库添加新内核 cloudberrydb (Greenplum 原班开发者的开源分支) 仓库添加新工具 walminer,从WAL(replica等级)中提取原始 SQL。(高级特性需自行购买License) 更新执行计划可视化工具 Pev2 版本至 1.12.1 新增Grafana插件:volkovlabs-rss-datasource 在PGCAT databases监控面板中添加了已安装和待安装的扩展插件 PGSQL 主库初始化后,会重启一次以便 pg_param & pg_files 生效,因此 Supabase PG / PolarDB 集群置备后无需重启。 问题修复
修复了 Grafana 11.1.4 面板插件默认不加载的问题 修复了特定操作系统上 BlackBox Exporter Ping 探针失效的问题 确保 /var/run/postgresql 与 /var/run/redis 临时目录总是在重启后自动创建 修复了 cache.yml 剧本没有正确移除老旧的 patroni 3.0.4 RPM 包问题 修复了个别告警规则中的描述信息错误 移除了 Patroni 配置文件中过时的 Bootstrap User/HBA 参数 v3.0.0 亮点特性
Pigsty v3 提供了史无前例的 333 个可用扩展插件。
包括 121 个扩展 RPM包 与 133 个 DEB包 ,数量已经超过了 PGDG 官方仓库提供的扩展数量总和(135 RPM/ 109 DEB)。
而且,Pigsty 还将EL系统与Debian生态的独有PG扩展插件相互移植,实现了两大发行版的插件生态大对齐。
- timescaledb periods temporal_tables emaj table_version pg_cron pg_later pg_background pg_timetable
- postgis pgrouting pointcloud pg_h3 q3c ogr_fdw geoip #pg_geohash #mobilitydb
- pgvector pgvectorscale pg_vectorize pg_similarity pg_tiktoken pgml #smlar
- pg_search pg_bigm zhparser hunspell
- hydra pg_lakehouse pg_duckdb duckdb_fdw pg_fkpart pg_partman plproxy #pg_strom citus
- pg_hint_plan age hll rum pg_graphql pg_jsonschema jsquery index_advisor hypopg imgsmlr pg_ivm pgmq pgq #rdkit
- pg_tle plv8 pllua plprql pldebugger plpgsql_check plprofiler plsh #pljava plr pgtap faker dbt2
- prefix semver pgunit md5hash asn1oid roaringbitmap pgfaceting pgsphere pg_country pg_currency pgmp numeral pg_rational pguint ip4r timestamp9 chkpass #pg_uri #pgemailaddr #acl #debversion #pg_rrule
- topn pg_gzip pg_http pg_net pg_html5_email_address pgsql_tweaks pg_extra_time pg_timeit count_distinct extra_window_functions first_last_agg tdigest aggs_for_arrays pg_arraymath pg_idkit pg_uuidv7 permuteseq pg_hashids
- sequential_uuids pg_math pg_random pg_base36 pg_base62 floatvec pg_financial pgjwt pg_hashlib shacrypt cryptint pg_ecdsa pgpcre icu_ext envvar url_encode #pg_zstd #aggs_for_vecs #quantile #lower_quantile #pgqr #pg_protobuf
- pg_repack pg_squeeze pg_dirtyread pgfincore pgdd ddlx pg_prioritize pg_checksums pg_readonly safeupdate pg_permissions pgautofailover pg_catcheck preprepare pgcozy pg_orphaned pg_crash pg_cheat_funcs pg_savior table_log pg_fio #pgpool pgagent
- pg_profile pg_show_plans pg_stat_kcache pg_stat_monitor pg_qualstats pg_store_plans pg_track_settings pg_wait_sampling system_stats pg_meta pgnodemx pg_sqlog bgw_replstatus pgmeminfo toastinfo pagevis powa pg_top #pg_statviz #pgexporter_ext #pg_mon
- passwordcheck supautils pgsodium pg_vault anonymizer pg_tde pgsmcrypto pgaudit pgauditlogtofile pg_auth_mon credcheck pgcryptokey pg_jobmon logerrors login_hook set_user pg_snakeoil pgextwlist pg_auditor noset #sslutils
- wrappers multicorn mysql_fdw tds_fdw sqlite_fdw pgbouncer_fdw mongo_fdw redis_fdw pg_redis_pubsub kafka_fdw hdfs_fdw firebird_fdw aws_s3 log_fdw #oracle_fdw #db2_fdw
- orafce pgtt session_variable pg_statement_rollback pg_dbms_metadata pg_dbms_lock pgmemcache #pg_dbms_job #wiltondb
- pglogical pgl_ddl_deploy pg_failover_slots wal2json wal2mongo decoderbufs decoder_raw mimeo pgcopydb pgloader pg_fact_loader pg_bulkload pg_comparator pgimportdoc pgexportdoc #repmgr #slony
- gis-stack rag-stack fdw-stack fts-stack etl-stack feat-stack olap-stack supa-stack stat-stack json-stack
Pigsty v3 允许您更换 PostgreSQL 内核,目前支持了 SQL Server 兼容的 Babelfish (线缆协议级仿真),Oracle 兼容的 IvorySQL,以及 PG 版的 RAC PolarDB;此外,现在自托管 Supabase 也在 Debian 系统中可用。
您可以让 Pigsty 中带有 HA,IaC,PITR,监控的生产级 PostgreSQL 集群仿真 MSSQL (via WiltonDB),Oracle via (IvorySQL),Oracle RAC (via PolarDB), MongoDB(via FerretDB),以及 Firebase (via Supabase)。
我们现在提供 Pigsty Pro 专业版 ,在开源版的功能基础上提供增值服务。专业版提供额外的功能模块:MSSQL,Oracle,Mongo,K8S,Victoria,Kafka,TigerBeetle 等……,并提供更广泛的 PG 大版本、操作系统、芯片架构的支持。
提供针对全系操作系统精准小版本定制的离线安装包,以及 EL7,Debian 11,Ubuntu 20.04 等过保老系统的支持;此外,专业版还提供内核可插拔定制服务,并对PolarDB PG 的原生部署、监控管控支持以满足“国产化”需要。
使用以下命令快速安装体验:
curl -fsSL https://repo.pigsty.cc/get | bash
cd ~/pigsty; ./bootstrap; ./configure; ./install.yml
重大变更
本次 Pigsty 发布调整大版本号,从 2.x 升级到 3.0,带有一些重大变更:
首要支持操作系统调整为:EL 8 / EL 9 / Debian 12 / Ubuntu 22.04
EL7 / Debian 11 / Ubuntu 20.04 等系统进入弃用阶段,不再提供支持 有在这些系统上运行需求的用户请考虑我们的 订阅服务 默认使用在线安装,不再提供离线软件包,从而解决操作系统小版本兼容性问题。
bootstrap 过程现在不再询问是否下载离线安装包,但如果 /tmp/pkg.tgz 存在,仍然会自动使用离线安装包。有离线安装需求请自行制作离线软件包或考虑我们的 订阅服务 Pigsty 使用的上游软件仓库进行统一调整,地址变更,并对所有软件包进行 GPG 签名与校验
标准仓库: https://repo.pigsty.io/{apt/yum} 国内镜像: https://repo.pigsty.cc/{apt/yum} API 参数变更与配置模板变更
EL 系与 Debian 系配置模板现在收拢统一,有差异的参数统一放置于 roles/node_id/vars/ 目录进行管理。 配置目录变更,所有配置文件模板统一放置在 conf 目录下,并分为 default, dbms, demo, build 四大类。 其他新特性
PG OLAP 分析能力史诗级加强:DuckDB 1.0.0,DuckDB FDW,以及 PG Lakehouse,Hydra 移植至 Deb 系统中。 PG 向量检索与全文检索能力加强:Vectorscale 提供 DiskANN 向量索引,Hunspell 分词字典支持,pg_search 0.8.6。 帮助 ParadeDB 解决了软件包构建问题,现在我们在 Debian/Ubuntu 上也能提供这一扩展。 Supabase 所需的扩展在 Debian/Ubuntu 上全部可用,Supabase 现在可在全OS上自托管。 提供了场景化预置扩展堆栈的能力,如果您不知道安装哪些扩展,我们准备了针对特定应用场景的扩展推荐包(Stack)。 针对所有 PostgreSQL 生态的扩展,制作了元数据表格、文档、索引、名称映射,针对 EL与Deb 进行对齐,确保扩展可用性。 为了解决 DockerHub 被 Ban 的问题,我们加强了 proxy_env 参数的功能并简化其配置方式。 建设了一个专用的新软件仓库,提供了 12-17 版本的全部扩展插件,其中,PG16的扩展仓库会在 Pigsty 默认的版本中实装。 现有软件仓库升级改造,使用标准的签名与校验机制,确保软件包的完整性与安全性。APT 仓库采用新的标准布局通过 reprepro 构建。 提供了 1,2,3,4,43 节点的沙箱环境:meta, dual, trio, full, prod,以及针对 7 大 OS Distro 的快捷配置模板。 PG Exporter 新增了 PostgreSQL 17 与 pgBouncer 1.23 新监控指标收集器的定义,与使用这些指标的 Grafana Panel 监控面板修缮,修复了各种问题,为 PGSQL Pgbouncer 与 PGSQL Patroni 监控面板添加了日志仪表盘。 使用全新的 cache.yml Ansible 剧本,替换了原有制作离线软件包的 bin/cache 与 bin/release-pkg 脚本。 API变更
新参数选项: pg_mode 现在支持的模式有 pgsql, citus, gpsql, mssql, ivory, polar,用于指定 PostgreSQL 集群的模式pgsql: 标准 PostgreSQL 高可用集群citus: Citus 水平分布式 PostgreSQL 原生高可用集群gpsql: 用于 Greenplum 与 GP 兼容数据库的监控(专业版)mssql: 安装 WiltonDB / Babelfish,提供 Microsoft SQL Server 兼容性模式的标准 PostgreSQL 高可用集群,线缆协议级支持,扩展不可用ivory: 安装 IvorySQL 提供的 Oracle 兼容性 PostgreSQL 高可用集群,Oracle语法/数据类型/函数/存储过程兼容,扩展不可用 (专业版)polar: 安装 PolarDB for PostgreSQL (PG RAC)开源版本,提供国产化数据库能力支持,扩展不可用。(专业版) 新参数: pg_parameters,用于在实例级别指定 postgresql.auto.conf 中的参数,覆盖集群配置,实现不同实例成员的个性化配置。 新参数: pg_files,用于将额外的文件拷贝到PGDATA数据目录,针对需要License文件的商业版PostgreSQL分叉内核设计。 新参数: repo_extra_packages,用于额外指定需要下载的软件包,与 repo_packages 共同使用,便于指定OS版本独有的扩展列表。 参数重命名: patroni_citus_db 重命名为 pg_primary_db,用于指定集群中的主要数据库(在 Citus 模式中使用) 参数强化:proxy_env 中的代理服务器配置会写入 Docker Daemon,解决科学上网问题,configure -x 选项会自动在配置中写入当前环境中的代理服务器配置。 参数强化:infra_portal 参数现在支持指定 path 选项,对外暴露本机上的目录,提供web服务。 参数强化:repo_url_packages 中的 repo.pigsty.io 会在区域为中国时自动替换为 repo.pigsty.cc,解决科学上网问题,此外,现在可以指定下载后的文件名称。 参数强化:pg_databases.extensions 中的 extension 字段现在可以支持字典与扩展名字符串两种模式,字典模式提供 version 支持,允许安装特定版本的扩展。 参数强化:repo_upstream 参数如果没有显式覆盖定义,将从 rpm.yml 或 deb.yml 中定义的 repo_upstream_default 提取对应系统的默认值。 参数强化:repo_packages 参数如果没有显式覆盖定义,将从 rpm.yml 或 deb.yml 中定义的 repo_packages_default 提取对应系统的默认值。 参数强化:infra_packages 参数如果没有显式覆盖定义,将从 rpm.yml 或 deb.yml 中定义的 infra_packages_default 提取对应系统的默认值。 参数强化:node_default_packages 参数如果没有显式覆盖定义,将从 rpm.yml 或 deb.yml 中定义的 node_packages_default 提取对应系统的默认值。 参数强化:pg_packages 与 pg_extensions 中的扩展现在都会从 rpm.yml 或 deb.yml 中定义的 pg_package_map 执行一次查找与翻译。 参数强化:node_packages 与 pg_extensions 参数中指定的软件包在安装时会升级至最新版本, node_packages 中现在默认值变为 [openssh-server],帮助修复 OpenSSH CVE 参数强化:pg_dbsu_uid 会自动根据操作系统类型调整为 26 (EL)或 543 (Debian),避免了手工调整。 设置了 pgbouncer 默认参数,max_prepared_statements = 128 启用了事物池化模式下的准备语句支持,并设置 server_lifetime 为 600, 修改了 patroni 模板默认参数,统一增大 max_worker_processes +8 可用后端进程,提高 max_wal_senders 与 max_replication_slots 至 50,并增大 OLAP 模板临时文件的大小限制为主磁盘的 1/5 版本升级
截止至发布时刻,Pigsty 主要组件的版本升级如下:
Pigsty 重新编译了所有 PostgreSQL 扩展插件,PostgreSQL 扩展插件的最新版本,可用的 333 个扩展插件请参考 扩展列表
新应用
Pigsty 现在提供开箱即用的 Dify 与 Odoo 两款使用 PostgreSQL 软件的 Docker Compose 模板:
Dify : AI智能体工作流编排与 LLMOps,使用 PostgreSQL 作为元数据库,PGVector 作为向量存储。Odoo : 企业级开源 ERP 系统,使用 PostgreSQL 作为底层数据库。Pigsty 专业版现在提供试点的 Kubernetes 部署支持与 Kafka KRaft 集群部署与监控支持
KUBE : 使用 cri-dockerd 或 containerd 部署由 Pigsty 托管的 Kubernetes 集群KAFKA :部署由 Kraft 协议支持的高可用 Kafka 集群问题修复
修复了 Ubuntu / Debian 系统中,节点重启后可能出现的 postgresql-common 服务自动启动替代默认数据库集群的缺陷 通过 node_packages 中的默认值 [openssh-server],CVE-2024-6387 可以在 Pigsty 安装过程中被自动修复。 修复了 Loki 解析 Nginx 日志标签基数过大导致的内存消耗问题。 修复了 EL8 系统中上游 Ansible 依赖变化导致的 bootstrap 失效问题(python3.11-jmespath 升级至 python3.12-jmespath) v2.7.0 亮点特性
新增了大量强力扩展插件,特别是一些使用 rust 与 pgrx 进行开发的强力扩展:
当然,也有一些使用原生 C 和 C++ 开发的强力扩展:
parquet_s3_fdw 1.1.0:从 S3 存取 Parquet 格式文件,作为湖仓之用plv8 3.2.2:使用 V8 引擎,允许在 PostgreSQL 中使用 Javascript 语言编写存储过程md5hash 1.0.1:用于存储原生MD5哈希数据类型,而非文本。pg_tde 1.0 alpha:PostgreSQL 的实验性加密存储引擎。pg_dirtyread 2.6:从 PostgreSQL 表中读取未清理的死元组,用于脏读新的 deb PGDG 扩展:pg_roaringbitmap, pgfaceting, mobilitydb, pgsql-http, pg_hint_plan, pg_statviz, pg_rrule 新的 rpm PGDG 扩展:pg_profile, pg_show_plans, 使用 PGDG 的 pgsql_http, pgsql_gzip, pg_net, pg_bigm 替代 Pigsty 维护的 RPM。 新特性
允许 Pigsty 在特定 Docker 虚拟机镜像中运行。 针对 Ubuntu 与 EL 系操作系统发行版准备了 INFRA & PGSQL 模块的 arm64 软件包 新安装脚本,可从 cloudflare 下载软件,可以指定版本,提供更完善的提示信息。 新增的 PGSQL PITR 监控面板,用于在 PITR 过程中提供更好的可观测性 针对在 Docker 虚拟机镜像中运行 Pigsty 进行了一系列铺垫与准备。 新增了 防呆设计 ,避免在非 Pigsty 纳管的节点上运行 pgsql.yml 剧本 (AdamYLK ) 针对每个支持的发行版大版本配置了独立的配置文件:el7, el8, el9, debian11, debian12, ubuntu20, ubuntu22 软件版本升级
PostgreSQL 16.3 Patroni 3.3.0 pgBackRest 2.51 VIP-Manager v2.5.0 Haproxy 2.9.7 Grafana 10.4.2 Prometheus 2.51 Loki & Promtail: 3.0.0 (警告:大版本非兼容性变更!) Alertmanager 0.27.0 BlackBox Exporter 0.25.0 Node Exporter 1.8.0 pgBackrest Exporter 0.17.0 duckdb 0.10.2 etcd 3.5.13 minio-20240510014138 / mcli-20240509170424 pev2 v1.8.0 -> v1.11.0 pgvector 0.6.1 -> 0.7.0pg_tle: v1.3.4 -> v1.4.0 hydra: v1.1.1 -> v1.1.2 duckdb_fdw: v1.1.0 重新针对 libduckdb 0.10.2 进行编译 pg_bm25 0.5.6 -> pg_search 0.7.0 pg_analytics: 0.5.6 -> 0.6.1 pg_graphql: 1.5.0 -> 1.5.4 pg_net 0.8.0 -> 0.9.1 pg_sparse (deprecated) Docker应用模板
缺陷修复
修复了 pg_exporters 角色中的变量空白问题。 修复了 minio_cluster 变量没有在全局配置中注释掉的问题 修复了 EL7 模板中的 postgis34 插件名称问题,应该使用 postgis33 修复了 EL8 python3.11-cryptography 依赖名的问题,上游现在变更为 python3-cryptography。 修复了 /pg/bin/pg-role 无法在非交互式 Shell 模式下获取操作系统用户名的问题 修复了 /pg/bin/pg-pitr 无法正确提示 -X -P 选项的问题 API变更
新参数 node_write_etc_hosts,用于控制是否向目标节点的 /etc/hosts 文件写入静态 DNS 解析记录 新增了 prometheus_sd_dir 参数,用于指定 Prometheus 静态服务发现的目标文件目录 configure 脚本新增了 -x|--proxy 参数,用于将当前环境的代理信息写入配置文件 by @waitingsong in https://github.com/Vonng/pigsty/pull/405 不再使用 Promtail & Loki 解析 Infra 节点上的 Nginx 日志细节标签,因为这样会导致标签基数爆炸。 在 Prometheus 配置中使用 alertmanager API v2 替代 v1 在 PGSQL 模块中,使用 /pg/cert/ca.crt 代替 /etc/pki/ca.crt,降低对节点根证书的依赖。 新的贡献者
完整的变更日志 : https://github.com/Vonng/pigsty/compar
离线软件包校验和
ec271a1d34b2b1360f78bfa635986c3a pigsty-pkg-v2.7.0.el8.x86_64.tgz
f3304bfd896b7e3234d81d8ff4b83577 pigsty-pkg-v2.7.0.debian12.x86_64.tgz
5b071c2a651e8d1e68fc02e7e922f2b3 pigsty-pkg-v2.7.0.ubuntu22.x86_64.tgz
v2.6.0 亮点特性
软件配置变更
使用 node_repo_modules 替换 node_repo_method 参数,并移除 node_repo_local_urls 参数。 暂时关闭 Grafana 统一告警功能,避免 “Database Locked” 错误。 新增 node_repo_modules 参数,用于指定在节点上添加的上游仓库源。 移除 node_local_repo_urls,其功能由 node_repo_modules & repo_upstream 替代。 移除 node_repo_method 参数,其功能由 node_repo_modules 替代。 在 repo_upstream 添加新的 local 源,并通过 node_repo_modules 使用,替代 node_local_repo_urls 的功能 重排 node_default_packages,infra_packages,pg_packages,pg_extensions 参数默认值。 在 repo_upstream 中替换 repo_upstream.baseurl 时,如果 EL8/9 PGDG小版本特定的仓库可用,使用 major.minor 而不是 major 替换 $releasever,提高小版本兼容性。 软件版本升级
Grafana 10.3 Prometheus 2.47 node_exporter 1.7.0 HAProxy 2.9.5 Loki / Promtail 2.9.4 minio-20240216110548 / mcli-20240217011557 etcd 3.5.11 Redis 7.2.4 Bytebase 2.13.2 DuckDB 0.10.0 FerretDB 1.19 Metabase:新Docker应用模板 PostgreSQL扩展插件
PostgreSQL 小版本升级: 16.2, 15.6, 14.11, 13.14, 12.18 PostgreSQL 16: 现在被提升为默认主版本 pg_exporter 0.6.1:安全修复 Patroni 3.2.2 pgBadger 12.4 pgBackRest 2.50 vip-manager 2.3.0 PostGIS 3.4.2 TimescaleDB 2.14.1 向量扩展 PGVector 0.6.0:新增并行创建 HNSW 索引功能 新增扩展插件 duckdb_fdw v1.1 ,支持读写 DuckDB 数据 v1.1 新增扩展插件 pgsql-gzip ,用于支持 Gzip 压缩解压缩 v1.0.0 新增扩展插件 pg_sparse ,高效处理稀疏向量(ParadeDB) v0.5.6 新增扩展插件 pg_bm25 ,用于支持高质量全文检索 BM25 算法的插件(ParadeDB) v0.5.6 新增扩展插件 pg_analytics ,支持 SIMD 与列式存储的PG分析插件(ParadeDB) v0.5.6 升级AIML插件 pgml 至 v2.8.1,新增 PG 16 支持。 升级列式存储插件 hydra 版本至 v1.1.1,新增 PG 16 支持。 升级图扩展插件 age 至 v1.5.0,新增 PG 16 支持。 升级GraphQL插件 pg_graphql 版本至 v1.5.0 ,支持 Supabase。 330e9bc16a2f65d57264965bf98174ff pigsty-v2.6.0.tgz
81abcd0ced798e1198740ab13317c29a pigsty-pkg-v2.6.0.debian11.x86_64.tgz
7304f4458c9abd3a14245eaf72f4eeb4 pigsty-pkg-v2.6.0.debian12.x86_64.tgz
f914fbb12f90dffc4e29f183753736bb pigsty-pkg-v2.6.0.el7.x86_64.tgz
fc23d122d0743d1c1cb871ca686449c0 pigsty-pkg-v2.6.0.el8.x86_64.tgz
9d258dbcecefd232f3a18bcce512b75e pigsty-pkg-v2.6.0.el9.x86_64.tgz
901ee668621682f99799de8932fb716c pigsty-pkg-v2.6.0.ubuntu20.x86_64.tgz
39872cf774c1fe22697c428be2fc2c22 pigsty-pkg-v2.6.0.ubuntu22.x86_64.tgz
v2.5.1 跟进 PostgreSQL v16.1, v15.5, 14.10, 13.13, 12.17, 11.22 小版本例行更新。
现在 PostgreSQL 16 的所有重要扩展已经就位(新增 pg_repack 与 timescaledb 支持)
软件更新:PostgreSQL to v16.1, v15.5, 14.10, 13.13, 12.17, 11.22 Patroni v3.2.0 PgBackrest v2.49 Citus 12.1 TimescaleDB 2.13 Grafana v10.2.0 FerretDB 1.15 SealOS 4.3.7 Bytebase 2.11.1 移除 PGCAT 监控面板中查询对 monitor 模式前缀(允许用户将 pg_stat_statements 扩展装到别的地方) 新的配置模板 wool.yml,为阿里云免费99 ECS 单机针对设计。 为 EL9 新增 python3-jmespath 软件包,解决 Ansible 依赖更新后 bootstrap 缺少 jmespath 的问题 31ee48df1007151009c060e0edbd74de pigsty-pkg-v2.5.1.el7.x86_64.tgz
a40f1b864ae8a19d9431bcd8e74fa116 pigsty-pkg-v2.5.1.el8.x86_64.tgz
c976cd4431fc70367124fda4e2eac0a7 pigsty-pkg-v2.5.1.el9.x86_64.tgz
7fc1b5bdd3afa267a5fc1d7cb1f3c9a7 pigsty-pkg-v2.5.1.debian11.x86_64.tgz
add0731dc7ed37f134d3cb5b6646624e pigsty-pkg-v2.5.1.debian12.x86_64.tgz
99048d09fa75ccb8db8e22e2a3b41f28 pigsty-pkg-v2.5.1.ubuntu20.x86_64.tgz
431668425f8ce19388d38e5bfa3a948c pigsty-pkg-v2.5.1.ubuntu22.x86_64.tgz
v2.5.0 curl https://get.pigsty.cc/latest | bash
亮点特性
Ubuntu / Debian 支持: bullseye, bookworm, jammy, focal
使用CDN repo.pigsty.cc 软件源,提供 rpm/deb 软件包下载。
Anolis 操作系统支持( 兼容 EL 8.8 )。
使用 PostgreSQL 16 替代 PostgreSQL 14 作为备选主要支持版本
新增了 PGSQL Exporter / PGSQL Patroni 监控面板,重做 PGSQL Query 面板
扩展更新:
PostGIS 版本至 3.4( EL8/EL9 ),EL7 仍使用 PostGIS 3.3 移除 pg_embedding,因为开发者不再对其进行维护,建议使用 pgvector 替换。 新扩展(EL):点云插件 pointcloud 支持,Ubuntu原生带有此扩展。 新扩展(EL): imgsmlr, pg_similarity,pg_bigm 用于搜索。 重新编译 pg_filedump 为 PG 大版本无关的软件包。。 新收纳 hydra 列存储扩展,不再默认安装 citus 扩展。 软件更新:
Grafana 更新至 v10.1.5 Prometheus 更新至 v2.47 Promtail/Loki 更新至 v2.9.1 Node Exporter 更新至 v1.6.1 Bytebase 更新至 v2.10.0 patroni 更新至 v3.1.2 pgbouncer 更新至 v1.21.0 pg_exporter 更新至 v0.6.0 pgbackrest 更新至 v2.48.0 pgbadger 更新至 v12.2 pg_graphql 更新至 v1.4.0 pg_net 更新至 v0.7.3 ferretdb 更新至 v0.12.1 sealos 更新至 4.3.5 Supabase 支持更新至 20231013070755 Ubuntu 支持说明
Pigsty 支持了 Ubuntu 22.04 (jammy) 与 20.04 (focal) 两个 LTS 版本,并提供相应的离线软件安装包。
相比 EL 系操作系统,一些参数的默认值需要显式指定调整,详情请参考 ubuntu.yml
repo_upstream:按照 Ubuntu/Debian 的包名进行了调整repo_packages:按照 Ubuntu/Debian 的包名进行了调整node_repo_local_urls:默认值为 ['deb [trusted=yes] http://${admin_ip}/pigsty ./']node_default_packages :zlib -> zlib1g, readline -> libreadline-devvim-minimal -> vim-tiny, bind-utils -> dnsutils, perf -> linux-tools-generic,新增软件包 acl,确保 Ansible 权限设置正常工作 infra_packages:所有含 _ 的包要替换为 - 版本,此外 postgresql-client-16 用于替换 postgresql16pg_packages:Ubuntu 下惯用 - 替代 _,不需要手工安装 patroni-etcd 包。pg_extensions:扩展名称与EL系不太一样,Ubuntu下缺少 passwordcheck_cracklib 扩展。pg_dbsu_uid: Ubuntu 下 Deb 包不显式指定uid,需要手动指定,Pigsty 默认分配为 543API变更
默认值变化:
repo_modules 现在的默认值为 infra,node,pgsql,redis,minio,启用所有上游源
repo_upstream 发生变化,现在添加了 Pigsty Infra/MinIO/Redis/PGSQL 模块化软件源
repo_packages 发生变化,移除未使用的 karma,mtail,dellhw_exporter,移除了 PG14 主要扩展,新增了 PG16 主要扩展,添加了 virtualenv 包。
node_default_packages 发生变化,默认安装 python3-pip 组件。
pg_libs: timescaledb 从 shared_preload_libraries 中移除,现在默认不自动启用。
pg_extensions 发生变化,不再默认安装 Citus 扩展,默认安装 passwordcheck_cracklib 扩展,EL8,9 PostGIS 默认版本升级至 3.4
- pg_repack_${pg_version}* wal2json_${pg_version}* passwordcheck_cracklib_${pg_version}*
- postgis34_${pg_version}* timescaledb-2-postgresql-${pg_version}* pgvector_${pg_version}*
Patroni 所有模板默认移除 wal_keep_size 参数,避免触发 Patroni 3.1.1 的错误,其功能由 min_wal_size 覆盖。
87e0be2edc35b18709d7722976e305b0 pigsty-pkg-v2.5.0.el7.x86_64.tgz
e71304d6f53ea6c0f8e2231f238e8204 pigsty-pkg-v2.5.0.el8.x86_64.tgz
39728496c134e4352436d69b02226ee8 pigsty-pkg-v2.5.0.el9.x86_64.tgz
e3f548a6c7961af6107ffeee3eabc9a7 pigsty-pkg-v2.5.0.debian11.x86_64.tgz
1e469cc86a19702e48d7c1a37e2f14f9 pigsty-pkg-v2.5.0.debian12.x86_64.tgz
cc3af3b7c12f98969d3c6962f7c4bd8f pigsty-pkg-v2.5.0.ubuntu20.x86_64.tgz
c5b2b1a4867eee624e57aed58ac65a80 pigsty-pkg-v2.5.0.ubuntu22.x86_64.tgz
v2.4.1 Supabase 支持:开源的 Firebase 替代,现可使用 Pigsty 本地托管的 PostgreSQL 实例作为数据存储。PostgresML 支持:使用SQL完成经典机器学习算法,训练、微调、调用大语言模型(hugging face)。FerretDB v1.10 支持,在 PostgreSQL 上提供 MongoDB API与协议兼容能力。GraphQL扩展: pg_graphql :从现有模式中反射出 GraphQL 模式,提供库内 GraphQL 查询能力。 JWT支持扩展:pgjwt 允许您使用 SQL 验证签发 JWT (JSON Web Tokens)。 密钥存储扩展: vault 可以在提供一个安全存储加密密钥的保险柜。 数据恢复扩展:pg_filedump :可用于快速从PostgreSQL二进制文件中恢复数据 图数据库扩展:Apache age ,为 PostgreSQL 添加 OpenCypher 查询支持,类似 Neo4J 中文分词扩展:zhparser ,为中文全文检索提供分词能力,类似 ElasticSearch。 高效位图扩展:pg_roaringbitmap ,在 PostgreSQL 中提供 roaring bitmap 的支持,高效计数聚合统计。 向量嵌入替代:pg_embedding ,提供了不同于 pgvector 的另一种 HNSW 替代实现。 可信语言扩展:pg_tle ,由 AWS 出品的,允许您打包分发管理由可信存储过程语言编写的函数。 HTTP客户端扩展:pgsql-http :使用 SQL 接口,curl API,发起 HTTP 请求,与各类系统交互。 异步HTTP扩展: pg_net 允许您使用 SQL 发起非阻塞的 HTTP/HTTPS 请求。 列式存储引擎:hydra 针对分析场景打造的向量化列存储引擎,原地替代 Citus 列存插件。 其他PGDG扩展:新收录8个由PGDG维护的扩展插件,Pigsty支持的插件总数达到 150+ 。 PostgreSQL 16 内核支持,监控云端 RDS / PolarDB for PostgreSQL。 亮点特性
Supabase 支持:开源的 Firebase 替代,现可使用 Pigsty 托管的 PostgreSQL 实例存储数据。PostgresML 支持:在 PostgreSQL 运行各类模型(hugging face),向量操作,经典机器学习算法。GraphQL支持扩展: pg_graphql :从现有模式中反射出 GraphQL 模式,提供库内 GraphQL 查询能力。 异步HTTP客户端扩展: pg_net 允许您使用 SQL 发起非阻塞的 HTTP/HTTPS 请求 JWT支持扩展:pgjwt 允许您使用 SQL 验证签发 JWT (JSON Web Tokens) 密钥存储扩展: vault 可以在保险柜里存储加密密钥 将FerretDB 版本升级至 v1.10 新增组件:pg_filedump :可用于快速从PostgreSQL二进制文件中恢复数据 减少 EL9 离线软件包的大小,移除非必须依赖项 proj-data* 修复了 Patroni 3.1.1 的错误 efabe7632d8994f3fb58f9838b8f9d7d pigsty-pkg-v2.5.0.el7.x86_64.tgz # 1.1G
ea78957e8c8434b120d1c8c43d769b56 pigsty-pkg-v2.5.0.el8.x86_64.tgz # 1.4G
4ef280a7d28872814e34521978b851bb pigsty-pkg-v2.5.0.el9.x86_64.tgz # 1.3G
v2.4.0 使用 bash -c "$(curl -fsSL https://get.pigsty.cc/latest)" 快速上手。
最新特性
PostgreSQL 16 正式发布,Pigsty提供支持。 可以监控云数据库,RDS for PostgreSQL,以及 PolarDB,提供全新的 PGRDS 监控面板 正式提供商业支持与咨询服务。并发布首个 LTS 版本,为订阅客户提供最长5年的支持。 新扩展插件: Apache AGE, openCypher graph query engine on PostgreSQL 新扩展插件: zhparser, full text search for Chinese language 新扩展插件: pg_roaringbitmap, roaring bitmap for PostgreSQL 新扩展插件: pg_embedding, hnsw alternative to pgvector 新扩展插件: pg_tle, admin / manage stored procedure extensions 新扩展插件: pgsql-http, issue http request with SQL interface 新增插件: pg_auth_mon pg_checksums pg_failover_slots pg_readonly postgresql-unit pg_store_plans pg_uuidv7 set_user Redis改进:支持 Redis 哨兵监控,配置主从集群的自动高可用。 API变化
新增参数,REDIS.redis_sentinel_monitor,用于指定 Sentinel 集群监控的主库列表 问题修复
修复 Grafana 10.1 注册数据源时缺少 uid 的问题 MD5 (pigsty-pkg-v2.4.0.el7.x86_64.tgz) = 257443e3c171439914cbfad8e9f72b17
MD5 (pigsty-pkg-v2.4.0.el8.x86_64.tgz) = 41ad8007ffbfe7d5e8ba5c4b51ff2adc
MD5 (pigsty-pkg-v2.4.0.el9.x86_64.tgz) = 9a950aed77a6df90b0265a6fa6029250
v2.3.1 使用 bash -c "$(curl -fsSL https://get.pigsty.cc/latest)" 快速开始。
最新特性
pgvector 更新至 0.5,添加 hnsw 算法支持。支持 PostgreSQL 16 RC1 (el8/el9) 默认包中添加了 SealOS 用于快速部署Kubernetes集群。 问题修复
修复了 infra.repo.repo_pkg 任务:当 repo_packages 中包名包含 * 时,下载可能会受到 /www/pigsty 现有内容的影响。 将 vip_dns_suffix 的默认值由 .vip 调整为空字符串,即集群本身的名称将默认作为节点集群的 L2 VIP modprobe watchdog and chown watchdog if patroni_watchdog_mode is required当 pg_dbsu_sudo = limit and patroni_watchdog_mode = required 时,授予数据库 dbsu 以下命令的 sudo 执行权限/usr/bin/sudo /sbin/modprobe softdog:在启动 Patroni 服务时确保 softdog 内核模块启用/usr/bin/sudo /bin/chown {{ pg_dbsu }} /dev/watchdog: 在启动 Patroni 服务时,确保 watchdog 属主正确 文档更新
向英文文档中添加了更新内容。 添加了简体中文版本的内置文档,修复了 pigsty.cc 文档站的中文文档。 软件更新
PostgreSQL 16 RC1 for EL8/EL9 PGVector 0.5.0,支持 hnsw 索引 TimescaleDB 2.11.2 grafana 10.1.0 loki & promtail 2.8.4 redis-stack 7.2 on el7/8 mcli-20230829225506 / minio-20230829230735 ferretdb 1.9 sealos 4.3.3 pgbadger 1.12.2 ce69791eb622fa87c543096cdf11f970 pigsty-pkg-v2.3.1.el7.x86_64.tgz
495aba9d6d18ce1ebed6271e6c96b63a pigsty-pkg-v2.3.1.el8.x86_64.tgz
38b45582cbc337ff363144980d0d7b64 pigsty-pkg-v2.3.1.el9.x86_64.tgz
v2.3.0 相关文章:《Pigsty v2.3 发布:应用生态丰富 》
发布注记:https://github.com/Vonng/pigsty/releases/tag/v2.3.0
使用 bash -c "$(curl -fsSL https://get.pigsty.cc/latest)" 快速开始。
亮点特性
INFRA: 添加了对 NODE/PGSQL VIP 的监控支持 PGSQL: 通过小版本升级修复了 PostgreSQL CVE-2023-39417 : 15.4, 14.9, 13.12, 12.16,以及 Patroni v3.1.0 NODE: 允许用户使用 keepalived 为一个节点集群绑定 L2 VIP REPO: Pigsty 专用 yum 源优化精简,全站默认使用 HTTPS: get.pigsty.cc 与 demo.pigsty.cc APP: 升级 app/bytebase 版本至 v2.6.0, app/ferretdb 版本至 v1.8;添加新的应用模板:nocodb ,开源的 Airtable。 REDIS: 升级版本至 v7.2,并重制了 Redis 监控面板。 MONGO: 添加基于 FerretDB 1.8 实现的基本支持。 MYSQL: 添加了 Prometheus / Grafana / CA 中的代码存根,便于后续纳管。 API变化
新增一个新的参数组 NODE.NODE_VIP:包含 8 个新参数
NODE.VIP.vip_enabled:在此节点集群上启用 vip 吗?NODE.VIP.vip_address:ipv4 格式的节点 vip 地址,如果启用了 vip,则必需NODE.VIP.vip_vrid:必需,整数,1-255 在相同 VLAN 中应该是唯一的NODE.VIP.vip_role:master/backup,默认为备份,用作初始角色NODE.VIP.vip_preempt:可选,true/false,默认为 false,启用 vip 抢占NODE.VIP.vip_interface:节点 vip 网络接口监听,eth0 默认NODE.VIP.vip_dns_suffix:节点 vip dns 名称后缀,默认为空字符串NODE.VIP.vip_exporter_port:keepalived 导出器监听端口,默认为 9650MD5 (pigsty-pkg-v2.3.0.el7.x86_64.tgz) = 81db95f1c591008725175d280ad23615
MD5 (pigsty-pkg-v2.3.0.el8.x86_64.tgz) = 6f4d169b36f6ec4aa33bfd5901c9abbe
MD5 (pigsty-pkg-v2.3.0.el9.x86_64.tgz) = 4bc9ae920e7de6dd8988ca7ee681459d
v2.2.0 相关文章:《Pigsty v2.2 发布 —— 监控系统大升级 》
发布注记:https://github.com/Vonng/pigsty/releases/tag/v2.2.0
快速开始: bash -c "$(curl -fsSL https://get.pigsty.cc/latest)"
亮点特性
监控面板重做: https://demo.pigsty.cc Vagrant沙箱重做: 支持 libvirt 与新的配置模板 Pigsty EL Yum 仓库: 统一收纳零碎 RPM,简化安装构建流程。 操作系统兼容性: 新增信创操作系统 UOS-v20-1050e 支持 新的配置模板:42 节点的生产仿真配置 统一使用官方 PGDG citus 软件包(el7) 软件升级
PostgreSQL 16 beta2 Citus 12 / PostGIS 3.3.3 / TimescaleDB 2.11.1 / PGVector 0.44 patroni 3.0.4 / pgbackrest 2.47 / pgbouncer 1.20 grafana 10.0.3 / loki/promtail/logcli 2.8.3 etcd 3.5.9 / haproxy v2.8.1 / redis v7.0.12 minio 20230711212934 / mcli 20230711233044 Bug修复
修复了 Docker 组权限的问题 29434bd 将 infra 操作系统用户组作为额外的组,而不是首要用户组。 修复了 Redis Sentinel Systemd 服务的自动启用状态 5c96feb 放宽了 bootstrap & configure 的检查,特别是当 /etc/redhat-release 不存在的时候。 升级到 Grafana 10,修复了 Grafana 9.x CVE-2023-1410 在 CMDB pglog 模式中添加了 PG 14 - 16 的 command tags 与 错误代码。 API变化
新增1个变量
INFRA.NGINX.nginx_exporter_enabled: 现在用户可以通过设置这个参数来禁用 nginx_exporter 。默认值变化:
repo_modules: node,pgsql,infra : redis 现在由 pigsty-el 仓库提供,不再需要 redis 模块。repo_upstream:新增 pigsty-el: 与具体EL版本无关的RPM: 例如 grafana, minio, pg_exporter, 等等…… 新增 pigsty-misc: 与具体EL版本有关的RPM: 例如 redis, prometheus 全家桶,等等…… 移除 citus: 现在 PGDG 中有完整的 EL7 - EL9 citus 12 支持 移除 remi: redis 现在由 pigsty-el 仓库提供,不再需要 redis 模块。 repo_packages:ansible python3 python3-pip python3-requests python3-jmespath python3.11-jmespath dnf-utils modulemd-tools # el7: python36-requests python36-idna yum-utils grafana loki logcli promtail prometheus2 alertmanager karma pushgateway node_exporter blackbox_exporter nginx_exporter redis_exporter redis etcd minio mcli haproxy vip-manager pg_exporter nginx createrepo_c sshpass chrony dnsmasq docker-ce docker-compose-plugin flamegraph lz4 unzip bzip2 zlib yum pv jq git ncdu make patch bash lsof wget uuid tuned perf nvme-cli numactl grubby sysstat iotop htop rsync tcpdump netcat socat ftp lrzsz net-tools ipvsadm bind-utils telnet audit ca-certificates openssl openssh-clients readline vim-minimal postgresql13* wal2json_13* pg_repack_13* passwordcheck_cracklib_13* postgresql12* wal2json_12* pg_repack_12* passwordcheck_cracklib_12* timescaledb-tools postgresql15 postgresql15* citus_15* pglogical_15* wal2json_15* pg_repack_15* pgvector_15* timescaledb-2-postgresql-15* postgis33_15* passwordcheck_cracklib_15* pg_cron_15* postgresql14 postgresql14* citus_14* pglogical_14* wal2json_14* pg_repack_14* pgvector_14* timescaledb-2-postgresql-14* postgis33_14* passwordcheck_cracklib_14* pg_cron_14* postgresql16* wal2json_16* pgvector_16* pg_squeeze_16* postgis34_16* passwordcheck_cracklib_16* pg_cron_16* patroni patroni-etcd pgbouncer pgbadger pgbackrest pgloader pg_activity pg_partman_15 pg_permissions_15 pgaudit17_15 pgexportdoc_15 pgimportdoc_15 pg_statement_rollback_15* orafce_15* mysqlcompat_15 mongo_fdw_15* tds_fdw_15* mysql_fdw_15 hdfs_fdw_15 sqlite_fdw_15 pgbouncer_fdw_15 multicorn2_15* powa_15* pg_stat_kcache_15* pg_stat_monitor_15* pg_qualstats_15 pg_track_settings_15 pg_wait_sampling_15 system_stats_15 plprofiler_15* plproxy_15 plsh_15* pldebugger_15 plpgsql_check_15* pgtt_15 pgq_15* pgsql_tweaks_15 count_distinct_15 hypopg_15 timestamp9_15* semver_15* prefix_15* rum_15 geoip_15 periods_15 ip4r_15 tdigest_15 hll_15 pgmp_15 extra_window_functions_15 topn_15 pg_background_15 e-maj_15 pg_catcheck_15 pg_prioritize_15 pgcopydb_15 pg_filedump_15 pgcryptokey_15 logerrors_15 pg_top_15 pg_comparator_15 pg_ivm_15* pgsodium_15* pgfincore_15* ddlx_15 credcheck_15 safeupdate_15 pg_squeeze_15* pg_fkpart_15 pg_jobmon_15 repo_url_packages:node_default_packages:lz4,unzip,bzip2,zlib,yum,pv,jq,git,ncdu,make,patch,bash,lsof,wget,uuid,tuned,nvme-cli,numactl,grubby,sysstat,iotop,htop,rsync,tcpdump netcat,socat,ftp,lrzsz,net-tools,ipvsadm,bind-utils,telnet,audit,ca-certificates,openssl,readline,vim-minimal,node_exporter,etcd,haproxy,python3,python3-pip infra_packagesgrafana,loki,logcli,promtail,prometheus2,alertmanager,karma,pushgateway node_exporter,blackbox_exporter,nginx_exporter,redis_exporter,pg_exporter nginx,dnsmasq,ansible,postgresql15,redis,mcli,python3-requests PGSERVICE in .pigsty 被移除了,取而代之的是 PGDATABASE=postgres,这用户只需 IP 地址就可以从管理节点访问特定实例。目录结构变化:
bin/dns and bin/ssh 现在被移动到 vagrant/ 目录中。MD5 ( pigsty-pkg-v2.2.0.el7.x86_64.tgz) = 5fb6a449a234e36c0d895a35c76add3c
MD5 ( pigsty-pkg-v2.2.0.el8.x86_64.tgz) = c7211730998d3b32671234e91f529fd0
MD5 ( pigsty-pkg-v2.2.0.el9.x86_64.tgz) = 385432fe86ee0f8cbccbbc9454472fdd
v2.1.0 相关文章:Pigsty v2.1 发布:向量扩展 / PG12-16 支持
发布注记:https://github.com/Vonng/pigsty/releases/tag/v2.1.0
Highlight
PostgreSQL 16 beta 支持, 以及 12 ~ 15 的支持. 为 PG 12 - 15 新增了 PGVector 扩展支持,用于存储 AI 嵌入。 为 Grafana 添加了额外6个默认的扩展面板/数据源插件。 添加 bin/profile 脚本用于执行远程 Profiling ,生成火焰图。 添加 bin/validate 用于校验 pigsty.yml 配置文件合法性。 添加 bin/repo-add 用于快速向节点添加软件源定义。 PostgreSQL 16 可观测性:添加了 pg_stat_io 支持与相关监控面板 软件升级
PostgreSQL 15.3 , 14.8, 13.11, 12.15, 11.20, and 16 beta1 pgBackRest 2.46 / pgbouncer 1.19 Redis 7.0.11 Grafana v9.5.3 Loki / Promtail / Logcli 2.8.2 Prometheus 2.44 TimescaleDB 2.11.0 minio-20230518000536 / mcli-20230518165900 Bytebase v2.2.0 改进增强
当添加本地用户的公钥时,所有的 id*.pub 都会被添加到远程机器上(例如椭圆曲线算法生成的密钥文件) v2.0.2 https://github.com/Vonng/pigsty/releases/tag/v2.0.2
亮点
使用开箱即用的 pgvector 存储 AI Embedding、索引、检索向量。
变更
新扩展插件 pgvector 用于存储 AI 嵌入,并执行向量相似度搜索。 修复 MinIO CVE-2023-28432 ,使用 20230324 新提供的 policy API. 为 DNSMASQ systemd 服务添加动态重载命令 更新 PEV 版本至 v1.8 更新 grafana 版本至 v9.4.7 更新 MinIO 与 MCLI 版本至 20230324 更新 bytebase 版本至 v1.15.0 更新监控面板并修复死链接 更新了阿里云 Terraform 模板,默认使用 RockyLinux 9 使用 Grafana v9.4 的 Provisioning API 为众多管理任务添加了 asciinema 视频 修复了 EL8 PostgreSQL 的破损依赖:移除 anonymizer_15 faker_15 pgloader MD5 ( pigsty-pkg-v2.0.2.el7.x86_64.tgz) = d46440a115d741386d29d6de646acfe2
MD5 ( pigsty-pkg-v2.0.2.el8.x86_64.tgz) = 5fa268b5545ac96b40c444210157e1e1
MD5 ( pigsty-pkg-v2.0.2.el9.x86_64.tgz) = c8b113d57c769ee86a22579fc98e8345
v2.0.1 https://github.com/Vonng/pigsty/releases/tag/v2.0.1
安全性改进,与对 v2.0.0 的 BUG 修复。
改进
更换猪头 logo 以符合 PostgreSQL 商标政策。 将 grafana 版本升级至 v9.4,界面更佳且修复了 bug。 将 patroni 版本升级至 v3.0.1,其中包含了一些 bug 修复。 修改:将 grafana systemd 服务文件回滚到 rpm 默认的版本。 使用缓慢的 copy 代替 rsync 来复制 grafana 仪表板,更加可靠。 增强:bootstrap 执行后会添加回默认 repo 文件。 添加 asciinema 视频,用于各种管理任务。 安全增强模式:限制监控用户权限。 新的配置模板:dual.yml,用于双节点部署。 在 crit.yml 模板中启用 log_connections 和 log_disconnections。 在 crit.yml 模板中的 pg_libs 中启用 $lib/passwordcheck。 明确授予 pg_monitor 角色监视视图权限。 从 dbuser_monitor 中移除默认的 dbrole_readonly 以限制监控用户的权限 现在 patroni 监听在 {{ inventory_hostname }} 而不是 0.0.0.0 现在你可以使用 pg_listen 控制 postgres/pgbouncer 监听的地址 现在你可以在 pg_listen 中使用 ${ip}, ${lo}, ${vip} 占位符 将 Aliyun terraform 镜像从 centos 7.9 提升到 rocky Linux 9 将 bytebase 版本升级到 v1.14.0 BUG修复
为 alertmanager 添加缺失的 advertise 地址。 解决使用 bin/pgsql-user 创建数据库用户时,pg_mode 变量缺失问题。 在 redis.yml 中为 Redis 集群加入任务添加 -a password 选项。 在 infra-rm.yml.remove infra data 任务中补充缺失的默认值。 修复 prometheus 监控对象定义文件的属主为 prometheus 用户。 使用 管理员用户 而不是 root 去删除 DCS 中的元数据。 修复了由 grafana 9.4 bug 导致的问题:Meta数据源缺失。 注意事项
EL8 pgdg 上游官方源处于依赖破损状态,请小心使用。涉及到的软件包: postgis33_15, pgloader, postgresql_anonymizer_15*, postgresql_faker_15
如何升级?
cd ~/pigsty; tar -zcf /tmp/files.tgz files; rm -rf ~/pigsty # backup files dir and remove
cd ~; bash -c " $( curl -fsSL https://get.pigsty.cc/latest) " # get latest pigsty source
cd ~/pigsty; rm -rf files; tar -xf /tmp/files.tgz -C ~/pigsty # restore files dir
Checksums
MD5 ( pigsty-pkg-v2.0.1.el7.x86_64.tgz) = 5cfbe98fd9706b9e0f15c1065971b3f6
MD5 ( pigsty-pkg-v2.0.1.el8.x86_64.tgz) = c34aa460925ae7548866bf51b8b8759c
MD5 ( pigsty-pkg-v2.0.1.el9.x86_64.tgz) = 055057cebd93c473a67fb63bcde22d33
特别感谢 @cocoonkid 提供的反馈。
v2.0.0 相关文章:
Pigsty v2.0.0 正式发布!
从v2.0.0开始,PIGSTY 现在是 “PostgreSQL In Great STYle"的首字母缩写,即"全盛状态的PostgreSQL”。
curl -fsSL https://get.pigsty.cc/latest | bash
Download directly from GitHub Release bash -c " $( curl -fsSL https://raw.githubusercontent.com/Vonng/pigsty/master/bin/get) "
# or download tarball directly with curl (EL9)
curl -L https://github.com/Vonng/pigsty/releases/download/v2.0.0/pigsty-v2.0.0.tgz -o ~/pigsty.tgz
curl -L https://github.com/Vonng/pigsty/releases/download/v2.0.0/pigsty-pkg-v2.0.0.el9.x86_64.tgz -o /tmp/pkg.tgz
# EL7: https://github.com/Vonng/pigsty/releases/download/v2.0.0/pigsty-pkg-v2.0.0.el7.x86_64.tgz
# EL8: https://github.com/Vonng/pigsty/releases/download/v2.0.0/pigsty-pkg-v2.0.0.el8.x86_64.tgz
亮点
完美整合 PostgreSQL 15, PostGIS 3.3, Citus 11.2, TimescaleDB 2.10,分布式地理时序超融合数据库。 OS兼容性大幅增强:支持 EL7,8,9,以及 RHEL, CentOS, Rocky, OracleLinux, AlmaLinux等兼容发行版。 安全性改进:自签名CA,全局网络流量SSL加密,密码scram-sha-256认证,备份采用AES加密,重制的HBA规则系统。 Patroni升级至3.0,提供原生的高可用 Citus 分布式集群支持,默认启用FailSafe模式,无惧DCS故障致全局主库瘫痪。 提供基于 pgBackRest 的开箱即用的时间点恢复 PITR 支持,默认支持本地文件系统与专用MinIO/S3集群备份。 新模块 ETCD,可独立部署,简易扩缩容,自带监控高可用,彻底取代 Consul 作为高可用 PG 的 DCS。 新模块 MINIO,可独立部署,支持多盘多节点部署,用作S3本地替代,亦用于集中式 PostgreSQL 备份仓库。 大幅精简配置文件参数,无需默认值即可使用;模板自动根据机器规格调整主机与PG参数,HBA/服务的定义更简洁泛用。 受 Grafana 与 MinIO 影响,软件协议由 Apache License 2.0 变更为 AGPL 3.0 兼容性
支持 EL7, EL8, EL9 三个大版本,并提供三个版本对应的离线软件包,默认开发测试环境由EL7升级至EL9。 支持更多EL兼容Linux发行版:RHEL, CentOS, RockyLinux, AlmaLinux, OracleLinux等… 源码包与离线软件包的命名规则发生改变,现在版本号,操作系统版本号,架构都会体现在包名中。 PGSQL: PostgreSQL 15.2, PostGIS 3.3, Citus 11.2, TimescaleDB 2.10 现可同时使用,协同工作。PGSQL: Patroni 升级至 3.0 版本,作为 PGSQL 的高可用组件。默认使用 ETCD 作为 DCS,取代 Consul,减少一个 Consul Agent 失效点。 因为 vip-manager 升级至 2.1 并使用 ETCDv3 API,彻底弃用 ETCDv2 API,Patroni同理 提供原生的高可用 Citus 分布式集群支持。使用完全开源所有功能的 Citus 11.2。 默认启用FailSafe模式,无惧DCS故障致全局主库瘫痪。 PGSQL: 引入 pgBackrest v2.44 提供开箱即用的 PostgreSQL 时间点恢复 PITR 功能默认使用主库上的备份目录创建备份仓库,滚动保留两天的恢复窗口。 默认备选备份仓库为专用 MinIO/S3 集群,滚动保留两周的恢复窗口,本地使用需要启用 MinIO 模块。 ETCD 现在作为一个独立部署的模块,带有完整的扩容/缩容方案与监控。MINIO 现在成为一个独立部署的模块,支持多盘多节点部署,用作S3本地替代,亦可用作集中式备份仓库。NODE 模块现在包含 haproxy, docker, node_exporter, promtail 功能组件chronyd 现在取代 ntpd 成为所有节点默认的 NTP 服务。HAPROXY 现从属于 NODE 的一部分,而不再是 PGSQL 专属,可以 NodePort 的方式对外暴露服务。 现在 PGSQL 模块可以使用专用的集中式 HAPROXY 集群统一对外提供服务。 INFRA 模块现在包含 dnsmasq, nginx, prometheus, grafana, loki 等组件Infra 模块中的 DNSMASQ 服务器默认启用,并添加为所有节点的默认 DNS 服务器之一。 添加了 blackbox_exporter 用于主机 PING 探测,pushgateway 用于批处理任务指标。 loki 与 promtail 现在使用 Grafana 默认的软件包,使用官方的 Grafana Echarts 面板插件提供针对 PostgreSQL 15 的新增可观测性位点的监控支持,添加 Patroni 监控 软件版本升级PostgreSQL 15.2 / PostGIS 3.3 / TimescaleDB 2.10 / Citus 11.2 Patroni 3.0 / Pgbouncer 1.18 / pgBackRest 2.44 / vip-manager 2.1 HAProxy 2.7 / Etcd 3.5 / MinIO 20230131022419 / mcli 20230128202938 Prometheus 2.42 / Grafana 9.3 / Loki & Promtail 2.7 / Node Exporter 1.5 安全性
启用了一个完整的本地自签名CA:pigsty-ca,用于签发内网组件所使用的证书。 创建用户/修改密码的操作将不再会在日志文件中留下痕迹。 Nginx 默认启用 SSL 支持(如需HTTPS,您需要在系统中信任pigsty-ca,或使用Chrome thisisunsafe) ETCD 全面启用 SSL 加密客户端与服务端对等通信 PostgreSQL 添加并默认启用了 SSL 支持,管理链接默认都使用SSL访问。 Pgbouncer 添加了 SSL 支持,出于性能考虑默认不启用。 Patroni 添加了 SSL 支持,并默认限制了管理 API 只能从本机与管理节点使用密码认证方可访问。 PostgreSQL 的默认密码认证方式由 md5 改为 scram-sha-256。 Pgbouncer添加了认证查询支持,可以动态管理连接池用户。 pgBackRest 使用远端集中备份存储仓库时,默认使用 AES-256-CBC 加密备份数据。 提供高安全等级配置模板:强制使用全局 SSL,并要求使用管理员证书登陆。 所有默认HBA规则现在全部在配置文件中显式定义。 可维护性
现有的配置模板可根据机器规格(CPU/内存/存储)自动调整优化。 现在可以动态配置 Postgres/Pgbouncer/Patroni/pgBackRest 的日志目录:默认为:/pg/log/<type>/ 原有的 IP 地址占位符 10.10.10.10 被替换为一个专用变量:${admin_ip},可在多处引用,便于切换备用管理节点。 您可以指定 region 来使用不同地区的上游镜像源,以加快软件包的下载速度。 现在允许用户定义更细粒度的上游源地址,您可以根据不同的EL版本、架构,以及地区,使用不同的上游源。 提供了阿里云与AWS中国地区的 Terraform 模板,可用于一键拉起所需的 EC2 虚拟机。 提供了多种不同规格的 Vagrant 沙箱模板:meta, full, el7/8/9, minio, build, citus 添加了新的专用剧本:pgsql-monitor.yml 用于监控现有的 Postgres 实例或 RDS。 添加了新的专用剧本:pgsql-migration.yml ,使用逻辑复制无缝迁移现有实例至 Pigsty管理的集群。 添加了一系列专用 Shell 实用命令,封装常见运维操作,方便用户使用。 优化了所有 Ansible Role 的实现,使其更加简洁、易读、易维护,无需默认参数即可使用。 允许在业务数据库/用户的层次上定义额外的 Pgbouncer 参数。 API变更
Pigsty v2.0 进行了大量变更,新增64个参数,移除13个参数,重命名17个参数。
新增的参数
INFRA.META.admin_ip : 主元节点 IP 地址INFRA.META.region : 上游镜像区域:default|china|europeINFRA.META.os_version : 企业版 Linux 发行版本:7,8,9INFRA.CA.ca_cn : CA 通用名称,默认为 pigsty-caINFRA.CA.cert_validity : 证书有效期,默认为 20 年INFRA.REPO.repo_enabled : 在 infra 节点上构建本地 yum 仓库吗?INFRA.REPO.repo_upstream : 上游 yum 仓库定义列表INFRA.REPO.repo_home : 本地 yum 仓库的主目录,通常与 nginx_home ‘/www’ 相同INFRA.NGINX.nginx_ssl_port : https 监听端口INFRA.NGINX.nginx_ssl_enabled : 启用 nginx https 吗?INFRA.PROMTETHEUS.alertmanager_endpoint : altermanager 端点(ip|domain):端口格式NODE.NODE_TUNE.node_hugepage_ratio : 内存 hugepage 比率,默认禁用,值为 0NODE.HAPROXY.haproxy_service : 要公开的 haproxy 服务列表PGSQL.PG_ID.pg_mode : pgsql 集群模式:pgsql,citus,gpsqlPGSQL.PG_BUSINESS.pg_dbsu_password : dbsu 密码,默认为空字符串表示没有 dbsu 密码PGSQL.PG_INSTALL.pg_log_dir : postgres 日志目录,默认为 /pg/data/logPGSQL.PG_BOOTSTRAP.pg_storage_type : SSD|HDD,默认为 SSDPGSQL.PG_BOOTSTRAP.patroni_log_dir : patroni 日志目录,默认为 /pg/logPGSQL.PG_BOOTSTRAP.patroni_ssl_enabled : 使用 SSL 保护 patroni RestAPI 通信?PGSQL.PG_BOOTSTRAP.patroni_username : patroni rest api 用户名PGSQL.PG_BOOTSTRAP.patroni_password : patroni rest api 密码(重要:请更改此密码)PGSQL.PG_BOOTSTRAP.patroni_citus_db : 由 patroni 管理的 citus 数据库,默认为 postgresPGSQL.PG_BOOTSTRAP.pg_max_conn : postgres 最大连接数,auto 将使用推荐值PGSQL.PG_BOOTSTRAP.pg_shmem_ratio : postgres 共享内存比率,默认为 0.25,范围 0.1~0.4PGSQL.PG_BOOTSTRAP.pg_rto : 恢复时间目标,故障转移的 ttl,默认为 30sPGSQL.PG_BOOTSTRAP.pg_rpo : 恢复点目标,默认最多丢失 1MB 数据PGSQL.PG_BOOTSTRAP.pg_pwd_enc : 密码加密算法:md5|scram-sha-256PGSQL.PG_BOOTSTRAP.pgbouncer_log_dir : pgbouncer 日志目录,默认为 /var/log/pgbouncerPGSQL.PG_BOOTSTRAP.pgbouncer_auth_query : 如果启用,查询 pg_authid 表以检索 biz 用户,而不是填充用户列表PGSQL.PG_BOOTSTRAP.pgbouncer_sslmode : pgbouncer 客户端的 SSL:disable|allow|prefer|require|verify-ca|verify-fullPGSQL.PG_BOOTSTRAP.pg_service_provider : 专用的 haproxy 节点组名称,或者默认为本地节点的空字符串PGSQL.PG_BOOTSTRAP.pg_default_service_dest : 如果 svc.dest=‘default’,则为默认服务目标PGSQL.PG_BACKUP.pgbackrest_enabled : 启用 pgbackrest 吗?PGSQL.PG_BACKUP.pgbackrest_clean : 初始化期间删除 pgbackrest 数据吗?PGSQL.PG_BACKUP.pgbackrest_log_dir : pgbackrest 日志目录,默认为 /pg/logPGSQL.PG_BACKUP.pgbackrest_method : pgbackrest 备份仓库方法,local 或 minioPGSQL.PG_BACKUP.pgbackrest_repo : pgbackrest 备份仓库配置PGSQL.PG_DNS.pg_dns_suffix : pgsql dns 后缀,默认为空字符串PGSQL.PG_DNS.pg_dns_target : auto, primary, vip, none 或 ad hoc ipETCD.etcd_seq : etcd 实例标识符,必需ETCD.etcd_cluster : etcd 集群和组名称,默认为 etcdETCD.etcd_safeguard : 防止清除正在运行的 etcd 实例吗?ETCD.etcd_clean : 在初始化期间清除现有的 etcd 吗?ETCD.etcd_data : etcd 数据目录,默认为 /data/etcdETCD.etcd_port : etcd 客户端端口,默认为 2379ETCD.etcd_peer_port : etcd 对等端口,默认为 2380ETCD.etcd_init : etcd 初始集群状态,新建或已存在ETCD.etcd_election_timeout : etcd 选举超时,默认为 1000msETCD.etcd_heartbeat_interval : etcd 心跳间隔,默认为 100msMINIO.minio_seq : minio 实例标识符,必须参数MINIO.minio_cluster : minio 集群名称,默认为 minioMINIO.minio_clean : 初始化时清理 minio 吗?默认为 falseMINIO.minio_user : minio 操作系统用户,默认为 minioMINIO.minio_node : minio 节点名模式MINIO.minio_data : minio 数据目录,使用 {x…y} 来指定多个驱动器MINIO.minio_domain : minio 外部域名,默认为 sss.pigstyMINIO.minio_port : minio 服务端口,默认为 9000MINIO.minio_admin_port : minio 控制台端口,默认为 9001MINIO.minio_access_key : 根访问密钥,默认为 minioadminMINIO.minio_secret_key : 根秘密密钥,默认为 minioadminMINIO.minio_extra_vars : minio 服务器的额外环境变量MINIO.minio_alias : 本地 minio 部署的别名MINIO.minio_buckets : 待创建的 minio 存储桶列表MINIO.minio_users : 待创建的 minio 用户列表移除的参数
INFRA.CA.ca_homedir : CA 主目录,现在固定为 /etc/pki/INFRA.CA.ca_cert : CA 证书文件名,现在固定为 ca.keyINFRA.CA.ca_key : CA 密钥文件名,现在固定为 ca.keyINFRA.REPO.repo_upstreams : 已被 repo_upstream 替代PGSQL.PG_INSTALL.pgdg_repo : 现在由节点 playbooks 负责PGSQL.PG_INSTALL.pg_add_repo : 现在由节点 playbooks 负责PGSQL.PG_IDENTITY.pg_backup : 未使用且与部分名称冲突PGSQL.PG_IDENTITY.pg_preflight_skip : 不再使用,由 pg_id 替代DCS.dcs_name : 由于使用 etcd 而被移除DCS.dcs_servers : 被 ad hoc 组 etcd 替代DCS.dcs_registry : 由于使用 etcd 而被移除DCS.dcs_safeguard : 被 etcd_safeguard 替代DCS.dcs_clean : 被 etcd_clean 替代重命名的参数
nginx_upstream -> infra_portalrepo_address -> repo_endpointpg_hostname -> node_id_from_pgpg_sindex -> pg_grouppg_services -> pg_default_servicespg_services_extra -> pg_servicespg_hba_rules_extra -> pg_hba_rulespg_hba_rules -> pg_default_hba_rulespgbouncer_hba_rules_extra -> pgb_hba_rulespgbouncer_hba_rules -> pgb_default_hba_rulesvip_mode -> pg_vip_enabledvip_address -> pg_vip_addressvip_interface -> pg_vip_interfacenode_packages_default -> node_default_packagesnode_packages_meta -> infra_packagesnode_packages_meta_pip -> infra_packages_pipnode_data_dir -> node_dataChecksums
MD5 (pigsty-pkg-v2.0.0-rc1.el7.x86_64.tgz) = af4b5db9dc38c860de609956a8f1f0d3
MD5 (pigsty-pkg-v2.0.0-rc1.el8.x86_64.tgz) = 5b7152e142df3e3cbc06de30bd70e433
MD5 (pigsty-pkg-v2.0.0-rc1.el9.x86_64.tgz) = 1362e2a5680fc1a3a014cc4f304100bd
特别感谢意大利用户 @alemacci 在 SSL加密,备份,多操作系统发行版适配与自适应参数模版上的贡献!
v1.5.1 亮点
重要:修复了PG14.0-14.3中 CREATE INDEX|REINDEX CONCURRENTLY 可能导致索引数据损坏的问题。
Pigsty v1.5.1 升级默认PostgreSQL版本至 14.4 强烈建议尽快更新。
软件升级
postgres 升级至 to 14.4 haproxy 升级至 to 2.6.0 grafana 升级至 to 9.0.0 prometheus 升级至 2.36.0 patroni 升级至 2.1.4 问题修复
修复了pgsql-migration.yml中的TYPO 移除了HAProxy配置文件中的PID配置项 移除了默认软件包中的 i686 软件包 默认启用所有Systemd Redis Service 默认启用所有Systemd Patroni Service API变更
grafana_database 与 grafana_pgurl 被标记为过时API,将从后续版本移除New Apps
wiki.js : 使用Postgres搭建本地维基百科 FerretDB : 使用Postgres提供MongoDB API v1.5.0 亮点概述
完善的Docker支持:在管理节点上默认启用并提供诸多开箱即用的软件模板:bytebase, pgadmin, pgweb, postgrest, minio等。 基础设施自我监控:Nginx, ETCD, Consul, Prometheus, Grafana, Loki 自我监控 CMDB升级:兼容性改善,支持Redis集群/Greenplum集群元数据,配置文件可视化。 服务发现改进:可以使用Consul自动发现所有待监控对象,并纳入Prometheus中。 更好的冷备份支持:默认定时备份任务,添加pg_probackup备份工具,一键创建延时从库。 ETCD现在可以用作PostgreSQL/Patroni的DCS服务,作为Consul的备选项。 Redis剧本/角色改善:现在允许对单个Redis实例,而非整个Redis节点进行初始化与移除。 详细变更列表
监控面板
CMDB Overview:可视化Pigsty CMDB Inventory。 DCS Overview:查阅Consul与ETCD集群的监控指标。 Nginx Overview:查阅Pigsty Web访问指标与访问日志。 Grafana Overview:Grafana自我监控 Prometheus Overview:Prometheus自我监控 INFRA Dashboard进行重制,反映基础设施整体状态 监控架构
现在允许使用 Consul 进行服务发现(当所有服务注册至Consul时) 现在所有的Infra组件会启用自我监控,并通过infra_register角色注册至Prometheus与Consul中。 指标收集器 pg_exporter 更新至 v0.5.0,添加新功能,scale 与 default,允许为指标指定一个倍乘因子,以及指定默认值。 pg_bgwriter, pg_wal, pg_query, pg_db, pgbouncer_stat 关于时间的指标,单位由默认的毫秒或微秒统一缩放至秒。pg_table 中的相关计数器指标,现在配置有默认值 0,替代原有的NaN。pg_class指标收集器默认移除,相关指标添加至 pg_table 与 pg_index 收集器中。pg_table_size 指标收集器现在默认启用,默认设置有300秒的缓存时间。部署方案
新增可选软件包 docker.tgz,带有常用应用镜像:Pgadmin, Pgweb, Postgrest, ByteBase, Kong, Minio等。 新增角色ETCD,可以在DCS Servers指定的节点上自动部署ETCD服务,并自动纳入监控。 允许通过 pg_dcs_type 指定PG高可用使用的DCS服务,Consul(默认),ETCD(备选) 允许通过 node_crontab 参数,为节点配置定时任务,例如数据库备份、VACUUM,统计收集等。 新增了 pg_checksum 选项,启用时,数据库集群将启用数据校验和(此前只有crit模板默认启用) 新增了pg_delay选项,当实例为Standby Cluster Leader时,此参数可以用于配置一个延迟从库 新增了软件包 pg_probackup,默认角色replicator现在默认赋予了备份相关函数所需的权限。 Redis部署现在拆分为两个部分:Redis节点与Redis实例,通过redis_port参数可以精确控制一个具体实例。 Loki 与 Promtail 现在使用 frpm 制作的 RPM软件包进行安装。 DCS3配置模板现在使用一个3节点的pg-meta集群,与一个单节点的延迟从库。 软件升级
升级 PostgreSQL 至 14.3 升级 Redis 至 6.2.7 升级 PG Exporter 至 0.5.0 升级 Consul 至 1.12.0 升级 vip-manager 至 v1.0.2 升级 Grafana 至 v8.5.2 升级 Loki & Promtail 至 v2.5.0,使用frpm打包。 问题修复
修复了Loki 与 Promtail 默认配置文件名的问题 修复了Loki 与 Promtail 环境变量无法正确展开的问题 对英文文档进行了一次完整的翻译与修缮,文档依赖的JS资源现在直接从本地获取,无需互联网访问。 API变化
新参数
node_data_dir : 主要的数据挂载路径,如果不存在会被创建。node_crontab_overwrite : 覆盖 /etc/crontab 而非追加内容。node_crontab: 要被追加或覆盖的 node crontab 内容。nameserver_enabled: 在这个基础设施节节点上启用 nameserver 吗?prometheus_enabled: 在这个基础设施节节点上启用 prometheus 吗?grafana_enabled: 在这个基础设施节节点上启用 grafana 吗?loki_enabled: 在这个基础设施节节点上启用 loki 吗?docker_enable: 在这个基础设施节点上启用 docker 吗?consul_enable: 启用 consul 服务器/代理吗?etcd_enable: 启用 etcd 服务器/客户端吗?pg_checksum: 启用 pg 集群数据校验和吗?pg_delay: 备份集群主库复制重放时的应用延迟。参数重制
现在 *_clean 是布尔类型的参数,用于在初始化期间清除现有实例。
*_safeguard 也是布尔类型的参数,用于在执行任何剧本时,避免清除正在运行的实例。
pg_exists_action -> pg_cleanpg_disable_purge -> pg_safeguarddcs_exists_action -> dcs_cleandcs_disable_purge -> dcs_safeguard参数重命名
node_ntp_config -> node_ntp_enablednode_admin_setup -> node_admin_enablednode_admin_pks -> node_admin_pk_listnode_dns_hosts -> node_etc_hosts_defaultnode_dns_hosts_extra -> node_etc_hostsnode_dns_server -> node_dns_methodnode_local_repo_url -> node_repo_local_urlsnode_packages -> node_packages_defaultnode_extra_packages -> node_packagesnode_packages_meta -> node_packages_metanode_meta_pip_install -> node_packages_meta_pipnode_sysctl_params -> node_tune_paramsapp_list -> nginx_indexesgrafana_plugin -> grafana_plugin_methodgrafana_cache -> grafana_plugin_cachegrafana_plugins -> grafana_plugin_listgrafana_git_plugin_git -> grafana_plugin_githaproxy_admin_auth_enabled -> haproxy_auth_enabledpg_shared_libraries -> pg_libsdcs_type -> pg_dcs_typev1.4.1 日常错误修复 / Docker 支持 / 英文文档
现在,默认在元节点上启用 docker。您可以使用它启动海量的各类软件
现在提供英文文档。
Bug 修复
v1.4.0 架构
将系统解耦为4大类别:INFRA、NODES、PGSQL、REDIS,这使得pigsty更加清晰、更易于扩展。 单节点部署 = INFRA + NODES + PGSQL 部署pgsql集群 = NODES + PGSQL 部署redis集群 = NODES + REDIS 部署其他数据库 = NODES + xxx(例如 MONGO、KAFKA…待定) 可访问性
为中国大陆提供CDN。 使用 bash -c "$(curl -fsSL http://get.pigsty.cc/latest)" 获取最新源代码。 使用新的 download 脚本下载并提取包。 监控增强
将监控系统分为5大类别:INFRA、NODES、REDIS、PGSQL、APP 默认启用日志记录 模型和标签为所有仪表板添加了一个隐藏的ds prometheus数据源变量,因此您只需选择一个新的数据源而不是修改Grafana数据源和仪表板。 为所有指标添加了一个ip标签,并将其用作数据库指标和节点指标之间的连接键。 INFRA监控Infra主仪表板:INFRA概览 添加日志仪表板:日志实例 PGLOG分析和PGLOG会话现在被视为一个示例Pigsty APP。 NODES监控应用如果您完全不关心数据库,现在可以单独使用Pigsty作为主机监控软件! 包括4个核心仪表板:节点概览 & 节点集群 & 节点实例 & 节点警报 为节点引入新的身份变量:node_cluster 和 nodename 变量pg_hostname现在意味着将主机名设置为与postgres实例名相同,以保持向后兼容性 变量nodename_overwrite 控制是否用nodename覆盖节点的主机名 变量nodename_exchange 将nodename写入彼此的/etc/hosts 所有节点指标引用都经过修订,通过ip连接 节点监控目标在/etc/prometheus/targets/nodes下单独管理 PGSQL监控增强完全新的PGSQL集群,简化并专注于集群中的重要内容。 新仪表板PGSQL数据库是集群级对象监控。例如整个集群而不是单个实例的表和查询。 PGSQL警报仪表板现在只关注pgsql警报。 PGSQL Shard已添加到PGSQL中。 Redis监控增强 MatrixDB支持
通过pigsty-matrix.yml playbook可以部署MatrixDB(Greenplum 7) MatrixDB监控仪表板:PGSQL MatrixDB 添加示例配置:pigsty-mxdb.yml 监控增强
将监控系统分为5大类别:INFRA、NODES、REDIS、PGSQL、APP 默认启用日志记录 模型和标签为所有仪表板添加了一个隐藏的ds prometheus数据源变量,因此您只需选择一个新的数据源而不是修改Grafana数据源和仪表板。 为所有指标添加了一个ip标签,并将其用作数据库指标和节点指标之间的连接键。 INFRA监控Infra主仪表板:INFRA概览 添加日志仪表板:日志实例 PGLOG分析和PGLOG会话现在被视为一个示例Pigsty APP。 NODES监控应用如果您完全不关心数据库,现在可以单独使用Pigsty作为主机监控软件! 包括4个核心仪表板:节点概览 & 节点集群 & 节点实例 & 节点警报 为节点引入新的身份变量:node_cluster 和 nodename 变量pg_hostname现在意味着将主机名设置为与postgres实例名相同,以保持向后兼容性 变量nodename_overwrite 控制是否用nodename覆盖节点的主机名 变量nodename_exchange 将nodename写入彼此的/etc/hosts 所有节点指标引用都经过修订,通过ip连接 节点监控目标在/etc/prometheus/targets/nodes下单独管理 PGSQL监控增强完全新的PGSQL集群,简化并专注于集群中的重要内容。 新仪表板PGSQL数据库是集群级对象监控。例如整个集群而不是单个实例的表和查询。 PGSQL警报仪表板现在只关注pgsql警报。 PGSQL Shard已添加到PGSQL中。 Redis监控增强 MatrixDB支持
通过pigsty-matrix.yml playbook可以部署MatrixDB(Greenplum 7) MatrixDB监控仪表板:PGSQL MatrixDB 添加示例配置:pigsty-mxdb.yml 置备改进
现在 pigsty 的工作流如下:
infra.yml ---> 在单一的元节点上安装 pigsty
| 然后将更多节点加入 pigsty 的管理下
|
nodes.yml ---> 为 pigsty 准备节点(节点设置、dcs、node_exporter、promtail)
| 然后选择一个 playbook 在这些节点上部署数据库集群
|
^--> pgsql.yml 在已准备好的节点上安装 postgres
^--> redis.yml 在已准备好的节点上安装 redis
infra-demo.yml =
infra.yml -l meta +
nodes.yml -l pg-test +
pgsql.yml -l pg-test +
infra-loki.yml + infra-jupyter.yml + infra-pgweb.yml
nodes.yml:用于设置和准备 pigsty 的节点,在节点上设置 node、node_exporter、consul agent node-remove.yml 用于节点注销pgsql.yml:现在只在已准备好的节点上工作pgsql-remove 现在只负责 postgres 本身(dcs 和节点监控由 node.yml 负责)添加一系列新选项以在 greenplum/matrixdb 中重用 postgres 角色 redis.yml:现在在已准备好的节点上工作而 redis-remove.yml 现在从节点上移除 redis。 pgsql-matrix.yml 现在在已准备好的节点上安装 matrixdb(Greenplum 7)。软件升级
PostgreSQL 14.2 PostGIS 3.2 TimescaleDB 2.6 Patroni 2.1.3 (Prometheus 指标 + 故障转移插槽) HAProxy 2.5.5 (修复统计错误,更多指标) PG 导出器 0.4.1 (超时参数等) Grafana 8.4.4 Prometheus 2.33.4 Greenplum 6.19.4 / MatrixDB 4.4.0 Loki 现在作为 rpm 包提供,而不是 zip 存档。 错误修复
删除 patroni 的 consul 依赖,这使其更容易迁移到新的 consul 集群 修复 prometheus bin/new 脚本的默认数据目录路径:从 /export/prometheus 更改为 /data/prometheus 在 vip-manager systemd 服务中添加重新启动秒数 修复错别字和任务 API 变更
新增变量
node_cluster:节点集群的身份变量nodename_overwrite:如果设置,则 nodename 将设置为节点的主机名nodename_exchange:交换 play 主机之间的节点主机名(在 /etc/hosts 中)node_dns_hosts_extra:可以通过单个实例/集群轻松覆盖的额外静态 dns 记录patroni_enabled:如果禁用,postgres & patroni 的引导过程不会在 postgres 角色期间执行pgbouncer_enabled:如果禁用,pgbouncer 在 postgres 角色期间不会启动pg_exporter_params:生成监控目标 url 时为 pg_exporter 提供的额外 url 参数。pg_provision:布尔值变量,表示是否执行 postgres 角色的资源配置部分(模板,数据库,用户)no_cmdb:用于 infra.yml 和 infra-demo.yml 播放书,不会在元节点上创建 cmdb。MD5 (app.tgz) = f887313767982b31a2b094e5589a75ea
MD5 (matrix.tgz) = 3d063437c482d94bd7e35df1a08bbc84
MD5 (pigsty.tgz) = e143b88ebea1474f9ebaffddc6072c49
MD5 (pkg.tgz) = 73e8f5ce995b1f1760cb63c1904fb91b
v1.3.1 监控
PGSQL & PGCAT 仪表盘改进 优化 pgcat 实例 & pgcat 数据库的布局 在 pgsql 实例仪表盘中添加关键指标面板,与 pgsql 集群保持一致 在 pgcat 数据库中添加表/索引膨胀面板,移除 pgcat 膨胀仪表盘 在 pgcat 数据库仪表盘中添加索引信息 修复在 grafana 8.3 中的损坏面板 在 nginx 主页中添加 redis 索引 部署
新的 infra-demo.yml 剧本用于一次性引导 使用 infra-jupyter.yml 剧本部署可选的 jupyter lab 服务器 使用 infra-pgweb.yml 剧本部署可选的 pgweb 服务器 在 meta 节点上新的 pg 别名,可以从 admin 用户启动 postgres 集群(除了 postgres) 根据 timescaledb-tune 的建议调整所有 patroni 配置模板中的 max_locks_per_transactions 在配置模板中添加 citus.node_conninfo: 'sslmode=prefer' 以便在没有 SSL 的情况下使用 citus 在 pgdg14 包列表中添加所有扩展(除了 pgrouting) 将 node_exporter 升级到 v1.3.1 将 PostgREST v9.0.0 添加到包列表。从 postgres 模式生成 API。 错误修复
Grafana 的安全漏洞(升级到 v8.3.1 问题 ) 修复 pg_instance & pg_service 在 register 角色中从剧本的中间开始时的问题 修复在没有 pg_cluster 变量存在的主机上 nginx 主页渲染问题 在升级到 grafana 8.3.1 时修复样式问题 v1.3.0 【功能增强】Redis 部署(集群、哨兵、主从) 【功能增强】Redis 监控Redis 总览仪表盘 Redis 集群仪表盘 Redis 实例仪表盘
-【功能增强】 监控:PGCAT 大修 新仪表盘:PGCAT 实例 新仪表盘:PGCAT 数据库仪表盘 重做仪表盘:PGCAT 表格 【功能增强】 监控:PGSQL 增强新面板:PGSQL 集群,添加 10 个关键指标面板(默认切换) 新面板:PGSQL 实例,添加 10 个关键指标面板(默认切换) 简化 & 重新设计:PGSQL 服务 在 PGCAT & PGSL 仪表盘之间添加交叉引用
-【功能增强】 监控部署 现在 grafana 数据源在仅监控部署期间自动注册
-【功能增强】 软件升级 将 PostgreSQL 13 添加到默认包列表 默认升级到 PostgreSQL 14.1 添加 greenplum rpm 和依赖项 添加 redis rpm & 源代码包 将 perf 添加为默认包 v1.2.0 【功能增强】默认使用 PostgreSQL 14 版本 【功能增强】默认使用 TimescaleDB 2.5 扩展现在 timescaledb 和 postgis 默认在 cmdb 中启用 【功能增强】 新增仅监控模式:仅通过可连接的 URL,您可以使用 pigsty 监控现有的 pg 实例 pg_exporter 将在本地的 meta 节点上部署 新仪表板 PGSQL Cluster Monly 用于远程集群 【功能增强】软件升级grafana 升级到 8.2.2 pev2 升级到 v0.11.9 promscale 升级到 0.6.2 pgweb 升级到 0.11.9 新增扩展:pglogical、pg_stat_monitor、orafce
-【功能增强】自动检测机器规格并使用适当的 node_tune 和 pg_conf 模板
-【功能增强】重做与膨胀相关的视图,现在公开更多信息
-【功能增强】删除 timescale 和 citus 的内部监控
-【功能增强】新剧本 pgsql-audit.yml 用于创建审计报告
-【BUG修复】现在 pgbouncer_exporter 资源所有者是 {{ pg_dbsu }} 而不是 postgres
-【BUG修复】 修复在执行 REINDEX TABLE CONCURRENTLY 时 pg_exporter 在 pg_table pg_index 上的重复指标
-【功能增强】现在所有配置模板都减少到两个:auto 和 demo。(已删除:pub4, pg14, demo4, tiny, oltp) 如果 vagrant 是默认用户,则配置 pigsty-demo,否则使用 pigsty-auto。 如何从 v1.1.1 升级
在 1.2.0 中没有 API 变更。您仍然可以使用旧的 pigsty.yml 配置文件 (PG13)。
对于基础设施部分,重新执行 repo 将完成大部分工作。
至于数据库,您仍然可以使用现有的 PG13 实例。就地升级在涉及到像 PostGIS 和 Timescale 这样的扩展时非常棘手。我强烈推荐使用逻辑复制进行数据库迁移。
新的剧本 pgsql-migration.yml 将使这一过程变得容易得多。它将创建一系列的脚本,帮助您近乎零停机时间地迁移您的集群。
v1.1.1 【功能增强】 用 timescale 版本替换 timescaledb 的 apache 版本 【功能增强】 升级 prometheus 到 2.30 【BUG修复】 现在 pg_exporter 配置目录的属主是 {{ pg_dbsu }},而不再是 prometheus 如何从v1.1.0升级?
这个版本的主要变动是 TimescaleDB,使用 TimescaleDB License (TSL)的官方版本替代了 PGDG 仓库中的 Apache License v2 的版本。
stop/pause postgres instance with timescaledb
yum remove -y timescaledb_13
[ timescale_timescaledb]
name = timescale_timescaledb
baseurl = https://packagecloud.io/timescale/timescaledb/el/7/$basearch
repo_gpgcheck = 0
gpgcheck = 0
enabled = 1
yum install timescaledb-2-postgresql13
v1.1.0 【增强功能】 增加 pg_dummy_filesize 以创建文件系统空间占位符 【增强功能】 主页大改版 【增强功能】 增加 Jupyter Lab 整合 【增强功能】 增加 pgweb 控制台整合 【增强功能】 增加 pgbadger 支持 【增强功能】 增加 pev2 支持,解释可视化工具 【增强功能】 增加 pglog 工具 【增强功能】 更新默认的 pkg.tgz 软件版本:PostgreSQL 升级至 v13.4(支持官方的 pg14) pgbouncer 升级至 v1.16(指标定义更新) Grafana 升级至 v8.1.4 Prometheus 升级至 v2.2.29 node_exporter 升级至 v1.2.2 haproxy 升级至 v2.1.1 consul 升级至 v1.10.2 vip-manager 升级至 v1.0.1 API 变更
nginx_upstream 现在持有不同的结构。(不兼容)新的配置条目:app_list,渲染至主页的导航条目 新的配置条目:docs_enabled,在默认服务器上设置本地文档 新的配置条目:pev2_enabled,设置本地的 pev2 工具 新的配置条目:pgbadger_enabled,创建日志概要/报告目录 新的配置条目:jupyter_enabled,在元节点上启用 Jupyter Lab 服务器 新的配置条目:jupyter_username,指定运行 Jupyter Lab 的用户 新的配置条目:jupyter_password,指定 Jupyter Lab 的默认密码 新的配置条目:pgweb_enabled,在元节点上启用 pgweb 服务器 新的配置条目:pgweb_username,指定运行 pgweb 的用户 将内部标记 repo_exist 重命名为 repo_exists 现在 repo_address 的默认值为 pigsty 而非 yum.pigsty 现在 haproxy 的访问点为 http://pigsty 而非 http://h.pigsty v1.0.1 2021-09-14
文档更新 错误修复:pgsql-remove 不会移除主实例 错误修复:用 pg_cluster + pg_seq 替换 pg_instanceStart-At-Task 可能因为 pg_instance 未定义而失败 错误修复:从默认共享预加载库中移除 cituscitus 会强制 max_prepared_transaction 的值为非零 错误修复:在 configure 中进行 ssh sudo 检查:现在使用 ssh -t sudo -n ls 进行权限检查 笔误修复:pg-backup 脚本的笔误 警报调整:移除 NTP 合理性检查警报(与 ClockSkew 重复) 导出器调整:移除 collector.systemd 以减少开销 v1.0.0 v1 正式发布,监控系统全面改进
亮点
监控系统全面改进在 Grafana 8.0 上新增仪表盘 新的度量定义,增加 PG14 支持 简化的标签系统:静态标签集:(job, cls, ins) 新的警报规则与衍生度量 同时监控多个数据库 实时日志搜索 & csvlog 分析 链接丰富的仪表盘,点击图形元素进行深入|汇总 架构变更将 citus 和 timescaledb 加入默认安装部分 增加对 PostgreSQL 14beta2 的支持 简化 haproxy 管理页面索引 通过添加新的角色 register 来解耦基础设施和 pgsql 添加新角色 loki 和 promtail 用于日志记录 为管理员节点上的管理员用户添加新角色 environ 以设置环境 默认使用 static 服务发现用于 prometheus(而不是 consul) 添加新角色 remove 以优雅地移除集群和实例 升级 prometheus 和 grafana 的配置逻辑 升级到 vip-manager 1.0,node_exporter 1.2,pg_exporter 0.4,grafana 8.0 现在,每个实例上的每个数据库都可以自动注册为 grafana 数据源 将 consul 注册任务移到 register 角色,更改 consul 服务标签 添加 cmdb.sql 作为 pg-meta 基线定义(CMDB & PGLOG) 应用框架可扩展框架用于新功能 核心应用:PostgreSQL 监控系统:pgsql 核心应用:PostgreSQL 目录浏览器:pgcat 核心应用:PostgreSQL Csvlog 分析器:pglog 添加示例应用 covid 用于可视化 covid-19 数据 添加示例应用 isd 用于可视化 isd 数据 其他添加 jupyterlab,为数据科学提供完整的 python 环境 添加 vonng-echarts-panel 以恢复对 Echarts 的支持 添加 wrap 脚本 createpg,createdb,createuser 添加 cmdb 动态库存脚本:load_conf.py,inventory_cmdb,inventory_conf 移除过时的剧本:pgsql-monitor,pgsql-service,node-remove 等…. API 变更
新变量: node_meta_pip_install 新变量: grafana_admin_username 新变量: grafana_database 新变量: grafana_pgurl 新变量: pg_shared_libraries 新变量: pg_exporter_auto_discovery 新变量: pg_exporter_exclude_database 新变量: pg_exporter_include_database 变量重命名: grafana_url 为 grafana_endpoint Bug 修复
修复默认时区 Asia/Shanghai (CST) 问题 修复 pgbouncer & patroni 的 nofile 限制 当执行标签 pgbouncer 时,pgbouncer 的用户列表和数据库列表将会被生成 v0.9.0 v0.9极大简化了安装流程,进行了大量日志相关改进,开发了命令行工具(Beta),并修复了一系列问题。
新功能
一键安装模式:
/bin/bash -c " $( curl -fsSL https://pigsty.cc/install) "
开发命令行工具 pigsty-cli封装常用Ansible命令,目前pigsty-cli处于Beta状态
使用Loki与Promtail收集日志:
默认收集Postgres,Pgbouncer,Patroni日志 新增部署脚本infra-loki.yml 与 pgsql-promtail.yml 定义基于日志的监控指标 使用Grafana制作日志相关可视化面板。 监控组件可以使用二进制安装,使用files/get_bin.sh下载监控二进制组件。
飞升模式:
当集群元节点初始化完成后,可以使用bin/upgrade升级为动态Inventory
使用pg-meta上的数据库代替YAML配置文件。
问题修复
集中修复日志相关问题:修复了HAProxy健康检查造成PG日志中大量 connection reset by peer的问题。 修复了HAProxy健康检查造成Patroni日志中大量出现Connect Reset Exception的问题 修复了Patroni日志时间戳格式,去除毫秒时间戳,附加完整时区信息。 为dbuser_monitor配置1秒的log_min_duration_statement,避免监控查询出现在日志中。 重构Grafana角色在保持API不变的前提下重构Grafana角色。 使用CDN下载预打包的Grafana插件,加速插件下载 其他问题修复修复了pgbouncer-create-user 未能正确处理 md5 密码的问题。 完善了数据库与用户创建SQL模版中参数空置检查。 修复了 NODE DNS配置时如果手工中断执行,DNS配置可能出错的问题。 重构了Makefile快捷方式 Makefile 中的错别字 参数变更
node_disable_swap 默认为 False,默认不会关闭SWAP。node_sysctl_params 不再有默认修改的系统参数。grafana_plugin 的默认值install 现在意味着当插件缓存不存在时,从CDN下载。repo_url_packages 现在从 Pigsty CDN 下载额外的RPM包,解决墙内无法访问的问题。proxy_env.no_proxy现在将Pigsty CDN加入到NOPROXY列表中。grafana_customize 现在默认为false,启用意味着安装Pigsty Pro版UI(默认不开源所以不要启用)node_admin_pk_current,新增选项,启用后会将当前用户的~/.ssh/id_rsa.pub添加至管理员的Key中loki_clean:新增选项,安装Loki时是否清除现有数据loki_data_dir:新增选项,指明安装Loki时的数据目录promtail_enabled 是否启用Promtail日志收集服务?promtail_clean 是否在安装promtail时移除已有状态信息?promtail_port promtail使用的默认端口,默认为9080promtail_status_file 保存Promtail状态信息的文件位置promtail_send_url 用于接收日志的loki服务endpointv0.8.0 v0.8 针对 服务(Service) 接入部分进行了彻底的重做。现在除了默认的primary, replica服务外,用户可以自行定义新的服务。服务的接口可以支持多种不同的实现,例如L4 DPKG VIP可作为Haproxy的替代品与Pigsty集成。同时,针对用户反馈的一些问题进行了集中处理与改进。
改动内容
v0.8是供给方案定稿版本,此后供给系统的API将保持稳定。
API变更
原有vip与haproxy角色的所有配置项,现在迁移至service角色中。
#------------------------------------------------------------------------------
# SERVICE PROVISION
#------------------------------------------------------------------------------
pg_weight : 100 # default load balance weight (instance level)
# - service - #
pg_services : # how to expose postgres service in cluster?
# primary service will route {ip|name}:5433 to primary pgbouncer (5433->6432 rw)
- name : primary # service name {{ pg_cluster }}_primary
src_ip : "*"
src_port : 5433
dst_port : pgbouncer # 5433 route to pgbouncer
check_url : /primary # primary health check, success when instance is primary
selector : "[]" # select all instance as primary service candidate
# replica service will route {ip|name}:5434 to replica pgbouncer (5434->6432 ro)
- name : replica # service name {{ pg_cluster }}_replica
src_ip : "*"
src_port : 5434
dst_port : pgbouncer
check_url : /read-only # read-only health check. (including primary)
selector : "[]" # select all instance as replica service candidate
selector_backup : "[? pg_role == `primary`]" # primary are used as backup server in replica service
# default service will route {ip|name}:5436 to primary postgres (5436->5432 primary)
- name : default # service's actual name is {{ pg_cluster }}-{{ service.name }}
src_ip : "*" # service bind ip address, * for all, vip for cluster virtual ip address
src_port : 5436 # bind port, mandatory
dst_port: postgres # target port : postgres|pgbouncer|port_number , pgbouncer(6432) by default
check_method: http # health check method : only http is available for now
check_port: patroni # health check port : patroni|pg_exporter|port_number , patroni by default
check_url : /primary # health check url path, / as default
check_code : 200 # health check http code, 200 as default
selector : "[]" # instance selector
haproxy : # haproxy specific fields
maxconn : 3000 # default front-end connection
balance : roundrobin # load balance algorithm (roundrobin by default)
default_server_options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
# offline service will route {ip|name}:5438 to offline postgres (5438->5432 offline)
- name : offline # service name {{ pg_cluster }}_replica
src_ip : "*"
src_port : 5438
dst_port : postgres
check_url : /replica # offline MUST be a replica
selector : "[? pg_role == `offline` || pg_offline_query ]" # instances with pg_role == 'offline' or instance marked with 'pg_offline_query == true'
selector_backup : "[? pg_role == `replica` && !pg_offline_query]" # replica are used as backup server in offline service
pg_services_extra : [] # extra services to be added
# - haproxy - #
haproxy_enabled : true # enable haproxy among every cluster members
haproxy_reload : true # reload haproxy after config
haproxy_policy : roundrobin # roundrobin, leastconn
haproxy_admin_auth_enabled : false # enable authentication for haproxy admin?
haproxy_admin_username : admin # default haproxy admin username
haproxy_admin_password : admin # default haproxy admin password
haproxy_exporter_port : 9101 # default admin/exporter port
haproxy_client_timeout : 3h # client side connection timeout
haproxy_server_timeout : 3h # server side connection timeout
# - vip - #
vip_mode : none # none | l2 | l4
vip_reload : true # whether reload service after config
# vip_address: 127.0.0.1 # virtual ip address ip (l2 or l4)
# vip_cidrmask: 24 # virtual ip address cidr mask (l2 only)
# vip_interface: eth0 # virtual ip network interface (l2 only)
新增选项
# - localization - #
pg_encoding : UTF8 # default to UTF8
pg_locale : C # default to C
pg_lc_collate : C # default to C
pg_lc_ctype : en_US.UTF8 # default to en_US.UTF8
pg_reload : true # reload postgres after hba changes
vip_mode : none # none | l2 | l4
vip_reload : true # whether reload service after config
移除选项
haproxy_check_port # Haproxy相关参数已经被Service定义覆盖
haproxy_primary_port
haproxy_replica_port
haproxy_backend_port
haproxy_weight
haproxy_weight_fallback
vip_enabled # vip_enabled参数被vip_mode覆盖
服务管理
pg_services 与 pg_services_extra 定义了集群中的服务 ,每一个服务的定义结构如下例所示:
一个服务必须指定以下内容:
名称 :服务的完整名称以数据库集群名为前缀,以service.name为后缀,通过-连接。例如在pg-test集群中name=primary的服务,其完整服务名称为pg-test-primary。
端口 :在Pigsty中,服务默认采用NodePort的形式对外暴露,因此暴露端口为必选项。但如果使用外部负载均衡服务接入方案,您也可以通过其他的方式区分服务。
选择器 :选择器指定了服务的成员,采用JMESPath的形式,从所有集群实例成员中筛选变量。默认的[]选择器会选取所有的集群成员。
此外selector_backup会选择或标记用于backup的实例列表(当集群中所有其他成员失效时方才接管服务)
# default service will route {ip|name}:5436 to primary postgres (5436->5432 primary)
- name : default # service's actual name is {{ pg_cluster }}-{{ service.name }}
src_ip : "*" # service bind ip address, * for all, vip for cluster virtual ip address
src_port : 5436 # bind port, mandatory
dst_port: postgres # target port : postgres|pgbouncer|port_number , pgbouncer(6432) by default
check_method: http # health check method : only http is available for now
check_port: patroni # health check port : patroni|pg_exporter|port_number , patroni by default
check_url : /primary # health check url path, / as default
check_code : 200 # health check http code, 200 as default
selector : "[]" # instance selector
haproxy : # haproxy specific fields
maxconn : 3000 # default front-end connection
balance : roundrobin # load balance algorithm (roundrobin by default)
default_server_options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
数据库管理
数据库现在可以对locale的细分选项:lc_ctype与lc_collate分别进行指定。支持这一功能的主要原因是PG的扩展插件pg_trgm需要在lc_ctype!=C的环境中才能正常支持中文。
旧接口定义
pg_databases :
- name : meta # name is the only required field for a database
owner : postgres # optional, database owner
template : template1 # optional, template1 by default
encoding : UTF8 # optional, UTF8 by default
locale : C # optional, C by default
allowconn : true # optional, true by default, false disable connect at all
revokeconn : false # optional, false by default, true revoke connect from public # (only default user and owner have connect privilege on database)
tablespace : pg_default # optional, 'pg_default' is the default tablespace
connlimit : -1 # optional, connection limit, -1 or none disable limit (default)
extensions : # optional, extension name and where to create
- {name: postgis, schema : public}
parameters : # optional, extra parameters with ALTER DATABASE
enable_partitionwise_join : true
pgbouncer : true # optional, add this database to pgbouncer list? true by default
comment : pigsty meta database # optional, comment string for database
新的接口定义
pg_databases :
- name : meta # name is the only required field for a database
# owner: postgres # optional, database owner
# template: template1 # optional, template1 by default
# encoding: UTF8 # optional, UTF8 by default , must same as template database, leave blank to set to db default
# locale: C # optional, C by default , must same as template database, leave blank to set to db default
# lc_collate: C # optional, C by default , must same as template database, leave blank to set to db default
# lc_ctype: C # optional, C by default , must same as template database, leave blank to set to db default
allowconn : true # optional, true by default, false disable connect at all
revokeconn : false # optional, false by default, true revoke connect from public # (only default user and owner have connect privilege on database)
# tablespace: pg_default # optional, 'pg_default' is the default tablespace
connlimit : -1 # optional, connection limit, -1 or none disable limit (default)
extensions : # optional, extension name and where to create
- {name: postgis, schema : public}
parameters : # optional, extra parameters with ALTER DATABASE
enable_partitionwise_join : true
pgbouncer : true # optional, add this database to pgbouncer list? true by default
comment : pigsty meta database # optional, comment string for database
v0.7.0 v0.7 针对接入已有数据库实例 进行了改进,现在用户可以采用 仅监控部署(Monly Deployment) 模式使用Pigsty。同时新增了专用于管理数据库与用户、以及单独部署监控的剧本,并对数据库与用户的定义进行改进。
Features
Bug Fix
API变更
新增选项
prometheus_sd_target : batch # batch|single 监控目标定义文件采用单体还是每个实例一个
exporter_install : none # none|yum|binary 监控Exporter的安装模式
exporter_repo_url : '' # 如果设置,这里的REPO连接会加入目标的Yum源中
node_exporter_options : '--no-collector.softnet --collector.systemd --collector.ntp --collector.tcpstat --collector.processes' # Node Exporter默认的命令行选项
pg_exporter_url : '' # 可选,PG Exporter监控对象的URL
pgbouncer_exporter_url : '' # 可选,PGBOUNCER EXPORTER监控对象的URL
移除选项
exporter_binary_install : false # 功能被 exporter_install 覆盖
定义结构变更
pg_default_roles # 变化细节参考 用户管理。
pg_users # 变化细节参考 用户管理。
pg_databases # 变化细节参考 数据库管理。
重命名选项
pg_default_privilegs -> pg_default_privileges # 很明显这是一个错别字
仅监控模式
有时用户不希望使用Pigsty供给方案,只希望使用Pigsty监控系统管理现有PostgreSQL实例。
Pigsty提供了仅监控部署(monly, monitor-only模式,剥离供给方案部分,可用于监控现有PostgreSQL集群。
仅监控模式的部署流程与标准模式大体上保持一致,但省略了很多步骤
在元节点 上完成基础设施初始化的部分与标准流程保持一致,仍然通过./infra.yml完成。 不需要在数据库节点 上完成 基础设施初始化 。 不需要在数据库节点 上执行数据库初始化的绝大多数任务,而是通过专用的./pgsql-monitor.yml 完成仅监控系统部署。 实际使用的配置项大大减少,只保留基础设施相关变量,与 监控系统相关的少量变量。 数据库管理
Database provisioning interface enhancement #33
旧接口定义
pg_databases : # create a business database 'meta'
- name : meta
schemas : [ meta] # create extra schema named 'meta'
extensions : [ {name : postgis}] # create extra extension postgis
parameters : # overwrite database meta's default search_path
search_path : public, monitor
新的接口定义
pg_databases :
- name : meta # name is the only required field for a database
owner : postgres # optional, database owner
template : template1 # optional, template1 by default
encoding : UTF8 # optional, UTF8 by default
locale : C # optional, C by default
allowconn : true # optional, true by default, false disable connect at all
revokeconn : false # optional, false by default, true revoke connect from public # (only default user and owner have connect privilege on database)
tablespace : pg_default # optional, 'pg_default' is the default tablespace
connlimit : -1 # optional, connection limit, -1 or none disable limit (default)
extensions : # optional, extension name and where to create
- {name: postgis, schema : public}
parameters : # optional, extra parameters with ALTER DATABASE
enable_partitionwise_join : true
pgbouncer : true # optional, add this database to pgbouncer list? true by default
comment : pigsty meta database # optional, comment string for database
接口变更
Add new options: template , encoding, locale, allowconn, tablespace, connlimit Add new option revokeconn, which revoke connect privileges from public for this database Add comment field for database 数据库变更
在运行中集群中创建新数据库可以使用pgsql-createdb.yml剧本,在配置中定义完新数据库后,执行以下剧本。
./pgsql-createdb.yml -e pg_database = <your_new_database_name>
通过-e pg_datbase=告知需要创建的数据库名称,则该数据库即会被创建(或修改)。具体执行的命令参见集群主库/pg/tmp/pg-db-{{ database.name}}.sql文件。
用户管理
User provisioning interface enhancement #34
旧接口定义
pg_users :
- username : test # example production user have read-write access
password : test # example user's password
options : LOGIN # extra options
groups : [ dbrole_readwrite ] # dborole_admin|dbrole_readwrite|dbrole_readonly
comment : default test user for production usage
pgbouncer : true # add to pgbouncer
新接口定义
pg_users :
# complete example of user/role definition for production user
- name : dbuser_meta # example production user have read-write access
password : DBUser.Meta # example user's password, can be encrypted
login : true # can login, true by default (should be false for role)
superuser : false # is superuser? false by default
createdb : false # can create database? false by default
createrole : false # can create role? false by default
inherit : true # can this role use inherited privileges?
replication : false # can this role do replication? false by default
bypassrls : false # can this role bypass row level security? false by default
connlimit : -1 # connection limit, -1 disable limit
expire_at : '2030-12-31' # 'timestamp' when this role is expired
expire_in : 365 # now + n days when this role is expired (OVERWRITE expire_at)
roles : [ dbrole_readwrite] # dborole_admin|dbrole_readwrite|dbrole_readonly
pgbouncer : true # add this user to pgbouncer? false by default (true for production user)
parameters : # user's default search path
search_path : public
comment : test user
接口变更
username field rename to namegroups field rename to rolesoptions now split into separated configration entries:
login, superuser, createdb, createrole, inherit, replication,bypassrls,connlimitexpire_at and expire_in optionspgbouncer option for user is now false by default用户管理
在运行中集群中创建新数据库可以使用pgsql-createuser.yml剧本,在配置中定义完新数据库后,执行以下剧本。
./pgsql-createuser.yml -e pg_user = <your_new_user_name>
通过-e pg_user=告知需要创建的数据库名称,则该数据库即会被创建(或修改)。具体执行的命令参见集群主库/pg/tmp/pg-user-{{ user.name}}.sql文件。
v0.6.0 v0.6 对数据库供给方案进行了修改与调整,根据用户的反馈添加了一系列实用功能与修正。针对监控系统的移植性进行优化,便于与其他外部数据库供给方案对接。
BUG修复
修复了新版本Patroni重启后会重置PG HBA的问题 修复了PG Overview Dashboard标题中的别字 修复了沙箱集群pg-test的默认主库,原来为pg-test-2,应当为pg-test-1 修复了过时代码注释 功能改进
改造Prometheus与监控供给方式允许在无基础设施的情况下对已有PG集群进行监控部署,便于监控系统与其他供给方案集成。#11 基于Inventory渲染所有监控对象的静态列表,用于静态服务发现。#11 Prometheus添加了静态对象模式,用于替代动态服务发现,集中进行身份管理#11 监控Exporter现在添加了service_registry选项,Consul服务注册变为可选项 #13 Exporter现在可以通过拷贝二进制的方式直接安装:exporter_binary_install,#14 Exporter现在具有xxx_enabled选项,控制是否启用该组件。 Haproxy供给重构与改进 #8 新增了全局HAProxy管理界面导航,默认域名h.pigsty 允许将主库加入只读服务集中,当集群中所有从库宕机时自动承接读流量。 #8 允许位Haproxy实例管理界面启用认证 haproxy_admin_auth_enabled 允许通过配置项调整每个服务对应后端的流量权重. #10 访问控制模型改进。#7 添加了默认角色dbrole_offline,用于慢查询,ETL,交互式查询场景。 修改默认HBA规则,允许dbrole_offline分组的用户访问pg_role == 'offline'及pg_offline_query == true的实例。 软件更新 Release v0.6PostgreSQL 13.2 Prometheus 2.25 PG Exporter 0.3.2 Node Exporter 1.1 Consul 1.9.3 更新默认PG源:PostgreSQL现在默认使用浙江大学的镜像,加速下载安装 接口变更
新增选项
service_registry : consul # 服务注册机制:none | consul | etcd | both
prometheus_options : '--storage.tsdb.retention=30d' # prometheus命令行选项
prometheus_sd_method : consul # Prometheus使用的服务发现机制:static|consul
prometheus_sd_interval : 2s # Prometheus服务发现刷新间隔
pg_offline_query : false # 设置后将允许dbrole_offline角色连接与查询该实例
node_exporter_enabled : true # 设置后将安装配置Node Exporter
pg_exporter_enabled : true # 设置后将安装配置PG Exporter
pgbouncer_exporter_enabled : true # 设置后将安装配置Pgbouncer Exporter
dcs_disable_purge : false # 双保险,强制 dcs_exists_action = abort 避免误删除DCS实例
pg_disable_purge : false # 双保险,强制 pg_exists_action = abort 避免误删除数据库实例
haproxy_weight : 100 # 配置实例的相对负载均衡权重
haproxy_weight_fallback : 1 # 配置集群主库在只读服务中的相对权重
移除选项
prometheus_metrics_path # 与 exporter_metrics_path 重复
prometheus_retention # 功能被 prometheus_options 覆盖
v0.5.0 Pigsty 现在有了官方网站啦:pigsty.cc 🎉 !
亮点特性
Pigsty官方文档站 正式上线! 添加了数据库模板的定制支持,用户可以通过配置文件定制所需的数据库内部对象。 对默认访问控制 模型进行了改进 重构了HBA管理的逻辑,现在将由Pigsty替代Patroni直接负责生成HBA 将Grafana监控系统的供给方案从sqlite改为JSON文件静态Provision 将pg-cluster-replication面板加入Pigsty开源免费套餐。 最新的经过测试的离线安装包:pkg.tgz (v0.5) 定制数据库
您是否烦恼过单实例多租户的问题?比如总有研发拿着PostgreSQL当MySQL使,明明是一个Schema就能解决的问题,非要创建一个新的数据库出来,在一个实例中创建出几十个不同的DB。
不要忧伤,不要心急。Pigsty已经提供数据库内部对象的Provision方案,您可以轻松地在配置文件中指定所需的数据库内对象,包括:
角色 数据库属主 额外的模式 额外的扩展插件 数据库级的自定义配置参数 数据库属主 额外的模式 额外的扩展插件 数据库级的自定义配置参数 默认权限默认情况下这里配置的权限会应用至所有由 超级用户 和 管理员用户创建的对象上。 默认扩展 默认模式 配置样例
# 通常是每个DB集群配置的变量
pg_users :
- username : test
password : test
comment : default test user
groups : [ dbrole_readwrite ] # dborole_admin|dbrole_readwrite|dbrole_readonly
pg_databases : # create a business database 'test'
- name : test
extensions : [ {name : postgis}] # create extra extension postgis
parameters : # overwrite database meta's default search_path
search_path : public,monitor
# 通常是整个环境统一配置的全局变量
# - system roles - #
pg_replication_username : replicator # system replication user
pg_replication_password : DBUser.Replicator # system replication password
pg_monitor_username : dbuser_monitor # system monitor user
pg_monitor_password : DBUser.Monitor # system monitor password
pg_admin_username : dbuser_admin # system admin user
pg_admin_password : DBUser.Admin # system admin password
# - default roles - #
pg_default_roles :
- username : dbrole_readonly # sample user :
options : NOLOGIN # role can not login
comment : role for readonly access # comment string
- username: dbrole_readwrite # sample user : one object for each user
options : NOLOGIN
comment : role for read-write access
groups : [ dbrole_readonly ] # read-write includes read-only access
- username: dbrole_admin # sample user : one object for each user
options : NOLOGIN BYPASSRLS # admin can bypass row level security
comment : role for object creation
groups : [ dbrole_readwrite,pg_monitor,pg_signal_backend]
# NOTE: replicator, monitor, admin password are overwritten by separated config entry
- username : postgres # reset dbsu password to NULL (if dbsu is not postgres)
options : SUPERUSER LOGIN
comment : system superuser
- username : replicator
options : REPLICATION LOGIN
groups : [ pg_monitor, dbrole_readonly]
comment : system replicator
- username : dbuser_monitor
options : LOGIN CONNECTION LIMIT 10
comment : system monitor user
groups : [ pg_monitor, dbrole_readonly]
- username : dbuser_admin
options : LOGIN BYPASSRLS
comment : system admin user
groups : [ dbrole_admin]
- username : dbuser_stats
password : DBUser.Stats
options : LOGIN
comment : business read-only user for statistics
groups : [ dbrole_readonly]
# object created by dbsu and admin will have their privileges properly set
pg_default_privilegs :
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT INSERT, UPDATE, DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE, UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE, REFERENCES, TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
- GRANT USAGE ON TYPES TO dbrole_admin
# schemas
pg_default_schemas : [ monitor]
# extension
pg_default_extensions :
- { name: 'pg_stat_statements', schema : 'monitor' }
- { name: 'pgstattuple', schema : 'monitor' }
- { name: 'pg_qualstats', schema : 'monitor' }
- { name: 'pg_buffercache', schema : 'monitor' }
- { name: 'pageinspect', schema : 'monitor' }
- { name: 'pg_prewarm', schema : 'monitor' }
- { name: 'pg_visibility', schema : 'monitor' }
- { name: 'pg_freespacemap', schema : 'monitor' }
- { name: 'pg_repack', schema : 'monitor' }
- name : postgres_fdw
- name : file_fdw
- name : btree_gist
- name : btree_gin
- name : pg_trgm
- name : intagg
- name : intarray
# postgres host-based authentication rules
pg_hba_rules :
- title : allow meta node password access
role : common
rules :
- host all all 10.10.10.10/32 md5
- title : allow intranet admin password access
role : common
rules :
- host all +dbrole_admin 10.0.0.0/8 md5
- host all +dbrole_admin 172.16.0.0/12 md5
- host all +dbrole_admin 192.168.0.0/16 md5
- title : allow intranet password access
role : common
rules :
- host all all 10.0.0.0/8 md5
- host all all 172.16.0.0/12 md5
- host all all 192.168.0.0/16 md5
- title : allow local read-write access (local production user via pgbouncer)
role : common
rules :
- local all +dbrole_readwrite md5
- host all +dbrole_readwrite 127.0.0.1/32 md5
- title : allow read-only user (stats, personal) password directly access
role : replica
rules :
- local all +dbrole_readonly md5
- host all +dbrole_readonly 127.0.0.1/32 md5
pg_hba_rules_extra : []
# pgbouncer host-based authentication rules
pgbouncer_hba_rules :
- title : local password access
role : common
rules :
- local all all md5
- host all all 127.0.0.1/32 md5
- title : intranet password access
role : common
rules :
- host all all 10.0.0.0/8 md5
- host all all 172.16.0.0/12 md5
- host all all 192.168.0.0/16 md5
pgbouncer_hba_rules_extra : []
数据库模板
权限模型
v0.5 改善了默认的权限模型,主要是针对单实例多租户的场景进行优化,并收紧权限控制。
撤回了普通业务用户对非所属数据库的默认CONNECT权限 撤回了非管理员用户对所属数据库的默认CREATE权限 撤回了所有用户在public模式下的默认创建权限。 供给方式
原先Pigsty采用直接拷贝Grafana自带的grafana.db的方式完成监控系统的初始化。
这种方式虽然简单粗暴管用,但不适合进行精细化的版本控制管理。在v0.5中,Pigsty采用了Grafana API完成了监控系统面板供给的工作。
您所需的就是在grafana_url中填入带有用户名密码的Grafana URL。
因此,监控系统可以背方便地添加至已有的Grafana中。
v0.4.0 第二个公开测试版v0.4现已正式发行!
监控系统
Pigsty v0.4对监控系统进行了整体升级改造,精心挑选了10个面板作为标准的Pigsty开源内容。同时,针对Grafana 7.3的不兼容升级进行了大量适配改造工作。使用升级的pg_exporter v0.3.1作为默认指标导出器,调整了监控报警规则的监控面板连接。
Pigsty开源版
Pigsty开源版选定了以下10个Dashboard作为开源内容。其他Dashboard作为可选的商业支持内容提供。
PG Overview PG Cluster PG Service PG Instance PG Database PG Query PG Table PG Table Catalog PG Table Detail Node 尽管进行了少量阉割,这10个监控面板所涵盖的内容仍然可以吊打所有同类软件。
软件升级
Pigsty v0.4进行了大量软件适配工作,包括:
Upgrade to PostgreSQL 13.1, Patroni 2.0.1-4, add citus to repo. Upgrade to pg_exporter 0.3.1 Upgrade to Grafana 7.3, Ton’s of compatibility work Upgrade to prometheus 2.23, with new UI as default Upgrade to consul 1.9 其他改进
Update prometheus alert rules Fix alertmanager info links Fix bugs and typos. add a simple backup script 离线安装包
v0.4的离线安装包(CentOS 7.8)已经可以从Github下载:pkg.tgz v0.3.0 首个Pigsty公开测试版本现在已经释出!
监控系统
Pigsty v0.3 包含以下8个监控面板作为开源内容:
PG Overview PG Cluster PG Service PG Instance PG Database PG Table Overview PG Table Catalog Node 离线安装包
v0.3 离线安装包(CentOS 7.8)已经可以从Github下载:pkg.tgz 3 - 上手 快速上手 Pigsty:根据需求进行规划,准备资源,置备服务器,创建管理用户,下载软件并完成安装。
Pigsty 采用可伸缩的架构设计,即可用于超大规模生产环境,也可用于单机开发和测试环境。
本节列出了设置和运行 Pigsty 的不同方法,您可以根据自己的场景与需求选择。
单机环境 如果您打算学习了解 Pigsty,可以从 单机安装 开始。一台 1C/2G 的 Linux 虚拟机即可运行 Pigsty。
您完全可以在不了解任何细节的情况下,使用预制配置模板一键拉起 Pigsty。
您可以利用一台 Linux MiniPC,或者云厂商提供的免费/优惠虚拟机,或者在自己的笔记本上创建虚拟机。
Pigsty 提供了开箱即用的 Vagrant 模板与 Terraform 模版,可以帮助您一键在本地或云端置备虚拟机环境。
单机版本的 Pigsty 包含了所有核心功能,440 + PG 扩展,自包含的 Grafana / Victoria 监控,IaC 制备能力。
以及本地 PITR 时间点恢复。如果您配备了外部的对象存储(用于 PostgreSQL 备份),那么对于 Demo,个人网站,小型服务等场景,
即使是单机环境,也可以提供一定程度的数据持久性保证。但单机无法实现高可用性 —— 故障自动切换至少需要 3 个节点。
如果您只需要 PostgreSQL 数据库本身,不需要监控基础设施,可以考虑 精简安装 模式。
如果您想要在没有互联网连接的环境中安装 Pigsty,参考 离线安装 模式。
生产环境 生产质量的 Pigsty 集群需要规划与准备,如果你的 Pigsty 集群是用来支撑关键业务系统的,
那么请务必使用至少三个节点以实现标准的高可用性。
Pigsty 提供了一个四节点的小型沙箱环境,与一个20节点的大型沙箱环境,用于仿真生产测试。
您可以在单台高规格的笔记本/PC/服务器上运行这些沙箱环境,以便进行功能测试与验证。
生产环境考量 如果您打算在严肃的生产环境中部署 Pigsty,那么通常需要准备至少 3 个节点,使用统一的操作系统,静态网络 IP 地址。
3.1 - 安装部署 在联网环境中,安装标准的 Pigsty 单机版本
安装 Pigsty 四步走: 准备 ,下载 ,配置 ,以及 安装 。没有互联网访问,请同时参阅 离线安装 。
简短版本
准备 一台具有 SSH权限 的 节点 并安装 兼容的Linux发行版 ,
使用带有免密 ssh 和 sudo 权限的管理用户执行以下命令:
curl -fsSL https://repo.pigsty.cc/get | bash; cd ~/pigsty;
该命令会 下载 并解压 Pigsty 源码至家目录,依次完成 配置 与安装 即可完成安装。
./configure; ./install.yml; # 生成配置文件,执行安装剧本!
整个安装过程根据服务器规格/网络条件需 5~10 分钟不等,离线安装 能显著加速。
安装完成后,您可以通过域名,或80/443端口通过 Nginx 访问 WEB 界面 ,
通过 5432 端口 访问 默认的 PostgreSQL 数据库 服务 。
您也可以继续使用 Pigsty 纳管 更多 节点,并部署各种 模块 。
如果您不需要 Pigsty 的基础设施组件,可以使用 精简安装 ,仅安装高可用 PostgreSQL 集群所必需的组件。
视频样例:在线单机安装(EL9)
准备 关于准备工作的完整详细说明,请参考 入门:准备工作 一节。
安装 Pigsty 涉及一些 准备工作 ,以下是简略检查清单:
项目 要求 项目 要求 节点 至少 1C1G,推荐 2C2G 规格 至少1个节点,2个为半高可用,3个以上真高可用 磁盘 /data,主挂载点,ext4/xfs网络 静态 IPv4 地址,单节点可使用 127.0.0.1 VIP L2 VIP,可选 域名 本地/公网域名,可选 内核 Linux发行版 el8/9/10,d12/13, u22/u24 x x86_64 / aarch64 Locale C.UTF-8 或 C防火墙 端口:80 / 443 / 22 / 5432 用户 避免使用 root 和 postgres Sudo nopass sudo 权限SSH 通过公钥 nopass 可达性 ssh <ip|alias> sudo ls 无错误
避免使用 root 用户安装
尽管使用 root 用户安装 Pigsty 是可行的,但 安全最佳实践
是使用一个不同于根用户(root)与数据库超级用户 (postgres) 的专用管理员用户(如:dba),
Pigsty 安装过程中会默认创建由配置文件指定的可选管理员用户 dba。
下载 (推荐)您可以使用以下命令自动下载、解压 Pigsty 源码包至 ~/pigsty 目录下使用:
curl -fsSL https://repo.pigsty.cc/get | bash # 安装最新稳定版本(中国镜像)
curl -fsSL https://repo.pigsty.io/get | bash # 安装最新稳定版本(国际区域)
curl -fsSL https://repo.pigsty.io/get | bash -s v4.0.0 # 安装特定版本
您也可以通过 git、pig 或直接从 GitHub 下载源码和离线软件包 压缩包的方式安装。
git clone https://github.com/pgsty/pigsty; cd pigsty; git checkout v4.0.0
检出特定版本使用
main 主干为活跃开发分支,使用 git 时请务必检出特定版本后使用,可用版本请参考 发行注记 。
配置 configure 脚本将根据您的环境和输入生成具有良好默认值的 pigsty.yml 配置文件(配置清单 )。
这是 可选的 ,您可以如 教程 所示直接编辑 pigsty.yml。
有许多 配置模板 供您参考,以下是一些快速示例:
./configure # 使用默认模板,安装默认的 PG 18,带有必要扩展
./configure -v 17 # 使用 PG 17 的版本,而非默认的 PG18
./configure -c rich # 创建本地软件仓库,下载所有扩展,安装主要扩展
./configure -c slim # 最小安装模板,与 ./slim.yml 剧本一起使用
./configure -c app/supa # 使用 app/supa 自托管 supabase 配置模板
./configure -c ivory # 使用 ivorysql 内核而非原生 PG
./configure -i 10.11.12.13 # 显式指定主 IP 地址
./configure -r china # 使用中国镜像而非默认仓库
./configure -c ha/full -s # 使用 4 节点沙箱配置模板,不进行 IP 替换和探测
配置 / configure 过程的样例输出 [ vagrant@node-2 pigsty] $ ./configure
configure pigsty v4.0.0 begin
[ OK ] region = default
[ OK ] kernel = Linux
[ OK ] machine = x86_64
[ OK ] package = rpm,dnf
[ OK ] vendor = rocky ( Rocky Linux)
[ OK ] version = 9 ( 9.6)
[ OK ] sudo = vagrant ok
[ OK ] ssh = vagrant@127.0.0.1 ok
[ WARN] Multiple IP address candidates found:
( 1) 192.168.121.24 inet 192.168.121.24/24 brd 192.168.121.255 scope global dynamic noprefixroute eth0
( 2) 10.10.10.12 inet 10.10.10.12/24 brd 10.10.10.255 scope global noprefixroute eth1
[ IN ] INPUT primary_ip address ( of current meta node, e.g 10.10.10.10) :
= > 10.10.10.12 # <------- 在这里输入你的首要 IPv4 地址!
[ OK ] primary_ip = 10.10.10.12 ( from input)
[ OK ] admin = vagrant@10.10.10.12 ok
[ OK ] mode = meta ( el9)
[ OK ] locale = C.UTF-8
[ OK ] configure pigsty done
proceed with ./install.yml
-i|--ip: 当前主机的首要内网IP地址,用于替换配置文件中的 IP 地址占位符 10.10.10.10。-c|--conf: 用于指定使用的配置 配置模板 ,相对于 conf/ 目录,不带 .yml 后缀的配置名称。-v|--version: 用于指定要安装的 PostgreSQL 大版本,如 13、14、15、16、17、18,部分模板不支持此配置。-r|--region: 用于指定上游软件源的区域,加速下载: (default|china|europe)-n|--non-interactive: 直接使用命令行参数提供首要IP地址,跳过交互式向导。-x|--proxy: 使用当前环境变量配置 proxy_env 变量(影响 http_proxy/HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY)。如果您的机器网卡绑定了多个 IP 地址,那么需要使用 -i|--ip <ipaddr> 显式指定一个当前节点的首要 IP 地址,或在交互式问询中提供。
该脚本将把 IP 占位符 10.10.10.10 替换为当前节点的主 IPv4 地址。选用的地址应为静态 IP 地址,请勿使用公网 IP 地址。
配置过程生成的配置文件默认位于:~/pigsty/pigsty.yml,您可以在安装前进行检查与修改定制。
修改默认密码!
我们强烈建议您在安装前,事先修改配置文件中使用的默认密码与凭据,详情参考 安全考量 。
安装 Pigsty 中的一切都由 配置清单 所定义,也就是 上面 生成的 pigsty.yml 配置。
运行 install.yml 剧本 会实施这个部署计划:
./install.yml # 一次性在所有节点上完成安装
安装过程的样例输出 ......
TASK [ pgsql : pgsql init done ] *************************************************
ok: [ 10.10.10.11] = > {
"msg" : "postgres://10.10.10.11/postgres | meta | dbuser_meta dbuser_view "
}
......
TASK [ pg_monitor : load grafana datasource meta] *******************************
changed: [ 10.10.10.11]
PLAY RECAP *********************************************************************
10.10.10.11 : ok = 302 changed = 232 unreachable = 0 failed = 0 skipped = 65 rescued = 0 ignored = 1
localhost : ok = 6 changed = 3 unreachable = 0 failed = 0 skipped = 1 rescued = 0 ignored = 0
输出尾部如果带有 pgsql init done,PLAY RECAP 等字样,说明安装已经完成!
上游仓库(如 Linux / PGDG 仓库)可能会因为更新而进入崩溃状态并导致安装失败(有过多次先例)!
您可以选择等待上游仓库修复后安装,或者使用预制的 离线软件包 来解决这个问题。
避免重复执行安装剧本!
警告: 在已经初始化的环境中再次运行 install.yml 会重置整个环境,所以请务必小心!
此剧本仅用于初始安装,安装完毕后可以用 rm install.yml 或 chmod a-x install.yml 来避免此剧本的误执行。
用户界面 安装完成后,当前节点会安装有四个核心模块:PGSQL ,INFRA ,NODE ,ETCD 。
您可以直接通过以下 端口 访问 WebUI 服务(不推荐用于生产环境)。或使用本地/公共域名通过 Nginx 门户访问它们。
Grafana 监控系统(g.pigsty / 3000端口)的默认用户名与密码为:admin / pigsty
您可以通过以下数据库用户和相应的 PGURL 访问默认端口 5432 上的默认 PostgreSQL 数据库(meta):
默认用户连接串
dbuser_dba
dbuser_meta
dbuser_view psql postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta # DBA / 超级用户 psql postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta # 业务管理员用户 psql postgres://dbuser_view:DBUser.Viewer@10.10.10.10:5432/meta # 只读查看者
如何通过域名访问 Pigsty WebUI ? 客户端可以通过几种不同的办法来使用域名访问:
通过 DNS 服务商解析互联网域名,适用于公网可访问的系统。 通过配置内网 DNS 服务器解析记录实现内网域名解析。 修改本机的 /etc/hosts 文件添加静态解析记录。 我们建议普通用户使用第三种方式,在使用浏览器访问 Web 系统的机器上,修改 /etc/hosts (需要 sudo 权限)或 C:\Windows\System32\drivers\etc\hosts(Windows)文件,添加以下的解析记录:
<your_ip_address> h.pigsty a.pigsty p.pigsty g.pigsty
这里的 IP 地址是安装 Pigsty 服务的 对外IP地址 。
如何配置服务端使用的域名? 服务器端域名使用 Nginx 进行配置,如果您想要替换默认的域名,在参数 infra_portal 中填入使用的域名即可。
当您使用 http://g.pigsty 访问 Grafana 监控主页时,实际上是通过 Nginx 代理访问了 Grafana 的 WebUI:
http://g.pigsty ️-> http://10.10.10.10:80 (nginx) -> http://10.10.10.10:3000 (grafana)
如何使用 HTTPS 访问 Pigsty WebUI ? Pigsty默认使用自动生成的自签名的 CA 证书为 Nginx 启用 SSL,如果您希望使用 HTTPS 访问这些页面,而不弹窗提示"不安全",通常有三个选择:
在您的浏览器或操作系统中信任 Pigsty 自签名的 CA 证书: files/pki/ca/ca.crt 如果您使用 Chrome,可以在提示不安全的窗口键入 thisisunsafe 跳过提示 您可以考虑使用 Let’s Encrypt 或其他免费的 CA 证书服务,为 Pigsty Nginx 生成正式的 SSL证书。 更多 您可以使用 Pigsty 部署和监控 更多集群 :向 配置清单 添加定义并运行:
bin/node-add pg-test # 将集群 pg-test 的3个节点纳入 Pigsty 管理
bin/pgsql-add pg-test # 初始化一个3节点的 pg-test 高可用PG集群
bin/redis-add redis-ms # 初始化 Redis 集群: redis-ms
记住,大多数模块都需要先安装 NODE 模块。查看可用的 模块 了解详情:
PGSQL ,INFRA ,NODE ,ETCD ,
MINIO ,REDIS ,FERRET ,DOCKER ……
3.2 - 离线安装 在没有互联网访问的环境中,使用离线安装包安装 Pigsty
Pigsty 默认从互联网上游 安装 所需软件包,但有些环境与互联网隔离。
为了解决这个问题,Pigsty 支持使用 离线软件包 进行离线安装。
离线软件包打包了所有需要的 RPM/DEB 软件包及其依赖;它本质上是在正常 安装 后采取的本地 APT / YUM 仓库的快照压缩包。
使用离线软件包的步骤:
下载 pigsty 离线软件包,将其放到 /tmp/pkg.tgz 下载 pigsty 源码包,解压(假设解压到 ~/pigsty) cd ~/pigsty; ./bootstrap,它将解压软件包并使用本地仓库vi ~/pigsty.yml,覆盖 node_repo_modules 设为 local 以使用本地仓库照常运行 ./install.yml。它将从本地仓库安装所有内容。 离线软件包 您可以从 GitHub 发布页面 找到这些软件包,例如:
d6e9d6fa73620460ceb373a0c2f41ebe pigsty-v4.0.0.tgz
987529769d85a3a01776caefefa93ecb pigsty-pkg-v4.0.0.d12.aarch64.tgz
2d8272493784ae35abeac84568950623 pigsty-pkg-v4.0.0.d12.x86_64.tgz
090cc2531dcc25db3302f35cb3076dfa pigsty-pkg-v4.0.0.d13.x86_64.tgz
ddc54a9c4a585da323c60736b8560f55 pigsty-pkg-v4.0.0.el10.aarch64.tgz
d376e75c490e8f326ea0f0fbb4a8fd9b pigsty-pkg-v4.0.0.el10.x86_64.tgz
8c2deeba1e1d09ef3d46d77a99494e71 pigsty-pkg-v4.0.0.el8.aarch64.tgz
9795e059bd884b9d1b2208011abe43cd pigsty-pkg-v4.0.0.el8.x86_64.tgz
08b860155d6764ae817ed25f2fcf9e5b pigsty-pkg-v4.0.0.el9.aarch64.tgz
1ac430768e488a449d350ce245975baa pigsty-pkg-v4.0.0.el9.x86_64.tgz
e033aaf23690755848db255904ab3bcd pigsty-pkg-v4.0.0.u22.aarch64.tgz
cc022ea89181d89d271a9aaabca04165 pigsty-pkg-v4.0.0.u22.x86_64.tgz
0e978598796db3ce96caebd76c76e960 pigsty-pkg-v4.0.0.u24.aarch64.tgz
48223898ace8812cc4ea79cf3178476a pigsty-pkg-v4.0.0.u24.x86_64.tgz
我们通常为以下 Linux 发行版 发布离线软件包,使用最新的操作系统次要版本。
EL 发行版 代号 架构 系统代码 软件包 RockyLinux 9.6 EL9 x86_64 el9.x86_64pigsty-pkg-v4.0.0.el9.x86_64.tgzUbuntu 24.04.2 U24 x86_64 u24.x86_64pigsty-pkg-v4.0.0.u24.x86_64.tgzDebian 12.11 D12 x86_64 d12.x86_64pigsty-pkg-v4.0.0.d12.x86_64.tgzRockyLinux 9.6 EL9 aarch64 el9.aarch64pigsty-pkg-v4.0.0.el9.aarch64.tgzUbuntu 24.04.2 U24 aarch64 u24.aarch64pigsty-pkg-v4.0.0.u24.aarch64.tgzDebian 12.11 D12 aarch64 d12.aarch64pigsty-pkg-v4.0.0.d12.aarch64.tgz
离线软件包是为特定的 Linux 操作系统小版本制作的
在较低的操作系统小版本上使用更高小版本的离线软件包,大概率可以使用,但也有失败的可能。
使用离线软件包 将离线软件包放置于 /tmp/pkg.tgz 路径下,进入 ~/pigsty 目录执行 ./bootstrap,即可解包使用离线安装包。
Pigsty 会将其解压至 /www/pigsty,然后配置系统仓库列表启用此仓库,并从中安装 ansible。
自从 Pigsty v3.6 版本起,大部份配置模板都默认不再构建本地软件仓库,而是直接从互联网上游安装软件包。
少部分配置模板如 rich 与 full 依然保留了旧版本的行为 —— 先构建本地仓库再使用。
如果您想要在自己的配置中使用已经解包配置好的离线软件包,请修改以下配置:
repo_enabled :将此参数打开,设置为 true,则会构建本地软件源(在大部份配置中被显式关闭)node_repo_modules :将此参数设置为 local,则环境中所有节点都从本地软件仓库安装在大部份模板中,此参数现在被显式配置为:node,infra,pgsql,即直接从这些上游软件仓库安装。 将其设置为 local,则会使用本地软件仓库安装所有软件包,速度最快,没有其他仓库的变数干扰。 如果你想同时使用本地软件仓库和上游软件仓库,可以将其设置为 local,node,infra,pgsql 制作离线软件包 如果您选择的操作系统不在默认列表中,您可以使用内置的 cache.yml 剧本制作自己的离线软件包:
找到一台运行完全相同操作系统版本,且可以访问互联网的节点 运行标准 在线安装 (建议使用 rich 配置模板:configure -c rich) cd ~/pigsty; ./cache.yml:制作并获取离线软件包到 ~/pigsty/dist/${version}/将离线软件包复制到没有互联网访问的环境中(ftp、scp、usb 等),通过 bootstrap 解包使用 v3.6 的行为变化
自从 Pigsty v3.6 开始,大部份配置模板都直接从互联网上游安装软件包,而不是先下载到管理节点本地构建软件仓库,再从中安装。
你可以通过调整参数来恢复此前的默认行为,如果你需要构建自己的离线软件包,这很有用:
部分配置模板,例如 rich 与 full 依然直接保留旧版本的行为 —— 先构建本地仓库再使用,故无需调整。
优缺点 如果您使用的是上述列表中给出的操作系统(精确匹配的小版本),那么建议使用离线软件包。
Pigsty 为这些系统提供了开箱即用的预制离线软件包,在 GitHub 上提供免费下载。
使用离线软件包的优点
官方离线软件包经过测试。 在与互联网隔离的环境中交付的最简单方法。 通过一次性预下载所有软件包来加速安装过程。 快照确保可以正常工作,无需担心上游依赖项的变动导致依赖错漏。 使用离线软件包的缺点
如果操作系统次要版本不匹配,操作系统的 rpm/deb 软件包可能会出现问题 可能不包含最新的更新和操作系统安全补丁。 如果你使用的操作系统版本不在上述列表中,你可以考虑自制离线安装包,我们也提供针对更多操作系统大小版本的离线安装包 预制服务 (¥200)
混合方法 有一种混合方法可以使用离线软件包作为基础,并在线补足不匹配的增量软件包,这种办法可以融合离线安装与在线安装的优点。
例如,假设您使用的是 RockyLinux 9.5,但官方离线软件包是为 RockyLinux 9.6 制作的。
您可以使用 el9 离线软件包(虽然是针对 9.6 制作的),然后在执行正式安装前,执行 make repo-build 重新下载 9.5 对应的缺失软件包,
Pigsty 将从上游仓库重新下载所需的增量。
Bootstrap bootstrap 脚本将自动检测 /tmp/pkg.tgz 并默认将其解压到 /www/pigsty。
它还将设置操作系统软件包管理器的仓库文件,并安装 ansible 和其他工具。
./bootstrap # 确保 ansible 正确安装(如果有离线包,优先使用离线安装并解包使用)
我的仓库文件在哪里?
引导程序默认会 清除 现有仓库,以确保只安装所需的仓库。
您可以在 /etc/yum.repos.d/backup (EL) 或 /etc/apt/backup (Debian / Ubuntu) 中找到它们。
如果您想保留现有仓库
您可以使用 -k|--keep 参数来保持现有仓库文件不变:
./bootstrap -k # 或 --keep
3.3 - 精简安装 只安装高可用 PostgreSQL 集群及其最小依赖的精简安装模式
如果您只想要高可用 PostgreSQL 本身,而不需要监控、基础设施等功能,请考虑精简安装。
没有 INFRA 模块,没有监控,没有 本地仓库 ,只有 ETCD 和 PGSQL 以及部分 NODE 功能
概览 使用精简安装,您需要:
使用 slim.yml 配置模板(configure -c slim) 运行 slim.yml 剧本而不是 install.yml curl https://repo.pigsty.cc/get | bash
./configure -c slim
./slim.yml
精简安装只安装这些核心组件:
组件 必需性 描述 patroni ⚠️ 必需 引导高可用 PostgreSQL 集群 etcd ⚠️ 必需 Patroni 的元数据库依赖(DCS) pgbouncer ✔️ 可选 PostgreSQL 连接池 vip-manager ✔️ 可选 L2 VIP 绑定到 PostgreSQL 集群主节点 haproxy ✔️ 可选 自动路由 服务 chronyd ✔️ 可选 与 NTP 服务器的时间同步 tuned ✔️ 可选 节点调优模板和内核参数管理
您可以关闭可选组件,只有两个必需组件是 patroni 和 etcd。
软件包直接从互联网上游仓库安装,离线安装 在此处不适用。
配置 精简安装的配置文件示例:conf/slim.yml :
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#----------------------------------------------#
# PostgreSQL Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
pg_databases :
- { name: meta, baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ vector ]}
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
vars :
#----------------------------------------------#
# INFRA : https://pigsty.io/docs/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # domain names and upstream servers
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9058" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
#----------------------------------------------#
# NODE : https://pigsty.io/docs/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://pigsty.io/docs/pgsql/param
#----------------------------------------------#
pg_version : 18 # Default PostgreSQL Major Version is 18
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#----------------------------------------------#
# SLIM: https://pigsty.io/docs/setup/slim
#----------------------------------------------#
nginx_enabled : false # nginx not exists
dns_enabled : false # dnsmasq not exists
prometheus_enabled : false # prometheus not exists
grafana_enabled : false # grafana not exists
pg_exporter_enabled : false # disable pg_exporter
pgbouncer_exporter_enabled : false # disable pgbouncer_exporter
pgbackrest_exporter_enabled : false # disable pgbackrest_exporter
pg_vip_enabled : false # disable pg_vip
安装 使用 slim.yml 剧本而不是 install.yml 剧本:
不要使用 install.yml 进行精简安装
这个 slim.yml 剧本是专门用来在精简安装场景中取代默认 install.yml 剧本的。
3.4 - 声明配置 使用声明式的配置来描述数据库集群与基础设施
Pigsty将基础设施和数据库视为代码 :Database as Code & Infra as Code
你可以通过声明式的接口/配置文件来描述基础设施和数据库集群,你只需在 配置清单 (Inventory) 中描述你的需求,然后用简单的幂等剧本使其生效即可。
配置清单 每一套 Pigsty 部署都有一个相应的 配置清单 (Inventory)。它可以以 YAML 的形式存储在本地,
并使用 git 管理;或从 CMDB 或任何 ansible 兼容的方式动态生成。
Pigsty 默认使用一个名为 pigsty.yml 的单体 YAML 配置文件作为默认的配置清单,
它位于 Pigsty 源码主目录下,但你也可以通过命令行参数 -i 指定路径以使用别的配置清单。
清单由两部分组成:全局变量 (all.vars)和多个 组定义 (all.children) 。 前者 all.vars 通常用于描述基础设施,并为集群设置全局默认参数。后者 all.children 则负责定义新的集群(PGSQL/Redis/MinIO/ETCD等等)。一个配置清单文件从最顶层来看大概如下所示:
all : # 顶层对象:all
vars : {...} # 全局参数
children : # 组定义
infra : # 组定义:'infra'
hosts : {...} # 组成员:'infra'
vars : {...} # 组参数:'infra'
etcd : {...} # 组定义:'etcd'
pg-meta : {...} # 组定义:'pg-meta'
pg-test : {...} # 组定义:'pg-test'
redis-test : {...} # 组定义:'redis-test'
# ...
集群 每个组定义通常代表一个集群,可以是节点集群、PostgreSQL 集群、Redis 集群、Etcd 集群或 Minio 集群等。它们都使用相同的格式:hosts 和 vars。
你可以用 all.children.<cls>.hosts 定义集群成员,并使用 all.children.<cls>.vars 中的集群参数描述集群。以下是名为 pg-test 的三节点 PostgreSQL 高可用集群的定义示例:
pg-test : # 集群名称
vars : # 集群参数
pg_cluster : pg-test
hosts : # 集群成员
10.10.10.11 : { pg_seq: 1, pg_role : primary } # 实例1,在 10.10.10.11 上,主库
10.10.10.12 : { pg_seq: 2, pg_role : replica } # 实例2,在 10.10.10.12 上,从库
10.10.10.13 : { pg_seq: 3, pg_role : offline } # 实例3,在 10.10.10.13 上,从库
你也可以为特定的主机/实例定义参数,也称为实例参数。它将覆盖集群参数和全局参数,实例参数通常用于为节点和数据库实例分配身份(实例号,角色)。
参数 全局变量、组变量和主机变量都是由一系列 键值对 组成的字典对象。每一对都是一个命名的参数,由一个字符串名作为键,和一个值组成。值是五种类型之一:布尔值、字符串、数字、数组或对象。查看配置参数 以了解详细的参数语法语义。
绝大多数参数都有着合适的默认值,身份参数 除外;它们被用作标识符,并必须显式配置,例如 pg_cluster , pg_role ,以及 pg_seq 。
参数可以被更高优先级的同名参数定义覆盖,优先级如下所示:
命令行参数 > 剧本变量 > 主机变量(实例参数) > 组变量(集群参数) > 全局变量(全局参数) > 默认值
例如:
使用命令行参数 -e pg_clean=true 强制删除现有数据库 使用实例参数 pg_role 和 pg_seq 来为一个数据库实例分配角色与标号。 使用集群变量来为集群设置默认值,如集群名称 pg_cluster 和数据库版本 pg_version 使用全局变量为所有 PGSQL 集群设置默认值,如使用的默认参数和插件列表 如果没有显式配置 pg_version ,默认值 18 版本号会作为最后兜底的缺省值。 模板 在 Pigsty 目录中的 conf/ 目录里,提供了针对许多不同场景的预置配置模板可供参考选用。
在 configure 过程中,您可以通过 -c 参数指定模板。否则会默认使用单节点安装的 meta 模板。
关于这些模版的功能,请参考 配置模板 中的介绍。
切换配置源 要使用不同的配置模板,您可以将模板的内容复制到 Pigsty 源码目录的 pigsty.yml 文件中,并按需进行相应调整。
您也可以在执行 Ansible 剧本时,通过 -i 命令行参数,显式指定使用的配置文件,例如:
./node.yml -i files/pigsty/rpmbuild.yml # 根据 rpmbuild 配置文件,初始化目标节点,而不是使用默认的 pigsty.yml 配置文件
如果您希望修改默认的配置文件名称与位置,您也可以修改源码根目录下的 ansible.cfg 的 inventory 参数,将其指向您的配置文件路径,这样您就可以直接执行 ansible-playbook 命令而无需显式指定 -i 参数。
Pigsty 允许您使用数据库(CMDB)作为动态配置源,而不是使用静态配置文件。 Pigsty 提供了三个便利脚本:
参考 Pigsty 带有 280+ 配置参数,分为以下32个参数组,详情请参考 配置参数 。
3.5 - 准备工作 如何准备部署 Pigsty 所需的节点,操作系统,管理员用户,端口,与所需权限。
与 Pigsty 部署有关的 101 入门知识。
节点准备 Pigsty 支持 Linux 内核与 x86_64/amd64 架构,适用于任意节点。
所谓节点(node),指 ssh 可达并提供裸操作系统环境的资源,例如物理机,裸金属,虚拟机,或者启用了 systemd 与 sshd 的操作系统容器。
部署 Pigsty 最少需要一个节点。最低配置要求为 1C1G,推荐至少使用 2C4G 以上的机型,适用配置上不封顶,参数会自动优化适配。
作为 Demo,个人站点,或者开发环境时,可以使用单个节点。作为独立监控基础设施使用时,建议使用 1-2 个节点,作为高可用 PostgreSQL 数据库集群使用时,建议至少使用 3 个节点。用于核心场景时,建议使用至少 4-5 个节点。
充分利用 IaC 工具完成琐事
手工配置大规模生产环境繁琐且容易出错,我们建议您充分利用 Infra as Code 工具,解决此类问题。
您可以使用 Pigsty 提供的 Terraform 模板与 Vagrant 模板,使用 IaC 的方式一键创建所需的节点环境,完成好网络,操作系统,管理用户,权限,安全组的置备工作。
网络准备 Pigsty 要求节点使用 静态IPv4地址 ,即您应当为节点显式分配指定固定的 IP 地址,而不应当使用 DHCP 动态分配的地址。
节点使用的 IP 地址应当是节点用于内网通信的首要 IP 地址,并将作为节点的唯一身份标识符。
如果您希望使用可选的 Node VIP 与 PG VIP 功能,应当确保所有节点位于一个大二层网络中。
您的防火墙策略应当保证所需的端口在节点间开放,不同模块所需的具体端口列表请参考 节点:端口 。
应该暴露哪些端口?
暴露端口的方法取决于您的网络安全策略实现,例如:公有云上的安全组策略,或本地 iptables 记录,防火墙配置等。
如果您只是希望尝尝鲜,不在乎安全,并且希望一切越简单越好,那么您可以仅对外部用户按需开放 5432 端口( PostgreSQL 数据库) 与 3000 端口(Grafana 可视化界面)。
在 Infra节点 上的 Nginx 默认会对外暴露 80/443 端口提供 Web 服务,并通过域名对不同服务进行区分,这一端口应当对办公网络(或整个整个互联网)开放。
严肃的生产数据库服务端口通常不应当直接暴露在公网上,如果您确实需要这么做,建议首先查阅 安全最佳实践 ,并小心行事。
操作系统准备 Pigsty 支持多种基于 Linux 内核的服务器操作系统发行版,我们建议使用 RockyLinux 9.6 、Ubuntu 24.04.2 或 Debian 12.11 作为安装 Pigsty 的 OS。
Pigsty 支持 RHEL (7,8,9,10),Debian (11,12,13),Ubuntu (20,22,24) 以及多种与之兼容的操作系统发行版,完整操作系统列表请参考 兼容性 。
在使用多个节点镜进行部署时,我们 强烈 建议您在所有用于 Pigsty 部署的节点上,使用相同版本 的操作系统发行版与 Linux 内核版本
我们强烈建议使用干净,全新安装的最小化安装的服务器操作系统环境 ,并使用 en_US 作为首要语言。
如何安装并启用 en_US locale?
使用其他系统语言包时,如何确保 en_US 本地化规则集可用:
yum install -y glibc-locale-source glibc-langpack-en
localedef -i en_US -f UTF-8 en_US.UTF-8
localectl set-locale LANG = en_US.UTF-8
注:Pigsty 部署的 PostgreSQL 集群默认使用 C.UTF8 locale,但字符集定义使用 en_US 以确保 pg_trgm 扩展可以正常工作。
如果您确实不需要此功能,可以配置 pg_lc_ctype 的值为 C.UTF8 ,以避免在系统语言包缺失的情况下,数据库初始化报错的问题。
管理用户准备 在安装 Pigsty 的节点上,您需要拥有一个 “管理用户 ” —— 拥有免密 ssh 登陆权限与免密 sudo 权限。
免密 sudo 是必选项,用于在安装过程中执行需要 sudo 权限的命令,例如安装软件包,配置系统参数等。
如何配置管理用户的免密码 sudo 权限?
假设您的管理用户名为 vagrant ,则可以创建 /etc/sudoers.d/vagrant 文件,并添加以下记录:
%vagrant ALL =( ALL) NOPASSWD: ALL
则 vagrant 用户即可免密 sudo 执行所有命令。如果你的用户名不是 vagrant,请将上面操作中的 vagrant 替换为您的用户名。
避免使用 root 用户安装
尽管使用 root 用户安装 Pigsty 是可行的,但我们不推荐这样做。
安全最佳实践 是使用一个不同于根用户(root)与数据库超级用户 (postgres) 的专用管理员用户(如:dba)
Pigsty 提供了专用剧本任务,可以使用一个现有的管理用户(例如 root),输入 ssh/sudo 密码,创建一个专用的 管理员用户 。
SSH 权限准备 除了免密 sudo 权限, Pigsty 还需要管理用户免密 ssh 登陆的权限。
对于单机安装 的节点而言,这意味着本机上的管理用户可以通过 ssh 免密码登陆到本机上。
如果的 Pigsty 部署涉及到多个节点,这意味着管理节点 上的管理用户应当可以通过 ssh 免密码登陆到所有被 Pigsty 纳管的节点上(包括本机),并免密执行 sudo 命令。
单机安装时,在 configure 过程中,如果您的当前管理用户没有 SSH key,Pigsty 会尝试修复此问题:随机生成一对新的 id_rsa 密钥,并添加至本地 ~/.ssh/authroized_keys 文件确保本机管理用户的 SSH 登陆能力。
Pigsty 默认会为您在纳管的节点上创建一个可用的管理用户 dba (uid=88),如果您已经使用了此用户,我们建议您修改 node_admin_username 使用新的用户名与其他 uid,或通过 node_admin_enabled 参数禁用。
如何配置管理用户的 ssh 免密码登陆?
假设您的管理用户名为 vagrant,则以 vagrant 用户身份执行以下命令,会为其生成公私钥对 ~/.ssh/id_rsa[.pub] 用于登陆。如果已经存在公私钥对,则无需生成新密钥对。
ssh-keygen -t rsa -b 2048 -N '' -f ~/.ssh/id_rsa -q
生成的公钥默认位于:/home/vagrant/.ssh/id_rsa.pub,私钥默认位于:/home/vagrant/.ssh/id_rsa,如果您操作系统用户名不叫 vagrant,将上面的 vagrant 替换为您的用户名即可。
您应当将公钥文件(id_rsa.pub)追加写入到需要登陆机器的对应用户上:/home/vagrant/.ssh/authorized_keys 文件中。如果您已经可以直接通过密码访问远程机器,可以直接通过ssh-copy-id的方式拷贝公钥:
ssh-copy-id <ip> # 输入密码以完成公钥拷贝
sshpass -p <password> ssh-copy-id <ip> # 直接将密码嵌入命令中,避免交互式密码输入(注意安全!)
Pigsty 推荐将管理用户的创建,权限配置与密钥分发放在虚拟机的置备阶段完成,作为标准化交付内容的一部分。
SSH 例外情况 如果您的 SSH 访问有一些额外限制,例如,使用了跳板机,或者进行了某些定制化修改,无法通过简单的 ssh <ip> 方式访问,那么可以考虑使用 ssh 别名。
例如,如果您的服务器可以通过 ~/.ssh/config 中定义的别名,例如 meta 通过 ssh 访问,那么可以为 配置清单 中的节点配置 ansible_host 参数,指定 SSH Alias:
nodes :
hosts : # 10.10.10.10 无法直接 ssh,但可以通过ssh别名 `meta` 访问
10.10.10.10 : { ansible_host : meta }
如果 SSH 别名无法满足您的需求,Ansible 还提供了一系列自定义 ssh 连接参数 ,可以精细控制 SSH 连接的行为。
最后,如果以下命令可以在管理节点上使用管理用户成功执行,意味着该目标节点上的管理用户与权限配置已经妥当:
软件准备 在 管理节点 上,Pigsty 需要使用 Ansible 发起控制命令。如果您使用本地单机安装,那么管理节点和被管理的节点是同一台,需要安装 Ansible。对于普通节点,则无需安装 Ansible。
在 bootstrap 过程中,Pigsty 会尽最大努力自动为您完成安装 Ansible 这一任务,但您也可以选择手工安装 Ansible。手工安装 Ansible 的过程因不同操作系统发行版/大版本而异(通常涉及到额外的弱依赖 jmespath):
安装 Ansible
EL 8 / 9
EL 7
Debian / Ubuntu
MacOS sudo dnf install -y ansible python3.12-jmespath python3-cryptography sudo yum install -y ansible # EL7 无需显式安装 Jmespath sudo apt install -y ansible python3-jmespath 为了安装 Pigsty,您还需要准备 Pigsty 源码包。您可以直接从 GitHub Release 页面下载特定版本,或使用以下命令获取最新稳定版本:
curl -fsSL https://repo.pigsty.cc/get | bash
如果您的环境没有互联网访问,也可以考虑直接从 GitHub Release 页面或其他渠道下载针对不同操作系统发行版预先制作的 离线安装包 。
3.6 - 执行剧本 Pigsty 使用 Ansible 剧本来实现所需的安装部署管理功能,但如果只是使用的话,您并不需要了解太多细节。
在 Pigsty 中,剧本 / Playbooks 用于在节点上安装模块 。
剧本可以视作可执行文件直接执行,例如:./install.yml.
剧本 以下是 Pigsty 中默认包含的剧本:
一次性安装 特殊的剧本 install.yml 实际上是一个复合剧本,它在当前环境上安装所有以下组件。
playbook / command / group infra nodes etcd minio pgsql
[ infra.yml] ./infra.yml [ -l infra] [ +infra][ +node]
[ node.yml] ./node.yml [ +node] [ +node] [ +node] [ +node]
[ etcd.yml] ./etcd.yml [ -l etcd ] [ +etcd]
[ minio.yml] ./minio.yml [ -l minio] [ +minio]
[ pgsql.yml] ./pgsql.yml [ +pgsql]
请注意,NODE 和 INFRA 之间存在循环依赖:为了在 INFRA 上注册 NODE,INFRA 应该已经存在,而 INFRA 模块依赖于 INFRA节点上的 NODE 模块才能工作。
为了解决这个问题,INFRA 模块的安装剧本也会在 INFRA 节点上安装 NODE 模块。所以,请确保首先初始化 INFRA 节点。
如果您非要一次性初始化包括 INFRA 在内的所有节点,install.yml 剧本就是用来解决这个问题的:它会正确的处理好这里的循环依赖,一次性完成整个环境的初始化。
Ansible 执行剧本需要 ansible-playbook 可执行文件,该文件包含在 ansible rpm/deb 包中。
Pigsty 将在 准备 期间在尽最大努力尝试在当前节点安装 ansible。
您可以自己使用 yum / apt / brew install ansible 来安装 Ansible,它含在各大发行版的默认仓库中。
了解 ansible 对于使用 Pigsty 很有帮助,但也不是必要的。对于基本使用,您只需要注意四个参数就足够了:
-i|--inventory <path> :显式指定使用的配置文件-l|--limit <pattern> : 限制剧本在特定的组/主机/模式上执行目标(在哪里/Where)-t|--tags <tags> : 只运行带有特定标签的任务(做什么/What)-e|--extra-vars <vars> : 传递额外的命令行参数(怎么做/How)指定配置文件 您可以使用 -i 命令行参数,显式指定使用的配置文件。
Pigsty 默认使用名为 pigsty.yml 配置文件,该文件位于 Pigsty 源码根目录中的 pigsty.yml。但您可以使用 -i 覆盖这一行为,例如:
./node.yml -i files/pigsty/rpmbuild.yml # 根据 rpmbuild 配置文件,初始化目标节点,而不是使用默认的 pigsty.yml 配置文件
./pgsql.yml -i files/pigsty/rpm.yml # 根据 files/pigsty/rpm.yml 配置文件中的定义,在目标节点上安装 pgsql 模块
./redis.yml -i files/pigsty/redis.yml # 根据 files/pigsty/redis.yml 配置文件中的定义,在目标节点上安装 redis 模块
如果您希望永久修改默认使用的配置文件,可以修改源码根目录下的 ansible.cfg 的 inventory 参数,将其指向您的配置文件路径。
这样您就可以在执行 ansible-playbook 命令时无需显式指定 -i 参数了。
指定执行对象 您可以使用 -l|-limit <selector> 限制剧本的执行目标。
缺少此值可能很危险,因为大多数剧本会在 all 分组,也就是所有主机上执行,使用时务必小心。
以下是一些主机限制的示例:
./pgsql.yml # 在所有主机上运行(非常危险!)
./pgsql.yml -l pg-test # 在 pg-test 集群上运行
./pgsql.yml -l 10.10.10.10 # 在单个主机 10.10.10.10 上运行
./pgsql.yml -l pg-* # 在与通配符 `pg-*` 匹配的主机/组上运行
./pgsql.yml -l '10.10.10.11,&pg-test' # 在组 pg-test 的 10.10.10.10 上运行
/pgsql-rm.yml -l 'pg-test,!10.10.10.11' # 在 pg-test 上运行,除了 10.10.10.11 以外
./pgsql.yml -l pg-test # 在 pg-test 集群的主机上执行 pgsql 剧本
执行剧本子集 你可以使用 -t|--tags <tag> 执行剧本的子集。 你可以在逗号分隔的列表中指定多个标签,例如 -t tag1,tag2。
如果指定了任务子集,将执行给定标签的任务,而不是整个剧本。以下是任务限制的一些示例:
./pgsql.yml -t pg_clean # 如果必要,清理现有的 postgres
./pgsql.yml -t pg_dbsu # 为 postgres dbsu 设置操作系统用户 sudo
./pgsql.yml -t pg_install # 安装 postgres 包和扩展
./pgsql.yml -t pg_dir # 创建 postgres 目录并设置 fhs
./pgsql.yml -t pg_util # 复制工具脚本,设置别名和环境
./pgsql.yml -t patroni # 使用 patroni 引导 postgres
./pgsql.yml -t pg_user # 提供 postgres 业务用户
./pgsql.yml -t pg_db # 提供 postgres 业务数据库
./pgsql.yml -t pg_backup # 初始化 pgbackrest 仓库和 basebackup
./pgsql.yml -t pgbouncer # 与 postgres 一起部署 pgbouncer sidecar
./pgsql.yml -t pg_vip # 使用 vip-manager 将 vip 绑定到 pgsql 主库
./pgsql.yml -t pg_dns # 将 dns 名称注册到 infra dnsmasq
./pgsql.yml -t pg_service # 使用 haproxy 暴露 pgsql 服务
./pgsql.yml -t pg_exporter # 使用 haproxy 暴露 pgsql 服务
./pgsql.yml -t pg_register # 将 postgres 注册到 pigsty 基础设施
# 运行多个任务:重新加载 postgres 和 pgbouncer hba 规则
./pgsql.yml -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload
# 运行多个任务:刷新 haproxy 配置并重新加载
./node.yml -t haproxy_config,haproxy_reload
传递额外参数 您可以通过 -e|-extra-vars KEY=VALUE 传递额外的命令行参数。
命令行参数具有压倒性的优先级,以下是一些额外参数的示例:
./node.yml -e ansible_user = admin -k -K # 作为另一个用户运行剧本(带有 admin sudo 密码)
./pgsql.yml -e pg_clean = true # 在初始化 pgsql 实例时强制清除现有的 postgres
./pgsql-rm.yml -e pg_uninstall = true # 在 postgres 实例被删除后明确卸载 rpm
./redis.yml -l 10.10.10.11 -e redis_port = 6379 -t redis # 初始化一个特定的 redis 实例:10.10.10.11:6379
./redis-rm.yml -l 10.10.10.13 -e redis_port = 6379 # 删除一个特定的 redis 实例:10.10.10.11:6379
此外,您还可以通过 JSON 的方式,传递诸如数组与对象这样的复杂参数:
# 通过指定软件包与仓库模块,在节点上安装 duckdb
./node.yml -t node_repo,node_pkg -e '{"node_repo_modules":"infra","node_default_packages":["duckdb"]}'
大多数剧本都是幂等的,这意味着在未打开保护选项的情况下,一些部署剧本可能会 删除现有的数据库 并创建新的数据库。
请仔细阅读文档,多次校对命令,并小心操作。作者不对因误用造成的任何数据库损失负责 。
3.7 - 置备机器 介绍 Pigsty 演示所使用的标准四节点沙箱环境,以及如何使用 Vagrant 与 Terraform 置备所需的虚拟机。
Pigsty 在节点上运行,这些节点可以是裸机或虚拟机。您可以手工置备它们,或使用 terraform 和 vagrant 这样的工具在云端或本地进行自动配置。
沙箱环境 Pigsty 带有一个演示沙箱,所谓沙箱,就是专门用来演示/测试的环境:IP地址和其他标识符都预先固定配置好,便于复现各种演示用例。
默认的沙箱环境由4个节点组成,配置文件请参考 full.yml 。
沙箱的 4 个节点有着固定的 IP 地址:10.10.10.10、10.10.10.11、10.10.10.12、10.10.10.13。
沙箱带有一个位于 meta 节点上的单实例 PostgreSQL 集群:pg-meta:
meta 10.10.10.10 pg-meta pg-meta-1沙箱中还有一个由三个实例组成的 PostgreSQL 高可用集群:pg-test,部署在另外三个节点上:
node-1 10.10.10.11 pg-test.pg-test-1node-2 10.10.10.12 pg-test.pg-test-2node-3 10.10.10.13 pg-test.pg-test-3两个可选的 L2 VIP 分别绑定在 pg-meta 和 pg-test 集群的主实例上:
10.10.10.2 pg-meta10.10.10.3 pg-test在 meta 节点上,还有一个单实例的 etcd “集群”和一个单实例的 minio “集群”。
您可以在本地虚拟机或云虚拟机上运行沙箱。Pigsty 提供基于 Vagrant 的本地沙箱(使用 Virtualbox/libvirt 启动本地虚拟机)以及基于 Terraform 的云沙箱(使用云供应商 API 创建虚拟机)。
此外,Pigsty 还提供了一个 42节点 的生产仿真环境沙箱 prod.yml 。
Vagrant Vagrant 可以按照声明式的方式创建本地虚拟机。请查看 Vagrant 模板介绍 以获取详情。
安装 确保您的操作系统中已经安装并可以使用 Vagrant 和 Virtualbox 。
如果您使用的是 macOS,您可以使用 homebrew 一键命令安装它们,注意安装 Virtualbox 后需要重启系统。
如果你用的是 Linux,可以使用 virtualbox,也可以考虑使用 KVM: vagrant-libvirt 。
/bin/bash -c " $( curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh) "
brew install vagrant virtualbox ansible # 在 MacOS 中可以轻松一键安装,但只有 x86_64 Intel 芯片的可以
配置 vagarnt/Vagranfile 是一个 Ruby 脚本文件,用来描述 Vagrant 要创建的虚拟机节点。Pigsty 提供了一些默认的配置模板:
模板 快捷方式 规格 注释 meta.rb v14C8G x 1 单一 Meta 节点 full.rb v42C4G + 1C2G x 3 完整的4节点沙盒示例 el7.rb v72C4G + 1C2G x 3 EL7 3-节点测试环境 el8.rb v82C4G + 1C2G x 3 EL8 3-节点测试环境 el9.rb v92C4G + 1C2G x 3 EL9 3-节点测试环境 build.rb vb2C4G x 3 3-节点 EL7,8,9 构建环境 check.rb vc2C4G x 30 30 EL7-9, PG12-16 测试环境 minio.rb vm2C4G x 3 + Disk 3-节点 MinIO/etcd 测试环境 prod.rb vp2C4G x 42 42节点的生产模拟环境
每个规格文件包含一个描述虚拟机节点的 Specs 变量。例如,full.rb 包含4节点沙盒规格的描述:
Specs = [
{ "name" => "meta" , "ip" => "10.10.10.10" , "cpu" => "2" , "mem" => "4096" , "image" => "generic/rocky9" },
{ "name" => "node-1" , "ip" => "10.10.10.11" , "cpu" => "1" , "mem" => "2048" , "image" => "generic/rocky9" },
{ "name" => "node-2" , "ip" => "10.10.10.12" , "cpu" => "1" , "mem" => "2048" , "image" => "generic/rocky9" },
{ "name" => "node-3" , "ip" => "10.10.10.13" , "cpu" => "1" , "mem" => "2048" , "image" => "generic/rocky9" },
]
您可以使用 vagrant/config 脚本切换 Vagrant 配置文件,它会根据规格以及虚拟机软件类型,渲染生成最终的 Vagrantfile。
cd ~/pigsty
vagrant/config <spec>
vagrant/config meta # singleton meta | 别名:`make v1`
vagrant/config full # 4-node sandbox | 别名:`make v4`
vagrant/config el7 # 3-node el7 test | 别名:`make v7`
vagrant/config el8 # 3-node el8 test | 别名:`make v8`
vagrant/config el9 # 3-node el9 test | 别名:`make v9`
vagrant/config prod # prod simulation | 别名:`make vp`
vagrant/config build # building environment | 别名:`make vd`
vagrant/config minio # 3-node minio env
vagrant/config check # 30-node check env
虚拟机管理 当您使用 vagrant/Vagrantfile 描述了所需的虚拟机后,你可以使用vagrant up命令创建这些虚拟机。
Pigsty 模板默认会使用你的 ~/.ssh/id_rsa[.pub] 作为这些虚拟机的默认ssh凭证。
在开始之前,请确保你有一个有效的ssh密钥对,你可以通过以下方式生成一对:ssh-keygen -t rsa -b 2048
此外,还有一些 makefile 快捷方式包装了 vagrant 命令,你可以使用它们来管理虚拟机。
make # 等于 make start
make new # 销毁现有虚拟机,根据规格创建新的
make ssh # 将 SSH 配置写入到 ~/.ssh/ 中 (新虚拟机拉起后必须完成这一步)
make dns # 将 虚拟机 DNS 记录写入到 /etc/hosts 中 (如果想使用名称访问虚拟机)
make start # 等于先执行 up ,再执行 ssh
make up # 根据配置拉起虚拟机,或启动现有虚拟机
make halt # 关停现有虚拟机 (down,dw)
make clean # 销毁现有虚拟机 (clean/del/destroy)
make status # 显示虚拟机状态 (st)
make pause # 暂停虚拟机运行 (suspend,pause)
make resume # 恢复虚拟机运行 (resume)
make nuke # 使用 virsh 销毁所有虚拟机 (仅libvirt可用)
快捷方式 你可以使用以下的 Makefile 快捷方式使用 vagrant 拉起虚拟机环境。
make meta # 单个元节点
make full # 4-节点沙箱
make el7 # 3-节点 el7 测试环境
make el8 # 3-节点 el8 测试环境
make el9 # 3-节点 el9 测试环境
make prod # 42 节点生产仿真环境
make build # 3-节点 EL7,8,9 构建环境
make check # 30-节点构建校验测试环境
make minio # 3-节点 MinIO 测试环境
make meta install # 进行完整的单机安装
make full install # 进行4节点沙箱安装
make prod install # 进行42节点生产仿真环境安装
make check install # 进行30节点本地测试环境安装
...
Terraform 是一个开源的实践“基础设施即代码”的工具:描述你想要的云资源,然后一键创建它们。
Pigsty 提供了 AWS,阿里云,腾讯云的 Terraform 模板,您可以使用它们在云上一键创建虚拟机。
在 MacOS 上,Terraform 可以使用 homebrew 一键安装:brew install terraform。你需要创建一个云帐户,获取 AccessKey 和 AccessSecret 凭证来继续下面的操作。
terraform/目录包含两个示例模板:一个 AWS 模板,一个阿里云模板,你可以按需调整它们,或者作为其他云厂商配置文件的参考,让我们用阿里云为例:
cd terraform # 进入 Terraform 模板目录
cp spec/alicloud.tf terraform.tf # 使用 阿里云 Terraform 模板
在执行 terraform apply 拉起虚拟机之前,你要执行一次 terraform init 安装相应云厂商的插件。
terraform init # 安装 terraform 云供应商插件:例如默认的 aliyun 插件 (第一次使用时安装即可)
terraform apply # 生成执行计划,显示会创建的云资源:虚拟机,网络,安全组,等等等等……
运行 apply 子命令并按提示回答 yes 后,Terraform 将为你创建虚拟机以及其他云资源(网络,安全组,以及其他各种玩意)。
执行结束时,管理员节点的IP地址将被打印出来,你可以登录并开始完成 Pigsty 本身的安装
3.8 - 安全考量 Pigsty部署中与安全有关的考量
Pigsty 的默认配置已经足以覆盖绝大多数场景对于安全的需求。
Pigsty 已经提供了开箱即用的认证 与访问控制 模型,对于绝大多数场景已经足够安全。
如果您希望进一步加固系统的安全性,那么以下建议供您参考:
机密性 重要文件 保护你的 pigsty.yml 配置文件或CMDB
pigsty.yml 配置文件通常包含了高度敏感的机密信息,您应当确保它的安全。严格控制管理节点的访问权限,仅限 DBA 或者 Infra 管理员访问。 严格控制 pigsty.yml 配置文件仓库的访问权限(如果您使用 git 进行管理) 保护你的 CA 私钥和其他证书,这些文件非常重要。
相关文件默认会在管理节点Pigsty源码目录的 files/pki 内生成。 你应该定期将它们备份到一个安全的地方存储。 密码 在生产环境部署时,必须更改这些密码,不要使用默认值!
如果您使用MinIO,请修改MinIO的默认用户密码,与pgbackrest中的引用
如果您使用远程备份仓库,请务必启用备份加密,并设置加解密密码
为 PostgreSQL 使用安全可靠的密码加密算法
使用 pg_pwd_enc 默认值 scram-sha-256 替代传统的 md5 这是默认行为,如果没有特殊理由(出于对历史遗留老旧客户端的支持),请不要将其修改回 md5 使用 passwordcheck 扩展强制执行强密码 。
在 pg_libs 中添加 $lib/passwordcheck 来强制密码策略。 使用加密算法加密远程备份
为业务用户配置密码自动过期实践
不要将更改密码的语句记录到 postgres 日志或其他日志中
SET log_statement TO 'none' ;
ALTER USER "{{ user.name }}" PASSWORD '{{ user.password }}' ;
SET log_statement TO DEFAULT;
IP地址 为 postgres/pgbouncer/patroni 绑定指定的 IP 地址,而不是所有地址。
默认的 pg_listen 地址是 0.0.0.0,即所有 IPv4 地址。 考虑使用 pg_listen: '${ip},${vip},${lo}' 绑定到特定IP地址(列表)以增强安全性。 不要将任何端口直接暴露到公网IP上,除了基础设施出口Nginx使用的端口(默认80/443)
出于便利考虑,Prometheus/Grafana 等组件默认监听所有IP地址,可以直接从公网IP端口访问 您可以修改它们的配置文件,只监听内网IP地址,限制其只能通过 Nginx 门户通过域名访问,你也可以当使用安全组,防火墙规则来实现这些安全限制。 出于便利考虑,Redis服务器默认监听所有IP地址,您可以修改 redis_bind_address 只监听内网IP地址。 使用 HBA 限制 postgres 客户端访问
限制 patroni 管理访问权限:仅 infra/admin 节点可调用控制API
网络流量 使用 SSL 和域名,通过Nginx访问基础设施组件
使用 SSL 保护 Patroni REST API
使用 SSL 保护 Pgbouncer 客户端流量
完整性 为关键场景下的 PostgreSQL 数据库集群配置一致性优先模式(例如与钱相关的库)
pg_conf 数据库调优模板,使用 crit.yml 将以一些可用性为代价,换取最佳的数据一致性。使用crit节点调优模板,以获得更好的一致性。
node_tune 主机调优模板使用 crit ,可以以减少脏页比率,降低数据一致性风险。启用数据校验和,以检测静默数据损坏。
记录建立/切断连接的日志
该配置默认关闭,但在 crit.yml 配置模板中是默认启用的。 可以手工配置集群 ,启用 log_connections 和 log_disconnections 功能参数。 如果您希望彻底杜绝PG集群在故障转移时脑裂的可能性,请启用watchdog
如果你的流量走默认推荐的 HAProxy 分发,那么即使你不启用 watchdog,你也不会遇到脑裂的问题。 如果你的机器假死,Patroni 被 kill -9 杀死,那么 watchdog 可以用来兜底:超时自动关机。 最好不要在基础设施节点上启用 watchdog。 可用性 对于关键场景的PostgreSQL数据库集群,请使用足够的节点/实例数量
你至少需要三个节点(能够容忍一个节点的故障)来实现生产级的高可用性。 如果你只有两个节点,你可以容忍特定备用节点的故障。 如果你只有一个节点,请使用外部的 S3/MinIO 进行冷备份和 WAL 归档存储。 对于 PostgreSQL,在可用性和一致性之间进行权衡
不要直接通过固定的 IP 地址访问数据库;请使用 VIP、DNS、HAProxy 或它们的排列组合
使用 HAProxy 进行服务接入 在故障切换/主备切换的情况下,Haproxy 将处理客户端的流量切换。 在重要的生产部署中使用多个基础设施节点(例如,1~3)
小规模部署或要求宽松的场景,可以使用单一基础设施节点 / 管理节点。 大型生产部署建议设置至少两个基础设施节点互为备份。 使用足够数量的 etcd 服务器实例,并使用奇数个实例(1,3,5,7)
3.9 - 常见问题 Pigsty 下载,安装,部署常见问题答疑
这里列出了Pigsty用户在下载、安装、部署时常遇到的问题,如果您遇到了难以解决的问题,可以提交 Issue 或者联系我们 。
如何获取Pigsty软件源码包? 使用以下命令一键安装 Pigsty: curl -fsSL https://repo.pigsty.cc/get | bash
上述命令会自动下载最新的稳定版本 pigsty.tgz 并解压到 ~/pigsty 目录。您也可以从以下位置手动下载 Pigsty 源代码的特定版本。
如果您需要在没有互联网的环境中安装,可以提前在有网络的环境中下载好,并通过 scp/sftp 或者 CDROM/USB 传输至生产服务器。
如何加速从上游仓库下载 RPM ? 考虑使用本地仓库镜像,仓库镜像在repo_upstream 参数中配置,你可以选择 region 来使用不同镜像站。
例如,您可以设置 region = china,这样将使用 baseurl 中键为 china 的 URL 而不是 default。
如果防火墙或GFW屏蔽了某些仓库,考虑使用proxy_env 来绕过。
安装失败应该如何解决? Pigsty 不依赖 Docker,所以期待的环境是一个全新安装操作系统后的状态,如果您使用已经跑了千奇百怪服务的系统,更容易遇到疑难杂症,我们建议不要这么做。
出现安装失败时,可以按照以下思路进行排查:
您应当确认当前失败的位置在哪个模块,不同模块失败有不同的原因。您应当保留 Ansible 剧本输出结果备用,并找到所有标红的 Failed 任务。 如果出现无法识别配置,剧本直接无法开始,请检查您的配置文件是否是合法的 YAML,缩进,括号等是否有问题。 如果错误与本地软件源,Nginx 有关,请检查你的系统是不是全新系统,是否已经运行了 Nginx 或其他组件?或者是否有特殊的防火墙与安全策略在运作? 如果是安装节点软件包时出现错误,您是否使用了OS小版本精确匹配的离线软件包?上游是否出现依赖错漏?请参考下面的内容解决 如果是系统配置出现错误,您的操作系统是否是全新安装的状态?或者 —— 精简安装到了 Locale 都没有配置的状态? 如果是 MinIO 出现问题,您是否使用了 SNMD,MNMD 部署却没有提供真实的磁盘挂载点?您的 sss.pigsty 静态域名是否指向了任意 MinIO 节点或 LB 集群? 如果是 PGSQL 安装出现了问题,您在 pg_extension 中指定安装的扩展,是否还没有添加到 repo_packages 中,或者还没有被覆盖? 如果是 PGSQL 启动出现了问题,例如 wait for patroni primary,请参考 PGSQL FAQ 解决。 软件包安装失败如何解决? 请注意,Pigsty 的预制 离线软件包 是针对 特定操作系统发行版小版本 打包的,
因此如果您使用的操作系统版本没有精确对齐,我们不建议使用离线软件安装包,而是直接从上游下载符合当前操作系统实际情况的软件包版本。
如果在线安装无法解决包冲突问题,您首先可以尝试修改 Pigsty 使用的上游软件源。例如在 EL 系操作系统中, Pigsty 默认的上游软件源中使用 $releasever 这样的大版本占位符,它将被解析为具体的 7,8,9 大版本号,但是许多操作系统发行版都提供了 Vault,允许您使用特定某一个版本的软件包镜像。
因此,您可以将 repo_upstream 参数中的 BaseURL 前段替换为具体的 Vault 小版本仓库,例如:
https://mirrors.aliyun.com/rockylinux/$releasever/ (原始 BaseURL 前缀,不带 vault )https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.6.1810/ (使用 7.6 而不是默认的 7.9)https://mirrors.aliyun.com/rockylinux-vault/8.6/ (使用 8.6 而不是默认的 8.9)https://mirrors.aliyun.com/rockylinux-vault/9.2/ (使用 9.2 而不是默认的 9.3)在替换前请注意目标软件源的路径是否真实存在,例如 EPEL 不提供小版本特定的软件源。支持这种方式的上游源包括:base, updates, extras, centos-sclo, centos-sclo-rh, baseos, appstream, extras, crb, powertools, pgdg-common, pgdg1*
repo_upstream :
- { name: pigsty-local ,description: 'Pigsty Local' ,module: local ,releases: [7,8,9] ,baseurl : { default : 'http://${admin_ip}/pigsty' }} # used by intranet nodes
- { name: pigsty-infra ,description: 'Pigsty INFRA' ,module: infra ,releases: [7,8,9] ,baseurl : { default: 'https://repo.pigsty.io/rpm/infra/$basearch' ,china : 'https://repo.pigsty.cc/rpm/infra/$basearch' }}
- { name: pigsty-pgsql ,description: 'Pigsty PGSQL' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default: 'https://repo.pigsty.io/rpm/pgsql/el$releasever.$basearch' ,china : 'https://repo.pigsty.cc/rpm/pgsql/el$releasever.$basearch' }}
- { name: nginx ,description: 'Nginx Repo' ,module: infra ,releases: [7,8,9] ,baseurl : { default : 'https://nginx.org/packages/centos/$releasever/$basearch/' }}
- { name: docker-ce ,description: 'Docker CE' ,module: infra ,releases: [7,8,9] ,baseurl : { default: 'https://download.docker.com/linux/centos/$releasever/$basearch/stable' ,china: 'https://mirrors.aliyun.com/docker-ce/linux/centos/$releasever/$basearch/stable' ,europe : 'https://mirrors.xtom.de/docker-ce/linux/centos/$releasever/$basearch/stable' }}
- { name: base ,description: 'EL 7 Base' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/os/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/os/$basearch/' }}
- { name: updates ,description: 'EL 7 Updates' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/updates/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/updates/$basearch/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/updates/$basearch/' }}
- { name: extras ,description: 'EL 7 Extras' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/extras/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/extras/$basearch/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/extras/$basearch/' }}
- { name: epel ,description: 'EL 7 EPEL' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://download.fedoraproject.org/pub/epel/$releasever/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/epel/$releasever/$basearch/' ,europe : 'https://mirrors.xtom.de/epel/$releasever/$basearch/' }}
- { name: centos-sclo ,description: 'EL 7 SCLo' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/sclo/$basearch/sclo/' ,china: 'https://mirrors.aliyun.com/centos/$releasever/sclo/$basearch/sclo/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/sclo/$basearch/sclo/' }}
- { name: centos-sclo-rh ,description: 'EL 7 SCLo rh' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/sclo/$basearch/rh/' ,china: 'https://mirrors.aliyun.com/centos/$releasever/sclo/$basearch/rh/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/sclo/$basearch/rh/' }}
- { name: baseos ,description: 'EL 8+ BaseOS' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/BaseOS/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/BaseOS/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/BaseOS/$basearch/os/' }}
- { name: appstream ,description: 'EL 8+ AppStream' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/AppStream/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/AppStream/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/AppStream/$basearch/os/' }}
- { name: extras ,description: 'EL 8+ Extras' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/extras/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/extras/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/extras/$basearch/os/' }}
- { name: crb ,description: 'EL 9 CRB' ,module: node ,releases: [ 9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/CRB/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/CRB/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/CRB/$basearch/os/' }}
- { name: powertools ,description: 'EL 8 PowerTools' ,module: node ,releases: [ 8 ] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/PowerTools/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/PowerTools/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/PowerTools/$basearch/os/' }}
- { name: epel ,description: 'EL 8+ EPEL' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'http://download.fedoraproject.org/pub/epel/$releasever/Everything/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/epel/$releasever/Everything/$basearch/' ,europe : 'https://mirrors.xtom.de/epel/$releasever/Everything/$basearch/' }}
- { name: pgdg-common ,description: 'PostgreSQL Common' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/redhat/rhel-$releasever-$basearch' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg-extras ,description: 'PostgreSQL Extra' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-rhel$releasever-extras/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/pgdg-rhel$releasever-extras/redhat/rhel-$releasever-$basearch' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-rhel$releasever-extras/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg-el8fix ,description: 'PostgreSQL EL8FIX' ,module: pgsql ,releases: [ 8 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-x86_64/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-x86_64/' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-x86_64/' } }
- { name: pgdg-el9fix ,description: 'PostgreSQL EL9FIX' ,module: pgsql ,releases: [ 9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-x86_64/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-x86_64/' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-x86_64/' }}
- { name: pgdg15 ,description: 'PostgreSQL 15' ,module: pgsql ,releases: [7 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/15/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/15/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/15/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg16 ,description: 'PostgreSQL 16' ,module: pgsql ,releases: [ 8,9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/16/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/16/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/16/redhat/rhel-$releasever-$basearch' }}
- { name: timescaledb ,description: 'TimescaleDB' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default : 'https://packagecloud.io/timescale/timescaledb/el/$releasever/$basearch' }}
在 Pigsty 配置文件中显式定义并覆盖 repo_upstream 后,(可清除 /www/pigsty/repo_complete 标记后)再次尝试安装。如果上游软件源与镜像源的软件没有解决问题,你可以考虑将上面的源替换为操作系统自带的软件源,再次尝试从上游直接安装。
最后如果以上手段都没有解决问题,你可以考虑移除 node_packages, infra_packages, pg_packages,pg_extensions 中出现冲突的软件包。或者移除、升级现有系统上的冲突软件包。
准备 / bootstrap 过程是干什么的? 检测环境是否就绪、用各种手段确保后续安装所必需的工具 ansible 被正确安装。
当你下载 Pigsty 源码后,可以进入目录并执行 bootstrap 脚本。它会检测你的节点环境,如果没有发现离线软件包,它会询问你要不要从互联网下载。
你可以选择 “是”(y),直接使用离线软件包安装又快又稳定。你也可以选“否” (n) 跳过,在安装时直接从互联网上游下载最新的软件包,这样会极大减少出现 RPM/DEB 包冲突的概率。
如果使用了离线软件包,bootstrap 会直接从离线软件包中安装 ansible,否则会从上游下载 ansible 并安装,如果你没有互联网访问,又没有 DVD,或者内网软件源,那就只能用离线软件包来安装了。
配置 / configure 过程会检测你的节点环境并为你生成一个 pigsty 配置文件:pigsty.yml,默认根据你的操作系统(EL 7/8/9)选用相应的单机安装模板。
所有默认的配置模板都在 files/pigsty中,你可以使用 -c 直接指定想要使用的配置模板。如果您已经知道如何配置 Pigsty 了,那么完全可以跳过这一步,直接编辑 Pigsty 配置文件。
Pigsty配置文件是干什么的? Pigsty主目录下的 pigsty.yml 是默认的配置文件,可以用来描述整套部署的环境,在 conf/ 目录中有许多配置示例供你参考。在 文档站:配置模板 中相关说明。
当执行剧本时,你可以使用 -i <path> 参数,选用其他位置的配置文件。例如,你想根据另一个专门的配置文件 redis.yml 来安装 redis,可以这样做:./redis.yml -i files/pigsty/redis.yml
如何使用 CMDB 作为配置清单? Ansible 默认使用的配置清单在 ansible.cfg 中指定为:inventory = pigsty.yml
你可以使用 bin/inventory_cmdb 切换到动态的 CMDB 清单,
使用 bin/inventory_conf 返回到本地配置文件。
你还需要使用 bin/inventory_load 将当前的配置文件清单加载到 CMDB。
如果使用 CMDB,你必须从数据库而不是配置文件中编辑清单配置,这种方式适合将 Pigsty 与外部系统相集成。
配置文件中的IP地址占位符是干什么的? Pigsty 使用 10.10.10.10 作为当前节点 IP 的占位符,配置过程中会用当前节点的主 IP 地址替换它。
当 configure 检测到当前节点有多个 NIC 带有多个 IP 时,配置向导会提示使用哪个主要 IP,即 用户用于从内部网络访问节点的 IP ,此 IP 将用于在配置文件模板中替换占位符 10.10.10.10。
请注意,您应当使用静态 IP 地址,而不是 DHCP 分配的动态 IP 地址,因为 Pigsty 使用静态 IPv4 地址唯一标识节点。
请注意:不要使用公共 IP 作为主 IP,因为 Pigsty 会使用主 IP 来配置内部服务,例如 Nginx,Prometheus,Grafana,Loki,AlertManager,Chronyd,DNSMasq 等,除了 Nginx 之外的服务不应该对外界暴露端口。
我没有静态IP,可以安装Pigsty吗? 如果您的服务器没有静态IP,在 单机部署 的情况下,可以使用本地环回地址 127.0.0.1 作为这个唯一节点的 IP 地址标识。
配置文件中的哪些参数需要用户特殊关注? Pigsty 提供了 280+ 配置参数,可以对整个环境与各个模块 infra / node / etcd / minio / pgsql 进行细致入微的定制。
通常在单节点安装中,你不需要对默认生成的配置文件进行任何调整。但如果需要,可以关注以下这些参数:
当访问 web 服务组件时,域名由 infra_portal 指定,有些服务只能通过 Nginx 代理使用域名访问。 Pigsty 假定存在一个 /data 目录用于存放所有数据;如果数据磁盘的挂载点与此不同,你可以使用 node_data 调整这些路径。 进行生产部署时,不要忘记在配置文件中更改密码 ,更多细节请参考 安全考量 。 在默认单机安装时,到底都安装了什么东西? 当您执行 make install 时,实际上是调用 Ansible 剧本 install.yml ,根据配置文件中的参数,安装以下内容:
INFRA 模块:提供本地软件源,Nginx Web接入点,DNS服务器,NTP服务器,Prometheus与Grafana可观测性技术栈。NODE 模块,将当前节点纳入 Pigsty 管理,部署 HAProxy 与 监控。ETCD 模块,部署一个单机 etcd 集群,作为 PG 高可用的 DCSMINIO 模块如果定义,则会安装,它可以作为 PG 的可选备份仓库。PGSQL 模块,一个单机 PostgreSQL 数据库实例。安装遇到软件包冲突怎么办? 在安装 node / infra / pgsql 软件包期间,可能有微小的几率出现软件包依赖错漏冲突。这里有几种常见原因:
上游软件源发布了不匹配的软件包版本或缺失了依赖,您可能要等待上游修复此问题,时间以周计。事先在依赖完备时制作的离线安装包可以预防这个问题。 您制作离线安装包操作系统小版本与当前操作系统的小版本不匹配,您可以使用在线安装,或重新使用相同系统下制作的离线软件包的方式解决此问题 个别不重要,非必选的软件包,可以直接将其从安装列表,或本地软件源中剔除的方式快速绕过。 如何重建本地软件仓库? 我想要从上游仓库重新下载软件包,但是执行 ./infra.yml 和 repo 子任务都跳过下载了,怎么办?
您可以使用以下快捷命令和剧本任务,强制重建本地软件源。 Pigsty 会重新检查上游仓库并下载软件包。
make repo-build # ./infra.yml -t repo_build
如何在安装后下载最新版本的软件包? 如果您想要下载最新的软件包版本(RPM/DEB),你可以选择在 /www/pigsty 中手工使用 apt/dnf 下载特定版本的软件包。
在这种情况下,您可以使用以下命令,只更新本地软件仓库的元数据库,而不是整个重建:
./infra.yml -t repo_create
或者移除 /www/pigsty 中的旧版本软件包后重新执行仓库重建命令:
make repo-build # ./infra.yml -t repo_build
如何使用 Vagrant 创建本地虚拟机? 当你第一次使用 Vagrant 启动某个特定的操作系统仓库时,它会下载相应的 Box/Img 镜像文件,Pigsty 沙箱默认使用 generic/rocky9 镜像。
使用代理可能会增加下载速度。Box/Image 只需下载一次,在重建沙箱时会被重复使用。
阿里云上 CentOS 7.9 特有的 RPM 冲突问题 阿里云的 CentOS 7.9 额外安装的 nscd 可能会导致 RPM 冲突问题:"Error: Package: nscd-2.17-307.el7.1.x86_64 (@base)"
遇见安装失败,RPM冲突报错不要慌,这是一个DNS缓存工具,把这个包卸载了就可以了:sudo yum remove nscd,或者使用 ansible 命令批量删除所有节点上的 nscd:
ansible all -b -a 'yum remove -y nscd'
腾讯云上 Rocky 9.x 特有的 RPM 冲突问题 腾讯云的 Rocky 9.x 需要额外的 annobin 软件包才可以正常完成 Pigsty 安装。
遇见安装失败,RPM冲突报错不要慌,进入 /www/pigsty 把这几个包手动下载下来就好了。
./infra.yml -t repo_upstream # add upstream repos
cd /www/pigsty; # download missing packages
repotrack annobin gcc-plugin-annobin libuser
./infra.yml -t repo_create # create repo
Ansible命令超时(Timeout waiting for xxx) Ansible 命令的默认 ssh 超时时间是10秒。由于网络延迟或其他原因,某些命令可能需要超过这个时间。
你可以在 ansible 配置文件 ansible.cfg 中增加超时参数:
[defaults]
timeout = 10 # 将其修改为 60,120 或更高。
如果你的SSH连接非常慢,通常会是 DNS的问题,请检查sshd配置确保 UseDNS no。
3.10 - PG 快速上手 新手上路,需要了解的 PostgreSQL 101 基本知识
恭喜你完成了 Pigsty 的部署!现在让我们开始使用 PostgreSQL。
本指南面向有基础 Linux 操作经验、但对 PostgreSQL 不太熟悉的开发者。我们将带你完成从连接数据库到执行第一条查询的全过程。
基本知识 PostgreSQL (简称 PG)是世界上最先进、最流行的开源关系型数据库,你可以用它来存储和检索多模态数据。
我们假设您是个人用户,使用默认单机安装模式。关于多节点高可用集群的访问接入,请参考 生产服务接入 。
在默认的单节点配置模板下,您将在当前界定啊上创建一个名为 pg-meta 的 PostgreSQL 数据库集群,只有一个主库实例。
监听在 5432 端口,集群中带有一个预置的数据库 meta 可供使用。
您可以在退出当前管理用户 ssh 会话并重新登陆后,敲一个 p 回车即可通过命令行工具 psql 访问该数据库:
vagrant@pg-meta-1:~$ p
psql (18.1 (Ubuntu 18.1-1.pgdg24.04+2))
Type "help" for help.
postgres=#
连接数据库 想要访问 PostgreSQL 数据库,您需要使用 命令行工具 或者 图形化客户端 工具,填入 PostgreSQL 的 连接字符串 :
postgres://username:password@host:port/dbname
一些驱动和工具也可能会要求你分别填写这些参数,通常以下五项为必选项:
参数 说明 示例值 备注 host数据库服务器地址 10.10.10.10换为你的节点 IP 地址或域名,本机可以省略 port端口号 5432PG 默认端口,可以省略 username用户名 dbuser_dbaPigsty 默认的数据库管理员 password密码 DBUser.DBAPigsty 默认的管理员密码 dbname数据库名 meta默认模板的数据库名称
个人使用时可以直接使用 Pigsty 默认的数据库超级用户 dbuser_dba 进行连接和管理,数据库管理用户 dbuser_dba 拥有数据库的全部权限。
默认情况下,如果您在配置 Pigsty 时指定了 configure -g 参数,密码会随机生成,并保存在 ~/pigsty/pigsty.yml 文件中,可以通过以下命令查看:
cat ~/pigsty/pigsty.yml | grep pg_admin_password
默认账号密码 Pigsty 默认配置预置了以下用户,可直接使用:
用户名 密码 角色 用途 dbuser_dbaDBUser.DBA超级用户 数据库管理 dbuser_metaDBUser.Meta业务管理员 应用读写 dbuser_viewDBUser.Viewer只读用户 数据查看
例如,你可以通过三个不同的连接串,使用三个不同的用户连接到 pg-meta 集群的 meta 数据库:
postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta
postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta
postgres://dbuser_view:DBUser.View@10.10.10.10:5432/meta
请注意,这些默认密码会在 configure -g 时自动被替换为随机强密码,请注意将 IP 地址和密码替换为实际值。
使用命令行工具 psql 是 PostgreSQL 官方命令行客户端工具,功能强大,是 DBA 和开发者的首选工具。
在部署了 Pigsty 的服务器上,你可以直接使用 psql 连接本地数据库:
# 最简单的方式:使用 postgres 系统用户本地连接(无需密码)
sudo -u postgres psql
# 使用连接字符串(推荐,通用性最好)
psql 'postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta'
# 使用参数形式
psql -h 10.10.10.10 -p 5432 -U dbuser_dba -d meta
# 使用环境变量避免密码出现在命令行
export PGPASSWORD = 'DBUser.DBA'
psql -h 10.10.10.10 -p 5432 -U dbuser_dba -d meta
成功连接后,你会看到类似这样的提示符:
psql ( 18.1)
Type "help" for help.
meta = #
常用 psql 命令
进入 psql 后,可以执行 SQL 语句,也可以使用以 \ 开头的元命令:
命令 说明 命令 说明 Ctrl+C中断查询 Ctrl+D退出 psql \?显示所有元命令帮助 \h显示 SQL 命令帮助 \l列出所有数据库 \c dbname切换到指定数据库 \d table查看表结构 \d+ table查看表的详细信息 \du列出所有用户/角色 \dx列出已安装的扩展 \dn列出所有的模式 \dt列出所有表
执行 SQL
在 psql 中直接输入 SQL 语句,以分号 ; 结尾:
-- 查看 PostgreSQL 版本
SELECT version ();
-- 查看当前时间
SELECT now ();
-- 创建一张测试表
CREATE TABLE test ( id SERIAL PRIMARY KEY , name TEXT , created_at TIMESTAMPTZ DEFAULT now ());
-- 插入数据
INSERT INTO test ( name ) VALUES ( 'hello' ), ( 'world' );
-- 查询数据
SELECT * FROM test ;
-- 删除测试表
DROP TABLE test ;
使用图形客户端 如果你更喜欢图形界面,以下是几款流行的 PostgreSQL 客户端:
Grafana
Pigsty Infra 模块中自带了 Grafana,并预先配置好了 PostgreSQL 数据源(Meta)。
您可以直接在 Grafana Explore 面板中使用 SQL 查询数据库,无需额外安装客户端工具。
要想访问 Grafana,直接访问 Pigsty 安装节点的 80/443 端口即可。例如:
默认的用户名是 admin,密码可以在 pigsty.yml 中的 grafana_admin_password 字段找到(默认 pigsty)。
DataGrip
DataGrip 是 JetBrains 出品的专业数据库 IDE,功能强大。
Intellij IDEA 自带的 Database Console 也可以使用类似的方式连接 PostgreSQL。
DBeaver
DBeaver 是免费开源的通用数据库工具,支持几乎所有主流数据库。
pgAdmin
pgAdmin 是 PGDG 官方提供的 PostgreSQL 专用 GUI 工具,可以通过浏览器使用,也有桌面客户端版本。
Pigsty 在 软件模板:pgAdmin 中提供了使用 Docker 一键部署 pgAdmin 服务的配置模板。
查阅监控大盘 Pigsty 提供了许多 PostgreSQL 监控面板 ,覆盖从集群总览到单表分析的各个层面:
推荐先从 PGSQL Overview 开始浏览,面板中的许多元素都可以点击,您可以逐层深入,查阅每个集群、实例、数据库甚至是表,索引,函数等数据库内对象的详情信息。
尝试扩展插件 PostgreSQL 最强大的特性之一是其扩展生态系统 。扩展可以为数据库添加新的数据类型、函数、索引方法等能力。
Pigsty 提供了 440+ 扩展 ,涵盖时序、地理、向量、全文检索等 16 大类别,一键安装即可使用。
你可以先从三个最强大常用的功能扩展开始,这三个扩展是 Pigsty 默认模板自动安装的:
\ dx -- psql 元命令,列出已经安装的扩展
TABLE pg_available_extensions ; -- 查询已经安装,可以启用的扩展
CREATE EXTENSION postgis ; -- 启用 postgis 扩展
更多扩展使用详情,请参考 扩展插件 章节。
下一步 恭喜你完成了 PostgreSQL 的快速上手!以下是一些建议的进阶方向:
PostgreSQL 官方文档 始终是学习 PostgreSQL 最权威的参考资料。
PG 36 计 提供了基于 Pigsty 的 PostgreSQL 开发与运维实战指南(编写中)。
数据分析应用 提供了几个使用 PostgreSQL 实现数据分析并通过 Grafana 可视化的实战案例。
4 - 概念 了解 Pigsty 的重要概念:整体架构、逻辑模型,基础设施,以及数据库 HA,PITR,服务接入的原理。
4.1 - 概述 Pigsty 是什么,为什么需要它,它能做什么,以及它的核心设计理念。
Pigsty 是一个可移植、可扩展的开源 PostgreSQL 发行版,用于在本地环境中构建生产级数据库服务,方便进行声明式配置和自动化。它拥有庞大的生态系统,提供了一整套工具、脚本和最佳实践,让 PostgreSQL 真正达到企业级 RDS 的服务水准。
Pigsty 名字源自 P ostgreSQL I n G reat STY le,也可理解为 P ostgres, I nfras, G raphics, S ervice, T oolbox, it’s all Y ours —— 一切皆为您所拥有的 PostgreSQL 完整解决方案。您可以在 GitHub 上找到源代码,访问 官方文档 了解更多信息,或在 在线演示 中体验监控系统。
为什么需要 Pigsty,它能做什么? PostgreSQL 是一个足够完美的数据库内核,但它需要更多工具与系统的配合才能成为一个足够好的数据库服务。在生产环境中,您需要管理数据库的方方面面:高可用、备份恢复、监控告警、访问控制、参数调优、扩展安装、连接池化、负载均衡……
如果这些复杂的运维工作都能自动化处理,是不是会更容易一些?这正是 Pigsty 诞生的原因。
Pigsty 为您提供:
开箱即用的 PostgreSQL 发行版
Pigsty 深度整合了 PostgreSQL 生态中的 440+ 扩展插件 ,为您提供开箱即用的分布式、时序、地理、空间、图、向量、搜索等多模态数据库能力。从内核到 RDS 发行版,在 EL/Debian/Ubuntu 下提供 13-18 版本的生产级数据库服务。
故障自愈的高可用架构
基于 Patroni、Etcd 和 HAProxy 打造的 高可用架构 ,让硬件故障自动切换,流量无缝衔接。主库故障恢复时间 RTO < 30s,数据恢复点 RPO ≈ 0。您可以在无需应用配合的情况下滚动维护升级整个集群。
完整的时间点恢复能力
基于 pgBackRest 与可选的 MinIO 集群,提供开箱即用的 PITR 时间点恢复 能力。让您拥有快速回到过去任意时间点的能力,为软件缺陷与人为删库兜底。
灵活的服务接入与流量管理
通过 HAProxy、Pgbouncer、VIP 提供灵活的 服务接入 模式,实现读写分离、连接池化、自动路由。交付稳定可靠、自动路由、事务池化的高性能数据库服务。
惊艳的可观测性
基于 Prometheus 与 Grafana 的现代可观测性技术栈,提供无与伦比的 监控最佳实践 。超过三千类监控指标描述系统的方方面面,从全局大盘到单个对象的增删改查都能一览无余。
声明式的配置管理
遵循 基础设施即代码 的理念,使用声明式配置描述整个环境。您只需告诉 Pigsty “想要什么样的数据库集群”,无需操心具体如何实现,系统会自动调整到期望状态。
模块化的架构设计
采用模块化 架构 设计,可自由组合以适应不同场景。除了核心的 PostgreSQL 模块外,还提供 Redis、MinIO、Etcd、FerretDB 等可选模块,以及对多种 PG 兼容内核的支持。
扎实的安全最佳实践
采用业界领先的安全最佳实践:自签名 CA 签发证书加密通信,AES 加密备份,scram-sha-256 加密密码,开箱即用的 ACL 模型,遵循最小权限原则的 HBA 规则集,确保数据安全。
简单易用的部署方案
所有依赖被预先打包,可在无互联网访问的环境中一键安装。本地沙箱环境可运行在 1核2G 的微型虚拟机中,提供与生产环境完全一致的功能模拟。提供基于 Vagrant 的本地沙箱与基于 Terraform 的云端部署方案。
Pigsty 不是什么 Pigsty 并不是传统的、包罗万象的 PaaS(平台即服务)系统。
Pigsty 不提供基础硬件资源 。它运行在您提供的节点之上,无论是裸金属、虚拟机还是云主机,但它本身不创建或管理这些资源(尽管提供了 Terraform 模板来简化云资源的准备)。
Pigsty 不是容器编排系统 。它直接运行在操作系统之上,不需要 Kubernetes 或 Docker 作为基础设施。当然,它可以与这些系统共存,并提供 Docker 模块来运行无状态应用。
Pigsty 不是通用的数据库管理工具 。它专注于 PostgreSQL 及其生态,虽然也支持 Redis、Etcd、MinIO 等周边组件,但核心始终是围绕 PostgreSQL 构建的。
Pigsty 不会锁定您 。它基于开源组件构建,不修改 PostgreSQL 内核,不引入专有协议。您随时可以脱离 Pigsty 继续使用管理好的 PostgreSQL 集群。
Pigsty 不限制您应该或不应该如何构建数据库服务。例如:
Pigsty 为您提供了良好的参数默认值和配置模板,但您可以覆盖任何参数。 Pigsty 提供了声明式 API,但您依然可以使用底层工具(Ansible、Patroni、pgBackRest 等)进行手动管理。 Pigsty 可以管理完整的生命周期,也可以只使用其中的监控系统来观测现有的数据库实例或 RDS。 Pigsty 提供的抽象层次不同于硬件层面,它工作在数据库服务层面,聚焦于如何让 PostgreSQL 以最佳状态交付价值,而不是重新发明轮子。
PostgreSQL 部署方式的演进 要理解 Pigsty 的价值,让我们回顾一下 PostgreSQL 部署方式的演进历程。
手工部署时代 在传统的部署方式中,DBA 需要手工安装配置 PostgreSQL,手工设置复制,手工配置监控,手工处理故障。这种方式的问题显而易见:
效率低下 :每个实例都需要重复大量手工操作,容易出错。缺乏标准化 :不同 DBA 配置的数据库可能千差万别,难以维护。可靠性差 :故障处理依赖人工介入,恢复时间长,容易出现人为失误。观测性弱 :缺乏统一的监控体系,问题发现和定位困难。托管数据库时代 为了解决这些问题,云厂商提供了托管数据库服务(RDS)。云 RDS 确实解决了部分运维问题,但也带来了新的挑战:
成本高昂 :托管服务通常收取硬件成本数倍到十几倍的"服务费"。供应商锁定 :迁移困难,受制于特定云平台。功能受限 :无法使用某些高级特性,扩展插件受限,参数调整受限。数据主权 :数据存储在云端,自主可控性降低。本地 RDS 时代 Pigsty 代表了第三种方式:在本地环境中构建媲美甚至超越云 RDS 的数据库服务。
Pigsty 结合了前两种方式的优点:
自动化程度高 :一键部署,自动配置,故障自愈,像云 RDS 一样便捷。完全自主可控 :运行在您自己的基础设施上,数据完全掌握在自己手中。成本极低 :以接近纯硬件的成本运行企业级数据库服务。功能完整 :无限制地使用 PostgreSQL 的全部能力和生态扩展。开放架构 :基于开源组件,无供应商锁定,可随时迁移。这种方式特别适合:
私有云与混合云 :需要在本地环境中运行数据库的企业。成本敏感型用户 :希望降低数据库 TCO 的组织。高安全要求场景 :需要完全自主可控的关键数据。PostgreSQL 深度用户 :需要使用高级特性和丰富扩展的场景。开发与测试 :需要在本地快速搭建与生产环境一致的数据库。接下来 现在您已经了解了 Pigsty 的基本概念,可以:
查看 系统架构 了解 Pigsty 的模块化设计 了解 集群模型 理解 Pigsty 如何组织数据库集群 学习 高可用 机制掌握故障自愈的原理 探索 时间点恢复 了解如何应对数据误删 研究 服务接入 理解如何稳定交付数据库服务 体验 基础设施即代码 感受声明式配置的魅力 或直接开始 快速上手 在几分钟内部署您的第一个 Pigsty 环境 4.2 - 系统架构 Pigsty的模块化架构:用声明的方式来组合模块
Pigsty 使用 模块化架构 与 声明式接口 。
Pigsty 使用配置清单 描述整套部署环境,并通过 ansible 剧本 实现。 Pigsty 在可以在任意节点上运行,无论是物理裸机还是虚拟机,只要操作系统兼容 即可。 Pigsty 的行为由配置参数控制,具有幂等性的剧本 会将节点调整到配置所描述的状态。 Pigsty 采用模块化设计,可自由组合以适应不同场景。使用剧本将模块安装到配置指定的节点上。 模块 Pigsty 采用模块化设计,有六个主要的默认模块:PGSQL 、INFRA 、NODE 、ETCD 、REDIS 和 MINIO 。
PGSQL :由 Patroni、Pgbouncer、HAproxy、PgBackrest 等驱动的自治高可用 Postgres 集群。INFRA :本地软件仓库、Prometheus、Grafana、Loki、AlertManager、PushGateway、Blackbox Exporter…NODE :调整节点到所需状态、名称、时区、NTP、ssh、sudo、haproxy、docker、promtail、keepalivedETCD :分布式键值存储,用作高可用 Postgres 集群的 DCS:共识选主/配置管理/服务发现。REDIS :Redis 服务器,支持独立主从、哨兵、集群模式,并带有完整的监控支持。MINIO :与 S3 兼容的简单对象存储服务器,可作为 PG数据库备份的可选目的地。你可以声明式地自由组合它们。如果你想要主机监控,在基础设施节点上安装INFRA 模块,并在纳管节点上安装 NODE 模块就足够了。
ETCD 和 PGSQL 模块用于搭建高可用 PG 集群,将模块安装在多个节点上,可以自动形成一个高可用的数据库集群。
您可以复用 Pigsty 基础架构并开发您自己的模块,REDIS 和 MINIO 可以作为一个样例。后续还会有更多的模块加入,例如对 Mongo 与 MySQL 的初步支持已经提上了日程。
请注意,所有模块都强依赖 NODE 模块:在 Pigsty 中节点必须先安装 NODE 模块,被 Pigsty 纳管后方可部署其他模块。
当节点(默认)使用本地软件源进行安装时,NODE 模块对 INFRA 模块有弱依赖。因此安装 INFRA 模块的管理节点/基础设施节点会在 deploy.yml 剧本中完成 Bootstrap 过程,解决循环依赖。
单机安装 默认情况下,Pigsty 将在单个 节点 (物理机/虚拟机) 上安装。deploy.yml 剧本将在当前 节点上安装 INFRA 、ETCD 、PGSQL 和可选的 MINIO 模块,
这将为你提供一个功能完备的可观测性技术栈全家桶 (Prometheus、Grafana、Loki、AlertManager、PushGateway、BlackboxExporter 等) ,以及一个内置的 PostgreSQL 单机实例作为 CMDB,也可以开箱即用。 (集群名 pg-meta,库名为 meta)。
这个节点现在会有完整的自我监控系统、可视化工具集,以及一个自动配置有 PITR 的 Postgres 数据库(HA不可用,因为你只有一个节点)。你可以使用此节点作为开发箱、测试、运行演示以及进行数据可视化和分析。或者,还可以把这个节点当作管理节点,部署纳管更多的节点!
监控 安装的 单机元节点 可用作管理节点 和监控中心 ,以将更多节点和数据库服务器置于其监视和控制之下。
Pigsty 的监控系统可以独立使用,如果你想安装 Prometheus / Grafana 可观测性全家桶,Pigsty 为你提供了最佳实践!
它为 主机节点 和 PostgreSQL数据库 提供了丰富的仪表盘。
无论这些节点或 PostgreSQL 服务器是否由 Pigsty 管理,只需简单的配置,你就可以立即拥有生产级的监控和告警系统,并将现有的主机与PostgreSQL纳入监管。
高可用PG集群 Pigsty 帮助您在任何地方 拥有 您自己的生产级高可用 PostgreSQL RDS 服务。
要创建这样一个高可用 PostgreSQL 集群/RDS服务,你只需用简短的配置来描述它,并运行剧本来创建即可:
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : replica }
vars : { pg_cluster : pg-test }
$ bin/pgsql-add pg-test # 初始化集群 'pg-test'
不到10分钟,您将拥有一个服务接入,监控,备份PITR,高可用配置齐全的 PostgreSQL 数据库集群。
硬件故障由 patroni、etcd 和 haproxy 提供的自愈高可用架构来兜底,在主库故障的情况下,默认会在 30 秒内执行自动故障转移(Failover)。
客户端无需修改配置重启应用:Haproxy 利用 patroni 健康检查进行流量分发,读写请求会自动分发到新的集群主库中,并避免脑裂的问题。
这一过程十分丝滑,例如在从库故障,或主动切换(switchover)的情况下,客户端只有一瞬间的当前查询闪断,
软件故障、人为错误和 数据中心级灾难由 pgbackrest 和可选的 MinIO 集群来兜底。这为您提供了本地/云端的 PITR 能力,并在数据中心失效的情况下提供了跨地理区域复制,与异地容灾功能。
4.3 - 集群模型 Pigsty 是如何将不同种类的功能抽象成为模块的,以及这些模块的逻辑模型。
在 Pigsty 中,功能模块是以 “集群” 的方式组织起来的。每一个集群都是一个 Ansible 分组,包含有若干节点资源,定义有实例
PGSQL 模块总览:关键概念与架构细节
PGSQL模块在生产环境中以集群 的形式组织,这些集群 是由一组由主-备 关联的数据库实例 组成的逻辑实体 。
每个数据库集群 都是一个自治 的业务服务单元,由至少一个 数据库(主库)实例 组成。
实体概念图 让我们从ER图开始。在Pigsty的PGSQL模块中,有四种核心实体:
集群 (Cluster):自治的PostgreSQL业务单元,用作其他实体的顶级命名空间。服务 (Service):集群能力的命名抽象,路由流量,并使用节点端口暴露postgres服务。实例 (Instance):一个在单个节点上的运行进程和数据库文件组成的单一postgres服务器。节点 (Node):硬件资源的抽象,可以是裸金属、虚拟机或甚至是k8s pods。
命名约定
集群名应为有效的 DNS 域名,不包含任何点号,正则表达式为:[a-zA-Z0-9-]+ 服务名应以集群名为前缀,并以特定单词作为后缀:primary、replica、offline、delayed,中间用-连接。 实例名以集群名为前缀,以正整数实例号为后缀,用-连接,例如${cluster}-${seq}。 节点由其首要内网IP地址标识,因为PGSQL模块中数据库与主机1:1部署,所以主机名通常与实例名相同。 身份参数 Pigsty使用身份参数 来识别实体:PG_ID 。
除了节点IP地址,pg_cluster 、pg_role 和pg_seq 三个参数是定义postgres集群所必需的最小参数集。
以沙箱环境 测试集群pg-test为例:
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : replica }
vars :
pg_cluster : pg-test
集群的三个成员如下所示:
集群 序号 角色 主机 / IP 实例 服务 节点名 pg-test1primary10.10.10.11pg-test-1pg-test-primarypg-test-1pg-test2replica10.10.10.12pg-test-2pg-test-replicapg-test-2pg-test3replica10.10.10.13pg-test-3pg-test-replicapg-test-3
这里包含了:
一个集群:该集群命名为pg-test。 两种角色:primary和replica。 三个实例:集群由三个实例组成:pg-test-1、pg-test-2、pg-test-3。 三个节点:集群部署在三个节点上:10.10.10.11、10.10.10.12和10.10.10.13。 四个服务: 在监控系统(Prometheus/Grafana/Loki)中,相应的指标将会使用这些身份参数进行标记:
pg_up{cls="pg-meta", ins="pg-meta-1", ip="10.10.10.10", job="pgsql"}
pg_up{cls="pg-test", ins="pg-test-1", ip="10.10.10.11", job="pgsql"}
pg_up{cls="pg-test", ins="pg-test-2", ip="10.10.10.12", job="pgsql"}
pg_up{cls="pg-test", ins="pg-test-3", ip="10.10.10.13", job="pgsql"}
4.4 - 监控系统 Pigsty 的监控系统是如何架构与实现的,被监控的目标对象又是如何被自动纳入管理的。
4.5 - 本地 CA Pigsty 带有一套自签名的 CA 公私钥基础设施,用于签发 SSL 证书,加密网络通信流量。
Pigsty 部署默认启用了一些安全最佳实践:使用 SSL 加密网络流量,使用 HTTPS 加密 Web 界面。
为了实现这一功能,Pigsty 内置了本地自签名的 CA ,用于签发 SSL 证书,加密网络通信流量。
在默认情况下,SSL 与 HTTPS 是启用,但不强制使用的。对于有着较高安全要求的环境,您可以强制使用 SSL 与 HTTPS。
本地CA Pigsty 默认会在初始化时,在 ADMIN节点 本机 Pigsty 源码目录(~/pigsty)中生成一个自签名的 CA,当您需要使用 SSL,HTTPS,数字签名,签发数据库客户端证书,高级安全特性时,可以使用此 CA。
因此,每一套 Pigsty 部署使用的 CA 都是唯一的,不同的 Pigsty 部署之间的 CA 是不相互信任的。
本地 CA 由两个文件组成,默认放置于 files/pki/ca 目录中:
ca.crt:自签名的 CA 根证书,应当分发安装至到所有纳管节点,用于证书验证。ca.key:CA 私钥,用于签发证书,验证 CA 身份,应当妥善保管,避免泄漏!请保护好CA私钥文件
请妥善保管 CA 私钥文件,不要遗失,不要泄漏。我们建议您在完成 Pigsty 安装后,加密备份此文件。
使用现有CA 如果您本身已经有 CA 公私钥基础设施,Pigsty 也可以配置为使用现有 CA 。
将您的 CA 公钥与私钥文件放置于 files/pki/ca 目录中即可。
files/pki/ca/ca.key # 核心的 CA 私钥文件,必须存在,如果不存在,默认会重新随机生成一个
files/pki/ca/ca.crt # 如果没有证书文件,Pigsty会自动重新从 CA 私钥生成新的根证书文件
当 Pigsty 执行 install.yml 与 infra.yml 剧本进行安装时,如果发现 files/pki/ca 目录中的 ca.key 私钥文件存在,则会使用已有的 CA 。ca.crt 文件可以从 ca.key 私钥文件生成,所以如果没有证书文件,Pigsty 会自动重新从 CA 私钥生成新的根证书文件。
使用现有CA时请注意
您可以将 ca_method 参数配置为 copy,确保 Pigsty 找不到本地 CA 时报错中止,而不是自行重新生成新的自签名 CA。
信任CA 在 Pigsty 安装过程中,ca.crt 会在 node.yml 剧本的 node_ca 任务中,被分发至所有节点上的 /etc/pki/ca.crt 路径下。
EL系操作系统与 Debian系操作系统默认信任的 CA 根证书路径不同,因此分发的路径与更新的方式也不同。
信任CA证书
EL
Debian / Ubuntu rm -rf /etc/pki/ca-trust/source/anchors/ca.crt
ln -s /etc/pki/ca.crt /etc/pki/ca-trust/source/anchors/ca.crt
/bin/update-ca-trust rm -rf /usr/local/share/ca-certificates/ca.crt
ln -s /etc/pki/ca.crt /usr/local/share/ca-certificates/ca.crt
/usr/sbin/update-ca-certificates Pigsty 默认会为基础设施节点上的 Web 系统使用的域名签发 HTTPS 证书,您可以 HTTPS 访问 Pigsty 的 Web 系统。
如果您希望在客户端电脑上浏览器访问时不要弹出“不受信任的 CA 证书”信息,可以将 ca.crt 分发至客户端电脑的信任证书目录中。
您可以双击 ca.crt 文件将其加入系统钥匙串,例如在 MacOS 系统中,需要打开“钥匙串访问” 搜索 pigsty-ca 然后“信任”此根证书
查看证书内容 使用以下命令,可以查阅 Pigsty CA 证书的内容
openssl x509 -text -in /etc/pki/ca.crt
本地 CA 根证书内容样例 Certificate:
Data:
Version: 3 (0x2)
Serial Number:
50:29:e3:60:96:93:f4:85:14:fe:44:81:73:b5:e1:09:2a:a8:5c:0a
Signature Algorithm: sha256WithRSAEncryption
Issuer: O=pigsty, OU=ca, CN=pigsty-ca
Validity
Not Before: Feb 7 00:56:27 2023 GMT
Not After : Jan 14 00:56:27 2123 GMT
Subject: O=pigsty, OU=ca, CN=pigsty-ca
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (4096 bit)
Modulus:
00:c1:41:74:4f:28:c3:3c:2b:13:a2:37:05:87:31:
....
e6:bd:69:a5:5b:e3:b4:c0:65:09:6e:84:14:e9:eb:
90:f7:61
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Alternative Name:
DNS:pigsty-ca
X509v3 Key Usage:
Digital Signature, Certificate Sign, CRL Sign
X509v3 Basic Constraints: critical
CA:TRUE, pathlen:1
X509v3 Subject Key Identifier:
C5:F6:23:CE:BA:F3:96:F6:4B:48:A5:B1:CD:D4:FA:2B:BD:6F:A6:9C
Signature Algorithm: sha256WithRSAEncryption
Signature Value:
89:9d:21:35:59:6b:2c:9b:c7:6d:26:5b:a9:49:80:93:81:18:
....
9e:dd:87:88:0d:c4:29:9e
-----BEGIN CERTIFICATE-----
...
cXyWAYcvfPae3YeIDcQpng==
-----END CERTIFICATE-----
签发证书 如果您希望通过客户端证书认证,那么可以使用本地 CA 与 cert.yml 剧本手工签发PostgreSQL 客户端证书。
将证书的 CN 字段设置为数据库用户名即可:
./cert.yml -e cn = dbuser_dba
./cert.yml -e cn = dbuser_monitor
签发的证书会默认生成在 files/pki/misc/<cn>.{key,crt} 路径下。
4.6 - Infra as Code Pigsty 使用基础设施即代码(IaC)的理念管理所有组件,针对大规模集群提供声明式管理能力。
Pigsty 遵循 IaC 与 GitOPS 的理念:使用声明式的 配置清单 描述整个环境,并通过 幂等剧本 来实现。
用户用声明的方式通过 参数 来描述自己期望的状态,而剧本则以幂等的方式调整目标节点以达到这个状态。
这类似于 Kubernetes 的 CRD & Operator,然而 Pigsty 在裸机和虚拟机上,通过 Ansible 实现了这样的功能。
Pigsty 诞生之初是为了解决超大规模 PostgreSQL 集群的运维管理问题,背后的想法很简单 —— 我们需要有在十分钟内在就绪的服务器上复刻整套基础设施(100+数据库集群 + PG/Redis + 可观测性)的能力。
任何 GUI + ClickOps 都无法在如此短的时间内完成如此复杂的任务,这让 CLI + IaC 成为唯一的选择 —— 它提供了精确,高效的控制能力。
配置清单 pigsty.yml 文件描述了整个部署的状态,无论是 生产环境(prod),预发环境(staging), 测试环境(test),还是 开发环境(devbox),
基础设施的区别仅在于配置清单的不同,而部署交付的逻辑则是完全相同的。
您可以使用 git 对这份部署的 “种子/基因” 进行版本控制与审计,而且,Pigsty 甚至支持将配置清单以数据库表的形式存储在 PostgreSQL CMDB 中,更进一步实现 Infra as Data 的能力。
无缝与您现有的工作流程集成与对接。
IaC 面向专业用户与企业场景而设计,但也针对个人开发者,SMB 进行了深度优化。
即使您并非专业 DBA,也无需了解这几百个调节开关与旋钮,所有参数都带有表现良好的默认值,
您完全可以在 零配置 的情况下,获得一个开箱即用的单机数据库节点;
简单地再添加两行 IP 地址,就能获得一套企业级的高可用的 PostgreSQL 集群。
声明模块 以下面的默认配置片段为例,这段配置描述了一个节点 10.10.10.10,其上安装了 INFRA 、NODE 、ETCD 和 PGSQL 模块。
# 监控、告警、DNS、NTP 等基础设施集群...
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
# minio 集群,兼容 s3 的对象存储
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
# etcd 集群,用作 PostgreSQL 高可用所需的 DCS
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
# PGSQL 示例集群: pg-meta
pg-meta : { hosts : { 10.10.10.10 : { pg_seq: 1, pg_role: primary }, vars : { pg_cluster : pg-meta } }
要真正安装这些模块,执行以下剧本:
./infra.yml -l 10.10.10.10 # 在节点 10.10.10.10 上初始化 infra 模块
./etcd.yml -l 10.10.10.10 # 在节点 10.10.10.10 上初始化 etcd 模块
./minio.yml -l 10.10.10.10 # 在节点 10.10.10.10 上初始化 minio 模块
./pgsql.yml -l 10.10.10.10 # 在节点 10.10.10.10 上初始化 pgsql 模块
声明集群 您可以声明 PostgreSQL 数据库集群,在多个节点上安装 PGSQL 模块,并使其成为一个服务单元:
例如,要在以下三个已被 Pigsty 纳管的节点上,部署一个使用流复制组建的三节点高可用 PostgreSQL 集群,
您可以在配置文件 pigsty.yml 的 all.children 中添加以下定义:
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : offline }
vars : { pg_cluster : pg-test }
定义完后,可以使用 剧本 将集群创建:
bin/pgsql-add pg-test # 创建 pg-test 集群
你可以使用不同的的实例角色,例如 主库 (primary),从库 (replica),离线从库 (offline),延迟从库 (delayed),同步备库 (sync standby);
以及不同的集群:例如 备份集群 (Standby Cluster),Citus集群 ,甚至是 Redis / MinIO / Etcd 集群
定制集群内容 您不仅可以使用声明式的方式定义集群,还可以定义集群中的数据库、用户、服务、HBA 规则等内容,例如,下面的配置文件对默认的 pg-meta 单节点数据库集群的内容进行了深度定制:
包括:声明了六个业务数据库与七个业务用户,添加了一个额外的 standby 服务(同步备库,提供无复制延迟的读取能力),定义了一些额外的 pg_hba 规则,一个指向集群主库的 L2 VIP 地址,与自定义的备份策略。
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role: primary , pg_offline_query : true } }
vars :
pg_cluster : pg-meta
pg_databases : # define business databases on this cluster, array of database definition
- name : meta # REQUIRED, `name` is the only mandatory field of a database definition
baseline : cmdb.sql # optional, database sql baseline path, (relative path among ansible search path, e.g files/)
pgbouncer : true # optional, add this database to pgbouncer database list? true by default
schemas : [ pigsty] # optional, additional schemas to be created, array of schema names
extensions: # optional, additional extensions to be installed : array of `{name[,schema]}`
- { name: postgis , schema : public }
- { name : timescaledb }
comment : pigsty meta database # optional, comment string for this database
owner : postgres # optional, database owner, postgres by default
template : template1 # optional, which template to use, template1 by default
encoding : UTF8 # optional, database encoding, UTF8 by default. (MUST same as template database)
locale : C # optional, database locale, C by default. (MUST same as template database)
lc_collate : C # optional, database collate, C by default. (MUST same as template database)
lc_ctype : C # optional, database ctype, C by default. (MUST same as template database)
tablespace : pg_default # optional, default tablespace, 'pg_default' by default.
allowconn : true # optional, allow connection, true by default. false will disable connect at all
revokeconn : false # optional, revoke public connection privilege. false by default. (leave connect with grant option to owner)
register_datasource : true # optional, register this database to grafana datasources? true by default
connlimit : -1 # optional, database connection limit, default -1 disable limit
pool_auth_user : dbuser_meta # optional, all connection to this pgbouncer database will be authenticated by this user
pool_mode : transaction # optional, pgbouncer pool mode at database level, default transaction
pool_size : 64 # optional, pgbouncer pool size at database level, default 64
pool_size_reserve : 32 # optional, pgbouncer pool size reserve at database level, default 32
pool_size_min : 0 # optional, pgbouncer pool size min at database level, default 0
pool_max_db_conn : 100 # optional, max database connections at database level, default 100
- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment : grafana primary database }
- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment : bytebase primary database }
- { name: kong ,owner: dbuser_kong ,revokeconn: true ,comment : kong the api gateway database }
- { name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment : gitea meta database }
- { name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment : wiki meta database }
pg_users : # define business users/roles on this cluster, array of user definition
- name : dbuser_meta # REQUIRED, `name` is the only mandatory field of a user definition
password : DBUser.Meta # optional, password, can be a scram-sha-256 hash string or plain text
login : true # optional, can log in, true by default (new biz ROLE should be false)
superuser : false # optional, is superuser? false by default
createdb : false # optional, can create database? false by default
createrole : false # optional, can create role? false by default
inherit : true # optional, can this role use inherited privileges? true by default
replication : false # optional, can this role do replication? false by default
bypassrls : false # optional, can this role bypass row level security? false by default
pgbouncer : true # optional, add this user to pgbouncer user-list? false by default (production user should be true explicitly)
connlimit : -1 # optional, user connection limit, default -1 disable limit
expire_in : 3650 # optional, now + n days when this role is expired (OVERWRITE expire_at)
expire_at : '2030-12-31' # optional, YYYY-MM-DD 'timestamp' when this role is expired (OVERWRITTEN by expire_in)
comment : pigsty admin user # optional, comment string for this user/role
roles: [dbrole_admin] # optional, belonged roles. default roles are : dbrole_{admin,readonly,readwrite,offline}
parameters : {} # optional, role level parameters with `ALTER ROLE SET`
pool_mode : transaction # optional, pgbouncer pool mode at user level, transaction by default
pool_connlimit : -1 # optional, max database connections at user level, default -1 disable limit
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly], comment : read-only viewer for meta database}
- {name: dbuser_grafana ,password: DBUser.Grafana ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for grafana database }
- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for bytebase database }
- {name: dbuser_kong ,password: DBUser.Kong ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for kong api gateway }
- {name: dbuser_gitea ,password: DBUser.Gitea ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for gitea service }
- {name: dbuser_wiki ,password: DBUser.Wiki ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for wiki.js service }
pg_services : # extra services in addition to pg_default_services, array of service definition
# standby service will route {ip|name}:5435 to sync replica's pgbouncer (5435->6432 standby)
- name: standby # required, service name, the actual svc name will be prefixed with `pg_cluster`, e.g : pg-meta-standby
port : 5435 # required, service exposed port (work as kubernetes service node port mode)
ip : "*" # optional, service bind ip address, `*` for all ip by default
selector : "[]" # required, service member selector, use JMESPath to filter inventory
dest : default # optional, destination port, default|postgres|pgbouncer|<port_number>, 'default' by default
check : /sync # optional, health check url path, / by default
backup : "[? pg_role == `primary`]" # backup server selector
maxconn : 3000 # optional, max allowed front-end connection
balance: roundrobin # optional, haproxy load balance algorithm (roundrobin by default, other : leastconn)
options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
node_crontab : # make a full backup 1 am everyday
- '00 01 * * * postgres /pg/bin/pg-backup full'
声明访问控制 您还可以通过声明式的配置,深度定制 Pigsty 的访问控制能力。例如下面的配置文件对 pg-meta 集群进行了深度安全定制:
使用三节点核心集群模板:crit.yml,确保数据一致性有限,故障切换数据零丢失。
启用了 L2 VIP,并将数据库与连接池的监听地址限制在了 本地环回IP + 内网IP + VIP 三个特定地址。
模板强制启用了 Patroni 的 SSL API,与 Pgbouncer 的 SSL,并在 HBA 规则中强制要求使用 SSL 访问数据库集群。
同时还在 pg_libs 中启用了 $libdir/passwordcheck 扩展,来强制执行密码强度安全策略。
最后,还单独声明了一个 pg-meta-delay 集群,作为 pg-meta 在一个小时前的延迟镜像从库,用于紧急数据误删恢复。
pg-meta : # 3 instance postgres cluster `pg-meta`
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
10.10.10.11 : { pg_seq: 2, pg_role : replica }
10.10.10.12 : { pg_seq: 3, pg_role: replica , pg_offline_query : true }
vars :
pg_cluster : pg-meta
pg_conf : crit.yml
pg_users :
- { name: dbuser_meta , password: DBUser.Meta , pgbouncer: true , roles: [ dbrole_admin ] , comment : pigsty admin user }
- { name: dbuser_view , password: DBUser.Viewer , pgbouncer: true , roles: [ dbrole_readonly ] , comment : read-only viewer for meta database }
pg_databases :
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name: postgis, schema : public}, {name: timescaledb}]}
pg_default_service_dest : postgres
pg_services :
- { name: standby ,src_ip : "*" ,port: 5435 , dest: default ,selector : "[]" , backup : "[? pg_role == `primary`]" }
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
pg_listen : '${ip},${vip},${lo}'
patroni_ssl_enabled : true
pgbouncer_sslmode : require
pgbackrest_method : minio
pg_libs : 'timescaledb, $libdir/passwordcheck, pg_stat_statements, auto_explain' # add passwordcheck extension to enforce strong password
pg_default_roles : # default roles and users in postgres cluster
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,expire_in: 7300 ,comment : system superuser }
- { name: replicator ,replication: true ,expire_in: 7300 ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,expire_in: 7300 ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 , comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,expire_in: 7300 ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
pg_default_hba_rules : # postgres host-based auth rules by default
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: ssl ,title : 'replicator replication from localhost' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: ssl ,title : 'replicator replication from intranet' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: ssl ,title : 'replicator postgres db from intranet' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: ssl ,title : 'monitor from infra host with password' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- {user : '${admin}' ,db: all ,addr: world ,auth: cert ,title : 'admin @ everywhere with ssl & cert' }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: ssl ,title : 'pgbouncer read/write via local socket' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: ssl ,title : 'read/write biz user via password' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: ssl ,title : 'allow etl offline tasks from intranet' }
pgb_default_hba_rules : # pgbouncer host-based authentication rules
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title : 'dbsu local admin access with os ident' }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title : 'allow all user local access with pwd' }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: ssl ,title : 'monitor access via intranet with pwd' }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other monitor access addr' }
- {user : '${admin}' ,db: all ,addr: intra ,auth: ssl ,title : 'admin access via intranet with pwd' }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other admin access addr' }
- {user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'allow all user intra access with pwd' }
# OPTIONAL delayed cluster for pg-meta
pg-meta-delay : # delayed instance for pg-meta (1 hour ago)
hosts : { 10.10.10.13 : { pg_seq: 1, pg_role: primary, pg_upstream: 10.10.10.10, pg_delay : 1h } }
vars : { pg_cluster : pg-meta-delay }
Citus分布式集群 下面是一个四节点的 Citus 分布式集群的声明式配置:
all :
children :
pg-citus0 : # citus coordinator, pg_group = 0
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus0 , pg_group : 0 }
pg-citus1 : # citus data node 1
hosts : { 10.10.10.11 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus1 , pg_group : 1 }
pg-citus2 : # citus data node 2
hosts : { 10.10.10.12 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus2 , pg_group : 2 }
pg-citus3 : # citus data node 3, with an extra replica
hosts :
10.10.10.13 : { pg_seq: 1, pg_role : primary }
10.10.10.14 : { pg_seq: 2, pg_role : replica }
vars : { pg_cluster: pg-citus3 , pg_group : 3 }
vars : # global parameters for all citus clusters
pg_mode: citus # pgsql cluster mode : citus
pg_shard: pg-citus # citus shard name : pg-citus
patroni_citus_db : meta # citus distributed database name
pg_dbsu_password : DBUser.Postgres # all dbsu password access for citus cluster
pg_users : [ { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles : [ dbrole_admin ] } ]
pg_databases : [ { name: meta ,extensions : [ { name : citus }, { name: postgis }, { name: timescaledb } ] } ]
pg_hba_rules :
- { user: 'all' ,db: all ,addr: 127.0.0.1/32 ,auth: ssl ,title : 'all user ssl access from localhost' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'all user ssl access from intranet' }
Redis集群 下面给出了 Redis 主从集群、哨兵集群、以及 Redis Cluster 的声明配置样例
redis-ms : # redis classic primary & replica
hosts : { 10.10.10.10 : { redis_node: 1 , redis_instances : { 6379 : { }, 6380 : { replica_of : '10.10.10.10 6379' } } } }
vars : { redis_cluster: redis-ms ,redis_password: 'redis.ms' ,redis_max_memory : 64MB }
redis-meta : # redis sentinel x 3
hosts : { 10.10.10.11 : { redis_node: 1 , redis_instances : { 26379 : { } ,26380 : { } ,26381 : { } } } }
vars :
redis_cluster : redis-meta
redis_password : 'redis.meta'
redis_mode : sentinel
redis_max_memory : 16MB
redis_sentinel_monitor : # primary list for redis sentinel, use cls as name, primary ip:port
- { name: redis-ms, host: 10.10.10.10, port: 6379 ,password: redis.ms, quorum : 2 }
redis-test: # redis native cluster : 3m x 3s
hosts :
10.10.10.12 : { redis_node: 1 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
10.10.10.13 : { redis_node: 2 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
vars : { redis_cluster: redis-test ,redis_password: 'redis.test' ,redis_mode: cluster, redis_max_memory : 32MB }
ETCD集群 下面给出了一个三节点的 Etcd 集群声明式配置样例:
etcd : # dcs service for postgres/patroni ha consensus
hosts : # 1 node for testing, 3 or 5 for production
10.10.10.10 : { etcd_seq : 1 } # etcd_seq required
10.10.10.11 : { etcd_seq : 2 } # assign from 1 ~ n
10.10.10.12 : { etcd_seq : 3 } # odd number please
vars : # cluster level parameter override roles/etcd
etcd_cluster : etcd # mark etcd cluster name etcd
etcd_safeguard : false # safeguard against purging
etcd_clean : true # purge etcd during init process
MinIO集群 下面给出了一个三节点的 MinIO 集群声明式配置样例:
minio :
hosts :
10.10.10.10 : { minio_seq : 1 }
10.10.10.11 : { minio_seq : 2 }
10.10.10.12 : { minio_seq : 3 }
vars :
minio_cluster : minio
minio_data : '/data{1...2}' # 每个节点使用两块磁盘
minio_node : '${minio_cluster}-${minio_seq}.pigsty' # 节点名称的模式
haproxy_services :
- name : minio # [必选] 服务名称,需要唯一
port : 9002 # [必选] 服务端口,需要唯一
options :
- option httpchk
- option http-keep-alive
- http-check send meth OPTIONS uri /minio/health/live
- http-check expect status 200
servers :
- { name: minio-1 ,ip: 10.10.10.10 , port: 9000 , options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-2 ,ip: 10.10.10.11 , port: 9000 , options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-3 ,ip: 10.10.10.12 , port: 9000 , options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
4.7 - 数据库高可用 Pigsty 使用 Patroni 实现了 PostgreSQL 的高可用,确保主库不可用时自动进行故障转移,由从库接管。
概览 Pigsty 的 PostgreSQL 集群带有开箱即用的高可用方案,由 Patroni 、Etcd 和 HAProxy 强力驱动。
当您的 PostgreSQL 集群含有两个或更多实例时,您无需任何配置即拥有了硬件故障自愈的数据库高可用能力 —— 只要集群中有任意实例存活,集群就可以对外提供完整的服务,而客户端只要连接至集群中的任意节点,即可获得完整的服务,而无需关心主从拓扑变化。
在默认配置下,主库故障恢复时间目标 RTO ≈ 30s,数据恢复点目标 RPO < 1MB;从库故障 RPO = 0,RTO ≈ 0 (闪断);在一致性优先模式下,可确保故障切换数据零损失:RPO = 0。以上指标均可通过参数,根据您的实际硬件条件与可靠性要求 按需配置 。
Pigsty 内置了 HAProxy 负载均衡器用于自动流量切换,提供 DNS/VIP/LVS 等多种接入方式供客户端选用。故障切换与主动切换对业务侧除零星闪断外几乎无感知,应用不需要修改连接串重启。
极小的维护窗口需求带来了极大的灵活便利:您完全可以在无需应用配合的情况下滚动维护升级整个集群。硬件故障可以等到第二天再抽空善后处置的特性,让研发,运维与 DBA 都能在故障时安心睡个好觉。
许多大型组织与核心机构已经在生产环境中长时间使用 Pigsty ,最大的部署有 25K CPU 核心与 220+ PostgreSQL 超大规格实例(64c / 512g / 3TB NVMe SSD);在这一部署案例中,五年内经历了数十次硬件故障与各类事故,但依然可以保持高于 99.999% 的总体可用性战绩。
高可用(High-Availability)解决什么问题?
将数据安全C/IA中的可用性提高到一个新高度:RPO ≈ 0, RTO < 30s。 获得无缝滚动维护的能力,最小化维护窗口需求,带来极大便利。 硬件故障可以立即自愈,无需人工介入,运维DBA可以睡个好觉。 从库可以用于承载只读请求,分担主库负载,让资源得以充分利用。 高可用有什么代价?
基础设施依赖:高可用需要依赖 DCS (etcd/zk/consul) 提供共识。 起步门槛增加:一个有意义的高可用部署环境至少需要 三个节点 。 额外的资源消耗:一个新从库就要消耗一份额外资源,不算大问题。 复杂度代价显著升高:备份成本显著加大,需要使用工具压制复杂度。 高可用的局限性
因为复制实时进⾏,所有变更被⽴即应⽤⾄从库。因此基于流复制的高可用方案⽆法应对⼈为错误与软件缺陷导致的数据误删误改。(例如:DROP TABLE,或 DELETE 数据)
此类故障需要使用 延迟集群 ,或使用先前的基础备份与 WAL 归档进行 时间点恢复 。
配置策略 RTO RPO 单机 + 什么也不做 数据永久丢失,无法恢复 数据全部丢失 单机 + 基础备份 取决于备份大小与带宽(几小时) 丢失上一次备份后的数据(几个小时到几天)单机 + 基础备份 + WAL归档 取决于备份大小与带宽(几小时) 丢失最后尚未归档的数据(几十MB)主从 + 手工故障切换 十分钟 丢失复制延迟中的数据(约百KB)主从 + 自动故障切换 一分钟内 丢失复制延迟中的数据(约百KB)主从 + 自动故障切换 + 同步提交 一分钟内 无数据丢失
原理 在 Pigsty 中,高可用架构的实现原理如下:
PostgreSQL 使⽤标准流复制搭建物理从库,主库故障时由从库接管。 Patroni 负责管理 PostgreSQL 服务器进程,处理高可用相关事宜。 Etcd 提供分布式配置存储(DCS)能力,并用于故障后的领导者选举 Patroni 依赖 Etcd 达成集群领导者共识,并对外提供健康检查接口。 HAProxy 对外暴露集群服务,并利⽤ Patroni 健康检查接口,自动分发流量至健康节点。 vip-manager 提供一个可选的二层 VIP,从 Etcd 中获取领导者信息,并将 VIP 绑定在集群主库所在节点上。 当主库故障时,将触发新一轮领导者竞选,集群中最为健康的从库将胜出(LSN位点最高,数据损失最小者),并被提升为新的主库。 胜选从库提升后,读写流量将立即路由至新的主库。
主库故障影响是 写服务短暂不可用 :从主库故障到新主库提升期间,写入请求将被阻塞或直接失败,不可用时长通常在 15秒 ~ 30秒,通常不会超过 1 分钟。
当从库故障时,只读流量将路由至其他从库,如果所有从库都故障,只读流量才会最终由主库承载。
从库故障的影响是 部分只读查询闪断 :当前从库上正在运行查询将由于连接重置而中止,并立即由其他可用从库接管。
故障检测由 Patroni 和 Etcd 共同完成,集群领导者将持有一个租约,
如果集群领导者因为故障而没有及时续租(10s),租约将会被释放,并触发 故障切换 (Failover) 与新一轮集群选举。
即使没有出现任何故障,您依然可以主动通过 主动切换 (Switchover)变更集群的主库。
在这种情况下,主库上的写入查询将会闪断,并立即路由至新主库执行。这一操作通常可用于滚动维护/升级数据库服务器。
利弊权衡 故障恢复时间目标 (RTO )与 数据恢复点目标 (RPO )是高可用集群设计时需要仔细进行利弊权衡的两个参数。
Pigsty 使用的 RTO 与 RPO 默认值满足绝大多数场景下的可靠性要求,您可以根据您的硬件水平,网络质量,业务需求来合理调整它们。
RTO 与 RPO 并非越小越好!
过小的 RTO 将增大误报几率,过小的 RPO 将降低成功自动切换的概率。
故障切换时的不可用时长上限由 pg_rto 参数控制,RTO 默认值为 30s,增大它将导致更长的主库故障转移写入不可用时长,而减少它将增加误报故障转移率(例如,由短暂网络抖动导致的反复切换)。
潜在数据丢失量的上限由 pg_rpo 参数控制,默认为 1MB,减小这个值可以降低故障切换时的数据损失上限,但也会增加故障时因为从库不够健康(落后太久)而拒绝自动切换的概率。
Pigsty 默认使用可用性优先 模式,这意味着当主库故障时,它将尽快进行故障转移,尚未复制到从库的数据可能会丢失(常规万兆网络下,复制延迟在通常在几KB到100KB)。
如果您需要确保故障切换时不丢失任何数据,您可以使用 crit.yml 模板来确保在故障转移期间没有数据丢失,但这会牺牲一些性能作为代价。
相关参数 参数名称: pg_rto, 类型: int, 层次:C
以秒为单位的恢复时间目标(RTO)。这将用于计算 Patroni 的 TTL 值,默认为 30 秒。
如果主实例在这么长时间内失踪,将触发新的领导者选举,此值并非越低越好,它涉及到利弊权衡:
减小这个值可以减少集群故障转移期间的不可用时间(无法写入), 但会使集群对短期网络抖动更加敏感,从而增加误报触发故障转移的几率。
您需要根据网络状况和业务约束来配置这个值,在 故障几率 和 故障影响 之间做出权衡 。
参数名称: pg_rpo, 类型: int, 层次:C
以字节为单位的恢复点目标(RPO),默认值:1048576。
默认为 1MiB,这意味着在故障转移期间最多可以容忍 1MiB 的数据丢失。
当主节点宕机并且所有副本都滞后时,你必须做出一个艰难的选择:
是马上提升一个从库成为新的主库,付出可接受的数据丢失代价(例如,少于 1MB),并尽快将系统恢复服务。
还是等待主库重新上线(可能永远不会)以避免任何数据丢失,或放弃自动故障切换,等人工介入作出最终决策。
您需要根据业务的需求偏好配置这个值,在 可用性 和 一致性 之间进行 利弊权衡 。
此外,您始终可以通过启用同步提交(例如:使用 crit.yml 模板),通过牺牲集群一部分延迟/吞吐性能来强制确保 RPO = 0。
对于数据一致性至关重要
4.8 - 时间点恢复 Pigsty 使用 pgBackRest 实现了 PostgreSQL 时间点恢复,允许用户回滚至备份策略容许范围内的任意时间点。
概览 您可以将集群恢复回滚至过去任意时刻,避免软件缺陷与人为失误导致的数据损失。
Pigsty 的 PostgreSQL 集群带有自动配置的时间点恢复(PITR)方案,基于备份组件 pgBackRest 与可选的对象存储仓库 MinIO 提供。
高可用方案 可以解决硬件故障,但却对软件缺陷与人为失误导致的数据删除/覆盖写入/删库等问题却无能为力。
对于这种情况,Pigsty 提供了开箱即用的 时间点恢复 (Point in Time Recovery, PITR)能力,无需额外配置即默认启用。
Pigsty 为您提供了基础备份与 WAL 归档的默认配置,您可以使用本地目录与磁盘,亦或专用的 MinIO 集群或 S3 对象存储服务来存储备份并实现异地容灾。
当您使用本地磁盘时,默认保留恢复至过去一天内的任意时间点的能力。当您使用 MinIO 或 S3 时,默认保留恢复至过去一周内的任意时间点的能力。
只要存储空间管够,您尽可保留任意长地可恢复时间段,丰俭由人。
时间点恢复(PITR)解决什么问题?
容灾能⼒增强:RPO 从 ∞ 降⾄ ⼗⼏MB, RTO 从 ∞ 降⾄ ⼏⼩时/⼏刻钟。 确保数据安全:C/I/A 中的 数据完整性 :避免误删导致的数据⼀致性问题。 确保数据安全:C/I/A 中的 数据可⽤性 :提供对“永久不可⽤”这种灾难情况的兜底 单实例配置策略 事件 RTO RPO 什么也不做宕机 永久丢失 全部丢失 基础备份宕机 取决于备份大小与带宽(几小时) 丢失上一次备份后的数据(几个小时到几天) 基础备份 + WAL归档宕机 取决于备份大小与带宽(几小时) 丢失最后尚未归档的数据(几十MB)
时间点恢复有什么代价?
降低数据安全中的 C:机密性 ,产生额外泄漏点,需要额外对备份进⾏保护。 额外的资源消耗:本地存储或⽹络流量 / 带宽开销,通常并不是⼀个问题。 复杂度代价升⾼:⽤户需要付出备份管理成本。 时间点恢复的局限性
如果只有 PITR 用于故障恢复,则 RTO 与 RPO 指标相比 高可用方案 更为逊色,通常应两者组合使用。
RTO :如果只有单机 + PITR,恢复时长取决于备份大小与网络/磁盘带宽,从十几分钟到几小时,几天不等。RPO :如果只有单机 + PITR,宕机时可能丢失少量数据,一个或几个 WAL 日志段文件可能尚未归档,损失 16 MB 到⼏⼗ MB 不等的数据。除了 PITR 之外,您还可以在 Pigsty 中使用 延迟集群 来解决人为失误或软件缺陷导致的数据误删误改问题。
原理 时间点恢复允许您将集群恢复回滚至过去的“任意时刻”,避免软件缺陷与人为失误导致的数据损失。要做到这一点,首先需要做好两样准备工作:基础备份 与 WAL归档 。
拥有 基础备份 ,允许用户将数据库恢复至备份时的状态,而同时拥有从某个基础备份开始的 WAL归档 ,允许用户将数据库恢复至基础备份时刻之后的任意时间点。
详细原理,请参阅:基础备份与时间点恢复 ;具体操作,请参考 PGSQL管理:备份恢复 。
基础备份 Pigsty 使用 pgbackrest 管理 PostgreSQL 备份。pgBackRest 将在所有集群实例上初始化空仓库,但只会在集群主库上实际使用仓库。
pgBackRest 支持三种备份模式:全量备份 ,增量备份 ,差异备份,其中前两者最为常用。
全量备份将对数据库集群取一个当前时刻的全量物理快照,增量备份会记录当前数据库集群与上一次全量备份之间的差异。
Pigsty 为备份提供了封装命令:/pg/bin/pg-backup [full|incr]。您可以通过 Crontab 或任何其他任务调度系统,按需定期制作基础备份。
WAL归档 Pigsty 默认在集群主库上启⽤了 WAL 归档,并使⽤ pgbackrest 命令行工具持续推送 WAL 段⽂件至备份仓库。
pgBackRest 会⾃动管理所需的 WAL ⽂件,并根据备份的保留策略及时清理过期的备份,与其对应的 WAL 归档⽂件。
如果您不需要 PITR 功能,可以通过 配置集群 : archive_mode: off 来关闭 WAL 归档,移除 node_crontab 来停止定期备份任务。
实现 默认情况下,Pigsty提供了两种预置备份策略 :默认使用本地文件系统备份仓库,在这种情况下每天进行一次全量备份,确保用户任何时候都能回滚至一天内的任意时间点。备选策略使用专用的 MinIO 集群或S3存储备份,每周一全备,每天一增备,默认保留两周的备份与WAL归档。
Pigsty 使用 pgBackRest 管理备份,接收 WAL 归档,执行 PITR。备份仓库可以进行灵活配置(pgbackrest_repo ):默认使用主库本地文件系统(local),但也可以使用其他磁盘路径,或使用自带的可选 MinIO 服务(minio)与云上 S3 服务。
pgbackrest_enabled : true # 在 pgsql 主机上启用 pgBackRest 吗?
pgbackrest_clean : true # 初始化时删除 pg 备份数据?
pgbackrest_log_dir : /pg/log/pgbackrest # pgbackrest 日志目录,默认为 `/pg/log/pgbackrest`
pgbackrest_method : local # pgbackrest 仓库方法:local, minio, [用户定义...]
pgbackrest_repo : # pgbackrest 仓库:https://pgbackrest.org/configuration.html#section-repository
local : # 默认使用本地 posix 文件系统的 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按计数保留完整备份
retention_full : 2 # 使用本地文件系统仓库时,最多保留 3 个完整备份,至少保留 2 个
minio : # pgbackrest 的可选 minio 仓库
type : s3 # minio 是与 s3 兼容的,所以使用 s3
s3_endpoint : sss.pigsty # minio 端点域名,默认为 `sss.pigsty`
s3_region : us-east-1 # minio 区域,默认为 us-east-1,对 minio 无效
s3_bucket : pgsql # minio 桶名称,默认为 `pgsql`
s3_key : pgbackrest # pgbackrest 的 minio 用户访问密钥
s3_key_secret : S3User.Backup # pgbackrest 的 minio 用户秘密密钥
s3_uri_style : path # 对 minio 使用路径风格的 uri,而不是主机风格
path : /pgbackrest # minio 备份路径,默认为 `/pgbackrest`
storage_port : 9000 # minio 端口,默认为 9000
storage_ca_file : /etc/pki/ca.crt # minio ca 文件路径,默认为 `/etc/pki/ca.crt`
bundle : y # 将小文件打包成一个文件
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 在 minio 仓库上按时间保留完整备份
retention_full : 14 # 保留过去 14 天的完整备份
# 您还可以添加其他的可选备份仓库,例如 S3,用于异地容灾
Pigsty 参数 pgbackrest_repo 中的目标仓库会被转换为 /etc/pgbackrest/pgbackrest.conf 配置文件中的仓库定义。
例如,如果您定义了一个美西区的 S3 仓库用于存储冷备份,可以使用下面的参考配置。
s3 : # ------> /etc/pgbackrest/pgbackrest.conf
repo1-type : s3 # ----> repo1-type=s3
repo1-s3-region : us-west-1 # ----> repo1-s3-region=us-west-1
repo1-s3-endpoint : s3-us-west-1.amazonaws.com # ----> repo1-s3-endpoint=s3-us-west-1.amazonaws.com
repo1-s3-key : '<your_access_key>' # ----> repo1-s3-key=<your_access_key>
repo1-s3-key-secret : '<your_secret_key>' # ----> repo1-s3-key-secret=<your_secret_key>
repo1-s3-bucket : pgsql # ----> repo1-s3-bucket=pgsql
repo1-s3-uri-style : host # ----> repo1-s3-uri-style=host
repo1-path : /pgbackrest # ----> repo1-path=/pgbackrest
repo1-bundle : y # ----> repo1-bundle=y
repo1-cipher-type : aes-256-cbc # ----> repo1-cipher-type=aes-256-cbc
repo1-cipher-pass : pgBackRest # ----> repo1-cipher-pass=pgBackRest
repo1-retention-full-type : time # ----> repo1-retention-full-type=time
repo1-retention-full : 90 # ----> repo1-retention-full=90
恢复 您可以直接使用以下封装命令可以用于 PostgreSQL 数据库集群的 时间点恢复 。
Pigsty 默认使用增量差分并行恢复,允许您以最快速度恢复到指定时间点。
pg-pitr # 恢复到WAL存档流的结束位置(例如在整个数据中心故障的情况下使用)
pg-pitr -i # 恢复到最近备份完成的时间(不常用)
pg-pitr --time= "2022-12-30 14:44:44+08" # 恢复到指定的时间点(在删除数据库或表的情况下使用)
pg-pitr --name= "my-restore-point" # 恢复到使用 pg_create_restore_point 创建的命名恢复点
pg-pitr --lsn= "0/7C82CB8" -X # 在LSN之前立即恢复
pg-pitr --xid= "1234567" -X -P # 在指定的事务ID之前立即恢复,然后将集群直接提升为主库
pg-pitr --backup= latest # 恢复到最新的备份集
pg-pitr --backup= 20221108-105325 # 恢复到特定备份集,备份集可以使用 pgbackrest info 列出
pg-pitr # pgbackrest --stanza=pg-meta restore
pg-pitr -i # pgbackrest --stanza=pg-meta --type=immediate restore
pg-pitr -t "2022-12-30 14:44:44+08" # pgbackrest --stanza=pg-meta --type=time --target="2022-12-30 14:44:44+08" restore
pg-pitr -n "my-restore-point" # pgbackrest --stanza=pg-meta --type=name --target=my-restore-point restore
pg-pitr -b 20221108-105325F # pgbackrest --stanza=pg-meta --type=name --set=20221230-120101F restore
pg-pitr -l "0/7C82CB8" -X # pgbackrest --stanza=pg-meta --type=lsn --target="0/7C82CB8" --target-exclusive restore
pg-pitr -x 1234567 -X -P # pgbackrest --stanza=pg-meta --type=xid --target="0/7C82CB8" --target-exclusive --target-action=promote restore
在执行 PITR 时,您可以使用 Pigsty 监控系统观察集群 LSN 位点状态,判断是否成功恢复到指定的时间点,事务点,LSN位点,或其他点位。
4.9 - 服务接入 Pigsty 使用 HAProxy 提供服务接入,并提供可选的 pgBouncer 池化连接,以及可选的 L2 VIP 与 DNS 接入。
分离读写操作,正确路由流量,稳定可靠地交付 PostgreSQL 集群提供的能力。
服务 是一种抽象:它是数据库集群对外提供能力的形式,并封装了底层集群的细节。
服务对于生产环境中的稳定接入 至关重要,在高可用 集群自动故障时方显其价值,单机用户 通常不需要操心这个概念。
单机用户 “服务” 的概念是给生产环境用的,个人用户/单机集群可以不折腾,直接拿实例名/IP地址访问数据库。
例如,Pigsty 默认的单节点 pg-meta.meta 数据库,就可以直接用下面三个不同的用户连接上去。
psql postgres://dbuser_dba:DBUser.DBA@10.10.10.10/meta # 直接用 DBA 超级用户连上去
psql postgres://dbuser_meta:DBUser.Meta@10.10.10.10/meta # 用默认的业务管理员用户连上去
psql postgres://dbuser_view:DBUser.View@pg-meta/meta # 用默认的只读用户走实例域名连上去
服务概述 在真实世界生产环境中,我们会使用基于复制的主从数据库集群。集群中有且仅有一个实例作为领导者(主库 )可以接受写入。
而其他实例(从库 )则会从持续从集群领导者获取变更日志,与领导者保持一致。同时,从库还可以承载只读请求,在读多写少的场景下可以显著分担主库的负担,
因此对集群的写入请求与只读请求进行区分,是一种十分常见的实践。
此外对于高频短连接的生产环境,我们还会通过连接池中间件(Pgbouncer)对请求进行池化,减少连接与后端进程的创建开销。但对于ETL与变更执行等场景,我们又需要绕过连接池,直接访问数据库。
同时,高可用集群在故障时会出现故障切换(Failover),故障切换会导致集群的领导者出现变更。因此高可用的数据库方案要求写入流量可以自动适配集群的领导者变化。
这些不同的访问需求(读写分离,池化与直连,故障切换自动适配)最终抽象出 服务 (Service)的概念。
通常来说,数据库集群都必须提供这种最基础的服务:
对于生产数据库集群,至少应当提供这两种服务:
读写服务(primary) :写入数据:只能由主库所承载。只读服务(replica) :读取数据:可以由从库承载,没有从库时也可由主库承载此外,根据具体的业务场景,可能还会有其他的服务,例如:
默认直连服务(default) :允许(管理)用户,绕过连接池直接访问数据库的服务离线从库服务(offline) :不承接线上只读流量的专用从库,用于ETL与分析查询同步从库服务(standby) :没有复制延迟的只读服务,由同步备库 /主库处理只读查询延迟从库服务(delayed) :访问同一个集群在一段时间之前的旧数据,由延迟从库 来处理接入服务 Pigsty的服务交付边界止步于集群的HAProxy,用户可以用各种手段访问这些负载均衡器。
典型的做法是使用 DNS 或 VIP 接入,将其绑定在集群所有或任意数量的负载均衡器上。
你可以使用不同的 主机 & 端口 组合,它们以不同的方式提供 PostgreSQL 服务。
主机
类型 样例 描述 集群域名 pg-test通过集群域名访问(由 dnsmasq @ infra 节点解析) 集群 VIP 地址 10.10.10.3通过由 vip-manager 管理的 L2 VIP 地址访问,绑定到主节点 实例主机名 pg-test-1通过任何实例主机名访问(由 dnsmasq @ infra 节点解析) 实例 IP 地址 10.10.10.11访问任何实例的 IP 地址
端口
Pigsty 使用不同的 端口 来区分 pg services
端口 服务 类型 描述 5432 postgres 数据库 直接访问 postgres 服务器 6432 pgbouncer 中间件 访问 postgres 前先通过连接池中间件 5433 primary 服务 访问主 pgbouncer (或 postgres) 5434 replica 服务 访问备份 pgbouncer (或 postgres) 5436 default 服务 访问主 postgres 5438 offline 服务 访问离线 postgres
组合
# 通过集群域名访问
postgres://test@pg-test:5432/test # DNS -> L2 VIP -> 主直接连接
postgres://test@pg-test:6432/test # DNS -> L2 VIP -> 主连接池 -> 主
postgres://test@pg-test:5433/test # DNS -> L2 VIP -> HAProxy -> 主连接池 -> 主
postgres://test@pg-test:5434/test # DNS -> L2 VIP -> HAProxy -> 备份连接池 -> 备份
postgres://dbuser_dba@pg-test:5436/test # DNS -> L2 VIP -> HAProxy -> 主直接连接 (用于管理员)
postgres://dbuser_stats@pg-test:5438/test # DNS -> L2 VIP -> HAProxy -> 离线直接连接 (用于 ETL/个人查询)
# 通过集群 VIP 直接访问
postgres://test@10.10.10.3:5432/test # L2 VIP -> 主直接访问
postgres://test@10.10.10.3:6432/test # L2 VIP -> 主连接池 -> 主
postgres://test@10.10.10.3:5433/test # L2 VIP -> HAProxy -> 主连接池 -> 主
postgres://test@10.10.10.3:5434/test # L2 VIP -> HAProxy -> 备份连接池 -> 备份
postgres://dbuser_dba@10.10.10.3:5436/test # L2 VIP -> HAProxy -> 主直接连接 (用于管理员)
postgres://dbuser_stats@10.10.10.3::5438/test # L2 VIP -> HAProxy -> 离线直接连接 (用于 ETL/个人查询)
# 直接指定任何集群实例名
postgres://test@pg-test-1:5432/test # DNS -> 数据库实例直接连接 (单例访问)
postgres://test@pg-test-1:6432/test # DNS -> 连接池 -> 数据库
postgres://test@pg-test-1:5433/test # DNS -> HAProxy -> 连接池 -> 数据库读/写
postgres://test@pg-test-1:5434/test # DNS -> HAProxy -> 连接池 -> 数据库只读
postgres://dbuser_dba@pg-test-1:5436/test # DNS -> HAProxy -> 数据库直接连接
postgres://dbuser_stats@pg-test-1:5438/test # DNS -> HAProxy -> 数据库离线读/写
# 直接指定任何集群实例 IP 访问
postgres://test@10.10.10.11:5432/test # 数据库实例直接连接 (直接指定实例, 没有自动流量分配)
postgres://test@10.10.10.11:6432/test # 连接池 -> 数据库
postgres://test@10.10.10.11:5433/test # HAProxy -> 连接池 -> 数据库读/写
postgres://test@10.10.10.11:5434/test # HAProxy -> 连接池 -> 数据库只读
postgres://dbuser_dba@10.10.10.11:5436/test # HAProxy -> 数据库直接连接
postgres://dbuser_stats@10.10.10.11:5438/test # HAProxy -> 数据库离线读-写
# 智能客户端:通过URL读写分离
postgres://test@10.10.10.11:6432,10.10.10.12:6432,10.10.10.13:6432/test?target_session_attrs= primary
postgres://test@10.10.10.11:6432,10.10.10.12:6432,10.10.10.13:6432/test?target_session_attrs= prefer-standby
4.10 - 访问控制 Pigsty 提供了标准的安全实践:密码与证书认证,开箱即用的权限模型,SSL加密网络流量,加密远程冷备份等。
Pigsty 提供了一套开箱即用的,基于角色系统 和权限系统 的访问控制模型。
权限控制很重要,但很多用户做不好。因此 Pigsty 提供了一套开箱即用的精简访问控制模型,为您的集群安全性提供一个兜底。
角色系统 Pigsty 默认的角色系统包含四个默认角色 和四个默认用户 :
角色名称 属性 所属 描述 dbrole_readonlyNOLOGIN角色:全局只读访问 dbrole_readwriteNOLOGINdbrole_readonly 角色:全局读写访问 dbrole_adminNOLOGINpg_monitor,dbrole_readwrite 角色:管理员/对象创建 dbrole_offlineNOLOGIN角色:受限的只读访问 postgresSUPERUSER系统超级用户 replicatorREPLICATIONpg_monitor,dbrole_readonly 系统复制用户 dbuser_dbaSUPERUSERdbrole_admin pgsql 管理用户 dbuser_monitorpg_monitor pgsql 监控用户
这些角色与用户 的详细定义如下所示:
pg_default_roles : # 全局默认的角色与系统用户
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
默认角色 Pigsty 中有四个默认角色:
业务只读 (dbrole_readonly): 用于全局只读访问的角色。如果别的业务想要此库只读访问权限,可以使用此角色。 业务读写 (dbrole_readwrite): 用于全局读写访问的角色,主属业务使用的生产账号应当具有数据库读写权限 业务管理员 (dbrole_admin): 拥有DDL权限的角色,通常用于业务管理员,或者需要在应用中建表的场景(比如各种业务软件) 离线只读访问 (dbrole_offline): 受限的只读访问角色(只能访问 offline 实例,通常是个人用户,ETL工具账号) 默认角色在 pg_default_roles 中定义,除非您确实知道自己在干什么,建议不要更改默认角色的名称。
- { name: dbrole_readonly , login: false , comment : role for global read-only access } # 生产环境的只读角色
- { name: dbrole_offline , login: false , comment : role for restricted read-only access (offline instance) } # 受限的只读角色
- { name: dbrole_readwrite , login: false , roles: [dbrole_readonly], comment : role for global read-write access } # 生产环境的读写角色
- { name: dbrole_admin , login: false , roles: [pg_monitor, dbrole_readwrite] , comment : role for object creation } # 生产环境的 DDL 更改角色
默认用户 Pigsty 也有四个默认用户(系统用户):
超级用户 (postgres),集群的所有者和创建者,与操作系统 dbsu 名称相同。 复制用户 (replicator),用于主-从复制的系统用户。 监控用户 (dbuser_monitor),用于监控数据库和连接池指标的用户。 管理用户 (dbuser_dba),执行日常操作和数据库更改的管理员用户。 这4个默认用户的用户名/密码通过4对专用参数进行定义,并在很多地方引用:
在生产部署中记得更改这些密码,不要使用默认值!
pg_dbsu : postgres # 数据库超级用户名,这个用户名建议不要修改。
pg_dbsu_password : '' # 数据库超级用户密码,这个密码建议留空!禁止dbsu密码登陆。
pg_replication_username : replicator # 系统复制用户名
pg_replication_password : DBUser.Replicator # 系统复制密码,请务必修改此密码!
pg_monitor_username : dbuser_monitor # 系统监控用户名
pg_monitor_password : DBUser.Monitor # 系统监控密码,请务必修改此密码!
pg_admin_username : dbuser_dba # 系统管理用户名
pg_admin_password : DBUser.DBA # 系统管理密码,请务必修改此密码!
如果您修改默认用户的参数,在 pg_default_roles 中修改相应的角色定义 即可:
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 , comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor, dbrole_readonly] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
权限系统 Pigsty 拥有一套开箱即用的权限模型,该模型与默认角色 一起配合工作。
所有用户都可以访问所有模式。 只读用户(dbrole_readonly)可以从所有表中读取数据。(SELECT,EXECUTE) 读写用户(dbrole_readwrite)可以向所有表中写入数据并运行 DML。(INSERT,UPDATE,DELETE)。 管理员用户(dbrole_admin)可以创建对象并运行 DDL(CREATE,USAGE,TRUNCATE,REFERENCES,TRIGGER)。 离线用户(dbrole_offline)类似只读用户,但访问受到限制,只允许访问离线实例 (pg_role = 'offline' 或 pg_offline_query = true) 由管理员用户创建的对象将具有正确的权限。 所有数据库上都配置了默认权限,包括模板数据库。 数据库连接权限由数据库定义 管理。 默认撤销PUBLIC在数据库和public模式下的CREATE权限。 对象权限 数据库中新建对象的默认权限由参数 pg_default_privileges 所控制:
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
由管理员新创建 的对象,默认将会上述权限。使用 \ddp+ 可以查看这些默认权限:
类型 访问权限 函数 =X dbrole_readonly=X dbrole_offline=X dbrole_admin=X 模式 dbrole_readonly=U dbrole_offline=U dbrole_admin=UC 序列号 dbrole_readonly=r dbrole_offline=r dbrole_readwrite=wU dbrole_admin=rwU 表 dbrole_readonly=r dbrole_offline=r dbrole_readwrite=awd dbrole_admin=arwdDxt
默认权限 SQL 语句 ALTER DEFAULT PRIVILEGES 允许您设置将来创建的对象的权限。 它不会影响已经存在对象的权限,也不会影响非管理员用户创建的对象。
在 Pigsty 中,默认权限针对三个角色进行定义:
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE {{ pg_dbsu }} {{ priv }} ;
{ % endfor % }
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE {{ pg_admin_username }} {{ priv }} ;
{ % endfor % }
-- 对于其他业务管理员而言,它们应当在执行 DDL 前执行 SET ROLE dbrole_admin,从而使用对应的默认权限配置。
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE "dbrole_admin" {{ priv }} ;
{ % endfor % }
这些内容将会被 PG集群初始化模板 pg-init-template.sql 所使用,在集群初始化的过程中渲染并输出至 /pg/tmp/pg-init-template.sql。
该命令会在 template1 与 postgres 数据库中执行,新创建的数据库会通过模板 template1 继承这些默认权限配置。
也就是说,为了维持正确的对象权限,您必须用管理员用户 来执行 DDL,它们可以是:
{{ pg_dbsu }} ,默认为 postgres{{ pg_admin_username }} ,默认为 dbuser_dba授予了 dbrole_admin 角色的业务管理员用户(通过 SET ROLE 切换为 dbrole_admin 身份)。 使用 postgres 作为全局对象所有者是明智的。如果您希望以业务管理员用户身份创建对象,创建之前必须使用 SET ROLE dbrole_admin 来维护正确的权限。
当然,您也可以在数据库中通过 ALTER DEFAULT PRIVILEGE FOR ROLE <some_biz_admin> XXX 来显式对业务管理员授予默认权限。
数据库权限 在 Pigsty 中,数据库(Database)层面的权限在数据库定义 中被涵盖。
数据库有三个级别的权限:CONNECT、CREATE、TEMP,以及一个特殊的’权限’:OWNERSHIP。
- name : meta # 必选,`name` 是数据库定义中唯一的必选字段
owner : postgres # 可选,数据库所有者,默认为 postgres
allowconn : true # 可选,是否允许连接,默认为 true。显式设置 false 将完全禁止连接到此数据库
revokeconn : false # 可选,撤销公共连接权限。默认为 false,设置为 true 时,属主和管理员之外用户的 CONNECT 权限会被回收
如果 owner 参数存在,它作为数据库属主,替代默认的 {{ pg_dbsu }} (通常也就是postgres) 如果 revokeconn 为 false,所有用户都有数据库的 CONNECT 权限,这是默认的行为。 如果显式设置了 revokeconn 为 true:数据库的 CONNECT 权限将从 PUBLIC 中撤销:普通用户无法连接上此数据库 CONNECT 权限将被显式授予 {{ pg_replication_username }}、{{ pg_monitor_username }} 和 {{ pg_admin_username }}CONNECT 权限将 GRANT OPTION 被授予数据库属主,数据库属主用户可以自行授权其他用户连接权限。 revokeconn 选项可用于在同一个集群间隔离跨数据库访问,您可以为每个数据库创建不同的业务用户作为属主,并为它们设置 revokeconn 选项。示例:数据库隔离 pg-infra :
hosts :
10.10.10.40 : { pg_seq: 1, pg_role : primary }
10.10.10.41 : { pg_seq: 2, pg_role: replica , pg_offline_query : true }
vars :
pg_cluster : pg-infra
pg_users :
- { name: dbuser_confluence, password: mc2iohos , pgbouncer: true, roles : [ dbrole_admin ] }
- { name: dbuser_gitlab, password: sdf23g22sfdd , pgbouncer: true, roles : [ dbrole_readwrite ] }
- { name: dbuser_jira, password: sdpijfsfdsfdfs , pgbouncer: true, roles : [ dbrole_admin ] }
pg_databases :
- { name: confluence , revokeconn: true, owner: dbuser_confluence , connlimit : 100 }
- { name: gitlab , revokeconn: true, owner: dbuser_gitlab, connlimit : 100 }
- { name: jira , revokeconn: true, owner: dbuser_jira , connlimit : 100 }
CREATE权限 出于安全考虑,Pigsty 默认从 PUBLIC 撤销数据库上的 CREATE 权限,从 PostgreSQL 15 开始这也是默认行为。
数据库属主总是可以根据实际需要,来自行调整 CREATE 权限。
5 - 任务 如何去完成单个任务。每个任务页面是一般通过给出若干步骤展示如何执行完成某事。
安装工具 离线安装 配置 管理 PGSQL 管理 INFRA 管理 NODE 管理 ETCD 管理 REDIS 管理 MONITOR 管理 BACKUP 5.1 - 高可用演习:3坏2如何处理 高可用典型场景处理预案:三节点坏了两个节点,高可用不生效了,怎么从紧急状态中恢复?
如果经典3节点高可用部署同时出现两台(多数主体)故障,系统通常无法自动完成故障切换,需要人工介入:
首先判断另外两台服务器的情况,如果短时间内可以拉起,优先选择拉起另外两台服务。否则进入 紧急止血流程
紧急止血流程假设您的管理节点故障 ,只有单台普通数据库节点存活,在这种情况下,最快的恢复操作流程为:
调整 HAProxy 配置,将流量指向主库。 关闭 Patroni,手动提升 PostgreSQL 从库为主库。 调整HAProxy配置 如果你通过其他方式绕开 HAProxy 访问集群,那么可以跳过这一步。
如果你通过 HAProxy 方式访问数据库集群,那么你需要调整负载均衡配置,将读写流量手工指向主库。
编辑 /etc/haproxy/<pg_cluster>-primary.cfg 配置文件,其中 <pg_cluster> 为你的 PostgreSQL 集群名称,例如 pg-meta。 将健康检查配置选项注释,停止进行健康鉴擦好 将服务器列表中,其他两台故障的机器注释掉,只保留当前主库服务器。 listen pg-meta-primary
bind *:5433
mode tcp
maxconn 5000
balance roundrobin
# 注释掉以下四行健康检查配置
#option httpchk # <---- remove this
#option http-keep-alive # <---- remove this
#http-check send meth OPTIONS uri /primary # <---- remove this
#http-check expect status 200 # <---- remove this
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
server pg-meta-1 10.10.10.10:6432 check port 8008 weight 100
# 注释掉其他两台故障的机器
#server pg-meta-2 10.10.10.11:6432 check port 8008 weight 100 <---- comment this
#server pg-meta-3 10.10.10.12:6432 check port 8008 weight 100 <---- comment this
配置调整完成后,先不着急执行 systemctl reload haproxy 重载生效,等待后续主库提升后一起执行。
以上配置的效果是,HAProxy 将不再进行主库健康检查(默认使用 Patroni),而是直接将写入流量指向当前主库
手工提升备库 登陆目标服务器,切换至 dbsu 用户,执行 CHECKPOINT 刷盘后,关闭 Patroni,重启 PostgreSQL 并执行 Promote。
sudo su - postgres # 切换到数据库 dbsu 用户
psql -c 'checkpoint; checkpoint;' # 两次 Checkpoint 刷脏页,避免PG后重启耗时过久
sudo systemctl stop patroni # 关闭 Patroni
pg-restart # 重新拉起 PostgreSQL
pg-promote # 将 PostgreSQL 从库提升为主库
psql -c 'SELECT pg_is_in_recovery();' # 如果结果为 f,表示已经提升为主库
如果你上面调整了 HAProxy 配置,那么现在可以执行 systemctl reload haproxy 重载 HAProxy 配置,将流量指向新的主库。
systemctl reload haproxy # 重载 HAProxy 配置,将写入流量指向当前实例
避免脑裂 紧急止血后,第二优先级问题为:避免脑裂 。用户应当防止另外两台服务器重新上线后,与当前主库形成脑裂,导致数据不一致。
简单的做法是:
将另外两台服务器直接 断电/断网 ,确保它们不会在不受控的情况下再次上线。 调整应用使用的数据库连接串,将其 HOST 直接指向唯一幸存服务器上的主库。 然后应当根据具体情况,决定下一步的操作:
A:这两台服务器是临时故障(比如断网断电),可以原地修复后继续服务 B:这两台故障服务器是永久故障(比如硬件损坏),将移除并下线。 临时故障后的复原 如果另外两台服务器是临时故障,可以修复后继续服务,那么可以按照以下步骤进行修复与重建:
每次处理一台故障服务器,优先处理 管理节点 / INFRA 管理节点 启动故障服务器,并在启动后关停 Patroni ETCD 集群在法定人数恢复后,将恢复工作,此时可以启动幸存服务器(当前主库)上的 Patroni,接管现有 PostgreSQL,并重新获取集群领导者身份。
Patroni 启动后进入维护模式。
systemctl restart patroni
pg pause <pg_cluster>
在另外两台实例上以 postgres 用户身份创建 touch /pg/data/standby.signal 标记文件将其标记为从库,然后拉起 Patroni:
systemctl restart patroni
确认 Patroni 集群身份/角色正常后,退出维护模式:
永久故障后的复原 出现永久故障后,首先需要恢复管理节点上的 ~/pigsty 目录,主要是需要 pigsty.yml 与 files/pki/ca/ca.key 两个核心文件。
如果您无法取回或没有备份这两个文件,您可以选择部署一套新的 Pigsty,并通过 备份集群 的方式将现有集群迁移至新部署中。
请定期备份 pigsty 目录(例如使用 Git 进行版本管理)。建议吸取教训,下次不要犯这样的错误。
配置修复 您可以将幸存的节点作为新的管理节点,将 ~/pigsty 目录拷贝到新的管理节点上,然后开始调整配置。
例如,将原本默认的管理节点 10.10.10.10 替换为幸存节点 10.10.10.12
all :
vars :
admin_ip : 10.10.10.12 # 使用新的管理节点地址
node_etc_hosts : [ 10.10.10.12 h.pigsty a.pigsty p.pigsty g.pigsty sss.pigsty]
infra_portal : {} # 一并修改其他引用旧管理节点 IP (10.10.10.10) 的配置
children :
infra : # 调整 Infra 集群
hosts :
# 10.10.10.10: { infra_seq: 1 } # 老的 Infra 节点
10.10.10.12 : { infra_seq : 3 } # 新增 Infra 节点
etcd : # 调整 ETCD 集群
hosts :
#10.10.10.10: { etcd_seq: 1 } # 注释掉此故障节点
#10.10.10.11: { etcd_seq: 2 } # 注释掉此故障节点
10.10.10.12 : { etcd_seq : 3 } # 保留幸存节点
vars :
etcd_cluster : etcd
pg-meta : # 调整 PGSQL 集群配置
hosts :
#10.10.10.10: { pg_seq: 1, pg_role: primary }
#10.10.10.11: { pg_seq: 2, pg_role: replica }
#10.10.10.12: { pg_seq: 3, pg_role: replica , pg_offline_query: true }
10.10.10.12 : { pg_seq: 3, pg_role: primary , pg_offline_query : true }
vars :
pg_cluster : pg-meta
ETCD修复 然后执行以下命令,将 ETCD 重置为单节点集群:
./etcd.yml -e etcd_safeguard = false -e etcd_clean = true
根据 ETCD重载配置 的说明,调整对 ETCD Endpoint 的引用。
INFRA修复 如果幸存节点上没有 INFRA 模块,请在当前节点上配置新的 INFRA 模块并安装。执行以下命令,将 INFRA 模块部署到幸存节点上:
./infra.yml -l 10.10.10.12
修复当前节点的监控
./node.yml -t node_monitor
PGSQL修复 ./pgsql.yml -t pg_conf # 重新生成 PG 配置文件
systemctl reload patroni # 在幸存节点上重载 Patroni 配置
各模块修复后,您可以参考标准扩容流程,将新的节点加入集群,恢复集群的高可用性。
5.2 - Nginx:向外代理暴露Web服务 如何在使用 Nginx 对外代理、转发、暴露 Web 服务?
Pigsty 在 INFRA节点 上默认会安装 Nginx 作为 Web 服务代理。(单机安装时,本机默认也是一个 INFRA节点 )
Nginx 是 Pigsty 所有 WebUI 类服务的访问入口,默认使用管理节点 80/443 端口。
Pigsty 提供了一个全局配置变量 infra_portal ,用于配置 Nginx 的代理规则,以及对应的上游服务。
如果您直接通过端口访问 Nginx,默认访问的是 h.pigsty,即 Pigsty 文件系统首页。(/www/ 目录)。
因为 Nginx 通过同一个端口对外提供多个服务,因此必须通过域名进行区分(浏览器的 HOST 首部),所以在默认情况下,Nginx 只会对外暴露 带有 domain` 参数的
默认情况下,Nginx 除了 home (文件系统,软件源)之外,还对外暴露 grafana,prometheus,alertmanager 三项可观测性服务:
infra_portal : # domain names and upstream servers
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9090" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9093" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
#minio : { domain: sss.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
如何配置 Nginx 代理? Pigsty 自带的配置模板 full.yml 配置文件,作为一个参考,额外对外部暴露了一些 Web 服务:
infra_portal : # domain names and upstream servers
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9090" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9093" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
minio : { domain: sss.pigsty ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
postgrest : { domain: api.pigsty ,endpoint : "127.0.0.1:8884" }
pgadmin : { domain: adm.pigsty ,endpoint : "127.0.0.1:8885" }
pgweb : { domain: cli.pigsty ,endpoint : "127.0.0.1:8886" }
bytebase : { domain: ddl.pigsty ,endpoint : "127.0.0.1:8887" }
jupyter : { domain: lab.pigsty ,endpoint : "127.0.0.1:8888" , websocket : true }
gitea : { domain: git.pigsty ,endpoint : "127.0.0.1:8889" }
wiki : { domain: wiki.pigsty ,endpoint : "127.0.0.1:9002" }
noco : { domain: noco.pigsty ,endpoint : "127.0.0.1:9003" }
supa : { domain: supa.pigsty ,endpoint : "10.10.10.10:8000" , websocket : true }
这里不难看出,每一条记录都有一个独一无二的 name 作为 key,一个配置字典作为 value。在配置字典中,目前有以下四个可用配置项:
endpoint:必填,指定上游服务的地址,可以是 IP:PORT 或者 DOMAIN:PORT。在此参数中,可以使用 ${admin_ip} 占位符,Pigsty会填入 admin_ip 的值。 domain:可选,指定代理的域名,如果不填写,则 Nginx 不会对外暴露此服务。对于那些需要知道 endpoint 地址,但不想对外暴露的服务(例如 Loki, Blackbox Exporter),可以不填写 domain。 scheme:可选,指定转发时的协议(http/https),留空则默认使用 http对于那些强制要求 HTTPS 访问的上游 Web 服务(例如 MinIO 管理界面),需要指定 scheme: https。 websocket:可选,指定是否开启 WebSocket,留空则默认关闭。类似 Grafana、Jupyter 等需要 WebSocket 的服务需要设置为 true 方能正常工作。 因此,如果您需要新增一个通过 Nginx 暴露的 Web 服务,首先需要在 infra_portal 中添加相应地记录,然后执行剧本生效:
./infra.yml -t nginx_config # 重新生成 Nginx 配置文件
./infra.yml -t nginx_cert # 重新签发自签名 HTTPS 证书,囊括新增的域名
./infra.yml -t nginx_launch # 重启 Nginx 以使配置生效(如果您不希望出现中断,手动使用 nginx -s reload)
如果您始终通过 Pigsty 管理 Nginx 配置,也可以直接使用以下任务重新初始化 Nginx 配置:
./infra.yml -t nginx # 直接重新初始化 Nginx 至描述的状态
Nginx相关配置参数位于:配置:INFRA - NGINX
如何通过域名访问 Nginx 代理的服务? Nginx 通过浏览器设置的 HOST 首部中的域名,来区分不同的服务,所以默认除了软件仓库之外服务,都的您需要通过域名访问。
您可以通过 IP地址 + 端口的方式直接访问这些服务。但我们更推荐您使用域名通过 Nginx 80/443 端口代理访问所有组件。
使用域名访问 Pigsty WebUI 时,您需要配置 DNS 解析,或者修改本地的 /etc/hosts 静态解析文件,有几种典型的方式
如果您的服务需要直接暴露在公网上,那么应当通过 DNS 服务商(Cloudflare,Aliyun DNS 等)解析互联网域名。注意,在这种情况下,通常您还需要修改 Pigsty 的 infra_portal 参数,因为默认的 *.pigsty 并不是一个适合公网使用的域名。
如果您的服务需要在办公网共享访问,那么应当通过内网 DNS 服务商(公司内部 DNS 服务器)解析内网域名,并将其指向 Nginx 服务器所在的 IP。您可以要求网络管理员在公司内部 DNS 服务器中添加相应的解析记录,也可以要求系统的用户手工配置静态的 DNS 解析记录。
如果您的服务仅供自己,或少数用户使用(例如 DBA),那么您可以要求这些用户使用静态域名解析记录。在 Linux / MacOS 系统上,修改 /etc/hosts 文件(需要 sudo 权限)或 C:\Windows\System32\drivers\etc\hosts(Windows)文件。
我们建议普通单机用户使用第三种方式,在 使用浏览器访问 Web 系统的机器上 ,添加以下解析记录:
<your_public_ip_address> h.pigsty a.pigsty p.pigsty g.pigsty
这里的 IP 地址是安装 Pigsty 服务的 对外IP地址 ,然后您就可以在浏览器中通过: http://g.pigsty 这样的域名网址,访问 Pigsty 的子系统了。
其他的 Web 服务与自定义域名,也可以通过同样的方式添加。例如以下是 Pigsty 沙箱 Demo 可能用到的域名解析记录:
10.10.10.10 h.pigsty a.pigsty p.pigsty g.pigsty
10.10.10.10 api.pigsty ddl.pigsty adm.pigsty cli.pigsty lab.pigsty
10.10.10.10 supa.pigsty noco.pigsty odoo.pigsty dify.pigsty
如何使用 HTTPS 访问 Nginx 代理的服务? Pigsty默认使用自动生成的自签名的 CA 证书为 Nginx 启用 SSL,如果您希望使用 HTTPS 访问这些页面,而不弹窗提示"不安全",通常有三个选择:
在您的浏览器或操作系统中信任 Pigsty 自签名的 CA 证书: files/pki/ca/ca.crt 如果您使用 Chrome,可以在提示不安全的窗口键入 thisisunsafe 跳过提示 您可以考虑使用 Let’s Encrypt 或其他免费的 CA 证书服务,为 Pigsty Nginx 生成正式的 SSL证书。 5.3 - Docker:启用容器支持与配置 如何在 Pigsty 启用 Docker 容器支持?Docker 的安装部署配置,以及如何解决DockerHub被“墙”的问题
Pigsty 提供了 DOCKER 模块,但默认并不安装。您可以使用 docker.yml 剧本在指定节点上安装并启用 Docker。
./docker.yml -l <ip| group| cls> # 在指定的节点、分组、集群上安装并启用 Docker
如何建配置代理服务器? 本文不会介绍如何“翻墙”,而是假设你已经有了一个可用的 HTTP(s) 代理服务器,应该如何配置,让 Docker 可以通过代理服务器,访问 docker hub 或 quay.io 等镜像站点:
你的代理服务器软件应该会提供一个形如:
http://<ip|domain>:<port> 或者 https://[user]:[pass]@<ip|domain>:<port> 的代理地址例如,假设您使用的代理服务器配置为:
export ALL_PROXY = http://192.168.0.106:8118
export HTTP_PROXY = http://192.168.0.106:8118
export HTTPS_PROXY = http://192.168.0.106:8118
export NO_PROXY = "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
您可以使用 curl 命令,检验代理服务器是否可以正常工作,例如成功可以访问 Google,通常说明代理服务器工作正常。
curl -x http://192.168.0.106:8118 -I http://www.google.com
如何为Docker Daemon配置代理服务器? 如果您希望 Docker 在 Pull 镜像时使用代理服务器,那么应当在 pigsty.yml 配置文件的全局变量中,指定 proxy_env 参数:
all :
vars :
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
http_proxy : http://192.168.0.106:8118
all_proxy : http://192.168.0.106:8118
https_proxy : http://192.168.0.106:8118
那么当 Docker 剧本执行,时,这些配置会被渲染为 /etc/docker/daemon.json 中的代理配置:
{
"proxies" : {
"http-proxy" : "{{ proxy_env['http_proxy'] }}" ,
"https-proxy" : "{{ proxy_env['http_proxy'] }}" ,
"no-proxy" : "{{ proxy_env['no_proxy'] }}"
}
}
请注意,Docker Daemon 不使用 all_proxy 参数
如果您希望手工指定代理服务器,可以选则直接修改 /etc/docker/daemon.json 中的 proxies 配置;
或者也可以修改 /lib/systemd/system/docker.service (Debian/Ubuntu) 与 /usr/lib/systemd/system/docker.service 的服务定义,在 [Service] 一节中添加环境变量声明,并重启生效:
[Service]
Environment = "HTTP_PROXY=http://192.168.0.106:8118"
Environment = "HTTPS_PROXY=http://192.168.0.106:8118"
Environment = "NO_PROXY=localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
重启后生效:
如何使用其他镜像站点? 您可以在 docker_registry_mirrors 参数中指定其他镜像站点,例如阿里云、腾讯云、清华大学等镜像站点:
[ "https://mirror.ccs.tencentyun.com" ] # tencent cloud mirror, intranet only
[ "https://registry.cn-hangzhou.aliyuncs.com" ] # aliyun cloud mirror, login required
不过目前来看,所有位于中国大陆的 DockerHub 公有镜像站都已经被封禁了,建议使用代理服务器直接访问 Docker Hub
如果您需要使用其他镜像站,例如 quay.io,可以首先执行:
docker login quay.io
username #> # input your username
password #> # input your password
5.4 - 使用 PostgreSQL 作为 Ansible 的配置清单与 CMDB 使用 PostgreSQL ,而不是静态 YAML 配置文件作为 Ansible 的配置源,从而更好地与外部系统集成整合。
您可以使用 PostgreSQL 作为 Pigsty 的配置源,替代静态 YAML 配置文件。
使用 CMDB 作为 Ansible 的动态 配置清单 具有一些优点:元数据以高度结构化的方式以数据表的形式呈现,并通过数据库约束确保一致性。 同时,使用 CMDB 允许您使用第三方的工具来编辑管理 Pigsty 元数据,便于与外部系统相互集成。
Ansible配置原理 Pigsty 默认的配置文件路径在 ansible.cfg 中指定为:inventory = pigsty.yml
修改该参数,可以更改默认使用的配置文件路径。如果您将其指向一个可执行的脚本文件,那么 Ansible 会使用动态 Inventory 机制,执行该脚本,并期待该脚本返回一份配置文件。
修改配置源实质上是编辑Pigsty目录下的 ansible.cfg 实现的:
---
inventory = pigsty.yml
+++
inventory = inventory.sh
而 inventory.sh 则是一个从 PostgreSQL CMDB 的记录中,生成等效 YAML/JSON 配置文件的简单脚本。
你可以使用 bin/inventory_cmdb 切换到动态的 CMDB 清单,
使用 bin/inventory_conf 返回到本地配置文件。
你还需要使用 bin/inventory_load 将当前的配置文件清单加载到 CMDB。
加载配置 Pigsty CMDB的模式会在pg-meta元数据库初始化时自动创建(files/cmdb.sql ),位于meta数据库的pigsty 模式中。使用bin/inventory_load可以将静态配置文件加载至CMDB中。
必须在元节点完整执行 infra.yml 安装完毕后,方可使用 CMDB
usage: inventory_load [ -h] [ -p PATH] [ -d CMDB_URL]
load config arguments
optional arguments:
-h, --help show this help message and exit„
-p PATH, --path PATH config path, ${ PIGSTY_HOME } /pigsty.yml by default
-d DATA, --data DATA postgres cmdb pgurl, ${ METADB_URL } by default
默认情况下,不带参数执行该脚本将会把$PIGSTY_HOME/pigsty.yml的名称载入默认CMDB中。
bin/inventory_load
bin/inventory_load -p conf/demo.yml
bin/inventory_load -p conf/prod.yml -d postgresql://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta
当原有配置文件加载至 CMDB 作为初始数据后,即可配置 Ansible 使用 CMDB 作为配置源:
您可以切换回静态配置文件:
5.5 - 使用 Keepalived 为 Pigsty 节点集群配置二层 VIP 您可以在节点集群上绑定一个可选的 L2 VIP —— 前提条件是:集群中的所有节点都在一个二层网络中。
在节点集群(任何一个 Ansible Group,包括数据库集群定义都可以视作一个节点集群)上,启用 vip_enabled 参数,即可在节点集群上启用 Keepalived ,绑定一个2层 VIP。
proxy:
hosts:
10.10.10.29: { nodename: proxy-1 } # 您可以显式指定初始的 VIP 角色:MASTER / BACKUP
10.10.10.30: { nodename: proxy-2 } # , vip_role: master }
vars:
node_cluster: proxy
vip_enabled: true
vip_vrid: 128
vip_address: 10.10.10.99
vip_interface: eth1
使用以下命令,刷新节点的 Keepalived 配置,并生效:
./node.yml -l proxy -t node_vip # 首次启用 VIP
./node.yml -l proxy -t vip_refresh # 刷新 vip 配置(例如指定 master)
5.6 - 使用 VIP-Manager 为 PostgreSQL 集群配置二层 VIP 您可以在 PostgreSQL 集群上绑定一个可选的 L2 VIP —— 前提条件是:集群中的所有节点都在一个二层网络中。
这个 L2 VIP 强制使用 Master - Backup 模式,Master 始终指向在数据库集群主库实例所在的节点。
这个 VIP 由 VIP-Manager 组件管理,它会从 DCS (etcd) 中直接读取由 Patroni 写入的 Leader Key,从而判断自己是否是 Master。
启用VIP 在 PostgreSQL 集群上定义 pg_vip_enabled 参数为 true,即可在集群上启用 VIP 组件。当然您也可以在全局配置中启用此配置项。
# pgsql 3 node ha cluster: pg-test
pg-test:
hosts:
10.10.10.11: { pg_seq: 1, pg_role: primary } # primary instance, leader of cluster
10.10.10.12: { pg_seq: 2, pg_role: replica } # replica instance, follower of leader
10.10.10.13: { pg_seq: 3, pg_role: replica, pg_offline_query: true } # replica with offline access
vars:
pg_cluster: pg-test # define pgsql cluster name
pg_users: [{ name: test , password: test , pgbouncer: true , roles: [ dbrole_admin ] }]
pg_databases: [{ name: test }]
# 启用 L2 VIP
pg_vip_enabled: true
pg_vip_address: 10.10.10.3/24
pg_vip_interface: eth1
请注意,pg_vip_address 必须是一个合法的 IP 地址,带有网段,且在当前二层网络中可用。
请注意,pg_vip_interface 必须是一个合法的网络接口名,并且应当是与 inventory 中使用 IPv4 地址一致的网卡。
如果集群成员的网卡名不一样,用户应当为每个实例显式指定 pg_vip_interface 参数,例如:
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role: primary , pg_vip_interface : eth0 }
10.10.10.12 : { pg_seq: 2, pg_role: replica , pg_vip_interface : eth1 }
10.10.10.13 : { pg_seq: 3, pg_role: replica , pg_vip_interface : ens33 }
vars :
pg_cluster : pg-test # define pgsql cluster name
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] }]
pg_databases : [ { name : test }]
# 启用 L2 VIP
pg_vip_enabled : true
pg_vip_address : 10.10.10.3 /24
#pg_vip_interface: eth1
使用以下命令,刷新 PG 的 vip-manager 配置并重启生效:
5.7 - Citus:部署 Citus 高可用集群 如何部署 Citus 高可用分布式集群?
Citus 是一个 PostgreSQL 扩展,可以将 PostgreSQL 原地转换为一个分布式数据库,并实现在多个节点上水平扩展,以处理大量数据和大量查询。
Patroni 在 v3.0 后,提供了对 Citus 原生高可用的支持,简化了 Citus 集群的搭建,Pigsty 也对此提供了原生支持。
注意:Citus 当前最新版本(12.1.6) 支持 PostgreSQL 16,15,14 三个大版本,尚不支持 PostgreSQL 17,且没有官方 ARM64 支持。 Pigsty 扩展仓库提供了 Citus ARM64 软件包,但在 ARM 架构下请谨慎使用。
Citus集群 Pigsty 原生支持 Citus。可以参考 conf/citus.yml
这里使用 Pigsty 四节点沙箱,定义了一个 Citus 集群 pg-citus,其中包括一个两节点的协调者集群 pg-citus0,
以及两个 Worker 集群 pg-citus1,pg-citus2。
pg-citus :
hosts :
10.10.10.10 : { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.2/24 ,pg_seq: 1, pg_role : primary }
10.10.10.11 : { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.2/24 ,pg_seq: 2, pg_role : replica }
10.10.10.12 : { pg_group: 1, pg_cluster: pg-citus1 ,pg_vip_address: 10.10.10.3/24 ,pg_seq: 1, pg_role : primary }
10.10.10.13 : { pg_group: 2, pg_cluster: pg-citus2 ,pg_vip_address: 10.10.10.4/24 ,pg_seq: 1, pg_role : primary }
vars :
pg_mode: citus # pgsql cluster mode : citus
pg_version : 16 # citus does not have pg16 available
pg_shard: pg-citus # citus shard name : pg-citus
pg_primary_db : citus # primary database used by citus
pg_vip_enabled : true # enable vip for citus cluster
pg_vip_interface : eth1 # vip interface for all members
pg_dbsu_password : DBUser.Postgres # all dbsu password access for citus cluster
pg_extensions : [ citus, postgis, pgvector, topn, pg_cron, hll ] # install these extensions
pg_libs : 'citus, pg_cron, pg_stat_statements' # citus will be added by patroni automatically
pg_users : [ { name: dbuser_citus ,password: DBUser.Citus ,pgbouncer: true ,roles : [ dbrole_admin ] }]
pg_databases : [ { name: citus ,owner: dbuser_citus ,extensions : [ citus, vector, topn, pg_cron, hll ] }]
pg_parameters :
cron.database_name : citus
citus.node_conninfo : 'sslmode=require sslrootcert=/pg/cert/ca.crt sslmode=verify-full'
pg_hba_rules :
- { user: 'all' ,db: all ,addr: 127.0.0.1/32 ,auth: ssl ,title : 'all user ssl access from localhost' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'all user ssl access from intranet' }
相比标准 PostgreSQL 集群,Citus 集群的配置有一些特殊之处,首先,你需要确保 Citus 扩展被下载,安装,加载并启用,这涉及到以下四个参数
其次,你需要确保 Citus 集群的配置正确:
配置完成后,您可以像创建普通 PostgreSQL 集群一样,使用 pgsql.yml 部署 Citus 集群。
管理Citus集群 定义好 Citus 集群后,部署 Citus 集群同样使用的剧本 pgsql.yml:
./pgsql.yml -l pg-citus # 部署 Citus 集群 pg-citus
使用任意成员的 DBSU(postgres)用户,都能通过 patronictl (alias: pg) 列出 Citus 集群的状态:
$ pg list
+ Citus cluster: pg-citus ----------+---------+-----------+----+-----------+--------------------+
| Group | Member | Host | Role | State | TL | Lag in MB | Tags |
+-------+-------------+-------------+---------+-----------+----+-----------+--------------------+
| 0 | pg-citus0-1 | 10.10.10.10 | Leader | running | 1 | | clonefrom: true |
| | | | | | | | conf: tiny.yml |
| | | | | | | | spec: 20C.40G.125G |
| | | | | | | | version: '16' |
+-------+-------------+-------------+---------+-----------+----+-----------+--------------------+
| 1 | pg-citus1-1 | 10.10.10.11 | Leader | running | 1 | | clonefrom: true |
| | | | | | | | conf: tiny.yml |
| | | | | | | | spec: 10C.20G.125G |
| | | | | | | | version: '16' |
+-------+-------------+-------------+---------+-----------+----+-----------+--------------------+
| 2 | pg-citus2-1 | 10.10.10.12 | Leader | running | 1 | | clonefrom: true |
| | | | | | | | conf: tiny.yml |
| | | | | | | | spec: 10C.20G.125G |
| | | | | | | | version: '16' |
+-------+-------------+-------------+---------+-----------+----+-----------+--------------------+
| 2 | pg-citus2-2 | 10.10.10.13 | Replica | streaming | 1 | 0 | clonefrom: true |
| | | | | | | | conf: tiny.yml |
| | | | | | | | spec: 10C.20G.125G |
| | | | | | | | version: '16' |
+-------+-------------+-------------+---------+-----------+----+-----------+--------------------+
您可以将每个水平分片集群视为一个独立的 PGSQL 集群,使用 pg (patronictl) 命令管理它们。
但是务必注意,当你使用 pg 命令管理 Citus 集群时,需要额外使用 --group 参数指定集群分片号
pg list pg-citus --group 0 # 需要使用 --group 0 指定集群分片号
Citus 中有一个名为 pg_dist_node 的系统表,用于记录 Citus 集群的节点信息,Patroni 会自动维护该表。
PGURL = postgres://postgres:DBUser.Postgres@10.10.10.10/citus
psql $PGURL -c 'SELECT * FROM pg_dist_node;' # 查看节点信息
nodeid | groupid | nodename | nodeport | noderack | hasmetadata | isactive | noderole | nodecluster | metadatasynced | shouldhaveshards
--------+---------+-------------+----------+----------+-------------+----------+-----------+-------------+----------------+------------------
1 | 0 | 10.10.10.10 | 5432 | default | t | t | primary | default | t | f
4 | 1 | 10.10.10.12 | 5432 | default | t | t | primary | default | t | t
5 | 2 | 10.10.10.13 | 5432 | default | t | t | primary | default | t | t
6 | 0 | 10.10.10.11 | 5432 | default | t | t | secondary | default | t | f
此外,你还可以查看用户认证信息(仅限超级用户访问):
$ psql $PGURL -c 'SELECT * FROM pg_dist_authinfo;' # 查看节点认证信息(仅限超级用户访问)
然后,你可以使用普通业务用户(例如,具有 DDL 权限的 dbuser_citus)来访问 Citus 集群:
psql postgres://dbuser_citus:DBUser.Citus@10.10.10.10/citus -c 'SELECT * FROM pg_dist_node;'
使用Citus集群 在使用 Citus 集群时,我们强烈建议您先阅读 Citus 官方文档 ,了解其架构设计与核心概念。
其中核心是了解 Citus 中的五种表,以及其特点与应用场景:
分布式表(Distributed Table) 参考表(Reference Table) 本地表(Local Table) 本地管理表(Local Management Table) 架构表(Schema Table) 在协调者节点上,您可以创建分布式表和引用表,并从任何数据节点查询它们。从 11.2 开始,任何 Citus 数据库节点都可以扮演协调者的角色了。
我们可以使用 pgbench 来创建一些表,并将其中的主表(pgbench_accounts)分布到各个节点上,然后将其他小表作为引用表:
PGURL = postgres://dbuser_citus:DBUser.Citus@10.10.10.10/citus
pgbench -i $PGURL
psql $PGURL <<-EOF
SELECT create_distributed_table('pgbench_accounts', 'aid'); SELECT truncate_local_data_after_distributing_table('public.pgbench_accounts');
SELECT create_reference_table('pgbench_branches') ; SELECT truncate_local_data_after_distributing_table('public.pgbench_branches');
SELECT create_reference_table('pgbench_history') ; SELECT truncate_local_data_after_distributing_table('public.pgbench_history');
SELECT create_reference_table('pgbench_tellers') ; SELECT truncate_local_data_after_distributing_table('public.pgbench_tellers');
EOF
执行读写测试:
pgbench -nv -P1 -c10 -T500 postgres://dbuser_citus:DBUser.Citus@10.10.10.10/citus # 直连协调者 5432 端口
pgbench -nv -P1 -c10 -T500 postgres://dbuser_citus:DBUser.Citus@10.10.10.10:6432/citus # 通过连接池,减少客户端连接数压力,可以有效提高整体吞吐。
pgbench -nv -P1 -c10 -T500 postgres://dbuser_citus:DBUser.Citus@10.10.10.13/citus # 任意 primary 节点都可以作为 coordinator
pgbench --select-only -nv -P1 -c10 -T500 postgres://dbuser_citus:DBUser.Citus@10.10.10.11/citus # 可以发起只读查询
更严肃的生产部署 要将 Citus 用于生产环境,您通常需要为 Coordinator 和每个 Worker 集群设置流复制物理副本。
例如,在 simu.yml 中定义了一个 10 节点的 Citus 集群。
pg-citus : # citus group
hosts :
10.10.10.50 : { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.60/24 ,pg_seq: 0, pg_role : primary }
10.10.10.51 : { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.60/24 ,pg_seq: 1, pg_role : replica }
10.10.10.52 : { pg_group: 1, pg_cluster: pg-citus1 ,pg_vip_address: 10.10.10.61/24 ,pg_seq: 0, pg_role : primary }
10.10.10.53 : { pg_group: 1, pg_cluster: pg-citus1 ,pg_vip_address: 10.10.10.61/24 ,pg_seq: 1, pg_role : replica }
10.10.10.54 : { pg_group: 2, pg_cluster: pg-citus2 ,pg_vip_address: 10.10.10.62/24 ,pg_seq: 0, pg_role : primary }
10.10.10.55 : { pg_group: 2, pg_cluster: pg-citus2 ,pg_vip_address: 10.10.10.62/24 ,pg_seq: 1, pg_role : replica }
10.10.10.56 : { pg_group: 3, pg_cluster: pg-citus3 ,pg_vip_address: 10.10.10.63/24 ,pg_seq: 0, pg_role : primary }
10.10.10.57 : { pg_group: 3, pg_cluster: pg-citus3 ,pg_vip_address: 10.10.10.63/24 ,pg_seq: 1, pg_role : replica }
10.10.10.58 : { pg_group: 4, pg_cluster: pg-citus4 ,pg_vip_address: 10.10.10.64/24 ,pg_seq: 0, pg_role : primary }
10.10.10.59 : { pg_group: 4, pg_cluster: pg-citus4 ,pg_vip_address: 10.10.10.64/24 ,pg_seq: 1, pg_role : replica }
vars :
pg_mode: citus # pgsql cluster mode : citus
pg_version : 16 # citus does not have pg16 available
pg_shard: pg-citus # citus shard name : pg-citus
pg_primary_db : citus # primary database used by citus
pg_vip_enabled : true # enable vip for citus cluster
pg_vip_interface : eth1 # vip interface for all members
pg_dbsu_password : DBUser.Postgres # enable dbsu password access for citus
pg_extensions : [ citus, postgis, pgvector, topn, pg_cron, hll ] # install these extensions
pg_libs : 'citus, pg_cron, pg_stat_statements' # citus will be added by patroni automatically
pg_users : [ { name: dbuser_citus ,password: DBUser.Citus ,pgbouncer: true ,roles : [ dbrole_admin ] }]
pg_databases : [ { name: citus ,owner: dbuser_citus ,extensions : [ citus, vector, topn, pg_cron, hll ] }]
pg_parameters :
cron.database_name : citus
citus.node_conninfo : 'sslrootcert=/pg/cert/ca.crt sslmode=verify-full'
pg_hba_rules :
- { user: 'all' ,db: all ,addr: 127.0.0.1/32 ,auth: ssl ,title : 'all user ssl access from localhost' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'all user ssl access from intranet' }
我们将在后续教程中覆盖一系列关于 Citus 的高级主题
读写分离 故障处理 一致性备份与恢复 高级监控与问题诊断 连接池 5.8 - 使用 PostgreSQL 作为 Grafana 后端数据库 使用 PostgreSQL 而不是 SQLite 作为 Grafana 后端使用的远程存储数据库,获取更好的性能与可用性。
您可以使用 PostgreSQL 作为 Grafana 后端使用的数据库。
这是了解Pigsty部署系统使用方式的好机会,完成此教程,您会了解:
太长不看 vi pigsty.yml # 取消注释DB/User定义:dbuser_grafana grafana
bin/pgsql-user pg-meta dbuser_grafana
bin/pgsql-db pg-meta grafana
psql postgres://dbuser_grafana:DBUser.Grafana@meta:5436/grafana -c \
'CREATE TABLE t(); DROP TABLE t;' # 检查连接串可用性
vi /etc/grafana/grafana.ini # 修改 [database] type url
systemctl restart grafana-server
创建数据库集群 我们可以在pg-meta上定义一个新的数据库grafana,也可以在新的机器节点上创建一个专用于Grafana的数据库集群:pg-grafana
定义集群 如果需要创建新的专用数据库集群pg-grafana,部署在10.10.10.11,10.10.10.12两台机器上,可以使用以下配置文件:
pg-grafana :
hosts :
10.10.10.11 : {pg_seq: 1, pg_role : primary}
10.10.10.12 : {pg_seq: 2, pg_role : replica}
vars :
pg_cluster : pg-grafana
pg_databases :
- name : grafana
owner : dbuser_grafana
revokeconn : true
comment : grafana primary database
pg_users :
- name : dbuser_grafana
password : DBUser.Grafana
pgbouncer : true
roles : [ dbrole_admin]
comment : admin user for grafana database
创建集群 使用以下命令完成数据库集群pg-grafana的创建:pgsql.yml 。
bin/createpg pg-grafana # 初始化pg-grafana集群
该命令实际上调用了Ansible Playbook pgsql.yml 创建数据库集群。
./pgsql.yml -l pg-grafana # 实际执行的等效Ansible剧本命令
定义在 pg_users 与 pg_databases 中的业务用户与业务数据库会在集群初始化时自动创建,因此使用该配置时,集群创建完毕后,(在没有DNS支持的情况下)您可以使用以下连接串访问 数据库(任一即可):
postgres://dbuser_grafana:DBUser.Grafana@10.10.10.11:5432/grafana # 主库直连
postgres://dbuser_grafana:DBUser.Grafana@10.10.10.11:5436/grafana # 直连default服务
postgres://dbuser_grafana:DBUser.Grafana@10.10.10.11:5433/grafana # 连接串读写服务
postgres://dbuser_grafana:DBUser.Grafana@10.10.10.12:5432/grafana # 主库直连
postgres://dbuser_grafana:DBUser.Grafana@10.10.10.12:5436/grafana # 直连default服务
postgres://dbuser_grafana:DBUser.Grafana@10.10.10.12:5433/grafana # 连接串读写服务
因为默认情况下Pigsty安装在单个元节点 上,接下来的步骤我们会在已有的pg-meta数据库集群上创建Grafana所需的用户与数据库,而并非使用这里创建的pg-grafana集群。
创建Grafana业务用户 通常业务对象管理的惯例是:先创建用户,再创建数据库。
因为如果为数据库配置了owner,数据库对相应的用户存在依赖。
定义用户 要在pg-meta集群上创建用户dbuser_grafana,首先将以下用户定义添加至pg-meta的集群定义 中:
添加位置:all.children.pg-meta.vars.pg_users
- name : dbuser_grafana
password : DBUser.Grafana
comment : admin user for grafana database
pgbouncer : true
roles : [ dbrole_admin ]
如果您在这里定义了不同的密码,请在后续步骤中将相应参数替换为新密码
创建用户 使用以下命令完成dbuser_grafana用户的创建(任一均可)。
bin/pgsql-user pg-meta dbuser_grafana # 在pg-meta集群上创建`dbuser_grafana`用户
实际上调用了Ansible Playbook pgsql-createuser.yml 创建用户
./pgsql-user.yml -l pg-meta -e pg_user = dbuser_grafana # Ansible
dbrole_admin 角色具有在数据库中执行DDL变更的权限,这正是Grafana所需要的。
创建Grafana业务数据库 定义数据库 创建业务数据库的方式与业务用户一致,首先在pg-meta的集群定义中添加新数据库grafana的定义 。
添加位置:all.children.pg-meta.vars.pg_databases
- { name: grafana, owner: dbuser_grafana, revokeconn : true }
创建数据库 使用以下命令完成grafana数据库的创建(任一均可)。
bin/pgsql-db pg-meta grafana # 在`pg-meta`集群上创建`grafana`数据库
实际上调用了Ansible Playbook pgsql-createdb.yml 创建数据库
./pgsql-db.yml -l pg-meta -e pg_database = grafana # 实际执行的Ansible剧本
使用Grafana业务数据库 检查连接串可达性 您可以使用不同的服务 或接入 方式访问数据库,例如:
postgres://dbuser_grafana:DBUser.Grafana@meta:5432/grafana # 直连
postgres://dbuser_grafana:DBUser.Grafana@meta:5436/grafana # default服务
postgres://dbuser_grafana:DBUser.Grafana@meta:5433/grafana # primary服务
这里,我们将使用通过负载均衡器直接访问主库的 Default服务 访问数据库。
首先检查连接串是否可达,以及是否有权限执行DDL命令。
psql postgres://dbuser_grafana:DBUser.Grafana@meta:5436/grafana -c \
'CREATE TABLE t(); DROP TABLE t;'
直接修改Grafana配置 为了让Grafana使用 Postgres 数据源,您需要编辑 /etc/grafana/grafana.ini,并修改配置项:
[database]
;type = sqlite3
;host = 127.0.0.1:3306
;name = grafana
;user = root
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
;password =
;url =
将默认的配置项修改为:
[database]
type = postgres
url = postgres://dbuser_grafana:DBUser.Grafana@meta/grafana
随后重启Grafana即可:
systemctl restart grafana-server
从监控系统中看到新增的 grafana 数据库已经开始有活动,则说明Grafana已经开始使用Postgres作为首要后端数据库了。
但一个新的问题是,Grafana中原有的Dashboards与Datasources都消失了!这里需要重新导入监控面板 与Postgres数据源
管理Grafana监控面板 您可以使用管理用户前往 Pigsty 目录下的files/ui目录,执行grafana.py init重新加载Pigsty监控面板。
cd ~/pigsty/files/ui
./grafana.py init # 使用当前目录下的Dashboards初始化Grafana监控面板
执行结果:
vagrant@meta:~/pigsty/files/ui
$ ./grafana.py init
Grafana API: admin:pigsty @ http://10.10.10.10:3000
init dashboard : home.json
init folder pgcat
init dashboard: pgcat / pgcat-table.json
init dashboard: pgcat / pgcat-bloat.json
init dashboard: pgcat / pgcat-query.json
init folder pgsql
init dashboard: pgsql / pgsql-replication.json
init dashboard: pgsql / pgsql-table.json
init dashboard: pgsql / pgsql-activity.json
init dashboard: pgsql / pgsql-cluster.json
init dashboard: pgsql / pgsql-node.json
init dashboard: pgsql / pgsql-database.json
init dashboard: pgsql / pgsql-xacts.json
init dashboard: pgsql / pgsql-overview.json
init dashboard: pgsql / pgsql-session.json
init dashboard: pgsql / pgsql-tables.json
init dashboard: pgsql / pgsql-instance.json
init dashboard: pgsql / pgsql-queries.json
init dashboard: pgsql / pgsql-alert.json
init dashboard: pgsql / pgsql-service.json
init dashboard: pgsql / pgsql-persist.json
init dashboard: pgsql / pgsql-proxy.json
init dashboard: pgsql / pgsql-query.json
init folder pglog
init dashboard: pglog / pglog-instance.json
init dashboard: pglog / pglog-analysis.json
init dashboard: pglog / pglog-session.json
该脚本会侦测当前的环境(安装时定义于~/pigsty),获取Grafana的访问信息,并将监控面板中的URL连接占位符域名(*.pigsty)替换为真实使用的域名。
export GRAFANA_ENDPOINT = http://10.10.10.10:3000
export GRAFANA_USERNAME = admin
export GRAFANA_PASSWORD = pigsty
export NGINX_UPSTREAM_YUMREPO = yum.pigsty
export NGINX_UPSTREAM_CONSUL = c.pigsty
export NGINX_UPSTREAM_PROMETHEUS = p.pigsty
export NGINX_UPSTREAM_ALERTMANAGER = a.pigsty
export NGINX_UPSTREAM_GRAFANA = g.pigsty
export NGINX_UPSTREAM_HAPROXY = h.pigsty
题外话,使用grafana.py clean会清空目标监控面板,使用grafana.py load会加载当前目录下所有监控面板,当Pigsty的监控面板发生变更,可以使用这两个命令升级所有的监控面板。
管理Postgres数据源 当使用 pgsql.yml 创建新PostgreSQL集群,或使用pgsql-createdb.yml 创建新业务数据库时,Pigsty会在Grafana中注册新的PostgreSQL数据源,您可以使用默认的监控用户通过Grafana直接访问目标数据库实例。应用pgcat的绝大部分功能有赖于此。
要注册Postgres数据库,可以使用pgsql.yml 中的register_grafana任务:
./pgsql.yml -t register_grafana # 重新注册当前环境中所有Postgres数据源
./pgsql.yml -t register_grafana -l pg-test # 重新注册 pg-test 集群中所有的数据库
一步到位更新Grafana 您可以直接通过修改Pigsty配置文件,更改Grafana使用的后端数据源,一步到位的完成切换Grafana后端数据库的工作。编辑pigsty.yml中grafana_database 与grafana_pgurl 参数,将其修改为:
grafana_database : postgres
grafana_pgurl : postgres://dbuser_grafana:DBUser.Grafana@meta:5436/grafana
然后重新执行 infral.yml 中的grafana任务,即可完成 Grafana升级
5.9 - 使用 TimescaleDB + Promscale 存储 Prometheus 时序指标数据 您可以通过 Promscale,使用TimescaleDB持久化Prometheus指标数据。
虽然这并不是推荐的行为,但这是了解Pigsty部署系统使用方式的好机会。
注意,使用 Promscale 存储 Prometheus 指标占用的存储空间大约是 Prometheus 的 4 倍,但是可以使用 SQL 来查询分析 Prometheus 监控指标。
准备Postgres数据库 vi pigsty.yml # 取消注释DB/User定义:dbuser_prometheus prometheus
pg_databases: # define business users/roles on this cluster, array of user definition
- { name: prometheus, owner: dbuser_prometheus , revokeconn: true, comment: prometheus primary database }
pg_users: # define business users/roles on this cluster, array of user definition
- { name: dbuser_prometheus , password: DBUser.Prometheus ,pgbouncer: true , createrole: true, roles: [ dbrole_admin] , comment: admin user for prometheus database }
创建 Prometheus 业务数据库与业务用户。
bin/createuser pg-meta dbuser_prometheus
bin/createdb pg-meta prometheus
检查数据库可用性并创建扩展
psql postgres://dbuser_prometheus:DBUser.Prometheus@10.10.10.10:5432/prometheus -c 'CREATE EXTENSION timescaledb;'
配置Promscale 在元节点上执行以下命令安装 promscale
如果默认软件包中没有,可以直接下载:
wget https://github.com/timescale/promscale/releases/download/0.6.1/promscale_0.6.1_Linux_x86_64.rpm
sudo rpm -ivh promscale_0.6.1_Linux_x86_64.rpm
编辑 promscale 的配置文件 /etc/sysconfig/promscale.conf
PROMSCALE_DB_HOST = "127.0.0.1"
PROMSCALE_DB_NAME = "prometheus"
PROMSCALE_DB_PASSWORD = "DBUser.Prometheus"
PROMSCALE_DB_PORT = "5432"
PROMSCALE_DB_SSL_MODE = "disable"
PROMSCALE_DB_USER = "dbuser_prometheus"
最后启动promscale,它会访问安装有 timescaledb 的数据库实例,并创建所需的schema
# launch
cat /usr/lib/systemd/system/promscale.service
systemctl start promscale && systemctl status promscale
配置Prometheus Prometheus可以使用Remote Write/ Remote Read的方式,通过Promscale,使用Postgres作为远程存储。
编辑Prometheus配置文件:
vi /etc/prometheus/prometheus.yml
添加以下记录:
remote_write :
- url : "http://127.0.0.1:9201/write"
remote_read :
- url : "http://127.0.0.1:9201/read"
重启Prometheus后,监控数据即可放入Postgres中。
systemctl restart prometheus
6 - 部署 在严肃生产环境中进行 Pigsty 多节点集群的规划与部署。
生产环境 生产质量的 Pigsty 集群需要规划与准备,如果你的 Pigsty 集群是用来支撑关键业务系统的,
那么请务必使用至少三个节点以实现标准的高可用性。
Pigsty 提供了一个四节点的小型沙箱环境,与一个20节点的大型沙箱环境,用于仿真生产测试。
您可以在单台高规格的笔记本/PC/服务器上运行这些沙箱环境,以便进行功能测试与验证。
生产环境考量 如果您打算在严肃的生产环境中部署 Pigsty,那么通常需要准备至少 3 个节点,使用统一的操作系统,静态网络 IP 地址。
6.1 - 精简安装 只安装高可用 PostgreSQL 集群及其最小依赖的精简安装模式
如果您只想要高可用 PostgreSQL 本身,而不需要监控、基础设施等功能,请考虑精简安装。
没有 INFRA 模块,没有监控,没有 本地仓库 ,只有 ETCD 和 PGSQL 以及部分 NODE 功能
概览 使用精简安装,您需要:
使用 slim.yml 配置模板(configure -c slim) 运行 slim.yml 剧本而不是 install.yml curl https://repo.pigsty.cc/get | bash
./configure -c slim
./slim.yml
精简安装只安装这些核心组件:
组件 必需性 描述 patroni ⚠️ 必需 引导高可用 PostgreSQL 集群 etcd ⚠️ 必需 Patroni 的元数据库依赖(DCS) pgbouncer ✔️ 可选 PostgreSQL 连接池 vip-manager ✔️ 可选 L2 VIP 绑定到 PostgreSQL 集群主节点 haproxy ✔️ 可选 自动路由 服务 chronyd ✔️ 可选 与 NTP 服务器的时间同步 tuned ✔️ 可选 节点调优模板和内核参数管理
您可以关闭可选组件,只有两个必需组件是 patroni 和 etcd。
软件包直接从互联网上游仓库安装,离线安装 在此处不适用。
配置 精简安装的配置文件示例:conf/slim.yml :
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#----------------------------------------------#
# PostgreSQL Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
pg_databases :
- { name: meta, baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ vector ]}
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
vars :
#----------------------------------------------#
# INFRA : https://pigsty.io/docs/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # domain names and upstream servers
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9058" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
#----------------------------------------------#
# NODE : https://pigsty.io/docs/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://pigsty.io/docs/pgsql/param
#----------------------------------------------#
pg_version : 18 # Default PostgreSQL Major Version is 18
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#----------------------------------------------#
# SLIM: https://pigsty.io/docs/setup/slim
#----------------------------------------------#
nginx_enabled : false # nginx not exists
dns_enabled : false # dnsmasq not exists
prometheus_enabled : false # prometheus not exists
grafana_enabled : false # grafana not exists
pg_exporter_enabled : false # disable pg_exporter
pgbouncer_exporter_enabled : false # disable pgbouncer_exporter
pgbackrest_exporter_enabled : false # disable pgbackrest_exporter
pg_vip_enabled : false # disable pg_vip
安装 使用 slim.yml 剧本而不是 install.yml 剧本:
不要使用 install.yml 进行精简安装
这个 slim.yml 剧本是专门用来在精简安装场景中取代默认 install.yml 剧本的。
6.2 - 声明配置 使用声明式的配置来描述数据库集群与基础设施
Pigsty将基础设施和数据库视为代码 :Database as Code & Infra as Code
你可以通过声明式的接口/配置文件来描述基础设施和数据库集群,你只需在 配置清单 (Inventory) 中描述你的需求,然后用简单的幂等剧本使其生效即可。
配置清单 每一套 Pigsty 部署都有一个相应的 配置清单 (Inventory)。它可以以 YAML 的形式存储在本地,
并使用 git 管理;或从 CMDB 或任何 ansible 兼容的方式动态生成。
Pigsty 默认使用一个名为 pigsty.yml 的单体 YAML 配置文件作为默认的配置清单,
它位于 Pigsty 源码主目录下,但你也可以通过命令行参数 -i 指定路径以使用别的配置清单。
清单由两部分组成:全局变量 (all.vars)和多个 组定义 (all.children) 。 前者 all.vars 通常用于描述基础设施,并为集群设置全局默认参数。后者 all.children 则负责定义新的集群(PGSQL/Redis/MinIO/ETCD等等)。一个配置清单文件从最顶层来看大概如下所示:
all : # 顶层对象:all
vars : {...} # 全局参数
children : # 组定义
infra : # 组定义:'infra'
hosts : {...} # 组成员:'infra'
vars : {...} # 组参数:'infra'
etcd : {...} # 组定义:'etcd'
pg-meta : {...} # 组定义:'pg-meta'
pg-test : {...} # 组定义:'pg-test'
redis-test : {...} # 组定义:'redis-test'
# ...
集群 每个组定义通常代表一个集群,可以是节点集群、PostgreSQL 集群、Redis 集群、Etcd 集群或 Minio 集群等。它们都使用相同的格式:hosts 和 vars。
你可以用 all.children.<cls>.hosts 定义集群成员,并使用 all.children.<cls>.vars 中的集群参数描述集群。以下是名为 pg-test 的三节点 PostgreSQL 高可用集群的定义示例:
pg-test : # 集群名称
vars : # 集群参数
pg_cluster : pg-test
hosts : # 集群成员
10.10.10.11 : { pg_seq: 1, pg_role : primary } # 实例1,在 10.10.10.11 上,主库
10.10.10.12 : { pg_seq: 2, pg_role : replica } # 实例2,在 10.10.10.12 上,从库
10.10.10.13 : { pg_seq: 3, pg_role : offline } # 实例3,在 10.10.10.13 上,从库
你也可以为特定的主机/实例定义参数,也称为实例参数。它将覆盖集群参数和全局参数,实例参数通常用于为节点和数据库实例分配身份(实例号,角色)。
参数 全局变量、组变量和主机变量都是由一系列 键值对 组成的字典对象。每一对都是一个命名的参数,由一个字符串名作为键,和一个值组成。值是五种类型之一:布尔值、字符串、数字、数组或对象。查看配置参数 以了解详细的参数语法语义。
绝大多数参数都有着合适的默认值,身份参数 除外;它们被用作标识符,并必须显式配置,例如 pg_cluster , pg_role ,以及 pg_seq 。
参数可以被更高优先级的同名参数定义覆盖,优先级如下所示:
命令行参数 > 剧本变量 > 主机变量(实例参数) > 组变量(集群参数) > 全局变量(全局参数) > 默认值
例如:
使用命令行参数 -e pg_clean=true 强制删除现有数据库 使用实例参数 pg_role 和 pg_seq 来为一个数据库实例分配角色与标号。 使用集群变量来为集群设置默认值,如集群名称 pg_cluster 和数据库版本 pg_version 使用全局变量为所有 PGSQL 集群设置默认值,如使用的默认参数和插件列表 如果没有显式配置 pg_version ,默认值 18 版本号会作为最后兜底的缺省值。 模板 在 Pigsty 目录中的 conf/ 目录里,提供了针对许多不同场景的预置配置模板可供参考选用。
在 configure 过程中,您可以通过 -c 参数指定模板。否则会默认使用单节点安装的 meta 模板。
关于这些模版的功能,请参考 配置模板 中的介绍。
切换配置源 要使用不同的配置模板,您可以将模板的内容复制到 Pigsty 源码目录的 pigsty.yml 文件中,并按需进行相应调整。
您也可以在执行 Ansible 剧本时,通过 -i 命令行参数,显式指定使用的配置文件,例如:
./node.yml -i files/pigsty/rpmbuild.yml # 根据 rpmbuild 配置文件,初始化目标节点,而不是使用默认的 pigsty.yml 配置文件
如果您希望修改默认的配置文件名称与位置,您也可以修改源码根目录下的 ansible.cfg 的 inventory 参数,将其指向您的配置文件路径,这样您就可以直接执行 ansible-playbook 命令而无需显式指定 -i 参数。
Pigsty 允许您使用数据库(CMDB)作为动态配置源,而不是使用静态配置文件。 Pigsty 提供了三个便利脚本:
参考 Pigsty 带有 280+ 配置参数,分为以下32个参数组,详情请参考 配置参数 。
6.3 - 准备工作 如何准备部署 Pigsty 所需的节点,操作系统,管理员用户,端口,与所需权限。
与 Pigsty 部署有关的 101 入门知识。
节点准备 Pigsty 支持 Linux 内核与 x86_64/amd64 架构,适用于任意节点。
所谓节点(node),指 ssh 可达并提供裸操作系统环境的资源,例如物理机,裸金属,虚拟机,或者启用了 systemd 与 sshd 的操作系统容器。
部署 Pigsty 最少需要一个节点。最低配置要求为 1C1G,推荐至少使用 2C4G 以上的机型,适用配置上不封顶,参数会自动优化适配。
作为 Demo,个人站点,或者开发环境时,可以使用单个节点。作为独立监控基础设施使用时,建议使用 1-2 个节点,作为高可用 PostgreSQL 数据库集群使用时,建议至少使用 3 个节点。用于核心场景时,建议使用至少 4-5 个节点。
充分利用 IaC 工具完成琐事
手工配置大规模生产环境繁琐且容易出错,我们建议您充分利用 Infra as Code 工具,解决此类问题。
您可以使用 Pigsty 提供的 Terraform 模板与 Vagrant 模板,使用 IaC 的方式一键创建所需的节点环境,完成好网络,操作系统,管理用户,权限,安全组的置备工作。
网络准备 Pigsty 要求节点使用 静态IPv4地址 ,即您应当为节点显式分配指定固定的 IP 地址,而不应当使用 DHCP 动态分配的地址。
节点使用的 IP 地址应当是节点用于内网通信的首要 IP 地址,并将作为节点的唯一身份标识符。
如果您希望使用可选的 Node VIP 与 PG VIP 功能,应当确保所有节点位于一个大二层网络中。
您的防火墙策略应当保证所需的端口在节点间开放,不同模块所需的具体端口列表请参考 节点:端口 。
应该暴露哪些端口?
暴露端口的方法取决于您的网络安全策略实现,例如:公有云上的安全组策略,或本地 iptables 记录,防火墙配置等。
如果您只是希望尝尝鲜,不在乎安全,并且希望一切越简单越好,那么您可以仅对外部用户按需开放 5432 端口( PostgreSQL 数据库) 与 3000 端口(Grafana 可视化界面)。
在 Infra节点 上的 Nginx 默认会对外暴露 80/443 端口提供 Web 服务,并通过域名对不同服务进行区分,这一端口应当对办公网络(或整个整个互联网)开放。
严肃的生产数据库服务端口通常不应当直接暴露在公网上,如果您确实需要这么做,建议首先查阅 安全最佳实践 ,并小心行事。
操作系统准备 Pigsty 支持多种基于 Linux 内核的服务器操作系统发行版,我们建议使用 RockyLinux 9.6 、Ubuntu 24.04.2 或 Debian 12.11 作为安装 Pigsty 的 OS。
Pigsty 支持 RHEL (7,8,9,10),Debian (11,12,13),Ubuntu (20,22,24) 以及多种与之兼容的操作系统发行版,完整操作系统列表请参考 兼容性 。
在使用多个节点镜进行部署时,我们 强烈 建议您在所有用于 Pigsty 部署的节点上,使用相同版本 的操作系统发行版与 Linux 内核版本
我们强烈建议使用干净,全新安装的最小化安装的服务器操作系统环境 ,并使用 en_US 作为首要语言。
如何安装并启用 en_US locale?
使用其他系统语言包时,如何确保 en_US 本地化规则集可用:
yum install -y glibc-locale-source glibc-langpack-en
localedef -i en_US -f UTF-8 en_US.UTF-8
localectl set-locale LANG = en_US.UTF-8
注:Pigsty 部署的 PostgreSQL 集群默认使用 C.UTF8 locale,但字符集定义使用 en_US 以确保 pg_trgm 扩展可以正常工作。
如果您确实不需要此功能,可以配置 pg_lc_ctype 的值为 C.UTF8 ,以避免在系统语言包缺失的情况下,数据库初始化报错的问题。
管理用户准备 在安装 Pigsty 的节点上,您需要拥有一个 “管理用户 ” —— 拥有免密 ssh 登陆权限与免密 sudo 权限。
免密 sudo 是必选项,用于在安装过程中执行需要 sudo 权限的命令,例如安装软件包,配置系统参数等。
如何配置管理用户的免密码 sudo 权限?
假设您的管理用户名为 vagrant ,则可以创建 /etc/sudoers.d/vagrant 文件,并添加以下记录:
%vagrant ALL =( ALL) NOPASSWD: ALL
则 vagrant 用户即可免密 sudo 执行所有命令。如果你的用户名不是 vagrant,请将上面操作中的 vagrant 替换为您的用户名。
避免使用 root 用户安装
尽管使用 root 用户安装 Pigsty 是可行的,但我们不推荐这样做。
安全最佳实践 是使用一个不同于根用户(root)与数据库超级用户 (postgres) 的专用管理员用户(如:dba)
Pigsty 提供了专用剧本任务,可以使用一个现有的管理用户(例如 root),输入 ssh/sudo 密码,创建一个专用的 管理员用户 。
SSH 权限准备 除了免密 sudo 权限, Pigsty 还需要管理用户免密 ssh 登陆的权限。
对于单机安装 的节点而言,这意味着本机上的管理用户可以通过 ssh 免密码登陆到本机上。
如果的 Pigsty 部署涉及到多个节点,这意味着管理节点 上的管理用户应当可以通过 ssh 免密码登陆到所有被 Pigsty 纳管的节点上(包括本机),并免密执行 sudo 命令。
单机安装时,在 configure 过程中,如果您的当前管理用户没有 SSH key,Pigsty 会尝试修复此问题:随机生成一对新的 id_rsa 密钥,并添加至本地 ~/.ssh/authroized_keys 文件确保本机管理用户的 SSH 登陆能力。
Pigsty 默认会为您在纳管的节点上创建一个可用的管理用户 dba (uid=88),如果您已经使用了此用户,我们建议您修改 node_admin_username 使用新的用户名与其他 uid,或通过 node_admin_enabled 参数禁用。
如何配置管理用户的 ssh 免密码登陆?
假设您的管理用户名为 vagrant,则以 vagrant 用户身份执行以下命令,会为其生成公私钥对 ~/.ssh/id_rsa[.pub] 用于登陆。如果已经存在公私钥对,则无需生成新密钥对。
ssh-keygen -t rsa -b 2048 -N '' -f ~/.ssh/id_rsa -q
生成的公钥默认位于:/home/vagrant/.ssh/id_rsa.pub,私钥默认位于:/home/vagrant/.ssh/id_rsa,如果您操作系统用户名不叫 vagrant,将上面的 vagrant 替换为您的用户名即可。
您应当将公钥文件(id_rsa.pub)追加写入到需要登陆机器的对应用户上:/home/vagrant/.ssh/authorized_keys 文件中。如果您已经可以直接通过密码访问远程机器,可以直接通过ssh-copy-id的方式拷贝公钥:
ssh-copy-id <ip> # 输入密码以完成公钥拷贝
sshpass -p <password> ssh-copy-id <ip> # 直接将密码嵌入命令中,避免交互式密码输入(注意安全!)
Pigsty 推荐将管理用户的创建,权限配置与密钥分发放在虚拟机的置备阶段完成,作为标准化交付内容的一部分。
SSH 例外情况 如果您的 SSH 访问有一些额外限制,例如,使用了跳板机,或者进行了某些定制化修改,无法通过简单的 ssh <ip> 方式访问,那么可以考虑使用 ssh 别名。
例如,如果您的服务器可以通过 ~/.ssh/config 中定义的别名,例如 meta 通过 ssh 访问,那么可以为 配置清单 中的节点配置 ansible_host 参数,指定 SSH Alias:
nodes :
hosts : # 10.10.10.10 无法直接 ssh,但可以通过ssh别名 `meta` 访问
10.10.10.10 : { ansible_host : meta }
如果 SSH 别名无法满足您的需求,Ansible 还提供了一系列自定义 ssh 连接参数 ,可以精细控制 SSH 连接的行为。
最后,如果以下命令可以在管理节点上使用管理用户成功执行,意味着该目标节点上的管理用户与权限配置已经妥当:
软件准备 在 管理节点 上,Pigsty 需要使用 Ansible 发起控制命令。如果您使用本地单机安装,那么管理节点和被管理的节点是同一台,需要安装 Ansible。对于普通节点,则无需安装 Ansible。
在 bootstrap 过程中,Pigsty 会尽最大努力自动为您完成安装 Ansible 这一任务,但您也可以选择手工安装 Ansible。手工安装 Ansible 的过程因不同操作系统发行版/大版本而异(通常涉及到额外的弱依赖 jmespath):
安装 Ansible
EL 8 / 9
EL 7
Debian / Ubuntu
MacOS sudo dnf install -y ansible python3.12-jmespath python3-cryptography sudo yum install -y ansible # EL7 无需显式安装 Jmespath sudo apt install -y ansible python3-jmespath 为了安装 Pigsty,您还需要准备 Pigsty 源码包。您可以直接从 GitHub Release 页面下载特定版本,或使用以下命令获取最新稳定版本:
curl -fsSL https://repo.pigsty.cc/get | bash
如果您的环境没有互联网访问,也可以考虑直接从 GitHub Release 页面或其他渠道下载针对不同操作系统发行版预先制作的 离线安装包 。
6.4 - 执行剧本 Pigsty 使用 Ansible 剧本来实现所需的安装部署管理功能,但如果只是使用的话,您并不需要了解太多细节。
在 Pigsty 中,剧本 / Playbooks 用于在节点上安装模块 。
剧本可以视作可执行文件直接执行,例如:./install.yml.
剧本 以下是 Pigsty 中默认包含的剧本:
一次性安装 特殊的剧本 install.yml 实际上是一个复合剧本,它在当前环境上安装所有以下组件。
playbook / command / group infra nodes etcd minio pgsql
[ infra.yml] ./infra.yml [ -l infra] [ +infra][ +node]
[ node.yml] ./node.yml [ +node] [ +node] [ +node] [ +node]
[ etcd.yml] ./etcd.yml [ -l etcd ] [ +etcd]
[ minio.yml] ./minio.yml [ -l minio] [ +minio]
[ pgsql.yml] ./pgsql.yml [ +pgsql]
请注意,NODE 和 INFRA 之间存在循环依赖:为了在 INFRA 上注册 NODE,INFRA 应该已经存在,而 INFRA 模块依赖于 INFRA节点上的 NODE 模块才能工作。
为了解决这个问题,INFRA 模块的安装剧本也会在 INFRA 节点上安装 NODE 模块。所以,请确保首先初始化 INFRA 节点。
如果您非要一次性初始化包括 INFRA 在内的所有节点,install.yml 剧本就是用来解决这个问题的:它会正确的处理好这里的循环依赖,一次性完成整个环境的初始化。
Ansible 执行剧本需要 ansible-playbook 可执行文件,该文件包含在 ansible rpm/deb 包中。
Pigsty 将在 准备 期间在尽最大努力尝试在当前节点安装 ansible。
您可以自己使用 yum / apt / brew install ansible 来安装 Ansible,它含在各大发行版的默认仓库中。
了解 ansible 对于使用 Pigsty 很有帮助,但也不是必要的。对于基本使用,您只需要注意四个参数就足够了:
-i|--inventory <path> :显式指定使用的配置文件-l|--limit <pattern> : 限制剧本在特定的组/主机/模式上执行目标(在哪里/Where)-t|--tags <tags> : 只运行带有特定标签的任务(做什么/What)-e|--extra-vars <vars> : 传递额外的命令行参数(怎么做/How)指定配置文件 您可以使用 -i 命令行参数,显式指定使用的配置文件。
Pigsty 默认使用名为 pigsty.yml 配置文件,该文件位于 Pigsty 源码根目录中的 pigsty.yml。但您可以使用 -i 覆盖这一行为,例如:
./node.yml -i files/pigsty/rpmbuild.yml # 根据 rpmbuild 配置文件,初始化目标节点,而不是使用默认的 pigsty.yml 配置文件
./pgsql.yml -i files/pigsty/rpm.yml # 根据 files/pigsty/rpm.yml 配置文件中的定义,在目标节点上安装 pgsql 模块
./redis.yml -i files/pigsty/redis.yml # 根据 files/pigsty/redis.yml 配置文件中的定义,在目标节点上安装 redis 模块
如果您希望永久修改默认使用的配置文件,可以修改源码根目录下的 ansible.cfg 的 inventory 参数,将其指向您的配置文件路径。
这样您就可以在执行 ansible-playbook 命令时无需显式指定 -i 参数了。
指定执行对象 您可以使用 -l|-limit <selector> 限制剧本的执行目标。
缺少此值可能很危险,因为大多数剧本会在 all 分组,也就是所有主机上执行,使用时务必小心。
以下是一些主机限制的示例:
./pgsql.yml # 在所有主机上运行(非常危险!)
./pgsql.yml -l pg-test # 在 pg-test 集群上运行
./pgsql.yml -l 10.10.10.10 # 在单个主机 10.10.10.10 上运行
./pgsql.yml -l pg-* # 在与通配符 `pg-*` 匹配的主机/组上运行
./pgsql.yml -l '10.10.10.11,&pg-test' # 在组 pg-test 的 10.10.10.10 上运行
/pgsql-rm.yml -l 'pg-test,!10.10.10.11' # 在 pg-test 上运行,除了 10.10.10.11 以外
./pgsql.yml -l pg-test # 在 pg-test 集群的主机上执行 pgsql 剧本
执行剧本子集 你可以使用 -t|--tags <tag> 执行剧本的子集。 你可以在逗号分隔的列表中指定多个标签,例如 -t tag1,tag2。
如果指定了任务子集,将执行给定标签的任务,而不是整个剧本。以下是任务限制的一些示例:
./pgsql.yml -t pg_clean # 如果必要,清理现有的 postgres
./pgsql.yml -t pg_dbsu # 为 postgres dbsu 设置操作系统用户 sudo
./pgsql.yml -t pg_install # 安装 postgres 包和扩展
./pgsql.yml -t pg_dir # 创建 postgres 目录并设置 fhs
./pgsql.yml -t pg_util # 复制工具脚本,设置别名和环境
./pgsql.yml -t patroni # 使用 patroni 引导 postgres
./pgsql.yml -t pg_user # 提供 postgres 业务用户
./pgsql.yml -t pg_db # 提供 postgres 业务数据库
./pgsql.yml -t pg_backup # 初始化 pgbackrest 仓库和 basebackup
./pgsql.yml -t pgbouncer # 与 postgres 一起部署 pgbouncer sidecar
./pgsql.yml -t pg_vip # 使用 vip-manager 将 vip 绑定到 pgsql 主库
./pgsql.yml -t pg_dns # 将 dns 名称注册到 infra dnsmasq
./pgsql.yml -t pg_service # 使用 haproxy 暴露 pgsql 服务
./pgsql.yml -t pg_exporter # 使用 haproxy 暴露 pgsql 服务
./pgsql.yml -t pg_register # 将 postgres 注册到 pigsty 基础设施
# 运行多个任务:重新加载 postgres 和 pgbouncer hba 规则
./pgsql.yml -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload
# 运行多个任务:刷新 haproxy 配置并重新加载
./node.yml -t haproxy_config,haproxy_reload
传递额外参数 您可以通过 -e|-extra-vars KEY=VALUE 传递额外的命令行参数。
命令行参数具有压倒性的优先级,以下是一些额外参数的示例:
./node.yml -e ansible_user = admin -k -K # 作为另一个用户运行剧本(带有 admin sudo 密码)
./pgsql.yml -e pg_clean = true # 在初始化 pgsql 实例时强制清除现有的 postgres
./pgsql-rm.yml -e pg_uninstall = true # 在 postgres 实例被删除后明确卸载 rpm
./redis.yml -l 10.10.10.11 -e redis_port = 6379 -t redis # 初始化一个特定的 redis 实例:10.10.10.11:6379
./redis-rm.yml -l 10.10.10.13 -e redis_port = 6379 # 删除一个特定的 redis 实例:10.10.10.11:6379
此外,您还可以通过 JSON 的方式,传递诸如数组与对象这样的复杂参数:
# 通过指定软件包与仓库模块,在节点上安装 duckdb
./node.yml -t node_repo,node_pkg -e '{"node_repo_modules":"infra","node_default_packages":["duckdb"]}'
大多数剧本都是幂等的,这意味着在未打开保护选项的情况下,一些部署剧本可能会 删除现有的数据库 并创建新的数据库。
请仔细阅读文档,多次校对命令,并小心操作。作者不对因误用造成的任何数据库损失负责 。
6.5 - 置备机器 介绍 Pigsty 演示所使用的标准四节点沙箱环境,以及如何使用 Vagrant 与 Terraform 置备所需的虚拟机。
Pigsty 在节点上运行,这些节点可以是裸机或虚拟机。您可以手工置备它们,或使用 terraform 和 vagrant 这样的工具在云端或本地进行自动配置。
沙箱环境 Pigsty 带有一个演示沙箱,所谓沙箱,就是专门用来演示/测试的环境:IP地址和其他标识符都预先固定配置好,便于复现各种演示用例。
默认的沙箱环境由4个节点组成,配置文件请参考 full.yml 。
沙箱的 4 个节点有着固定的 IP 地址:10.10.10.10、10.10.10.11、10.10.10.12、10.10.10.13。
沙箱带有一个位于 meta 节点上的单实例 PostgreSQL 集群:pg-meta:
meta 10.10.10.10 pg-meta pg-meta-1沙箱中还有一个由三个实例组成的 PostgreSQL 高可用集群:pg-test,部署在另外三个节点上:
node-1 10.10.10.11 pg-test.pg-test-1node-2 10.10.10.12 pg-test.pg-test-2node-3 10.10.10.13 pg-test.pg-test-3两个可选的 L2 VIP 分别绑定在 pg-meta 和 pg-test 集群的主实例上:
10.10.10.2 pg-meta10.10.10.3 pg-test在 meta 节点上,还有一个单实例的 etcd “集群”和一个单实例的 minio “集群”。
您可以在本地虚拟机或云虚拟机上运行沙箱。Pigsty 提供基于 Vagrant 的本地沙箱(使用 Virtualbox/libvirt 启动本地虚拟机)以及基于 Terraform 的云沙箱(使用云供应商 API 创建虚拟机)。
此外,Pigsty 还提供了一个 42节点 的生产仿真环境沙箱 prod.yml 。
Vagrant Vagrant 可以按照声明式的方式创建本地虚拟机。请查看 Vagrant 模板介绍 以获取详情。
安装 确保您的操作系统中已经安装并可以使用 Vagrant 和 Virtualbox 。
如果您使用的是 macOS,您可以使用 homebrew 一键命令安装它们,注意安装 Virtualbox 后需要重启系统。
如果你用的是 Linux,可以使用 virtualbox,也可以考虑使用 KVM: vagrant-libvirt 。
/bin/bash -c " $( curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh) "
brew install vagrant virtualbox ansible # 在 MacOS 中可以轻松一键安装,但只有 x86_64 Intel 芯片的可以
配置 vagarnt/Vagranfile 是一个 Ruby 脚本文件,用来描述 Vagrant 要创建的虚拟机节点。Pigsty 提供了一些默认的配置模板:
模板 快捷方式 规格 注释 meta.rb v14C8G x 1 单一 Meta 节点 full.rb v42C4G + 1C2G x 3 完整的4节点沙盒示例 el7.rb v72C4G + 1C2G x 3 EL7 3-节点测试环境 el8.rb v82C4G + 1C2G x 3 EL8 3-节点测试环境 el9.rb v92C4G + 1C2G x 3 EL9 3-节点测试环境 build.rb vb2C4G x 3 3-节点 EL7,8,9 构建环境 check.rb vc2C4G x 30 30 EL7-9, PG12-16 测试环境 minio.rb vm2C4G x 3 + Disk 3-节点 MinIO/etcd 测试环境 prod.rb vp2C4G x 42 42节点的生产模拟环境
每个规格文件包含一个描述虚拟机节点的 Specs 变量。例如,full.rb 包含4节点沙盒规格的描述:
Specs = [
{ "name" => "meta" , "ip" => "10.10.10.10" , "cpu" => "2" , "mem" => "4096" , "image" => "generic/rocky9" },
{ "name" => "node-1" , "ip" => "10.10.10.11" , "cpu" => "1" , "mem" => "2048" , "image" => "generic/rocky9" },
{ "name" => "node-2" , "ip" => "10.10.10.12" , "cpu" => "1" , "mem" => "2048" , "image" => "generic/rocky9" },
{ "name" => "node-3" , "ip" => "10.10.10.13" , "cpu" => "1" , "mem" => "2048" , "image" => "generic/rocky9" },
]
您可以使用 vagrant/config 脚本切换 Vagrant 配置文件,它会根据规格以及虚拟机软件类型,渲染生成最终的 Vagrantfile。
cd ~/pigsty
vagrant/config <spec>
vagrant/config meta # singleton meta | 别名:`make v1`
vagrant/config full # 4-node sandbox | 别名:`make v4`
vagrant/config el7 # 3-node el7 test | 别名:`make v7`
vagrant/config el8 # 3-node el8 test | 别名:`make v8`
vagrant/config el9 # 3-node el9 test | 别名:`make v9`
vagrant/config prod # prod simulation | 别名:`make vp`
vagrant/config build # building environment | 别名:`make vd`
vagrant/config minio # 3-node minio env
vagrant/config check # 30-node check env
虚拟机管理 当您使用 vagrant/Vagrantfile 描述了所需的虚拟机后,你可以使用vagrant up命令创建这些虚拟机。
Pigsty 模板默认会使用你的 ~/.ssh/id_rsa[.pub] 作为这些虚拟机的默认ssh凭证。
在开始之前,请确保你有一个有效的ssh密钥对,你可以通过以下方式生成一对:ssh-keygen -t rsa -b 2048
此外,还有一些 makefile 快捷方式包装了 vagrant 命令,你可以使用它们来管理虚拟机。
make # 等于 make start
make new # 销毁现有虚拟机,根据规格创建新的
make ssh # 将 SSH 配置写入到 ~/.ssh/ 中 (新虚拟机拉起后必须完成这一步)
make dns # 将 虚拟机 DNS 记录写入到 /etc/hosts 中 (如果想使用名称访问虚拟机)
make start # 等于先执行 up ,再执行 ssh
make up # 根据配置拉起虚拟机,或启动现有虚拟机
make halt # 关停现有虚拟机 (down,dw)
make clean # 销毁现有虚拟机 (clean/del/destroy)
make status # 显示虚拟机状态 (st)
make pause # 暂停虚拟机运行 (suspend,pause)
make resume # 恢复虚拟机运行 (resume)
make nuke # 使用 virsh 销毁所有虚拟机 (仅libvirt可用)
快捷方式 你可以使用以下的 Makefile 快捷方式使用 vagrant 拉起虚拟机环境。
make meta # 单个元节点
make full # 4-节点沙箱
make el7 # 3-节点 el7 测试环境
make el8 # 3-节点 el8 测试环境
make el9 # 3-节点 el9 测试环境
make prod # 42 节点生产仿真环境
make build # 3-节点 EL7,8,9 构建环境
make check # 30-节点构建校验测试环境
make minio # 3-节点 MinIO 测试环境
make meta install # 进行完整的单机安装
make full install # 进行4节点沙箱安装
make prod install # 进行42节点生产仿真环境安装
make check install # 进行30节点本地测试环境安装
...
Terraform 是一个开源的实践“基础设施即代码”的工具:描述你想要的云资源,然后一键创建它们。
Pigsty 提供了 AWS,阿里云,腾讯云的 Terraform 模板,您可以使用它们在云上一键创建虚拟机。
在 MacOS 上,Terraform 可以使用 homebrew 一键安装:brew install terraform。你需要创建一个云帐户,获取 AccessKey 和 AccessSecret 凭证来继续下面的操作。
terraform/目录包含两个示例模板:一个 AWS 模板,一个阿里云模板,你可以按需调整它们,或者作为其他云厂商配置文件的参考,让我们用阿里云为例:
cd terraform # 进入 Terraform 模板目录
cp spec/alicloud.tf terraform.tf # 使用 阿里云 Terraform 模板
在执行 terraform apply 拉起虚拟机之前,你要执行一次 terraform init 安装相应云厂商的插件。
terraform init # 安装 terraform 云供应商插件:例如默认的 aliyun 插件 (第一次使用时安装即可)
terraform apply # 生成执行计划,显示会创建的云资源:虚拟机,网络,安全组,等等等等……
运行 apply 子命令并按提示回答 yes 后,Terraform 将为你创建虚拟机以及其他云资源(网络,安全组,以及其他各种玩意)。
执行结束时,管理员节点的IP地址将被打印出来,你可以登录并开始完成 Pigsty 本身的安装
6.6 - 安全考量 Pigsty部署中与安全有关的考量
Pigsty 的默认配置已经足以覆盖绝大多数场景对于安全的需求。
Pigsty 已经提供了开箱即用的认证 与访问控制 模型,对于绝大多数场景已经足够安全。
如果您希望进一步加固系统的安全性,那么以下建议供您参考:
机密性 重要文件 保护你的 pigsty.yml 配置文件或CMDB
pigsty.yml 配置文件通常包含了高度敏感的机密信息,您应当确保它的安全。严格控制管理节点的访问权限,仅限 DBA 或者 Infra 管理员访问。 严格控制 pigsty.yml 配置文件仓库的访问权限(如果您使用 git 进行管理) 保护你的 CA 私钥和其他证书,这些文件非常重要。
相关文件默认会在管理节点Pigsty源码目录的 files/pki 内生成。 你应该定期将它们备份到一个安全的地方存储。 密码 在生产环境部署时,必须更改这些密码,不要使用默认值!
如果您使用MinIO,请修改MinIO的默认用户密码,与pgbackrest中的引用
如果您使用远程备份仓库,请务必启用备份加密,并设置加解密密码
为 PostgreSQL 使用安全可靠的密码加密算法
使用 pg_pwd_enc 默认值 scram-sha-256 替代传统的 md5 这是默认行为,如果没有特殊理由(出于对历史遗留老旧客户端的支持),请不要将其修改回 md5 使用 passwordcheck 扩展强制执行强密码 。
在 pg_libs 中添加 $lib/passwordcheck 来强制密码策略。 使用加密算法加密远程备份
为业务用户配置密码自动过期实践
不要将更改密码的语句记录到 postgres 日志或其他日志中
SET log_statement TO 'none' ;
ALTER USER "{{ user.name }}" PASSWORD '{{ user.password }}' ;
SET log_statement TO DEFAULT;
IP地址 为 postgres/pgbouncer/patroni 绑定指定的 IP 地址,而不是所有地址。
默认的 pg_listen 地址是 0.0.0.0,即所有 IPv4 地址。 考虑使用 pg_listen: '${ip},${vip},${lo}' 绑定到特定IP地址(列表)以增强安全性。 不要将任何端口直接暴露到公网IP上,除了基础设施出口Nginx使用的端口(默认80/443)
出于便利考虑,Prometheus/Grafana 等组件默认监听所有IP地址,可以直接从公网IP端口访问 您可以修改它们的配置文件,只监听内网IP地址,限制其只能通过 Nginx 门户通过域名访问,你也可以当使用安全组,防火墙规则来实现这些安全限制。 出于便利考虑,Redis服务器默认监听所有IP地址,您可以修改 redis_bind_address 只监听内网IP地址。 使用 HBA 限制 postgres 客户端访问
限制 patroni 管理访问权限:仅 infra/admin 节点可调用控制API
网络流量 使用 SSL 和域名,通过Nginx访问基础设施组件
使用 SSL 保护 Patroni REST API
使用 SSL 保护 Pgbouncer 客户端流量
完整性 为关键场景下的 PostgreSQL 数据库集群配置一致性优先模式(例如与钱相关的库)
pg_conf 数据库调优模板,使用 crit.yml 将以一些可用性为代价,换取最佳的数据一致性。使用crit节点调优模板,以获得更好的一致性。
node_tune 主机调优模板使用 crit ,可以以减少脏页比率,降低数据一致性风险。启用数据校验和,以检测静默数据损坏。
记录建立/切断连接的日志
该配置默认关闭,但在 crit.yml 配置模板中是默认启用的。 可以手工配置集群 ,启用 log_connections 和 log_disconnections 功能参数。 如果您希望彻底杜绝PG集群在故障转移时脑裂的可能性,请启用watchdog
如果你的流量走默认推荐的 HAProxy 分发,那么即使你不启用 watchdog,你也不会遇到脑裂的问题。 如果你的机器假死,Patroni 被 kill -9 杀死,那么 watchdog 可以用来兜底:超时自动关机。 最好不要在基础设施节点上启用 watchdog。 可用性 对于关键场景的PostgreSQL数据库集群,请使用足够的节点/实例数量
你至少需要三个节点(能够容忍一个节点的故障)来实现生产级的高可用性。 如果你只有两个节点,你可以容忍特定备用节点的故障。 如果你只有一个节点,请使用外部的 S3/MinIO 进行冷备份和 WAL 归档存储。 对于 PostgreSQL,在可用性和一致性之间进行权衡
不要直接通过固定的 IP 地址访问数据库;请使用 VIP、DNS、HAProxy 或它们的排列组合
使用 HAProxy 进行服务接入 在故障切换/主备切换的情况下,Haproxy 将处理客户端的流量切换。 在重要的生产部署中使用多个基础设施节点(例如,1~3)
小规模部署或要求宽松的场景,可以使用单一基础设施节点 / 管理节点。 大型生产部署建议设置至少两个基础设施节点互为备份。 使用足够数量的 etcd 服务器实例,并使用奇数个实例(1,3,5,7)
6.7 - 常见问题 Pigsty 下载,安装,部署常见问题答疑
这里列出了Pigsty用户在下载、安装、部署时常遇到的问题,如果您遇到了难以解决的问题,可以提交 Issue 或者联系我们 。
如何获取Pigsty软件源码包? 使用以下命令一键安装 Pigsty: curl -fsSL https://repo.pigsty.cc/get | bash
上述命令会自动下载最新的稳定版本 pigsty.tgz 并解压到 ~/pigsty 目录。您也可以从以下位置手动下载 Pigsty 源代码的特定版本。
如果您需要在没有互联网的环境中安装,可以提前在有网络的环境中下载好,并通过 scp/sftp 或者 CDROM/USB 传输至生产服务器。
如何加速从上游仓库下载 RPM ? 考虑使用本地仓库镜像,仓库镜像在repo_upstream 参数中配置,你可以选择 region 来使用不同镜像站。
例如,您可以设置 region = china,这样将使用 baseurl 中键为 china 的 URL 而不是 default。
如果防火墙或GFW屏蔽了某些仓库,考虑使用proxy_env 来绕过。
安装失败应该如何解决? Pigsty 不依赖 Docker,所以期待的环境是一个全新安装操作系统后的状态,如果您使用已经跑了千奇百怪服务的系统,更容易遇到疑难杂症,我们建议不要这么做。
出现安装失败时,可以按照以下思路进行排查:
您应当确认当前失败的位置在哪个模块,不同模块失败有不同的原因。您应当保留 Ansible 剧本输出结果备用,并找到所有标红的 Failed 任务。 如果出现无法识别配置,剧本直接无法开始,请检查您的配置文件是否是合法的 YAML,缩进,括号等是否有问题。 如果错误与本地软件源,Nginx 有关,请检查你的系统是不是全新系统,是否已经运行了 Nginx 或其他组件?或者是否有特殊的防火墙与安全策略在运作? 如果是安装节点软件包时出现错误,您是否使用了OS小版本精确匹配的离线软件包?上游是否出现依赖错漏?请参考下面的内容解决 如果是系统配置出现错误,您的操作系统是否是全新安装的状态?或者 —— 精简安装到了 Locale 都没有配置的状态? 如果是 MinIO 出现问题,您是否使用了 SNMD,MNMD 部署却没有提供真实的磁盘挂载点?您的 sss.pigsty 静态域名是否指向了任意 MinIO 节点或 LB 集群? 如果是 PGSQL 安装出现了问题,您在 pg_extension 中指定安装的扩展,是否还没有添加到 repo_packages 中,或者还没有被覆盖? 如果是 PGSQL 启动出现了问题,例如 wait for patroni primary,请参考 PGSQL FAQ 解决。 软件包安装失败如何解决? 请注意,Pigsty 的预制 离线软件包 是针对 特定操作系统发行版小版本 打包的,
因此如果您使用的操作系统版本没有精确对齐,我们不建议使用离线软件安装包,而是直接从上游下载符合当前操作系统实际情况的软件包版本。
如果在线安装无法解决包冲突问题,您首先可以尝试修改 Pigsty 使用的上游软件源。例如在 EL 系操作系统中, Pigsty 默认的上游软件源中使用 $releasever 这样的大版本占位符,它将被解析为具体的 7,8,9 大版本号,但是许多操作系统发行版都提供了 Vault,允许您使用特定某一个版本的软件包镜像。
因此,您可以将 repo_upstream 参数中的 BaseURL 前段替换为具体的 Vault 小版本仓库,例如:
https://mirrors.aliyun.com/rockylinux/$releasever/ (原始 BaseURL 前缀,不带 vault )https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.6.1810/ (使用 7.6 而不是默认的 7.9)https://mirrors.aliyun.com/rockylinux-vault/8.6/ (使用 8.6 而不是默认的 8.9)https://mirrors.aliyun.com/rockylinux-vault/9.2/ (使用 9.2 而不是默认的 9.3)在替换前请注意目标软件源的路径是否真实存在,例如 EPEL 不提供小版本特定的软件源。支持这种方式的上游源包括:base, updates, extras, centos-sclo, centos-sclo-rh, baseos, appstream, extras, crb, powertools, pgdg-common, pgdg1*
repo_upstream :
- { name: pigsty-local ,description: 'Pigsty Local' ,module: local ,releases: [7,8,9] ,baseurl : { default : 'http://${admin_ip}/pigsty' }} # used by intranet nodes
- { name: pigsty-infra ,description: 'Pigsty INFRA' ,module: infra ,releases: [7,8,9] ,baseurl : { default: 'https://repo.pigsty.io/rpm/infra/$basearch' ,china : 'https://repo.pigsty.cc/rpm/infra/$basearch' }}
- { name: pigsty-pgsql ,description: 'Pigsty PGSQL' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default: 'https://repo.pigsty.io/rpm/pgsql/el$releasever.$basearch' ,china : 'https://repo.pigsty.cc/rpm/pgsql/el$releasever.$basearch' }}
- { name: nginx ,description: 'Nginx Repo' ,module: infra ,releases: [7,8,9] ,baseurl : { default : 'https://nginx.org/packages/centos/$releasever/$basearch/' }}
- { name: docker-ce ,description: 'Docker CE' ,module: infra ,releases: [7,8,9] ,baseurl : { default: 'https://download.docker.com/linux/centos/$releasever/$basearch/stable' ,china: 'https://mirrors.aliyun.com/docker-ce/linux/centos/$releasever/$basearch/stable' ,europe : 'https://mirrors.xtom.de/docker-ce/linux/centos/$releasever/$basearch/stable' }}
- { name: base ,description: 'EL 7 Base' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/os/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/os/$basearch/' }}
- { name: updates ,description: 'EL 7 Updates' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/updates/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/updates/$basearch/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/updates/$basearch/' }}
- { name: extras ,description: 'EL 7 Extras' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/extras/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/extras/$basearch/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/extras/$basearch/' }}
- { name: epel ,description: 'EL 7 EPEL' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://download.fedoraproject.org/pub/epel/$releasever/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/epel/$releasever/$basearch/' ,europe : 'https://mirrors.xtom.de/epel/$releasever/$basearch/' }}
- { name: centos-sclo ,description: 'EL 7 SCLo' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/sclo/$basearch/sclo/' ,china: 'https://mirrors.aliyun.com/centos/$releasever/sclo/$basearch/sclo/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/sclo/$basearch/sclo/' }}
- { name: centos-sclo-rh ,description: 'EL 7 SCLo rh' ,module: node ,releases: [7 ] ,baseurl : { default: 'http://mirror.centos.org/centos/$releasever/sclo/$basearch/rh/' ,china: 'https://mirrors.aliyun.com/centos/$releasever/sclo/$basearch/rh/' ,europe : 'https://mirrors.xtom.de/centos/$releasever/sclo/$basearch/rh/' }}
- { name: baseos ,description: 'EL 8+ BaseOS' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/BaseOS/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/BaseOS/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/BaseOS/$basearch/os/' }}
- { name: appstream ,description: 'EL 8+ AppStream' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/AppStream/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/AppStream/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/AppStream/$basearch/os/' }}
- { name: extras ,description: 'EL 8+ Extras' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/extras/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/extras/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/extras/$basearch/os/' }}
- { name: crb ,description: 'EL 9 CRB' ,module: node ,releases: [ 9] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/CRB/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/CRB/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/CRB/$basearch/os/' }}
- { name: powertools ,description: 'EL 8 PowerTools' ,module: node ,releases: [ 8 ] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/PowerTools/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/PowerTools/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/PowerTools/$basearch/os/' }}
- { name: epel ,description: 'EL 8+ EPEL' ,module: node ,releases: [ 8,9] ,baseurl : { default: 'http://download.fedoraproject.org/pub/epel/$releasever/Everything/$basearch/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/epel/$releasever/Everything/$basearch/' ,europe : 'https://mirrors.xtom.de/epel/$releasever/Everything/$basearch/' }}
- { name: pgdg-common ,description: 'PostgreSQL Common' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/redhat/rhel-$releasever-$basearch' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg-extras ,description: 'PostgreSQL Extra' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-rhel$releasever-extras/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/pgdg-rhel$releasever-extras/redhat/rhel-$releasever-$basearch' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-rhel$releasever-extras/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg-el8fix ,description: 'PostgreSQL EL8FIX' ,module: pgsql ,releases: [ 8 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-x86_64/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-x86_64/' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-x86_64/' } }
- { name: pgdg-el9fix ,description: 'PostgreSQL EL9FIX' ,module: pgsql ,releases: [ 9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-x86_64/' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-x86_64/' , europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-x86_64/' }}
- { name: pgdg15 ,description: 'PostgreSQL 15' ,module: pgsql ,releases: [7 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/15/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/15/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/15/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg16 ,description: 'PostgreSQL 16' ,module: pgsql ,releases: [ 8,9] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/16/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/16/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/16/redhat/rhel-$releasever-$basearch' }}
- { name: timescaledb ,description: 'TimescaleDB' ,module: pgsql ,releases: [7,8,9] ,baseurl : { default : 'https://packagecloud.io/timescale/timescaledb/el/$releasever/$basearch' }}
在 Pigsty 配置文件中显式定义并覆盖 repo_upstream 后,(可清除 /www/pigsty/repo_complete 标记后)再次尝试安装。如果上游软件源与镜像源的软件没有解决问题,你可以考虑将上面的源替换为操作系统自带的软件源,再次尝试从上游直接安装。
最后如果以上手段都没有解决问题,你可以考虑移除 node_packages, infra_packages, pg_packages,pg_extensions 中出现冲突的软件包。或者移除、升级现有系统上的冲突软件包。
准备 / bootstrap 过程是干什么的? 检测环境是否就绪、用各种手段确保后续安装所必需的工具 ansible 被正确安装。
当你下载 Pigsty 源码后,可以进入目录并执行 bootstrap 脚本。它会检测你的节点环境,如果没有发现离线软件包,它会询问你要不要从互联网下载。
你可以选择 “是”(y),直接使用离线软件包安装又快又稳定。你也可以选“否” (n) 跳过,在安装时直接从互联网上游下载最新的软件包,这样会极大减少出现 RPM/DEB 包冲突的概率。
如果使用了离线软件包,bootstrap 会直接从离线软件包中安装 ansible,否则会从上游下载 ansible 并安装,如果你没有互联网访问,又没有 DVD,或者内网软件源,那就只能用离线软件包来安装了。
配置 / configure 过程会检测你的节点环境并为你生成一个 pigsty 配置文件:pigsty.yml,默认根据你的操作系统(EL 7/8/9)选用相应的单机安装模板。
所有默认的配置模板都在 files/pigsty中,你可以使用 -c 直接指定想要使用的配置模板。如果您已经知道如何配置 Pigsty 了,那么完全可以跳过这一步,直接编辑 Pigsty 配置文件。
Pigsty配置文件是干什么的? Pigsty主目录下的 pigsty.yml 是默认的配置文件,可以用来描述整套部署的环境,在 conf/ 目录中有许多配置示例供你参考。在 文档站:配置模板 中相关说明。
当执行剧本时,你可以使用 -i <path> 参数,选用其他位置的配置文件。例如,你想根据另一个专门的配置文件 redis.yml 来安装 redis,可以这样做:./redis.yml -i files/pigsty/redis.yml
如何使用 CMDB 作为配置清单? Ansible 默认使用的配置清单在 ansible.cfg 中指定为:inventory = pigsty.yml
你可以使用 bin/inventory_cmdb 切换到动态的 CMDB 清单,
使用 bin/inventory_conf 返回到本地配置文件。
你还需要使用 bin/inventory_load 将当前的配置文件清单加载到 CMDB。
如果使用 CMDB,你必须从数据库而不是配置文件中编辑清单配置,这种方式适合将 Pigsty 与外部系统相集成。
配置文件中的IP地址占位符是干什么的? Pigsty 使用 10.10.10.10 作为当前节点 IP 的占位符,配置过程中会用当前节点的主 IP 地址替换它。
当 configure 检测到当前节点有多个 NIC 带有多个 IP 时,配置向导会提示使用哪个主要 IP,即 用户用于从内部网络访问节点的 IP ,此 IP 将用于在配置文件模板中替换占位符 10.10.10.10。
请注意,您应当使用静态 IP 地址,而不是 DHCP 分配的动态 IP 地址,因为 Pigsty 使用静态 IPv4 地址唯一标识节点。
请注意:不要使用公共 IP 作为主 IP,因为 Pigsty 会使用主 IP 来配置内部服务,例如 Nginx,Prometheus,Grafana,Loki,AlertManager,Chronyd,DNSMasq 等,除了 Nginx 之外的服务不应该对外界暴露端口。
我没有静态IP,可以安装Pigsty吗? 如果您的服务器没有静态IP,在 单机部署 的情况下,可以使用本地环回地址 127.0.0.1 作为这个唯一节点的 IP 地址标识。
配置文件中的哪些参数需要用户特殊关注? Pigsty 提供了 280+ 配置参数,可以对整个环境与各个模块 infra / node / etcd / minio / pgsql 进行细致入微的定制。
通常在单节点安装中,你不需要对默认生成的配置文件进行任何调整。但如果需要,可以关注以下这些参数:
当访问 web 服务组件时,域名由 infra_portal 指定,有些服务只能通过 Nginx 代理使用域名访问。 Pigsty 假定存在一个 /data 目录用于存放所有数据;如果数据磁盘的挂载点与此不同,你可以使用 node_data 调整这些路径。 进行生产部署时,不要忘记在配置文件中更改密码 ,更多细节请参考 安全考量 。 在默认单机安装时,到底都安装了什么东西? 当您执行 make install 时,实际上是调用 Ansible 剧本 install.yml ,根据配置文件中的参数,安装以下内容:
INFRA 模块:提供本地软件源,Nginx Web接入点,DNS服务器,NTP服务器,Prometheus与Grafana可观测性技术栈。NODE 模块,将当前节点纳入 Pigsty 管理,部署 HAProxy 与 监控。ETCD 模块,部署一个单机 etcd 集群,作为 PG 高可用的 DCSMINIO 模块如果定义,则会安装,它可以作为 PG 的可选备份仓库。PGSQL 模块,一个单机 PostgreSQL 数据库实例。安装遇到软件包冲突怎么办? 在安装 node / infra / pgsql 软件包期间,可能有微小的几率出现软件包依赖错漏冲突。这里有几种常见原因:
上游软件源发布了不匹配的软件包版本或缺失了依赖,您可能要等待上游修复此问题,时间以周计。事先在依赖完备时制作的离线安装包可以预防这个问题。 您制作离线安装包操作系统小版本与当前操作系统的小版本不匹配,您可以使用在线安装,或重新使用相同系统下制作的离线软件包的方式解决此问题 个别不重要,非必选的软件包,可以直接将其从安装列表,或本地软件源中剔除的方式快速绕过。 如何重建本地软件仓库? 我想要从上游仓库重新下载软件包,但是执行 ./infra.yml 和 repo 子任务都跳过下载了,怎么办?
您可以使用以下快捷命令和剧本任务,强制重建本地软件源。 Pigsty 会重新检查上游仓库并下载软件包。
make repo-build # ./infra.yml -t repo_build
如何在安装后下载最新版本的软件包? 如果您想要下载最新的软件包版本(RPM/DEB),你可以选择在 /www/pigsty 中手工使用 apt/dnf 下载特定版本的软件包。
在这种情况下,您可以使用以下命令,只更新本地软件仓库的元数据库,而不是整个重建:
./infra.yml -t repo_create
或者移除 /www/pigsty 中的旧版本软件包后重新执行仓库重建命令:
make repo-build # ./infra.yml -t repo_build
如何使用 Vagrant 创建本地虚拟机? 当你第一次使用 Vagrant 启动某个特定的操作系统仓库时,它会下载相应的 Box/Img 镜像文件,Pigsty 沙箱默认使用 generic/rocky9 镜像。
使用代理可能会增加下载速度。Box/Image 只需下载一次,在重建沙箱时会被重复使用。
阿里云上 CentOS 7.9 特有的 RPM 冲突问题 阿里云的 CentOS 7.9 额外安装的 nscd 可能会导致 RPM 冲突问题:"Error: Package: nscd-2.17-307.el7.1.x86_64 (@base)"
遇见安装失败,RPM冲突报错不要慌,这是一个DNS缓存工具,把这个包卸载了就可以了:sudo yum remove nscd,或者使用 ansible 命令批量删除所有节点上的 nscd:
ansible all -b -a 'yum remove -y nscd'
腾讯云上 Rocky 9.x 特有的 RPM 冲突问题 腾讯云的 Rocky 9.x 需要额外的 annobin 软件包才可以正常完成 Pigsty 安装。
遇见安装失败,RPM冲突报错不要慌,进入 /www/pigsty 把这几个包手动下载下来就好了。
./infra.yml -t repo_upstream # add upstream repos
cd /www/pigsty; # download missing packages
repotrack annobin gcc-plugin-annobin libuser
./infra.yml -t repo_create # create repo
Ansible命令超时(Timeout waiting for xxx) Ansible 命令的默认 ssh 超时时间是10秒。由于网络延迟或其他原因,某些命令可能需要超过这个时间。
你可以在 ansible 配置文件 ansible.cfg 中增加超时参数:
[defaults]
timeout = 10 # 将其修改为 60,120 或更高。
如果你的SSH连接非常慢,通常会是 DNS的问题,请检查sshd配置确保 UseDNS no。
7 - 参考 详细的参考信息与列表:支持的操作系统,模块,参数,监控指标,数据库扩展,同类对比,术语表等。
7.1 - Linux 兼容性 Pigsty 兼容的 Linux 操作系统发行版大版本,以及芯片架构指令集
Pigsty 运行于 Linux 操作系统上,支持 amd64/x86_64 与 arm64/aarch64 架构,支持 EL ,Debian ,Ubuntu 三大主流 Linux 发行版。
Pigsty 不使用任何虚拟化容器化技术,直接运行于裸操作系统上。我们为三大主流 Linux 发行版最近两个大版本的两种架构提供支持。
概述 Pigsty 推荐使用的操作系统版本:RockyLinux 10.0、Ubuntu 24.04、Debian 13.1。
EL Pigsty 支持 RHEL / Rocky / Alma / Anolis / CentOS 8、9、10 版本。
推荐使用 RockyLinux 10.0 与 9.6
请注意,PGDG Yum 仓库 从 EL9 / EL10 开始,针对 EL 小版本 进行构建,目前支持的小版本为:9.6, 9.7, 10.0, 10.1。
Pigsty 当前离线安装包基于 RockyLinux 9.6 与 RockyLinux 10.0 构建,不适用于 9.7 / 10.1 系统(OpenSSL 3.2 -> 3.5 跳变)
EL8 即将不再支持
EL8 将于 2029 年进入 EOL,建议尽早规划升级。鉴于 EL10 适配已经完成,我们将在下个版本移除对 EL8 的支持。
EL 7 @ 2024-06
Red Hat Enterprise Linux 7 已经于 2024年6月停止维护,PGDG 也不再为 PostgreSQL 16/17/18 提供 EL7 二进制包支持。
如需在老旧操作系统上获得运行支持,请考虑我们的 专业订阅服务 。
Ubuntu Pigsty 支持 Ubuntu 24.04 / 22.04:
推荐使用 Ubuntu 22.04 / 24.04 LTS
Ubuntu 24.04 在系统可靠性/稳定性与软件版本的新颖性/齐全性上取得了良好的平衡,推荐使用此系统。
Ubuntu 20.04 已 EOL
Ubuntu 20.04 已于 2025年4月进入 EOL。
如需在老旧操作系统上获得扩展支持,请考虑我们的 专业订阅服务 。
Debian Pigsty 支持 Debian 12 / 13,推荐使用最新的 Debian 13.1
Debian 11 EOL @ 2024-07
Debian 11 已经于 2024-07 进入 EOL。如需在老旧操作系统上获得扩展支持,请考虑我们的 专业订阅服务 。
Vagrant 当您使用本地虚拟机部署 Pigsty 时,可以考虑使用以下 Vagrant 操作系统镜像,这也是 Pigsty 开发测试使用的镜像。
当您使用云服务器部署 Pigsty 时,可以考虑在 Terraform 中使用以下操作系统基础镜像,以 阿里云 为例:
x86_64 镜像 Rocky 8.10 rockylinux_8_10_x64_20G_alibase_20240923.vhdRocky 9.6 rockylinux_9_6_x64_20G_alibase_20250101.vhdRocky 10.0 rockylinux_10_0_x64_20G_alibase_20251120.vhdUbuntu 22.04 ubuntu_22_04_x64_20G_alibase_20240926.vhdUbuntu 24.04 ubuntu_24_04_x64_20G_alibase_20240923.vhdDebian 12.11 debian_12_11_x64_20G_alibase_20241201.vhdDebian 13.2 debian_13_x64_20G_alibase_20250101.vhd
aarch64 镜像 Rocky 8.10 rockylinux_8_10_arm64_20G_alibase_20251120.vhdRocky 9.6 rockylinux_9_6_arm64_20G_alibase_20251120.vhdRocky 10.0 rockylinux_10_0_arm64_20G_alibase_20251120.vhdUbuntu 22.04 ubuntu_22_04_arm64_20G_alibase_20251126.vhdUbuntu 24.04 ubuntu_24_04_arm64_20G_alibase_20251126.vhdDebian 12.11 debian_12_11_arm64_20G_alibase_20250825.vhdDebian 13.2 debian_13_2_arm64_20G_alibase_20251121.vhd
7.2 - 模块列表 本文列出了 Pigsty 中可用的功能模块,以及后续的功能模块规划。
核心模块 Pigsty 提供了四个 基础 功能模块,对于提供完整高可用的 PostgreSQL 服务必不可少:
PGSQL :带有高可用,时间点恢复,IaC,SOP,监控系统,以及 390 个扩展插件的自治的 PostgreSQL 集群。INFRA :本地软件仓库、Prometheus、Grafana、Loki、AlertManager、PushGateway、Blackbox Exporter…NODE :调整节点到所需状态、名称、时区、NTP、ssh、sudo、haproxy、docker、promtail、keepalivedETCD :分布式键值存储,用作高可用 Postgres 集群的 DCS:共识选主/配置管理/服务发现。内核模块 Pigsty 提供了四个 内核 功能模块 ,它们是 PostgreSQL 内核的可选原位替代,提供不同风味的数据库能力。
MSSQL :微软 SQL Server 线缆协议兼容的 PG 内核,由 AWS, WiltonDB & Babelfish 出品!IVORY :Oracle 兼容的 PostgreSQL 16 内核,由瀚高开源的 IvorySQL 项目提供。POLAR : 由阿里云开源的“云原生” PostgreSQL 内核,Aurora 风味的 RAC PostgreSQL Fork。CITUS :使用扩展实现分布式PostgreSQL集群(Azure Hyperscale),带有原生的 Patroni 高可用支持!国产化内核支持!
Pigsty 专业版 提供国产化数据库内核支持:PolarDB-O v2 —— 基于 PolarPG 的 Oracle 兼容的国产化数据库内核
扩展模块 Pigsty 提供了四个 扩展 功能模块,它对于核心功能来说并非必须,但可以用于增强 PostgreSQL 的能力:
MINIO :S3 兼容的简单对象存储服务器,可作为可选的 PostgreSQL 数据库备份仓库,带有生产部署支持与监控。REDIS :Redis 服务器,高性能数据结构服务器,支持独立主从、哨兵、集群模式生产部署,并带有完善的监控支持。MONGO :FerertDB 原生部署支持 —— 它为 PostgreSQL 添加了 MongoDB 线缆协议级别的 API 兼容支持!DOCKER :Docker Daemon 服务,允许用户一键拉起容器化的无状态软件工具模板,为 Pigsty 加装各种功能!外围模块 Pigsty 同时支持那些与 PostgreSQL 内核带有紧密联系的 外围 模块(扩展,分支,衍生,包装):
DUCKDB :强大的嵌入式OLAP数据库,Pigsty提供二进制/动态库及相关PG扩展:pg_duckdb,pg_lakehouse与duckdb_fdwSUPABASE : Pigsty 允许用户在现有高可用 PostgreSQL 集群基础上,运行火爆的 Firebase 开源替代 —— Supabase !GREENPLUM :基于 PostgreSQL 12 内核的 MPP 数据仓库,目前仅提供监控支持与 RPM 安装支持。(Beta )CLOUDBERRY :Greenplum 闭源后原班开发者打造的开源分支,基于 PG 14 内核,目前仅提供RPM安装支持。(Beta )NEON :带有数据库分支功能特性的的无服务器 PostgreSQL 内核 (WIP )试点模块 Pigsty 正在支持一些与 PostgreSQL 生态相关的 试点 模块 试点模块,它们可能会在未来成为 Pigsty 的正式模块:
KAFKA :使用 Pigsty 部署由 KRaft 驱动的 Kafka 消息队列,并提供开箱即用的监控支持 (Beta )MYSQL :使用 Pigsty 部署高可用的 MySQL 8.0 集群,并提供开箱即用的监控支持(供批判/迁移评估之用) (Beta )KUBE :使用 SealOS 搭建开箱即用的生产级 Kubernetes 部署与监控支持 (Alpha ).VICTORIA :基于 VictoriaMetrics 与 VictoriaLogs 的 Infra 替代选项,提供更好的性能与资源利用率(Alpha )JUPYTER :开箱即用的 Jupyter Notebook 环境,用于数据分析与机器学习等场景(Alpha )监控其他数据库 Pigsty 的 INFRA 模块可以独立使用,作为开箱即用的监控基础设施,监控其他节点或现有 PostgreSQL 数据库
现有 PostgreSQL 服务:Pigsty 可以监控外部的、非 Pigsty 托管的 PostgreSQL 服务,并仍可提供相对完整的监控支持。 RDS PG :是云厂商提供的 PostgreSQL RDS 服务,将其视作标准的外部 Postgres 实例即可纳入监控PolarDB :是阿里云的云原生数据库,将其视作外部 PostgreSQL 11 / 14 实例即可纳入监控。KingBase : 是人大金仓提供的信创国产数据库,视作外部 PostgreSQL 12 实例即可纳入监控。Greenplum / YMatrixDB 监控,目前将其视作水平分片的 PostgreSQL 集群即可纳入监控。7.3 - 扩展列表 本文列出了 Pigsty 支持的 PostgreSQL 扩展插件,以及这些插件在不同系统下的支持情况。
Pigsty 中总共有 440 个可用扩展,详情请参考 PGEXT.CLOUD 专门站,这是由 PIGSTY 维护的扩展仓库。
分类 All PGDG PIGSTY CONTRIB MISS PG18 PG17 PG16 PG15 PG14 PG13 ALL 440 149 268 71 0 408 429 428 430 415 386 EL 434 143 268 71 6 397 421 422 424 412 382 Debian 426 105 250 71 14 394 416 414 416 404 371
7.4 - 文件结构 Pigsty 的文件系统结构是如何设计与组织的,以及各个模块使用的目录结构。
Pigsty FHS Pigsty 的主目录默认放置于于 ~/pigsty,该目录下的文件结构如下所示:
#------------------------------------------------------------------------------
# pigsty
# ^-----@app # 额外的示例应用资源
# ^-----@bin # bin 脚本
# ^-----@docs # 文档(可docsify化)
# ^-----@files # ansible 文件资源
# ^-----@pigsty # pigsty 配置模板文件
# ^-----@prometheus # prometheus 规则定义
# ^-----@grafana # grafana 仪表盘
# ^-----@postgres # /pg/bin/ 脚本
# ^-----@migration # pgsql 迁移任务定义
# ^-----@pki # 自签名 CA 和证书
# ^-----@roles # ansible 剧本实现
# ^-----@templates # ansible 模板文件
# ^-----@vagrant # Vagrant 沙箱虚拟机定义模板
# ^-----@terraform # Terraform 云虚拟机申请模板
# ^-----configure # 配置向导脚本
# ^-----ansible.cfg # ansible 默认配置文件
# ^-----pigsty.yml # pigsty 默认配置文件
# ^-----*.yml # ansible 剧本
#------------------------------------------------------------------------------
# /etc/pigsty/
# ^-----@targets # 基于文件的服务发现目标定义
# ^-----@dashboards # grafana 监控面板
# ^-----@datasources # grafana 数据源
# ^-----@playbooks # ansible 剧本
#------------------------------------------------------------------------------
CA FHS Pigsty 的自签名 CA 位于 Pigsty 主目录下的 files/pki/。
你必须妥善保管 CA 的密钥文件 :files/pki/ca/ca.key,该密钥是在 install.yml 或 infra.yml 的 ca 角色负责生成的。
# pigsty/files/pki
# ^-----@ca # 自签名 CA 密钥和证书
# ^-----@ca.key # 非常重要:保守其秘密
# ^-----@ca.crt # 非常重要:在所有地方都受信任
# ^-----@csr # 签名请求 csr
# ^-----@misc # 杂项证书,已签发证书
# ^-----@etcd # etcd 服务器证书
# ^-----@minio # minio 服务器证书
# ^-----@nginx # nginx SSL 证书
# ^-----@infra # infra 客户端证书
# ^-----@pgsql # pgsql 服务器证书
# ^-----@mongo # mongodb/ferretdb 服务器证书
# ^-----@mysql # mysql 服务器证书(占位符)
被 Pigsty 所管理的节点将安装以下证书文件:
/etc/pki/ca.crt # 所有节点都添加的根证书
/etc/pki/ca-trust/source/anchors/ca.crt # 软链接到系统受信任的锚点
所有 infra 节点都会有以下证书:
/etc/pki/infra.crt # infra 节点证书
/etc/pki/infra.key # infra 节点密钥
当您的管理节点出现故障时,files/pki 目录与 pigsty.yml 文件应当在备份的管理节点上可用。你可以用 rsync 做到这一点。
# run on meta-1, rsync to meta2
cd ~/pigsty;
rsync -avz ./ meta-2:~/pigsty
NODE FHS 节点的数据目录由参数 node_data 指定,默认为 /data,由 root 用户持有,权限为 0777。
每个组件的默认数据目录都位于这个数据库目录下,如下所示:
/data
# ^-----@postgres # postgres 数据库目录
# ^-----@backups # postgres 备份数据目录(没有专用备份盘时)
# ^-----@redis # redis 数据目录(多实例共用)
# ^-----@minio # minio 数据目录(单机单盘模式)
# ^-----@etcd # etcd 主数据目录
# ^-----@prometheus # prometheus 监控时序数据目录
# ^-----@loki # Loki 日志数据目录
# ^-----@docker # Docker数据目录
# ^-----@... # 其他组件的数据目录
Prometheus FHS Prometheus 的主配置文件则位于 roles/infra/templates/prometheus/prometheus.yml.j2 ,并渲染至所有基础设施节点的 /etc/prometheus/prometheus.yml。
Prometheus 相关的脚本与规则定义放置于 pigsty 主目录下的 files/prometheus/ 目录,会被拷贝至所有基础设施节点的 /etc/prometheus/ 下。
# /etc/prometheus/
# ^-----prometheus.yml # Prometheus 主配置文件
# ^-----@bin # 工具脚本:检查配置,显示状态,重载配置,重建集群
# ^-----@rules # 记录和报警规则定义
# ^-----agent.yml # agnet 规则和报警
# ^-----infra.yml # infra 规则和报警
# ^-----etcd.yml # etcd 规则和报警
# ^-----node.yml # node 规则和报警
# ^-----pgsql.yml # pgsql 规则和报警
# ^-----redis.yml # redis 规则和报警
# ^-----minio.yml # minio 规则和报警
# ^-----mysql.yml # mysql 规则和报警(占位)
# ^-----@targets # 基于文件的服务发现目标定义
# ^-----@infra # infra 静态目标定义
# ^-----@node # node 静态目标定义
# ^-----@pgsql # pgsql 静态目标定义
# ^-----@pgrds # pgsql 远程RDS目标
# ^-----@redis # redis 静态目标定义
# ^-----@minio # minio 静态目标定义
# ^-----@mongo # mongo 静态目标定义
# ^-----@mysql # mysql 静态目标定义
# ^-----@etcd # etcd 静态目标定义
# ^-----@ping # ping 静态目标定义
# ^-----@patroni # patroni 静态目标定义 (当patroni启用SSL时使用此目录)
# ^-----@..... # 其他监控目标定义
# /etc/alertmanager.yml # 告警组件主配置文件
# /etc/blackbox.yml # 黑盒探测主配置文件
Postgres FHS 以下参数与PostgreSQL数据库目录结构相关:
# 工作假设:
# {{ pg_fs_main }} 主数据目录,默认位置:`/data` [快速SSD]
# {{ pg_fs_bkup }} 备份数据盘,默认位置:`/data/backups` [廉价HDD]
#--------------------------------------------------------------#
# 默认配置:
# pg_fs_main = /data 高速SSD
# pg_fs_bkup = /data/backups 廉价HDD (可选)
#
# /pg -> /data/postgres/pg-test-15 (软链接)
# /pg/data -> /data/postgres/pg-test-15/data
#--------------------------------------------------------------#
- name : create postgresql directories
tags : pg_dir
become : yes
block :
- name : make main and backup data dir
file : path={{ item }} state=directory owner=root mode=0777
with_items :
- "{{ pg_fs_main }}"
- "{{ pg_fs_bkup }}"
# pg_cluster_dir: "{{ pg_fs_main }}/postgres/{{ pg_cluster }}-{{ pg_version }}"
- name : create postgres directories
file : path={{ item }} state=directory owner={{ pg_dbsu }} group=postgres mode=0700
with_items :
- "{{ pg_fs_main }}/postgres"
- "{{ pg_cluster_dir }}"
- "{{ pg_cluster_dir }}/bin"
- "{{ pg_cluster_dir }}/log"
- "{{ pg_cluster_dir }}/tmp"
- "{{ pg_cluster_dir }}/cert"
- "{{ pg_cluster_dir }}/conf"
- "{{ pg_cluster_dir }}/data"
- "{{ pg_cluster_dir }}/meta"
- "{{ pg_cluster_dir }}/stat"
- "{{ pg_cluster_dir }}/change"
- "{{ pg_backup_dir }}/backup"
数据文件结构
# 真实目录
{{ pg_fs_main }} /data # 顶层数据目录,通常为高速SSD挂载点
{{ pg_dir_main }} /data/postgres # 包含所有 Postgres 实例的数据目录(可能有多个实例/不同版本)
{{ pg_cluster_dir }} /data/postgres/pg-test-15 # 包含了 `pg-test` 集群的数据 (大版本是15)
/data/postgres/pg-test-15/bin # 关于 PostgreSQL 的实用脚本
/data/postgres/pg-test-15/log # 日志:postgres/pgbouncer/patroni/pgbackrest
/data/postgres/pg-test-15/tmp # 临时文件,例如渲染出的 SQL 文件
/data/postgres/pg-test-15/cert # postgres 服务器证书
/data/postgres/pg-test-15/conf # postgres 相关配置文件索引
/data/postgres/pg-test-15/data # postgres 主数据目录
/data/postgres/pg-test-15/meta # postgres 身份信息
/data/postgres/pg-test-15/stat # 统计信息,日志报表,汇总摘要
/data/postgres/pg-test-15/change # 变更记录
/data/postgres/pg-test-15/backup # 指向备份目录的软链接。
{{ pg_fs_bkup }} /data/backups # 可选的备份盘目录/挂载点
/data/backups/postgres/pg-test-15/backup # 集群备份的实际存储位置
# 软链接
/pg -> /data/postgres/pg-test-15 # pg 根软链接
/pg/data -> /data/postgres/pg-test-15/data # pg 数据目录
/pg/backup -> /var/backups/postgres/pg-test-15/backup # pg 备份目录
二进制文件结构
在 EL 兼容发行版上(使用yum),PostgreSQL 默认安装位置为
/usr/pgsql-${ pg_version } /
Pigsty 会创建一个名为 /usr/pgsql 的软连接,指向由 pg_version 参数指定的实际版本,例如
/usr/pgsql -> /usr/pgsql-15
因此,默认的 pg_bin_dir 是 /usr/pgsql/bin/,而该路径会被添加至系统的 PATH 环境变量中,定义文件为:/etc/profile.d/pgsql.sh.
export PATH = "/usr/pgsql/bin:/pg/bin: $PATH "
export PGHOME = /usr/pgsql
export PGDATA = /pg/data
在 Ubuntu/Debian 上,PostgreSQL Deb 包的默认安装位置是:
/usr/lib/postgresql/${ pg_version } /bin
Pgbouncer FHS Pgbouncer 使用与 {{ pg_dbsu }} (默认为 postgres) 相同的用户运行,配置文件位于/etc/pgbouncer。
pgbouncer.ini,连接池主配置文件database.txt:定义连接池中的数据库userlist.txt:定义连接池中的用户pgb_hba.conf:定义连接池的访问权限Redis FHS Pigsty提供了对Redis部署与监控对基础支持。
Redis二进制使用RPM包或复制二进制的方式安装于/bin/中,包括
redis-server
redis-server
redis-cli
redis-sentinel
redis-check-rdb
redis-check-aof
redis-benchmark
/usr/libexec/redis-shutdown
对于一个名为 redis-test-1-6379 的 Redis 实例,与其相关的资源如下所示:
/usr/lib/systemd/system/redis-test-1-6379.service # 服务 (在Debian系中为/lib/systemd)
/etc/redis/redis-test-1-6379.conf # 配置
/data/redis/redis-test-1-6379 # 数据库目录
/data/redis/redis-test-1-6379/redis-test-1-6379.rdb # RDB文件
/data/redis/redis-test-1-6379/redis-test-1-6379.aof # AOF文件
/var/log/redis/redis-test-1-6379.log # 日志
/var/run/redis/redis-test-1-6379.pid # PID
对于 Ubuntu / Debian 而言,systemd 服务的默认目录不是 /usr/lib/systemd/system/ 而是 /lib/systemd/system/
7.5 - 参数列表 Pigsty 配置参数总览与导航
Pigsty 提供了约 380+ 个配置参数,分布在 8 个默认模块中,用于精细控制系统的各个方面。
总览 本页面提供 Pigsty 所有配置参数的导航与概览,点击模块名称可以跳转到对应的详细参数文档。
模块 参数组 参数总数 说明 PGSQL 9 123 PostgreSQL 数据库集群的核心配置 INFRA 10 82 基础设施组件:软件源、Nginx、DNS、监控、Grafana 等 NODE 11 82 主机节点调优:身份、DNS、包、调优、安全、管理员、时间、VIP等 ETCD 2 13 分布式配置存储与服务发现 REDIS 1 21 Redis 缓存与数据结构服务器 MINIO 2 21 S3 兼容对象存储服务 FERRET 1 9 MongoDB 兼容数据库 FerretDB DOCKER 1 8 Docker 容器引擎
PGSQL PGSQL 模块提供了 9 组共 123 个 PostgreSQL 相关配置参数。
INFRA INFRA 模块提供了 10 组共 82 个 基础设施相关配置参数。
NODE NODE 模块提供了 11 组共 82 个 主机节点相关配置参数。
ETCD ETCD 模块提供了 2 组共 13 个 分布式配置存储相关参数。
REDIS REDIS 模块提供了 21 个 Redis 相关配置参数。
参数组 参数数 说明 REDIS21 Redis 集群的部署与配置
MINIO MINIO 模块提供了 2 组共 21 个 MinIO 对象存储相关参数。
FERRET FERRET 模块提供了 9 个 FerretDB 相关配置参数。
DOCKER DOCKER 模块提供了 8 个 Docker 容器引擎相关配置参数。
参数总览 以下是所有模块的参数汇总表格,按模块分类列出。
PGSQL 参数 PG_ID 参数组用于定义 PostgreSQL 集群与实例的身份标识,包括集群名称、实例序号、角色、分片等核心身份参数。
参数 类型 说明 pg_modeenumpgsql 集群模式: pgsql,citus,mssql,mysql,polar,ivory,oracle,gpsql pg_clusterstringpgsql 集群名称, 必选身份参数 pg_seqintpgsql 实例号, 必选身份参数 pg_roleenumpgsql 实例角色, 必选身份参数, 可为 primary,replica,offline pg_instancesdict在一个节点上定义多个 pg 实例,使用 {port:ins_vars} 格式 pg_upstreamip级联从库或备份集群或的复制上游节点IP地址 pg_shardstringpgsql 分片名,对 citus 与 gpsql 等水平分片集群为必选身份参数 pg_groupintpgsql 分片号,正整数,对 citus 与 gpsql 等水平分片集群为必选身份参数 gp_roleenum这个集群的 greenplum 角色,可以是 master 或 segment pg_exportersdict在该节点上设置额外的 pg_exporters 用于监控远程 postgres 实例 pg_offline_querybool设置为 true 将此只读实例标记为特殊的离线从库,承载 Offline 服务,允许离线查询
PG_BUSINESS 参数组用于定义业务用户、数据库、服务与访问控制规则,以及默认的系统用户凭据。
PG_INSTALL 参数组用于配置 PostgreSQL 安装相关选项,包括版本、路径、软件包与扩展插件。
PG_BOOTSTRAP 参数组用于配置 PostgreSQL 集群初始化引导,包括 Patroni 高可用、数据目录、存储、连接、编码等核心设置。
参数 类型 说明 pg_datapathpostgres 数据目录,默认为 /pg/data pg_fs_mainpathpostgres 主数据的挂载点/路径,默认为 /data/postgres pg_fs_backuppathpg 备份数据的挂载点/路径,默认为 /data/backups pg_storage_typeenumpg 主数据的存储类型,SSD、HDD,默认为 SSD,影响自动优化的参数。 pg_dummy_filesizesize/pg/dummy 的大小,默认保留 64MB 磁盘空间用于紧急抢修pg_listenip(s)postgres/pgbouncer 的监听地址,用逗号分隔的IP列表,默认为 0.0.0.0 pg_portportpostgres 监听端口,默认为 5432 pg_localhostpathpostgres 的 Unix 套接字目录,用于本地连接 pg_namespacepath在 etcd 中的顶级键命名空间,被 patroni & vip 用于高可用管理 patroni_enabledbool如果禁用,初始化期间不会创建 postgres 集群 patroni_modeenumpatroni 工作模式:default,pause,remove patroni_portportpatroni 监听端口,默认为 8008 patroni_log_dirpathpatroni 日志目录,默认为 /pg/log/patroni patroni_ssl_enabledbool使用 SSL 保护 patroni RestAPI 通信? patroni_watchdog_modeenumpatroni 看门狗模式:automatic,required,off,默认为 off patroni_usernameusernamepatroni restapi 用户名,默认为 postgres patroni_passwordpasswordpatroni restapi 密码,默认为 Patroni.API pg_primary_dbstring指定集群中首要使用的数据库名,Citus等模式会用到,默认为 postgres pg_parametersdict覆盖 postgresql.auto.conf 中的 PostgreSQL 参数 pg_filespath[]拷贝至PGDATA目录中的额外文件列表 (例如许可证文件) pg_confenum配置模板:oltp,olap,crit,tiny,默认为 oltp.yml pg_max_connintpostgres 最大连接数,auto 将使用推荐值 pg_shared_buffer_ratiofloatpostgres 共享缓冲区内存比率,默认为 0.25,范围 0.1~0.4 pg_rtoint恢复时间目标(秒),默认为 30s pg_rpoint恢复点目标(字节),默认为 1MiB pg_libsstring预加载的库,默认为 pg_stat_statements,auto_explain pg_delayinterval备份集群主库的WAL重放应用延迟,用于制备延迟从库 pg_checksumbool为 postgres 集群启用数据校验和? pg_pwd_encenum密码加密算法:固定为 scram-sha-256 pg_encodingenum数据库集群编码,默认为 UTF8 pg_localeenum数据库集群本地化设置,默认为 C pg_lc_collateenum数据库集群排序,默认为 C pg_lc_ctypeenum数据库字符类型,默认为 C pg_io_methodenumPostgreSQL IO 方法:auto, sync, worker, io_uring pg_etcd_passwordpassword此 PostgreSQL 集群在 etcd 中使用的密码,默认使用集群名 pgsodium_keystringpgsodium 加密主密钥,64 位十六进制数字,默认使用 sha256(pg_cluster) pgsodium_getkey_scriptpathpgsodium 获取密钥脚本路径,默认使用模板中的 pgsodium_getkey
PG_PROVISION 参数组用于配置 PostgreSQL 集群模板置备,包括默认角色、权限、模式、扩展与 HBA 规则。
PG_BACKUP 参数组用于配置 pgBackRest 备份与恢复,包括仓库类型、路径、保留策略等。
PG_ACCESS 参数组用于配置服务暴露、连接池、VIP、DNS 等客户端访问相关选项。
PG_MONITOR 参数组用于配置 PostgreSQL 监控 Exporter,包括 pg_exporter、pgbouncer_exporter 和 pgbackrest_exporter。
PG_REMOVE 参数组用于配置 PostgreSQL 实例清理与卸载行为,包括数据目录、备份、软件包的删除控制。
INFRA 参数 META 参数组用于定义 Pigsty 的元信息,包括版本号、管理节点 IP、软件源区域、默认语言以及代理设置。
CA 参数组用于配置 Pigsty 自签名 CA 证书管理,包括是否创建 CA、CA 名称以及证书有效期。
INFRA_ID 参数组用于定义基础设施节点的身份标识,包括节点序号、服务门户配置以及数据目录。
REPO 参数组用于配置本地软件仓库,包括仓库启用开关、目录路径、上游源定义以及要下载的软件包列表。
INFRA_PACKAGE 参数组用于定义在基础设施节点上安装的软件包,包括 RPM/DEB 包和 PIP 包。
NGINX 参数组用于配置 Nginx Web 服务器与反向代理,包括启用开关、端口、SSL 模式、证书以及基础认证。
DNS 参数组用于配置 DNSMasq 域名解析服务,包括启用开关、监听端口以及动态 DNS 记录。
VICTORIA 参数组用于配置 VictoriaMetrics/Logs/Traces 可观测性套件,包括启用开关、端口、数据保留策略等。
PROMETHEUS 参数组用于配置 Alertmanager 与 Blackbox Exporter,提供告警管理和网络探测功能。
GRAFANA 参数组用于配置 Grafana 可视化平台,包括启用开关、端口、管理员凭据以及数据源配置。
NODE 参数 NODE_ID 参数组用于定义节点的身份标识参数,包括节点名称、集群名称,以及是否从 PostgreSQL 借用身份。
NODE_DNS 参数组用于配置节点的 DNS 解析,包括静态 hosts 记录与动态 DNS 服务器。
NODE_PACKAGE 参数组用于配置节点的软件源与软件包安装。
NODE_TUNE 参数组用于配置节点的内核参数、特性开关与性能调优模板。
NODE_SEC 参数组用于配置节点的安全相关选项,包括 SELinux、防火墙等。
NODE_ADMIN 参数组用于配置节点的管理员用户、数据目录与命令别名。
NODE_TIME 参数组用于配置节点的时区、NTP 时间同步与定时任务。
NODE_VIP 参数组用于配置节点集群的 L2 VIP,由 keepalived 实现。
HAPROXY 参数组用于配置节点上的 HAProxy 负载均衡器与服务暴露。
NODE_EXPORTER 参数组用于配置节点监控 Exporter。
VECTOR 参数组用于配置 Vector 日志收集器。
ETCD 参数 ETCD 参数组用于 etcd 集群的部署与配置,包括实例标识、集群名称、数据目录、端口以及认证密码。
ETCD_REMOVE 参数组控制 etcd 集群的移除行为,包括防误删保险、数据清理以及软件包卸载。
REDIS 参数 REDIS 参数组用于 Redis 集群的部署与配置,包括身份标识、实例定义、工作模式、内存配置、持久化以及监控。
MINIO 参数 MINIO 参数组用于 MinIO 集群的部署与配置,包括身份标识、存储路径、端口、认证凭据以及存储桶和用户的置备。
MINIO_REMOVE 参数组控制 MinIO 集群的移除行为,包括防误删保险、数据清理以及软件包卸载。
FERRET 参数 FERRET 参数组用于 FerretDB 部署与配置,包括身份标识、底层 PostgreSQL 连接、监听端口以及 SSL 设置。
DOCKER 参数 DOCKER 参数组用于 Docker 容器引擎的部署与配置,包括启用开关、数据目录、存储驱动、镜像加速以及监控。
7.6 - 剧本列表 Pigsty 预置剧本总览与导航
Pigsty 提供了一系列 Ansible 剧本用于自动化部署与管理各个模块,本页面提供了所有剧本的导航与汇总。
模块导航 剧本汇总 以下表格列出了 Pigsty 中所有可用的预置剧本:
剧本使用注意事项 保护机制 多个模块提供了防误删保险,通过 *_safeguard 参数控制:
默认情况下,这些 safeguard 参数均未启用(未定义)。建议在生产环境中为已初始化的集群显式设置为 true。
当保护开关设置为 true 时,对应的 *-rm.yml 剧本会立即中止执行,防止误删。可以通过命令行参数强制覆盖:
./pgsql-rm.yml -l pg-test -e pg_safeguard = false
./etcd-rm.yml -e etcd_safeguard = false
./minio-rm.yml -l minio -e minio_safeguard = false
限制执行范围 执行剧本时建议使用 -l 参数限制命令执行的对象范围:
./pgsql.yml -l pg-meta # 限制在集群 pg-meta 上执行
./node.yml -l 10.10.10.10 # 限制在特定节点上执行
./redis.yml -l redis-test # 限制在 redis-test 集群上执行
幂等性 大部分剧本都是幂等的,可以重复执行。但需要注意:
infra.yml 默认不会 清除数据,可安全重复执行。所有 clean 参数(vmetrics_clean、vlogs_clean、vtraces_clean、grafana_clean、nginx_clean)默认均为 false如需清除基础设施数据重建,需显式设置对应的 clean 参数为 true 重复执行 *-rm.yml 删除剧本需格外小心,确保在正确的目标上执行 任务标签 可以使用 -t 参数只执行特定的任务子集:
./pgsql.yml -l pg-test -t pg_service # 只刷新集群 pg-test 的服务
./node.yml -t haproxy # 只在节点上设置 haproxy
./etcd.yml -t etcd_launch # 只重启 etcd 服务
常用命令速查 INFRA 模块 ./infra.yml # 初始化基础设施
./infra-rm.yml # 移除基础设施
./install.yml # 一次性安装 Pigsty
NODE 模块 ./node.yml -l <cls| ip> # 添加节点
./node-rm.yml -l <cls| ip> # 移除节点
bin/node-add <cls| ip> # 添加节点 (包装脚本)
bin/node-rm <cls| ip> # 移除节点 (包装脚本)
ETCD 模块 ./etcd.yml # 初始化 etcd 集群
./etcd-rm.yml # 移除 etcd 集群
bin/etcd-add <ip> # 添加 etcd 成员 (包装脚本)
bin/etcd-rm <ip> # 移除 etcd 成员 (包装脚本)
PGSQL 模块 ./pgsql.yml -l <cls> # 初始化 PostgreSQL 集群
./pgsql-rm.yml -l <cls> # 移除 PostgreSQL 集群
./pgsql-user.yml -l <cls> -e username = <user> # 创建业务用户
./pgsql-db.yml -l <cls> -e dbname = <db> # 创建业务数据库
./pgsql-monitor.yml -e clsname = <cls> # 监控远程集群
./pgsql-migration.yml -e@files/migration/<cls>.yml # 生成迁移手册
./pgsql-pitr.yml -l <cls> -e '{"pg_pitr": {}}' # 执行 PITR 恢复
bin/pgsql-add <cls> # 初始化集群 (包装脚本)
bin/pgsql-rm <cls> # 移除集群 (包装脚本)
bin/pgsql-user <cls> <user> # 创建用户 (包装脚本)
bin/pgsql-db <cls> <db> # 创建数据库 (包装脚本)
bin/pgsql-svc <cls> # 刷新服务 (包装脚本)
bin/pgsql-hba <cls> # 重载 HBA (包装脚本)
bin/pgmon-add <cls> # 监控远程集群 (包装脚本)
REDIS 模块 ./redis.yml -l <cls> # 初始化 Redis 集群
./redis-rm.yml -l <cls> # 移除 Redis 集群
MINIO 模块 ./minio.yml -l <cls> # 初始化 MinIO 集群
./minio-rm.yml -l <cls> # 移除 MinIO 集群
FERRET 模块 ./mongo.yml -l ferret # 安装 FerretDB
DOCKER 模块 ./docker.yml -l <host> # 安装 Docker
8 - 应用 使用 Docker 拉起应用软件模板,使用 Pigsty Grafana & Echarts 工具箱进行数据分析与可视化
Applet的结构 Applet,是一种自包含的,运行于Pigsty基础设施中的数据小应用。
一个Pigsty应用通常包括以下内容中的至少一样或全部:
图形界面(Grafana Dashboard定义) 放置于ui目录 数据定义(PostgreSQL DDL File),放置于 sql 目录 数据文件(各类资源,需要下载的文件),放置于data目录 逻辑脚本(执行各类逻辑),放置于bin目录 Pigsty默认提供了几个样例应用:
pglog , 分析PostgreSQL CSV日志样本。covid , 可视化WHO COVID-19数据,查阅各国疫情数据。pglog , NOAA ISD,可以查询全球30000个地表气象站从1901年来的气象观测记录。应用的结构 一个Pigsty应用会在应用根目录提供一个安装脚本:install或相关快捷方式。您需要使用管理用户在 管理节点 执行安装。安装脚本会检测当前的环境(获取 METADB_URL, PIGSTY_HOME,GRAFANA_ENDPOINT等信息以执行安装)
通常,带有APP标签的面板会被列入Pigsty Grafana首页导航中App下拉菜单中,带有APP和Overview标签的面板则会列入首页面板导航中。
您可以从 https://github.com/Vonng/pigsty/releases/download/v1.5.1/app.tgz 下载带有基础数据的应用进行安装。
8.1 - Supabase 企业级自建 使用 Pigsty 自托管企业级 supabase,带有监控,高可用,PITR,IaC 以及 400+ PG扩展。
Supabase 很好,拥有属于你自己的 supabase 则好上加好。
Pigsty 可以帮助您在自己的服务器上(物理机/虚拟机/云服务器),一键自建企业级 supabase —— 更多扩展,更好性能,更深入的控制,更合算的成本。
Pigsty 是 Supabase 官网文档上列举的三种自建部署之一:Self-hosting: Third-Party Guides
简短版本 准备 Linux ,执行 Pigsty 标准安装 流程,选择 supabase 配置模板,依次执行:
curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
./configure -c supabase # 使用 supabase 配置(请在 pigsty.yml 中更改凭据)
vi pigsty.yml # 编辑域名、密码、密钥...
./deploy.yml # 安装 pigsty
./docker.yml # 安装 docker compose 组件
./app.yml # 使用 docker 启动 supabase 无状态部分(可能较慢)
安装完毕后,使用浏览器访问 8000 端口造访 Supa Studio,用户名 supabase,密码 pigsty。
目录 Supabase是什么? Supabase 是一个 BaaS (Backend as Service),开源的 Firebase,是 AI Agent 时代最火爆的数据库 + 后端解决方案。
Supabase 对 PostgreSQL 进行了封装,并提供了身份认证,消息传递,边缘函数,对象存储,并基于 PG 数据库模式自动生成 REST API 与 GraphQL API。
Supabase 旨在为开发者提供一条龙式的后端解决方案,减少开发和维护后端基础设施的复杂性。
它能让开发者告别绝大部分后端开发的工作,只需要懂数据库设计与前端即可快速出活!
开发者只要用 Vibe Coding 糊个前端与数据库模式设计,就可以快速完成一个完整的应用。
目前,Supabase 是 PostgreSQL 开源生态 中人气最高的开源项目,在 GitHub 上已有 八万 Star。
Supabase 还为小微创业者提供了"慷慨"的免费云服务额度 —— 免费的 500 MB 空间,对于存个用户表,浏览数之类的东西绰绰有余。
为什么要自建? 既然 Supabase 云服务这么香,为什么要自建呢?
最直观的原因是是我们在《云数据库是智商税吗? 》中提到过的:当你的数据/计算规模超出云计算适用光谱(Supabase:4C/8G/500MB免费存储),成本很容易出现爆炸式增长。
而且在当下,足够可靠的 本地企业级 NVMe SSD 在性价比上与 云端存储 有着三到四个数量级的优势,而自建能更好地利用这一点。
另一个重要的原因是 功能 , Supabase 云服务的功能受限 —— 很多强力PG扩展因为多租户安全挑战与许可证的原因无法以云服务的形式。
故而尽管 扩展是 PostgreSQL 的核心特色 ,在 Supabase 云服务上也依然只有 64 个扩展可用。
而通过 Pigsty 自建的 Supabase 则提供了多达 437 个开箱即用的 PG 扩展。
此外,自主可控与规避供应商锁定也是自建的重要原因 —— 尽管 Supabase 虽然旨在提供一个无供应商锁定的 Google Firebase 开源替代,但实际上自建高标准企业级的 Supabase 门槛并不低。
Supabase 内置了一系列由他们自己开发维护的 PG 扩展插件,并计划将原生的 PostgreSQL 内核替换为收购的 OrioleDB ,而这些内核与扩展在 PGDG 官方仓库中并没有提供。
这实际上是某种隐性的供应商锁定,阻止了用户使用除了 supabase/postgres Docker 镜像之外的方式自建,Pigsty 则提供开源,透明,通用的方案解决这个问题。
我们将所有 Supabase 自研与用到的 10 个缺失的扩展打成开箱即用的 RPM/DEB 包,确保它们在所有 主流Linux操作系统发行版 上都可用:
扩展 说明 pg_graphql提供PG内的GraphQL支持 (RUST),Rust扩展,由PIGSTY提供 pg_jsonschema提供JSON Schema校验能力,Rust扩展,由PIGSTY提供 wrappersSupabase提供的外部数据源包装器捆绑包,,Rust扩展,由PIGSTY提供 index_advisor查询索引建议器,SQL扩展,由PIGSTY提供 pg_net用 SQL 进行异步非阻塞HTTP/HTTPS 请求的扩展 (supabase),C扩展,由PIGSTY提供 vault在 Vault 中存储加密凭证的扩展 (supabase),C扩展,由PIGSTY提供 pgjwtJSON Web Token API 的PG实现 (supabase),SQL扩展,由PIGSTY提供 pgsodium表数据加密存储 TDE,扩展,由PIGSTY提供 supautils用于在云环境中确保数据库集群的安全,C扩展,由PIGSTY提供 pg_plan_filter使用执行计划代价过滤阻止特定查询语句,C扩展,由PIGSTY提供
同时,我们在 Supabase 自建部署中默认 安装 绝大多数扩展,您可以参考可用扩展列表按需 启用 。
同时,Pigsty 还会负责好底层 高可用 PostgreSQL 数据库集群,高可用 MinIO 对象存储集群的自动搭建,甚至是 Docker 容器底座的部署与 Nginx 反向代理,域名配置 与 HTTPS证书签发 。 您可以使用 Docker Compose 拉起任意数量的无状态 Supabase 容器集群,并将状态存储在外部 Pigsty 自托管数据库服务中。
在这一自建部署架构中,您获得了使用不同内核的自由(PG 15-18,OrioleDB),加装 437 个扩展的自由,扩容与伸缩 Supabase / Postgres / MinIO 的自由,
免于数据库运维杂务的自由,以及免于供应商锁定,本地运行到地老天荒的自由。 而相比于使用云服务需要付出的代价,不过是准备服务器和多敲几行命令而已。
单节点自建快速上手 让我们先从单节点 Supabase 部署开始,我们会在后面进一步介绍多节点高可用部署的方法。
准备 一台全新 Linux 服务器 ,使用 Pigsty 提供的 supabase 配置模板执行 标准安装 ,
然后额外运行 docker.yml 与 app.yml 拉起无状态部分的 Supabase 容器即可(默认端口 8000/8433)。
curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
./configure -c supabase # 使用 supabase 配置(请在 pigsty.yml 中更改凭据)
vi pigsty.yml # 编辑域名、密码、密钥...
./deploy.yml # 安装 pigsty
./docker.yml # 安装 docker compose 组件
./app.yml # 使用 docker 启动 supabase 无状态部分
在部署 Supabase 前请根据实际情况修改自动生成的 pigsty.yml 配置文件中的参数(域名与密码)
如果只是本地开发测试,可以先跳过,我们将在后面介绍如何通过修改配置文件来进一步定制。
如果配置无误,大约十分钟后,就可以在本地网络通过 http://<your_ip_address>:8000 访问到 Supabase Studio 图形管理界面了。
默认的用户名与密码分别是: supabase 与 pigsty。
注意事项:
在中国大陆地区,Pigsty 默认使用 1Panel 与 1ms 提供的 DockerHub 镜像站点下载 Supabase 相关镜像,可能会较慢。你也可以自行配置 代理 与 镜像站 ,cd /opt/supabase; docker compose pull 手动拉取镜像。我们亦提供包含完整离线安装方案的 Supabase 自建专家咨询服务。 如果你需要使用的对象存储功能,那么需要通过域名与 HTTPS 访问 Supabase,否则会出现报错。 对于严肃的生产部署,请 务必 修改所有默认密码! 自建关键技术决策 以下是一些自建 Supabase 会涉及到的关键技术决策,供您参考:
使用默认的单节点部署 Supabase 无法享受到 PostgreSQL / MinIO 的高可用能力。
尽管如此,单节点部署相比官方纯 Docker Compose 方案依然要有显著优势: 例如开箱即用的监控系统,自由安装扩展的能力,各个组件的扩缩容能力,以及提供兜底数据库时间点恢复能力等。
如果您只有一台服务器,或者选择在云服务器上自建,Pigsty 建议您使用外部的 S3 替代本地的 MinIO 作为对象存储,存放 PostgreSQL 的备份,并承载 Supabase Storage 服务。
这样的部署在故障时可以在单机部署条件下,提供一个兜底级别的 RTO (小时级恢复时长)/ RPO (MB级数据损失)容灾水平。
在严肃的生产部署中,Pigsty 建议使用至少3~4个节点的部署策略,确保 MinIO 与 PostgreSQL 都使用满足企业级高可用要求的多节点部署。 在这种情况下,您需要相应准备更多节点与磁盘,并相应调整 pigsty.yml 配置清单中的集群配置,以及 supabase 集群配置中的接入信息,使用高可用接入点访问服务。
Supabase 的部分功能需要发送邮件,所以要用到 SMTP 服务。除非单纯用于内网,否则对于严肃的生产部署,建议使用 SMTP 云服务。自建的邮件服务器发送的邮件容易被标记为垃圾邮件导致拒收。
如果您的服务直接向公网暴露,我们强烈建议您使用真正的域名与 HTTPS 证书,并通过 Nginx 门户 访问。
接下来,我们会依次讨论一些进阶主题。如何在单节点部署的基础上,进一步提升 Supabase 的安全性、可用性与性能。
进阶主题:安全加固 Pigsty基础组件
对于严肃的生产部署,我们强烈建议您修改 Pigsty 基础组件的密码。因为这些默认值是公开且众所周知的,不改密码上生产无异于裸奔:
以上密码为 Pigsty 组件模块的密码,强烈建议在安装部署前就设置完毕。
Supabase密钥
除了 Pigsty 组件的密码,你还需要 修改 Supabase 的密钥 ,包括
这里请您务必参照 Supabase教程:保护你的服务 里的说明:
Supabase 部分的凭据修改后,您可以重启 Docker Compose 容器以应用新的配置:
./app.yml -t app_config,app_launch # 使用剧本
cd /opt/supabase; make up # 手工执行
进阶主题:域名接入 如果你在本机或局域网内使用 Supabase,那么可以选择 IP:Port 直连 Kong 对外暴露的 HTTP 8000 端口访问 Supabase。
你可以使用一个内网静态解析的域名,但对于严肃的生产部署,我们建议您使用真域名 + HTTPS 来访问 Supabase。
在这种情况下,您的服务器应当有一个公网 IP 地址,你应当拥有一个域名,使用云/DNS/CDN 供应商提供的 DNS 解析服务,将其指向安装节点的公网 IP(可选默认下位替代:本地 /etc/hosts 静态解析)。
比较简单的做法是,直接批量替换占位域名(supa.pigsty)为你的实际域名,假设为 supa.pigsty.cc:
sed -ie 's/supa.pigsty.cc/supa.pigsty/g' ~/pigsty/pigsty.yml
如果你没有事先配置好,那么重载 Nginx 和 Supabase 的配置生效即可:
make nginx # 重载 nginx 配置
make cert # 申请 certbot 免费 HTTPS 证书
./app.yml # 重载 Supabase 配置
修改后的配置应当类似下面的片段:
all :
vars :
infra_portal :
supa :
domain : supa.pigsty.cc # 替换为你的域名!
endpoint : "10.10.10.10:8000"
websocket : true
certbot : supa.pigsty.cc # 证书名称,通常与域名一致即可
children :
supabase :
vars :
supabase : # the definition of supabase app
conf : # override /opt/supabase/.env
SITE_URL : https://supa.pigsty # <------- Change This to your external domain name
API_EXTERNAL_URL : https://supa.pigsty # <------- Otherwise the storage api may not work!
SUPABASE_PUBLIC_URL : https://supa.pigsty # <------- DO NOT FORGET TO PUT IT IN infra_portal!
完整的域名/HTTPS 配置可以参考 证书管理 教程,您也可以使用 Pigsty 自带的本地静态解析与自签发 HTTPS 证书作为下位替代。
进阶主题:外部对象存储 您可以使用 S3 或 S3 兼容的服务,来作为 PGSQL 备份与 Supabase 使用的对象存储。这里我们使用一个 阿里云 OSS 对象存储作为例子。
Pigsty 提供了一个 terraform/spec/aliyun-meta-s3.tf 模板,
可以用于在阿里云上拉起一台服务器,以及一个 OSS 存储桶。
首先,我们修改 all.children.supa.vars.apps.[supabase].conf 中 S3 相关的配置,将其指向阿里云 OSS 存储桶:
# if using s3/minio as file storage
S3_BUCKET : data # 替换为 S3 兼容服务的连接信息
S3_ENDPOINT : https://sss.pigsty:9000 # 替换为 S3 兼容服务的连接信息
S3_ACCESS_KEY : s3user_data # 替换为 S3 兼容服务的连接信息
S3_SECRET_KEY : S3User.Data # 替换为 S3 兼容服务的连接信息
S3_FORCE_PATH_STYLE : true # 替换为 S3 兼容服务的连接信息
S3_REGION : stub # 替换为 S3 兼容服务的连接信息
S3_PROTOCOL : https # 替换为 S3 兼容服务的连接信息
同样使用以下命令重载 Supabase 配置:
./app.yml -t app_config,app_launch
您同样可以使用 S3 作为 PostgreSQL 的备份仓库,在 all.vars.pgbackrest_repo 新增一个 aliyun 备份仓库的定义:
all :
vars :
pgbackrest_method : aliyun # pgbackrest 备份方法:local,minio,[其他用户定义的仓库...],本例中将备份存储到 MinIO 上
pgbackrest_repo: # pgbackrest 备份仓库 : https://pgbackrest.org/configuration.html#section-repository
aliyun : # 定义一个新的备份仓库 aliyun
type : s3 # 阿里云 oss 是 s3-兼容的对象存储
s3_endpoint : oss-cn-beijing-internal.aliyuncs.com
s3_region : oss-cn-beijing
s3_bucket : pigsty-oss
s3_key : xxxxxxxxxxxxxx
s3_key_secret : xxxxxxxx
s3_uri_style : host
path : /pgbackrest
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest.MyPass # 设置一个加密密码,pgBackRest 备份仓库的加密密码
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the last 14 days
然后在 all.vars.pgbackrest_mehod 中指定使用 aliyun 备份仓库,重置 pgBackrest 备份:
./pgsql.yml -t pgbackrest
Pigsty 会将备份仓库切换到外部对象存储上,更多备份配置可以参考 PostgreSQL 备份 文档。
进阶主题:使用SMTP 你可以使用 SMTP 来发送邮件,修改 supabase 应用配置,添加 SMTP 信息:
all :
children :
supabase : # supa group
vars : # supa group vars
apps : # supa group app list
supabase : # the supabase app
conf : # the supabase app conf entries
SMTP_HOST : smtpdm.aliyun.com:80
SMTP_PORT : 80
SMTP_USER : no_reply@mail.your.domain.com
SMTP_PASS : your_email_user_password
SMTP_SENDER_NAME : MySupabase
SMTP_ADMIN_EMAIL : adminxxx@mail.your.domain.com
ENABLE_ANONYMOUS_USERS : false
不要忘了使用 app.yml 来重载配置
进阶主题:真·高可用 经过这些配置,您拥有了一个带公网域名,HTTPS 证书,SMTP,PITR 备份,监控,IaC,以及 400+ 扩展的企业级 Supabase (基础单机版)。
高可用的配置请参考 Pigsty 其他部份的文档,如果您懒得阅读学习,我们提供手把手扶上马的 Supabase 自建专家咨询服务 —— ¥2000 元免去折腾与下载的烦恼。
单节点的 RTO / RPO 依赖外部对象存储服务提供兜底,如果您的这个节点挂了,外部 S3 存储中保留了备份,您可以在新的节点上重新部署 Supabase,然后从备份中恢复。
这样的部署在故障时可以提供一个最低标准的 RTO (小时级恢复时长)/ RPO (MB级数据损失)兜底容灾水平 兜底。
如果想要达到 RTO < 30s ,切换零数据丢失,那么需要使用多节点 进行高可用部署,这涉及到:
ETCD : DCS 需要使用三个节点或以上,才能容忍一个节点的故障。PGSQL : PGSQL 同步提交不丢数据模式,建议使用至少三个节点。INFRA :监控基础设施故障影响稍小,建议生产环境使用双副本Supabase 无状态容器本身也可以是多节点的副本,可以实现高可用。 在这种情况下,您还需要修改 PostgreSQL 与 MinIO 的接入点,使用 DNS / L2 VIP / HAProxy 等 高可用接入点
关于这些部分,您只需参考 Pigsty 中各个模块的文档进行配置部署即可。
建议您参考 conf/ha/trio.yml 与 conf/ha/safe.yml 中的配置,将集群规模升级到三节点或以上。
8.2 - Odoo:自建开源 ERP 如何拉起开箱即用的企业级应用全家桶 Odoo,并使用 Pigsty 管理其后端 PostgreSQL 数据库。
Odoo 是一个开源企业资源规划 (ERP) 软件,提供一整套业务应用程序,包括 CRM、销售、采购、库存、生产、会计和其他管理功能。Odoo 是一个典型的 Web 应用程序,使用 PostgreSQL 作为底层数据库。
您的所有业务,都在一个平台上,简单、高效且实惠
公开演示(不一定开放):http://odoo.pigsty.io, 用户名: test@pigsty.io, 密码: pigsty
快速开始 在运行兼容操作系统的全新 Linux x86 / ARM 服务器上执行:
curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
./bootstrap # 安装 ansible
./configure -c app/odoo # 使用 odoo 配置(请在 pigsty.yml 中更改凭据)
./deploy.yml # 安装 pigsty
./docker.yml # 安装 docker compose
./app.yml # 使用 docker 启动 odoo 无状态部分
Odoo 默认监听在 8069 端口,您可以通过浏览器访问 http://<ip>:8069。默认的用户名和密码都是 admin。
您可以在浏览器所在主机(/etc/hosts)添加一条解析记录 odoo.pigsty 指向您的服务器,这样您就可以通过 http://odoo.pigsty 访问 Odoo 网络界面了。
如果您想要通过 SSL/HTTPS 访问 Odoo,您需要使用真正的 SSL 证书,或者信任 Pigsty 自动生成的自签名 CA 证书。(当然,在 Chrome 浏览器中,您也可以使用敲击键入 thisisunsafe 来绕过证书验证)
配置模板 conf/app/odoo.yml 定义了一个模板配置文件,包含单个 Odoo 实例所需的资源。
all :
children :
# odoo 应用程序(默认用户名和密码:admin/admin)
odoo :
hosts : { 10.10.10.10 : {} }
vars :
app : odoo # 指定要安装的应用程序名称(在 apps 中)
apps : # 定义所有应用程序
odoo : # 应用程序名称应该有对应的 ~/app/odoo 文件夹
file : # 要创建的可选目录
- { path: /data/odoo ,state: directory, owner: 100, group : 101 }
- { path: /data/odoo/webdata ,state: directory, owner: 100, group : 101 }
- { path: /data/odoo/addons ,state: directory, owner: 100, group : 101 }
conf : # 覆盖 /opt/<app>/.env 配置文件
PG_HOST : 10.10.10.10 # postgres 主机
PG_PORT : 5432 # postgres 端口
PG_USERNAME : odoo # postgres 用户
PG_PASSWORD : DBUser.Odoo # postgres 密码
ODOO_PORT : 8069 # odoo 应用程序端口
ODOO_DATA : /data/odoo/webdata # odoo webdata
ODOO_ADDONS : /data/odoo/addons # odoo 插件
ODOO_DBNAME : odoo # odoo 数据库名称
ODOO_VERSION : 19.0 # odoo 镜像版本
# odoo 数据库
pg-odoo :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-odoo
pg_users :
- { name: odoo ,password: DBUser.Odoo ,pgbouncer: true ,roles: [ dbrole_admin ] ,createdb: true ,comment : admin user for odoo service }
- { name: odoo_ro ,password: DBUser.Odoo ,pgbouncer: true ,roles: [ dbrole_readonly ] ,comment : read only user for odoo service }
- { name: odoo_rw ,password: DBUser.Odoo ,pgbouncer: true ,roles: [ dbrole_readwrite ] ,comment : read write user for odoo service }
pg_databases :
- { name: odoo ,owner: odoo ,revokeconn: true ,comment : odoo main database }
pg_hba_rules :
- { user: all ,db: all ,addr: 172.17.0.0/16 ,auth: pwd ,title : 'allow access from local docker network' }
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 } }, vars: { minio_cluster: minio } }
vars : # 全局变量
version : v3.7.0 # pigsty 版本字符串
admin_ip : 10.10.10.10 # 管理节点 ip 地址
region : default # 上游镜像区域:default|china|europe
node_tune : oltp # 节点调优规格:oltp,olap,tiny,crit
pg_conf : oltp.yml # pgsql 调优规格:{oltp,olap,tiny,crit}.yml
docker_enabled : true # 在应用程序组上启用 docker
#docker_registry_mirrors: ["https://docker.m.daocloud.io"] # 在中国大陆使用道云镜像
proxy_env : # 下载包和拉取 docker 镜像时的全局代理环境
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.tsinghua.edu.cn"
#http_proxy: 127.0.0.1:12345 # 在此处添加代理环境以下载包或拉取镜像
#https_proxy: 127.0.0.1:12345 # 通常代理格式为 http://user:pass@proxy.xxx.com
#all_proxy: 127.0.0.1:12345
infra_portal : # 域名和上游服务器
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9058" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
minio : { domain: m.pigsty ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
odoo : { domain: odoo.pigsty, endpoint : "127.0.0.1:8069" ,websocket: true } #cert: /path/to/crt ,key : /path/to/key
# 在这里设置您自己的域名 ^^^,或使用默认域名,或 ip + 8069 端口直接访问
# certbot --nginx --agree-tos --email your@email.com -n -d odoo.your.domain # 替换为您的邮箱和 odoo 域名
#----------------------------------#
# 凭据:更改这些密码
#----------------------------------#
#grafana_admin_username: admin
grafana_admin_password : pigsty
#pg_admin_username: dbuser_dba
pg_admin_password : DBUser.DBA
#pg_monitor_username: dbuser_monitor
pg_monitor_password : DBUser.Monitor
#pg_replication_username: replicator
pg_replication_password : DBUser.Replicator
#patroni_username: postgres
patroni_password : Patroni.API
#haproxy_admin_username: admin
haproxy_admin_password : pigsty
repo_modules : infra,node,pgsql,docker
repo_packages : [ node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, docker ]
repo_extra_packages : [ pg18-main ]
pg_version : 18
基础 检查 .env 文件中的可配置环境变量:
# https://hub.docker.com/_/odoo#
PG_HOST = 10.10.10.10
PG_PORT = 5432
PG_USER = dbuser_odoo
PG_PASS = DBUser.Odoo
ODOO_PORT = 8069
然后使用以下命令启动 odoo:
make up # docker compose up
访问 http://ddl.pigsty 或 http://10.10.10.10:8887
Makefile make up # 在最小模式下使用 docker compose 启动 odoo
make run # 使用 docker 启动 odoo,本地数据目录和外部 PostgreSQL
make view # 打印 odoo 访问点
make log # tail -f odoo 日志
make info # 使用 jq 检查 odoo
make stop # 停止 odoo 容器
make clean # 移除 odoo 容器
make pull # 拉取最新的 odoo 镜像
make rmi # 移除 odoo 镜像
make save # 保存 odoo 镜像到 /tmp/docker/odoo.tgz
make load # 从 /tmp/docker/odoo.tgz 加载 odoo 镜像
使用外部 PostgreSQL 您可以为 Odoo 使用外部 PostgreSQL。Odoo 将在设置期间创建自己的数据库,因此您不需要这样做
pg_users : [ { name: dbuser_odoo ,password: DBUser.Odoo ,pgbouncer: true ,roles: [ dbrole_admin ] ,comment : admin user for odoo database } ]
pg_databases : [ { name: odoo ,owner: dbuser_odoo ,revokeconn: true ,comment : odoo primary database } ]
并使用以下命令创建业务用户和数据库:
bin/pgsql-user pg-meta dbuser_odoo
#bin/pgsql-db pg-meta odoo # odoo 将在设置期间创建数据库
检查连接性:
psql postgres://dbuser_odoo:DBUser.Odoo@10.10.10.10:5432/odoo
暴露 Odoo 服务 通过 nginx 门户 暴露 odoo Web 服务:
infra_portal : # 域名和上游服务器
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9058" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
odoo : { domain: odoo.pigsty, endpoint : "127.0.0.1:8069" , websocket : true } # <------ 添加这一行
./infra.yml -t nginx # 设置 nginx 基础设施门户
Odoo 插件 社区中有很多 Odoo 模块可用,您可以通过下载并将它们放在 addons 文件夹中来安装它们。
volumes :
- ./addons:/mnt/extra-addons
您可以将 ./addons 目录挂载到容器中的 /mnt/extra-addons,然后下载并解压到 addons 文件夹,
要启用插件模块,首先进入 开发者模式
设置 -> 通用设置 -> 开发者工具 -> 激活开发者模式
然后转到 > 应用程序 -> 更新应用程序列表,然后您可以找到额外的插件并从面板安装。
常用的 免费 插件:会计套件
演示 查看公共演示:http://odoo.pigsty.io ,用户名:test@pigsty.io,密码:pigsty
如果您想通过 SSL 访问 odoo,您必须在浏览器中信任 files/pki/ca/ca.crt(或在 chrome 中使用肮脏的黑客 thisisunsafe)
8.3 - Dify:AI 工作流平台 如何使用 Pigsty 自建 AI Workflow LLMOps 平台 —— Dify,并使用外部 PostgreSQL,PGVector,Redis 作为存储?
Dify 是一个生成式 AI 应用创新引擎和开源 LLM 应用开发平台。它提供从 Agent 构建到 AI 工作流编排、RAG 检索和模型管理的能力,帮助用户轻松构建和运营生成式 AI 原生应用程序。
Pigsty 提供对自托管 Dify 的支持,允许您使用单个命令部署 Dify,同时将关键状态存储在外部管理的 PostgreSQL 中。您可以在同一个 PostgreSQL 实例中使用 pgvector 作为向量数据库,进一步简化部署。
当前 Pigsty v3.4 支持 Dify 版本:v1.1.3
快速开始 在运行 兼容操作系统 的全新 Linux x86 / ARM 服务器上执行:
curl -fsSL https://repo.pigsty.cc/get | bash; cd ~/pigsty
./bootstrap # 安装 Pigsty 依赖
./configure -c app/dify # 使用 Dify 配置模板
vi pigsty.yml # 编辑密码、域名、密钥等
./deploy.yml # 安装 Pigsty
./docker.yml # 安装 Docker 和 Compose
./app.yml # 安装 Dify
Dify 默认监听端口 5001。您可以通过浏览器访问 http://<ip>:5001 并设置您的初始用户凭据来登录。
Dify 启动后,您可以安装各种扩展、配置系统模型并开始使用它!
为什么要自托管 自托管 Dify 有很多原因,但主要动机是数据安全。Dify 提供的 DockerCompose 模板使用基本的默认数据库镜像,缺乏企业级功能,如高可用性、灾难恢复、监控、IaC 和 PITR 能力。
Pigsty 为 Dify 优雅地解决了这些问题,基于配置文件使用单个命令部署所有组件,并使用镜像解决中国地区访问挑战。这使得 Dify 部署和交付变得非常顺畅。它一次性处理 PostgreSQL 主数据库、PGVector 向量数据库、MinIO 对象存储、Redis、Prometheus 监控、Grafana 可视化、Nginx 反向代理和免费 HTTPS 证书。
Pigsty 确保所有 Dify 状态都存储在外部管理的服务中,包括 PostgreSQL 中的元数据和文件系统中的其他数据。通过 Docker Compose 启动的 Dify 实例成为可以随时销毁和重建的无状态应用程序,大大简化了运维。
安装 让我们从单节点 Dify 部署开始。我们稍后将介绍生产高可用部署方法。
首先,使用 Pigsty 的 标准安装过程 安装 Dify 所需的 PostgreSQL 实例:
curl -fsSL https://repo.pigsty.cc/get | bash; cd ~/pigsty
./bootstrap # 准备 Pigsty 依赖
./configure -c app/dify # 使用 Dify 应用程序模板
vi pigsty.yml # 编辑配置文件,修改域名和密码
./deploy.yml # 安装 Pigsty 和各种数据库
当您使用 ./configure -c app/dify 命令时,Pigsty 会根据 conf/app/dify.yml 模板和您当前的环境自动生成配置文件。
您应该根据实际需要在生成的 pigsty.yml 配置文件中修改密码、域名和其他相关参数,然后使用 ./deploy.yml 执行标准安装过程。
接下来,运行 docker.yml 安装 Docker 和 Docker Compose,然后使用 app.yml 完成 Dify 部署:
./docker.yml # 安装 Docker 和 Docker Compose
./app.yml # 使用 Docker 部署 Dify 无状态组件
您可以在本地网络上通过 http://<your_ip_address>:5001 访问 Dify Web 管理界面。
首次登录时会提示设置默认用户名、邮箱和密码。
您也可以使用本地解析的占位符域名 dify.pigsty,或按照下面的配置使用带有 HTTPS 证书的真实域名。
配置 当您使用 ./configure -c app/dify 命令进行配置时,Pigsty 会根据 conf/app/dify.yml 模板和您当前的环境自动生成配置文件。以下是默认配置的详细说明:
all :
children :
# dify 应用程序
dify :
hosts : { 10.10.10.10 : {} }
vars :
app : dify # 指定要安装的应用程序名称(在 apps 中)
apps : # 定义所有应用程序
dify : # 应用程序名称,应该有对应的 ~/pigsty/app/dify 文件夹
file : # 要创建的数据目录
- { path: /data/dify ,state: directory ,mode : 0755 }
conf : # 覆盖 /opt/dify/.env 配置文件
# 更改域名、镜像、代理、密钥
NGINX_SERVER_NAME : dify.pigsty
# 用于签名和加密的密钥,使用 `openssl rand -base64 42` 生成(更改密码!)
SECRET_KEY : sk-9f73s3ljTXVcMT3Blb3ljTqtsKiGHXVcMT3BlbkFJLK7U
# 默认使用端口 5001 暴露 DIFY nginx 服务
DIFY_PORT : 5001
# dify 文件存储位置?默认是 ./volume,我们将使用上面创建的另一个卷
DIFY_DATA : /data/dify
# 代理和镜像设置
#PIP_MIRROR_URL: https://pypi.tuna.tsinghua.edu.cn/simple
#SANDBOX_HTTP_PROXY: http://10.10.10.10:12345
#SANDBOX_HTTPS_PROXY: http://10.10.10.10:12345
# 数据库凭据
DB_USERNAME : dify
DB_PASSWORD : difyai123456
DB_HOST : 10.10.10.10
DB_PORT : 5432
DB_DATABASE : dify
VECTOR_STORE : pgvector
PGVECTOR_HOST : 10.10.10.10
PGVECTOR_PORT : 5432
PGVECTOR_USER : dify
PGVECTOR_PASSWORD : difyai123456
PGVECTOR_DATABASE : dify
PGVECTOR_MIN_CONNECTION : 2
PGVECTOR_MAX_CONNECTION : 10
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dify ,password: difyai123456 ,pgbouncer: true ,roles: [ dbrole_admin ] ,superuser: true ,comment : dify superuser }
pg_databases :
- { name: dify ,owner: dify ,revokeconn: true ,comment : dify main database }
pg_hba_rules :
- { user: dify ,db: all ,addr: 172.17.0.0/16 ,auth: pwd ,title : 'allow dify access from local docker network' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # 每天凌晨 1 点进行完整备份
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 } }, vars: { minio_cluster: minio } }
vars : # 全局变量
version : v3.4.1 # pigsty 版本字符串
admin_ip : 10.10.10.10 # 管理节点 ip 地址
region : default # 上游镜像区域:default|china|europe
node_tune : oltp # 节点调优规格:oltp,olap,tiny,crit
pg_conf : oltp.yml # pgsql 调优规格:{oltp,olap,tiny,crit}.yml
docker_enabled : true # 在应用程序组上启用 docker
#docker_registry_mirrors: ["https://docker.1ms.run"] # 在中国大陆使用镜像
proxy_env : # 下载包和拉取 docker 镜像时的全局代理环境
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.tsinghua.edu.cn"
#http_proxy: 127.0.0.1:12345 # 在此处添加代理环境以下载包或拉取镜像
#https_proxy: 127.0.0.1:12345 # 通常代理格式为 http://user:pass@proxy.xxx.com
#all_proxy: 127.0.0.1:12345
infra_portal : # 域名和上游服务器
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9058" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
dify : # dify 的 nginx 服务器配置
domain : dify.pigsty # 替换为您自己的域名!
endpoint : "10.10.10.10:5001" # dify 服务端点:IP:PORT
websocket : true # 添加 websocket 支持
certbot : dify.pigsty # certbot 证书名称,使用 `make cert` 申请
#----------------------------------#
# 凭据:更改这些密码
#----------------------------------#
#grafana_admin_username: admin
grafana_admin_password : pigsty
#pg_admin_username: dbuser_dba
pg_admin_password : DBUser.DBA
#pg_monitor_username: dbuser_monitor
pg_monitor_password : DBUser.Monitor
#pg_replication_username: replicator
pg_replication_password : DBUser.Replicator
#patroni_username: postgres
patroni_password : Patroni.API
#haproxy_admin_username: admin
haproxy_admin_password : pigsty
#minio_access_key: minioadmin
minio_secret_key : minioadmin # minio root 密钥,默认为 `minioadmin`
repo_extra_packages : [ pg17-main ]
pg_version : 17
检查清单 以下是您需要关注的配置项检查清单:
硬件/软件:准备所需的机器资源 :Linux x86_64/arm64 服务器,主流 Linux 操作系统 的全新安装 网络/权限:SSH 免密登录访问权限,用户具有 免密 sudo 权限 确保机器在内网中有静态 IPv4 网络地址且可访问互联网 如果通过公网访问,确保您有可用的域名指向当前节点的 公网 IP 地址 确保使用 app/dify 配置模板并根据需要修改参数configure -c app/dify,并输入节点的内网主 IP 地址,或通过 -i <primary_ip> 命令行参数指定 您是否修改了所有密码相关的配置参数?【可选】 您是否修改了 PostgreSQL 集群业务用户密码和使用这些密码的应用程序配置?默认用户名 dify 和密码 difyai123456 是 Pigsty 为 Dify 生成的,请根据实际情况修改 在 Dify 的配置块中,请相应修改 DB_USERNAME、DB_PASSWORD、PGVECTOR_USER、PGVECTOR_PASSWORD 等参数 您是否修改了 Dify 的默认加密密钥?您可以使用 openssl rand -base64 42 随机生成密码字符串并填入 SECRET_KEY 参数 您是否修改了 Dify 使用的域名?将占位符域名 dify.pigsty 替换为您的实际域名,例如 dify.pigsty.cc 您可以使用 sed -ie 's/dify.pigsty/dify.pigsty.cc/g' pigsty.yml 修改 Dify 的域名 域名和 SSL 如果您想使用带有 HTTPS 证书的真实域名,需要在 pigsty.yml 配置文件中修改:
all :
children : # 集群定义
dify : # Dify 组
vars : # Dify 组变量
apps : # 应用程序配置
dify : # Dify 应用程序定义
conf : # Dify 应用程序配置
NGINX_SERVER_NAME : dify.pigsty
vars : # 全局参数
#certbot_sign: true # 使用 Certbot 申请免费 HTTPS 证书
certbot_email : your@email.com # 证书申请邮箱,用于过期通知,可选
infra_portal : # 配置 Nginx 服务器
dify : # Dify 服务器定义
domain : dify.pigsty # 请在此处替换为您自己的域名!
endpoint : "10.10.10.10:5001" # 请在此处指定 Dify 的 IP 和端口(默认自动配置)
websocket : true # Dify 需要启用 websocket
certbot : dify.pigsty # 指定 Certbot 证书名称
使用以下命令申请 Nginx 证书:
# 申请证书,也可以手动执行 /etc/nginx/sign-cert 脚本
make cert
# 上述 Makefile 快捷命令实际执行以下剧本任务:
./infra.yml -t nginx_certbot,nginx_reload -e certbot_sign = true
执行 app.yml 剧本重新部署 Dify 服务以使 NGINX_SERVER_NAME 配置生效。
文件备份 您可以使用 restic 备份 Dify 的文件存储(默认位于 /data/dify 目录),使用以下命令进行备份:
export RESTIC_REPOSITORY = /data/backups/dify # 指定 dify 备份目录
export RESTIC_PASSWORD = some-strong-password # 指定备份加密密码
mkdir -p ${ RESTIC_REPOSITORY } # 创建 dify 备份目录
restic init
创建 Restic 备份仓库后,您可以使用以下命令备份 Dify:
export RESTIC_REPOSITORY = /data/backups/dify # 指定 dify 备份目录
export RESTIC_PASSWORD = some-strong-password # 指定备份加密密码
restic backup /data/dify # 将 /dify 数据目录备份到仓库
restic snapshots # 查看备份快照列表
restic restore -t /data/dify 0b11f778 # 将快照 xxxxxx 恢复到 /data/dify
restic check # 定期检查仓库完整性
另一种更可靠的方法是使用 JuiceFS 将 MinIO 对象存储挂载到 /data/dify 目录,这样您就可以使用 MinIO/S3 存储文件状态。
如果您想将所有数据存储在 PostgreSQL 中,请考虑"使用 JuiceFS 将文件系统数据存储在 PostgreSQL 中"
例如,您可以创建另一个 dify_fs 数据库并将其用作 JuiceFS 的元数据存储:
METAURL = postgres://dify:difyai123456@:5432/dify_fs
OPTIONS =(
--storage postgres
--bucket :5432/dify_fs
--access-key dify
--secret-key difyai123456
${ METAURL }
jfs
)
juicefs format " ${ OPTIONS [@] } " # 创建 PG 文件系统
juicefs mount ${ METAURL } /data/dify -d # 后台挂载到 /data/dify 目录
juicefs bench /data/dify # 测试性能
juicefs umount /data/dify # 停止挂载
参考 Dify 自托管常见问题
8.5 - NocoDB:开源 Airtable 使用 NocoDB 将 PostgreSQL 数据库转变为智能电子表格,无代码数据库应用平台。
NocoDB 是一个开源的 Airtable 替代方案,可以将任何数据库转变为智能电子表格。
它提供了丰富的用户界面,让您无需编写代码即可创建强大的数据库应用。NocoDB 支持 PostgreSQL、MySQL、SQL Server 等多种数据库,是构建内部工具和数据管理系统的理想选择。
快速开始 在 Pigsty 软件模板目录中提供了 NocoDB 的 Docker Compose 配置文件:
检查并修改 .env 配置文件(根据需要调整数据库连接等配置)。
启动服务:
make up # 使用 Docker Compose 启动 NocoDB
访问 NocoDB:
管理命令 Pigsty 提供了便捷的 Makefile 命令来管理 NocoDB 服务:
make up # 启动 NocoDB 服务
make run # 使用 Docker 启动(连接外部 PostgreSQL)
make view # 显示 NocoDB 访问地址
make log # 查看容器日志
make info # 查看服务详细信息
make stop # 停止服务
make clean # 停止并移除容器
make pull # 拉取最新镜像
make rmi # 移除 NocoDB 镜像
make save # 保存镜像到 /tmp/nocodb.tgz
make load # 从 /tmp/nocodb.tgz 加载镜像
连接 PostgreSQL NocoDB 可以连接到 Pigsty 管理的 PostgreSQL 数据库。
在 NocoDB 界面中添加新项目时,选择「External Database」,然后输入 PostgreSQL 连接信息:
主机:10.10.10.10
端口:5432
数据库名:your_database
用户名:your_username
密码:your_password
SSL:禁用(或根据实际情况启用)
连接成功后,NocoDB 会自动读取数据库的表结构,您可以通过可视化界面进行数据管理。
功能特性 智能电子表格界面 :类似 Excel/Airtable 的用户体验多种视图 :网格、表单、看板、日历、画廊视图协作功能 :团队协作、权限管理、评论API 支持 :自动生成 REST API集成能力 :支持 Webhook、Zapier 等集成数据导入导出 :支持 CSV、Excel 等格式公式和验证 :支持复杂的数据计算和验证规则配置说明 NocoDB 的配置在 .env 文件中:
# 数据库连接(NocoDB 元数据存储)
NC_DB = pg://postgres:DBUser.Postgres@10.10.10.10:5432/nocodb
# JWT 密钥(建议修改)
NC_AUTH_JWT_SECRET = your-secret-key
# 其他配置
NC_PUBLIC_URL = http://nocodb.pigsty
NC_DISABLE_TELE = true
数据持久化 NocoDB 的元数据默认存储在外部 PostgreSQL 数据库中,应用数据也可以存储在 PostgreSQL 中。
如果使用本地存储,数据会保存在 /data/nocodb 目录中。
安全建议 修改默认密钥 :在 .env 文件中修改 NC_AUTH_JWT_SECRET使用强密码 :为管理员账户设置强密码配置 HTTPS :生产环境建议启用 HTTPS限制访问 :通过防火墙或 Nginx 限制访问权限定期备份 :定期备份 NocoDB 元数据库相关链接 8.6 - Teable:AI 无代码数据库 使用 Teable 构建 AI 驱动的无代码数据库应用,提升团队生产力。
Teable 是一个 AI 驱动的无代码数据库平台,专为团队协作和自动化而设计。
Teable 将数据库的强大功能与电子表格的易用性完美结合,并集成 AI 能力,帮助团队高效地生成、自动化和协作处理数据。
快速开始 Teable 需要完整的 Pigsty 环境支持(包括 PostgreSQL、Redis、MinIO)。
准备环境 cd ~/pigsty
./bootstrap # 准备本地源与 Ansible
./configure -c app/teable # 重要:修改默认凭据!
./deploy.yml # 安装 Pigsty、PostgreSQL、MinIO
./redis.yml # 安装 Redis 实例
./docker.yml # 安装 Docker 与 Docker Compose
./app.yml # 使用 Docker Compose 安装 Teable
访问服务 管理命令 在 Pigsty 软件模板目录中管理 Teable:
cd ~/pigsty/app/teable
make up # 启动 Teable 服务
make down # 停止 Teable 服务
make log # 查看容器日志
make clean # 清理容器和数据
架构说明 Teable 依赖以下组件:
PostgreSQL :存储应用数据和元数据Redis :缓存和会话管理MinIO :对象存储(文件、图片等)Docker :容器运行环境确保这些服务在部署 Teable 前已正确安装。
功能特性 AI 集成 :内置 AI 助手,自动生成数据、公式和工作流智能表格 :强大的表格功能,支持多种字段类型自动化工作流 :无代码自动化,提升团队效率多视图支持 :网格、表单、看板、日历等多种视图团队协作 :实时协作、权限管理、评论API 和集成 :自动生成 API,支持 Webhook 集成模板库 :丰富的应用模板,快速启动项目配置说明 Teable 的配置通过环境变量管理,主要配置在 docker-compose.yml 中:
# PostgreSQL 连接
POSTGRES_HOST=10.10.10.10
POSTGRES_PORT=5432
POSTGRES_DB=teable
POSTGRES_USER=dbuser_teable
POSTGRES_PASSWORD=DBUser.Teable
# Redis 连接
REDIS_HOST=10.10.10.10
REDIS_PORT=6379
REDIS_DB=0
# MinIO 连接
MINIO_ENDPOINT=http://10.10.10.10:9000
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=minioadmin
# 应用配置
BACKEND_URL=http://teable.pigsty
PUBLIC_ORIGIN=http://teable.pigsty
重要 :在生产环境中,请修改所有默认密码和密钥!
数据持久化 Teable 的数据持久化依赖:
PostgreSQL :所有结构化数据存储在 PostgreSQL 中MinIO :文件、图片等非结构化数据存储在 MinIO 中Redis :缓存数据(可选持久化)定期备份 PostgreSQL 数据库和 MinIO 存储桶以确保数据安全。
安全建议 修改默认凭据 :在配置文件中修改所有默认用户名和密码启用 HTTPS :生产环境建议配置 SSL 证书配置防火墙 :限制对服务的访问定期备份 :定期备份 PostgreSQL 和 MinIO 数据更新组件 :及时更新 Teable 和依赖组件的版本相关链接 8.7 - Gitea:自建简易代码托管平台 使用Docker拉起Gitea,并使用Pigsty的PG作为外部的元数据库
公开Demo地址:http://git.pigsty.cc
太长;不看 cd ~/pigsty/app/gitea; make up
在本例中,Gitea 默认使用 8889 端口,您可以访问以下位置:
http://git.pigsty 或 http://10.10.10.10:8889
make up # pull up gitea with docker-compose in minimal mode
make run # launch gitea with docker , local data dir and external PostgreSQL
make view # print gitea access point
make log # tail -f gitea logs
make info # introspect gitea with jq
make stop # stop gitea container
make clean # remove gitea container
make pull # pull latest gitea image
make rmi # remove gitea image
make save # save gitea image to /tmp/gitea.tgz
make load # load gitea image from /tmp
使用外部的PostgreSQL Pigsty默认使用容器内的 Sqlite 作为元数据存储,您可以让 Gitea 通过连接串环境变量使用外部的PostgreSQL
# postgres://dbuser_gitea:DBUser.gitea@10.10.10.10:5432/gitea
db : { name: gitea, owner: dbuser_gitea, comment : gitea primary database }
user : { name: dbuser_gitea , password: DBUser.gitea, roles : [ dbrole_admin ] }
8.8 - Wiki.js:维基百科站 如何使用 Wiki.js 搭建你自己的开源维基百科,并使用 Pigsty 管理的PG作为持久数据存储
公开Demo地址:http://wiki.pigsty.cc
太长;不看 cd app/wiki ; docker-compose up -d
准备数据库 # postgres://dbuser_wiki:DBUser.Wiki@10.10.10.10:5432/wiki
- { name: wiki, owner: dbuser_wiki, revokeconn: true , comment : wiki the api gateway database }
- { name: dbuser_wiki, password: DBUser.Wiki , pgbouncer: true , roles : [ dbrole_admin ] }
bin/createuser pg-meta dbuser_wiki
bin/createdb pg-meta wiki
容器配置 version : "3"
services :
wiki :
container_name : wiki
image : requarks/wiki:2
environment :
DB_TYPE : postgres
DB_HOST : 10.10.10.10
DB_PORT : 5432
DB_USER : dbuser_wiki
DB_PASS : DBUser.Wiki
DB_NAME : wiki
restart : unless-stopped
ports :
- "9002:3000"
Access Default Port for wiki: 9002 # add to nginx_upstream
- { name: wiki , domain: wiki.pigsty.cc , endpoint : "127.0.0.1:9002" }
./infra.yml -t nginx_config
ansible all -b -a 'nginx -s reload'
8.9 - Mattermost:开源 IM 使用 Mattermost 构建私有化的团队协作平台,开源的 Slack 替代方案。
Mattermost 是一个开源的团队协作和消息平台。
Mattermost 提供即时消息、文件共享、音视频通话等功能,是 Slack 和 Microsoft Teams 的开源替代方案,特别适合需要私有化部署的企业。
快速开始 cd ~/pigsty/app/mattermost
make up # 使用 Docker Compose 启动 Mattermost
访问地址: http://mattermost.pigsty 或 http://10.10.10.10:8065
首次访问需要创建管理员账户。
功能特性 即时消息 :个人和群组聊天频道管理 :公开和私有频道文件共享 :安全的文件存储和共享音视频通话 :内置通话功能集成能力 :支持 Webhook、Bot、插件移动应用 :iOS 和 Android 客户端企业级 :SSO、LDAP、合规性功能连接 PostgreSQL Mattermost 使用 PostgreSQL 存储数据,在配置中指定连接信息:
MM_SQLSETTINGS_DRIVERNAME = postgres
MM_SQLSETTINGS_DATASOURCE = postgres://dbuser_mm:DBUser.MM@10.10.10.10:5432/mattermost
相关链接 8.10 - Maybe:个人财务管理 使用 Maybe 管理个人财务,开源的 Mint/Personal Capital 替代方案。
Maybe 是一个开源的个人财务管理应用。
Maybe 提供财务跟踪、预算管理、投资分析等功能,是 Mint 和 Personal Capital 的开源替代方案,让您完全掌控自己的财务数据。
快速开始 cd ~/pigsty/app/maybe
cp .env.example .env
vim .env # 必须修改 SECRET_KEY_BASE
make up # 启动 Maybe 服务
访问地址: http://maybe.pigsty 或 http://10.10.10.10:5002
配置说明 在 .env 文件中配置:
SECRET_KEY_BASE = your-secret-key-here # 必须修改!
DATABASE_URL = postgresql://...
重要 :首次部署前必须修改 SECRET_KEY_BASE!
功能特性 账户管理 :追踪多个银行账户和信用卡预算规划 :设置和跟踪预算投资分析 :监控投资组合表现账单提醒 :自动提醒即将到期的账单隐私优先 :数据完全在您的控制之下相关链接 8.11 - Metabase:BI 分析工具 使用 Metabase 进行快速的商业智能分析,友好的用户界面让团队自主探索数据。
Metabase 是一个快速、易用的开源商业智能工具,让您的团队无需 SQL 知识即可探索和可视化数据。
Metabase 提供友好的用户界面和丰富的图表类型,支持连接多种数据库,是企业数据分析的理想选择。
快速开始 在 Pigsty 软件模板目录中提供了 Metabase 的 Docker Compose 配置文件:
检查并修改 .env 配置文件:
启动服务:
make up # 使用 Docker Compose 启动 Metabase
访问 Metabase:
管理命令 Pigsty 提供了便捷的 Makefile 命令来管理 Metabase 服务:
make up # 启动 Metabase 服务
make run # 使用 Docker 启动(连接外部 PostgreSQL)
make view # 显示 Metabase 访问地址
make log # 查看容器日志
make info # 查看服务详细信息
make stop # 停止服务
make clean # 停止并移除容器
make pull # 拉取最新镜像
make rmi # 移除 Metabase 镜像
make save # 保存镜像到文件
make load # 从文件加载镜像
连接 PostgreSQL Metabase 可以连接到 Pigsty 管理的 PostgreSQL 数据库。
在 Metabase 初始化或添加数据库时,选择「PostgreSQL」,然后输入连接信息:
数据库类型:PostgreSQL
名称:自定义名称(如 "生产数据库")
主机:10.10.10.10
端口:5432
数据库名:your_database
用户名:dbuser_meta
密码:DBUser.Meta
连接成功后,Metabase 会自动扫描数据库结构,您可以开始创建问题和仪表板。
功能特性 无需 SQL :通过可视化界面构建查询丰富的图表类型 :折线图、柱状图、饼图、地图等交互式仪表板 :创建美观的数据仪表板自动刷新 :定时更新数据和仪表板权限管理 :精细的用户和数据访问控制SQL 模式 :高级用户可以直接编写 SQL嵌入功能 :将图表嵌入到其他应用告警功能 :数据变化自动通知配置说明 Metabase 的配置在 .env 文件中:
# Metabase 元数据库(建议使用 PostgreSQL)
MB_DB_TYPE = postgres
MB_DB_DBNAME = metabase
MB_DB_PORT = 5432
MB_DB_USER = dbuser_metabase
MB_DB_PASS = DBUser.Metabase
MB_DB_HOST = 10.10.10.10
# 应用配置
JAVA_OPTS = -Xmx2g
建议 :为 Metabase 使用独立的 PostgreSQL 数据库存储元数据。
数据持久化 Metabase 的元数据(用户、问题、仪表板等)存储在配置的数据库中。
如果使用 H2 数据库(默认),数据会保存在 /data/metabase 目录。强烈建议在生产环境中使用 PostgreSQL 作为元数据库。
性能优化 使用 PostgreSQL :替代默认的 H2 数据库增加内存 :通过 JAVA_OPTS=-Xmx4g 增加 JVM 内存数据库索引 :为常查询的字段创建索引结果缓存 :启用 Metabase 的查询结果缓存定时更新 :合理设置仪表板的自动刷新频率安全建议 修改默认凭据 :修改元数据库的用户名和密码启用 HTTPS :生产环境配置 SSL 证书配置认证 :启用 SSO 或 LDAP 认证限制访问 :通过防火墙限制访问定期备份 :备份 Metabase 元数据库相关链接 8.12 - Kong:API 网关 拉起基于 Nginx 与 OpenResty 的强力开源 API 网关,并使用 PostgreSQL 与 Redis 作为其后端状态存储
TL;DR cd app/kong ; docker-compose up -d
make up # pull up kong with docker-compose
make ui # run swagger ui container
make log # tail -f kong logs
make info # introspect kong with jq
make stop # stop kong container
make clean # remove kong container
make rmui # remove swagger ui container
make pull # pull latest kong image
make rmi # remove kong image
make save # save kong image to /tmp/kong.tgz
make load # load kong image from /tmp
Scripts Default Port: 8000 Default SSL Port: 8443 Default Admin Port: 8001 Default Postgres Database: postgres://dbuser_kong:DBUser.Kong@10.10.10.10:5432/kong # postgres://dbuser_kong:DBUser.Kong@10.10.10.10:5432/kong
- { name: kong, owner: dbuser_kong, revokeconn: true , comment : kong the api gateway database }
- { name: dbuser_kong, password: DBUser.Kong , pgbouncer: true , roles : [ dbrole_admin ] }
8.13 - Registry:容器镜像仓库 部署 Docker Registry 镜像服务,加速 Docker 镜像拉取,特别适合中国用户。
Docker Registry 镜像服务用于缓存 Docker Hub 和其他镜像仓库的镜像。
特别适合中国用户或访问 Docker Hub 速度较慢的地区,显著减少镜像拉取时间。
快速开始 cd ~/pigsty/app/registry
make up # 启动 Registry 镜像服务
访问地址: http://registry.pigsty 或 http://10.10.10.10:5000
功能特性 镜像缓存 :缓存 Docker Hub 和其他仓库的镜像Web 界面 :可选的镜像管理界面高性能 :本地缓存大幅提升拉取速度存储管理 :可配置的清理和管理策略健康检查 :内置健康检查端点配置 Docker 配置 Docker 使用本地镜像:
# 编辑 /etc/docker/daemon.json
{
"registry-mirrors" : [ "http://10.10.10.10:5000" ]
}
# 重启 Docker
systemctl restart docker
存储管理 镜像数据存储在 /data/registry 目录,建议预留至少 100GB 空间。
相关链接 8.15 - ByteBase:模式迁移 使用Docker拉起Bytebase,对PG的模式进行版本化管理
ByteBase ByteBase 是一个进行数据库模式变更的工具,以下命令将在元节点 8887 端口启动一个ByteBase。
mkdir -p /data/bytebase/data;
docker run --init --name bytebase --restart always --detach --publish 8887:8887 --volume /data/bytebase/data:/var/opt/bytebase \
bytebase/bytebase:1.0.4 --data /var/opt/bytebase --host http://ddl.pigsty --port 8887
访问 http://10.10.10.10:8887/ 或 http://ddl.pigsty 即可使用 ByteBase,您需要依次创建项目、环境、实例、数据库,即可开始进行模式变更。 公开Demo地址: http://ddl.pigsty.cc
公开Demo地址:http://ddl.pigsty.cc
默认用户名与密码: admin / pigsty
Bytebase概览 Schema Migrator for PostgreSQL
Visit http://ddl.pigsty or http://10.10.10.10:8887
make up # pull up bytebase with docker-compose in minimal mode
make run # launch bytebase with docker , local data dir and external PostgreSQL
make view # print bytebase access point
make log # tail -f bytebase logs
make info # introspect bytebase with jq
make stop # stop bytebase container
make clean # remove bytebase container
make pull # pull latest bytebase image
make rmi # remove bytebase image
make save # save bytebase image to /tmp/bytebase.tgz
make load # load bytebase image from /tmp
使用外部的PostgreSQL Bytebase use its internal PostgreSQL database by default, You can use external PostgreSQL for higher durability.
# postgres://dbuser_bytebase:DBUser.Bytebase@10.10.10.10:5432/bytebase
db : { name: bytebase, owner: dbuser_bytebase, comment : bytebase primary database }
user : { name: dbuser_bytebase , password: DBUser.Bytebase, roles : [ dbrole_admin ] }
if you wish to user an external PostgreSQL, drop monitor extensions and views & pg_repack
DROP SCHEMA monitor CASCADE;
DROP EXTENSION pg_repack;
After bytebase initialized, you can create them back with /pg/tmp/pg-init-template.sql
psql bytebase < /pg/tmp/pg-init-template.sql
8.16 - PGAdmin:GUI 工具 使用Docker拉起PgAdmin4,并加载Pigsty服务器列表
pgAdmin 是最受欢迎且功能丰富的 PostgreSQL 开源管理和开发平台,PostgreSQL 是世界上最先进的开源数据库。
快速开始 Pigsty 内置(但可选)支持 pgAdmin,它使用 Docker Compose 启动 pgadmin:
./docker.yml
./app.yml -e app = pgadmin
pgadmin 的默认端口是 8885,您可以通过 IP:端口访问它:http://10.10.10.10:8885。
默认凭据在 .env 中定义,用户名:admin@pigsty.cc,密码:pigsty。
自定义 在 /opt/pgadmin/.env 中自定义 pgadmin 配置并使用 docker compose 管理它。
您还可以自定义 apps 参数并使用以下方式覆盖默认 .env 配置:
all :
children :
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
vars :
docker_enabled : true
app : pgadmin # 指定要安装的应用程序名称(pgadmin)(在 apps 中)
apps : # 定义所有应用程序
pgadmin : # pgadmin 应用程序的定义
conf : # 覆盖 /opt/pgadmin/.env
PGADMIN_DEFAULT_EMAIL : your@email.com
PGADMIN_DEFAULT_PASSWORD : yourPassword
PGADMIN_LISTEN_ADDRESS : 0.0.0.0
PGADMIN_PORT : 8885
PGADMIN_SERVER_JSON_FILE : /pgadmin4/servers.json
PGADMIN_REPLACE_SERVERS_ON_STARTUP : true
要启动应用程序,运行:
域名和证书 要通过 nginx(而不是直接访问端口 8885)访问 pgadmin,请使用以下方式配置 基础设施门户 :
all :
vars :
infra_portal :
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9058" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
# 在此处添加 pgadmin 上游服务器定义
pgadmin : { domain: adm.pigsty ,endpoint : "127.0.0.1:8885" }
然后运行 make nginx 更新 nginx 配置,并在 /etc/hosts 或 本地 / 公共 DNS 服务器中配置 本地静态 DNS 记录 <your_ip_address> adm.pigsty。
Pigsty 将自动为 infra_portal 中列出的域名签发自签名 SSL 证书。
如果您想使用真实域名,请定义 certbot 条目并运行 make cert,查看 SSL 证书 了解详情。
all :
vars : # 确保您的域名(adm.pigsty.cc)解析到您的公网 IP
certbot_sign : true # 使用 certbot 签发真实 HTTPS 证书(需要互联网访问!)
infra_portal :
pgadmin : { domain: adm.pigsty.cc ,endpoint : "127.0.0.1:8885" , certbot : adm.pigsty.cc }
使用方法 Pigsty 的 Pgadmin 应用模板默认使用 8885 端口,您可以通过以下地址访问:
http://adm.pigsty 或 http://10.10.10.10:8885
默认用户名与密码: admin@pigsty.cc / pigsty
make up # 使用 docker compose 启动 pgadmin
make run # 使用 docker 启动 pgadmin
make view # 打印 pgadmin 访问点
make log # tail -f pgadmin 日志
make info # 使用 jq 检查 pgadmin
make stop # 停止 pgadmin 容器
make clean # 移除 pgadmin 容器
make conf # 使用 pigsty pg 服务器列表配置 pgadmin
make dump # 从 pgadmin 容器导出 servers.json
make pull # 拉取最新的 pgadmin 镜像
make rmi # 移除 pgadmin 镜像
make save # 保存 pgadmin 镜像到 /tmp/pgadmin.tgz
make load # 从 /tmp 加载 pgadmin 镜像
Demo 公开 Demo 地址:http://adm.pigsty.cc
默认用户名与密码: admin@pigsty.cc / pigsty
8.17 - PGWeb:网页客户端 使用Docker拉起PGWEB,以便从浏览器进行小批量在线数据查询
PGWeb客户端工具 PGWeb 是一款基于浏览器的PG客户端工具,使用以下命令,在元节点上拉起PGWEB服务,默认为主机8886端口。可使用域名: http://cli.pigsty 访问,公开Demo:http://cli.pigsty.cc。
# docker stop pgweb; docker rm pgweb
docker run --init --name pgweb --restart always --detach --publish 8886:8081 sosedoff/pgweb
用户需要自行填写数据库连接串,例如默认CMDB的连接串:
postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta?sslmode=disable
公开Demo地址:http://cli.pigsty.cc
使用Docker Compose拉起PGWEB容器:
cd ~/pigsty/app/pgweb ; docker-compose up -d
接下来,访问您本机的 8886 端口,即可看到 PGWEB 的UI界面: http://10.10.10.10:8886
您可以尝试使用下面的URL连接串,通过 PGWEB 连接至数据库实例并进行探索。
postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta?sslmode= disable
postgres://test:test@10.10.10.11:5432/test?sslmode= disable
快捷方式 make up # pull up pgweb with docker-compose
make run # launch pgweb with docker
make view # print pgweb access point
make log # tail -f pgweb logs
make info # introspect pgweb with jq
make stop # stop pgweb container
make clean # remove pgweb container
make pull # pull latest pgweb image
make rmi # remove pgweb image
make save # save pgweb image to /tmp/pgweb.tgz
make load # load pgweb image from /tmp
8.18 - PostgREST:自动 API 使用Docker拉起PostgREST,自动根据PostgreSQL模式生成后端REST API
PostgREST PostgREST 是一个自动根据 PostgreSQL 数据库模式生成 REST API的二进制组件。
例如,以下命令将使用docker拉起 postgrest (本地 8884 端口,使用默认管理员用户,暴露Pigsty CMDB模式)
docker run --init --name postgrest --restart always --detach --publish 8884:8081 postgrest/postgrest
访问 http://10.10.10.10:8884 会展示所有自动生成API的定义,并自动使用 Swagger Editor 暴露API文档。
如果您想要进行增删改查,设计更精细的权限控制,请参考 Tutorial 1 - The Golden Key ,生成一个签名JWT。
This is an example of creating pigsty cmdb API with PostgREST
cd ~/pigsty/app/postgrest ; docker-compose up -d
http://10.10.10.10:8884 is the default endpoint for PostgREST
http://10.10.10.10:8883 is the default api docs for PostgREST
make up # pull up postgrest with docker-compose
make run # launch postgrest with docker
make ui # run swagger ui container
make view # print postgrest access point
make log # tail -f postgrest logs
make info # introspect postgrest with jq
make stop # stop postgrest container
make clean # remove postgrest container
make rmui # remove swagger ui container
make pull # pull latest postgrest image
make rmi # remove postgrest image
make save # save postgrest image to /tmp/postgrest.tgz
make load # load postgrest image from /tmp
Swagger UI Launch a swagger OpenAPI UI and visualize PostgREST API on 8883 with:
docker run --init --name postgrest --name swagger -p 8883:8080 -e API_URL = http://10.10.10.10:8884 swaggerapi/swagger-ui
# docker run -d -e API_URL=http://10.10.10.10:8884 -p 8883:8080 swaggerapi/swagger-editor # swagger editor
Check http://10.10.10.10:8883/
8.19 - Electric:PGLite 同步引擎 使用 Electric 解决 PostgreSQL 数据同步难题,支持部分复制和实时数据传输。
Electric 是一个 PostgreSQL 同步引擎,解决了数据同步的复杂问题。
Electric 支持部分复制、扇出传输和高效的数据交付,是构建实时应用和离线优先应用的理想选择。
快速开始 cd ~/pigsty/app/electric
make up # 启动 Electric 服务
访问地址: http://electric.pigsty 或 http://10.10.10.10:3000
功能特性 部分复制 :只同步需要的数据实时同步 :毫秒级数据更新离线优先 :支持离线工作,自动同步冲突解决 :自动处理数据冲突类型安全 :TypeScript 支持相关链接 8.20 - Jupyter:笔记本 AI IDE 使用 Jupyter Lab 并访问 PostgreSQL 数据库,组合使用 SQL 与 Python 的能力进行数据分析。
Jupyter Lab 是基于 IPython Notebook 的完整数据科学研发环境,可用于数据分析与可视化。
Pigsty 提供了 Docker Compose 模板,可以一键在容器中启动 Jupyter Lab 服务,并方便地访问 PostgreSQL 数据库。
快速开始 在 Pigsty 软件模板目录中提供了 Jupyter 的 Docker Compose 配置文件:
修改默认密码,编辑 .env 文件中的 JUPYTER_TOKEN 参数(默认值为 pigsty)。
创建数据目录并启动服务:
make dir # 创建 /data/jupyter 目录并设置权限
make up # 使用 Docker Compose 启动服务
访问 Jupyter Lab:
管理命令 Pigsty 提供了便捷的 Makefile 命令来管理 Jupyter 服务:
make up # 启动 Jupyter Lab 服务
make dir # 创建 /data/jupyter 数据目录
make log # 查看容器日志
make info # 显示服务信息
make stop # 停止服务
make clean # 停止并移除容器
make pull # 拉取最新镜像
make save # 保存 Docker 镜像到文件
make load # 从文件加载 Docker 镜像
访问 PostgreSQL 数据库 在 Jupyter Lab 中访问 PostgreSQL 数据库需要先安装驱动。
在 Jupyter Lab 的 Terminal 中执行:
pip install psycopg2-binary psycopg2
然后在 Notebook 中使用 psycopg2 驱动访问 PostgreSQL:
import psycopg2
# 连接到 PostgreSQL 数据库
conn = psycopg2 . connect ( 'postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta' )
# 执行查询
cursor = conn . cursor ()
cursor . execute ( "SELECT date, new_cases FROM covid.country_history WHERE country_code = 'CN';" )
data = cursor . fetchall ()
# 处理数据
for row in data :
print ( row )
你也可以使用其他 Python 数据分析库,如 Pandas、SQLAlchemy 等:
import pandas as pd
from sqlalchemy import create_engine
# 使用 SQLAlchemy 连接
engine = create_engine ( 'postgresql://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta' )
# 使用 Pandas 读取数据
df = pd . read_sql ( "SELECT * FROM covid.country_history WHERE country_code = 'CN'" , engine )
print ( df . head ())
配置说明 Jupyter 服务的配置在 .env 文件中:
JUPYTER_TOKEN = pigsty # Jupyter Lab 访问 Token(密码)
如果需要修改端口或其他配置,可以编辑 docker-compose.yml 文件:
services :
jupyter :
image : jupyter/scipy-notebook:latest
ports :
- "8888:8888"
volumes :
- /data/jupyter:/home/jovyan/work
environment :
- JUPYTER_TOKEN=${JUPYTER_TOKEN}
安装额外的 Python 包 Jupyter 容器支持使用 pip 或 conda 安装 Python 包。
在 Jupyter Lab 的 Terminal 中执行:
# 使用 pip 安装
pip install numpy pandas matplotlib seaborn scikit-learn
# 使用 conda 安装
conda install -c conda-forge geopandas
# 使用国内镜像加速(可选)
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy
数据持久化 Jupyter 的数据存储在 /data/jupyter 目录中,该目录会被挂载到容器的 /home/jovyan/work 路径。
所有保存在 work 目录下的 Notebook 和数据文件都会持久化保存在宿主机上,即使容器重启或删除也不会丢失。
安全建议 强烈建议修改默认的 Token(密码)!
编辑 .env 文件,修改 JUPYTER_TOKEN 的值 重启服务:make up 如果在生产环境中使用 Jupyter Lab,还应该:
使用强密码或禁用 Token 认证 配置 HTTPS 访问 限制网络访问权限 定期备份数据目录 相关链接 8.21 - 数据应用 基于 PostgreSQL 的数据可视化应用
8.22 - PGLOG:PG自带日志分析应用 Pigsty自带的,用于分析PostgreSQL CSV日志样本的一个样例Applet
PGLOG是Pigsty自带的一个样例应用,固定使用MetaDB中pglog.sample表作为数据来源。您只需要将日志灌入该表,然后访问相关Dashboard即可。
Pigsty提供了一些趁手的命令,用于拉取csv日志,并灌入样本表中。在元节点上,默认提供下列快捷命令:
catlog [ node = localhost] [ date = today] # 打印CSV日志到标准输出
pglog # 从标准输入灌入CSVLOG
pglog12 # 灌入PG12格式的CSVLOG
pglog13 # 灌入PG13格式的CSVLOG
pglog14 # 灌入PG14格式的CSVLOG (=pglog)
catlog | pglog # 分析当前节点当日的日志
catlog node-1 '2021-07-15' | pglog # 分析node-1在2021-07-15的csvlog
接下来,您可以访问以下的连接,查看样例日志分析界面。
catlog命令从特定节点拉取特定日期的CSV数据库日志,写入stdout
默认情况下,catlog会拉取当前节点当日的日志,您可以通过参数指定节点与日期。
组合使用pglog与catlog,即可快速拉取数据库CSV日志进行分析。
catlog | pglog # 分析当前节点当日的日志
catlog node-1 '2021-07-15' | pglog # 分析node-1在2021-07-15的csvlog
8.23 - NOAA ISD 全球气象站历史数据查询 以ISD数据集为例,展现如何将数据导入数据库中
如果您拥有数据库后不知道干点什么,不妨参试试这个开源项目:Vonng/isd
您可以直接复用监控系统Grafana,以交互式的方式查阅近30000个地面气象站过去120年间的亚小时级气象数据。
这是一个功能完成的数据应用,可以查询全球30000个地表气象站从1901年来的气象观测记录。
项目地址:https://github.com/Vonng/isd
在线Demo地址:https://demo.pigsty.cc/d/isd-overview
快速上手 克隆本仓库
git clone https://github.com/Vonng/isd.git; cd isd;
准备一个 PostgreSQL 实例
该 PostgreSQL 实例应当启用了 PostGIS 扩展。使用 PGURL 环境变量传递数据库连接信息:
# Pigsty 默认使用的管理员账号是 dbuser_dba,密码是 DBUser.DBA
export PGURL = postgres://dbuser_dba:DBUser.DBA@127.0.0.1:5432/meta?sslmode= disable
psql " ${ PGURL } " -c 'SELECT 1' # 检查连接是否可用
获取并导入ISD气象站元数据
这是一份每日更新的气象站元数据,包含了气象站的经纬度、海拔、名称、国家、省份等信息,使用以下命令下载并导入。
make reload-station # 相当于先下载最新的Station数据再加载:get-station + load-station
获取并导入最新的 isd.daily 数据
isd.daily 是一个每日更新的数据集,包含了全球各气象站的日观测数据摘要,使用以下命令下载并导入。
请注意,直接从 NOAA 网站下载的原始数据需要经过解析 方可入库,所以你需要下载或构建一个 ISD 数据 Parser。
make get-parser # 从 Github 下载 Parser 二进制,当然你也可以用 make build 直接用 go 构建。
make reload-daily # 下载本年度最新的 isd.daily 数据并导入数据库中
加载解析好的 CSV 数据集
ISD Daily 数据集有一些脏数据与重复数据 ,如果你不想手工解析处理清洗,这里也提供了一份解析好的稳定CSV数据集。
该数据集包含了截止到 2023-06-24 的 isd.daily 数据,你可以直接下载并导入 PostgreSQL 中,不需要 Parser,
make get-stable # 从 Github 上获取稳定的 isd.daily 历史数据集。
make load-stable # 将下载好的稳定历史数据集加载到 PostgreSQL 数据库中。
更多数据 ISD数据集有两个部分是每日更新的,气象站元数据,以及最新年份的 isd.daily (如 2023 年的 Tarball)。
你可以使用以下命令下载并刷新这两个部分。如果数据集没有更新,那么这些命令不会重新下载同样的数据包
make reload # 实际上是:reload-station + reload-daily
你也可以使用以下命令下载并加载特定年份的 isd.daily 数据:
bin/get-daily 2022 # 获取 2022 年的每日气象观测摘要 (1900-2023)
bin/load-daily " ${ PGURL } " 2022 # 加载 2022 年的每日气象观测摘要 (1900-2023)
除了每日摘要 isd.daily, ISD 还提供了一份更详细的亚小时级原始观测记录 isd.hourly,下载与加载的方式与前者类似:
bin/get-hourly 2022 # 下载特定某一年的小时级观测记录(例如2022年,可选 1900-2023)
bin/load-hourly " ${ PGURL } " 2022 # 加载特定某一年的小时级观测记录
数据 数据集概要 ISD提供了四个数据集:亚小时级原始观测数据,每日统计摘要数据,月度统计摘要,年度统计摘要
数据集 备注 ISD Hourly 亚小时级观测记录 ISD Daily 每日统计摘要 ISD Monthly 没有用到,因为可以从 isd.daily 计算生成 ISD Yearly 没有用到,因为可以从 isd.daily 计算生成
每日摘要数据集
压缩包大小 2.8GB (截止至 2023-06-24) 表大小 24GB,索引大小 6GB,PostgreSQL 中总大小约为 30GB 如果启用了 timescaledb 压缩,总大小可以压缩到 4.5 GB。 亚小时级观测数据级
压缩包总大小 117GB 灌入数据库后表大小 1TB+ ,索引大小 600GB+,总大小 1.6TB 数据库模式 气象站元数据表
CREATE TABLE isd . station
(
station VARCHAR ( 12 ) PRIMARY KEY ,
usaf VARCHAR ( 6 ) GENERATED ALWAYS AS ( substring ( station , 1 , 6 )) STORED ,
wban VARCHAR ( 5 ) GENERATED ALWAYS AS ( substring ( station , 7 , 5 )) STORED ,
name VARCHAR ( 32 ),
country VARCHAR ( 2 ),
province VARCHAR ( 2 ),
icao VARCHAR ( 4 ),
location GEOMETRY ( POINT ),
longitude NUMERIC GENERATED ALWAYS AS ( Round ( ST_X ( location ):: NUMERIC , 6 )) STORED ,
latitude NUMERIC GENERATED ALWAYS AS ( Round ( ST_Y ( location ):: NUMERIC , 6 )) STORED ,
elevation NUMERIC ,
period daterange ,
begin_date DATE GENERATED ALWAYS AS ( lower ( period )) STORED ,
end_date DATE GENERATED ALWAYS AS ( upper ( period )) STORED
);
每日摘要表
CREATE TABLE IF NOT EXISTS isd . daily
(
station VARCHAR ( 12 ) NOT NULL , -- station number 6USAF+5WBAN
ts DATE NOT NULL , -- observation date
-- 气温 & 露点
temp_mean NUMERIC ( 3 , 1 ), -- mean temperature ℃
temp_min NUMERIC ( 3 , 1 ), -- min temperature ℃
temp_max NUMERIC ( 3 , 1 ), -- max temperature ℃
dewp_mean NUMERIC ( 3 , 1 ), -- mean dew point ℃
-- 气压
slp_mean NUMERIC ( 5 , 1 ), -- sea level pressure (hPa)
stp_mean NUMERIC ( 5 , 1 ), -- station pressure (hPa)
-- 可见距离
vis_mean NUMERIC ( 6 ), -- visible distance (m)
-- 风速
wdsp_mean NUMERIC ( 4 , 1 ), -- average wind speed (m/s)
wdsp_max NUMERIC ( 4 , 1 ), -- max wind speed (m/s)
gust NUMERIC ( 4 , 1 ), -- max wind gust (m/s)
-- 降水 / 雪深
prcp_mean NUMERIC ( 5 , 1 ), -- precipitation (mm)
prcp NUMERIC ( 5 , 1 ), -- rectified precipitation (mm)
sndp NuMERIC ( 5 , 1 ), -- snow depth (mm)
-- FRSHTT (Fog/Rain/Snow/Hail/Thunder/Tornado) 雾/雨/雪/雹/雷/龙卷
is_foggy BOOLEAN , -- (F)og
is_rainy BOOLEAN , -- (R)ain or Drizzle
is_snowy BOOLEAN , -- (S)now or pellets
is_hail BOOLEAN , -- (H)ail
is_thunder BOOLEAN , -- (T)hunder
is_tornado BOOLEAN , -- (T)ornado or Funnel Cloud
-- 统计聚合使用的记录数
temp_count SMALLINT , -- record count for temp
dewp_count SMALLINT , -- record count for dew point
slp_count SMALLINT , -- record count for sea level pressure
stp_count SMALLINT , -- record count for station pressure
wdsp_count SMALLINT , -- record count for wind speed
visib_count SMALLINT , -- record count for visible distance
-- 气温标记
temp_min_f BOOLEAN , -- aggregate min temperature
temp_max_f BOOLEAN , -- aggregate max temperature
prcp_flag CHAR , -- precipitation flag: ABCDEFGHI
PRIMARY KEY ( station , ts )
); -- PARTITION BY RANGE (ts);
亚小时级原始观测数据表
ISD Hourly CREATE TABLE IF NOT EXISTS isd . hourly
(
station VARCHAR ( 12 ) NOT NULL , -- station id
ts TIMESTAMP NOT NULL , -- timestamp
-- air
temp NUMERIC ( 3 , 1 ), -- [-93.2,+61.8]
dewp NUMERIC ( 3 , 1 ), -- [-98.2,+36.8]
slp NUMERIC ( 5 , 1 ), -- [8600,10900]
stp NUMERIC ( 5 , 1 ), -- [4500,10900]
vis NUMERIC ( 6 ), -- [0,160000]
-- wind
wd_angle NUMERIC ( 3 ), -- [1,360]
wd_speed NUMERIC ( 4 , 1 ), -- [0,90]
wd_gust NUMERIC ( 4 , 1 ), -- [0,110]
wd_code VARCHAR ( 1 ), -- code that denotes the character of the WIND-OBSERVATION.
-- cloud
cld_height NUMERIC ( 5 ), -- [0,22000]
cld_code VARCHAR ( 2 ), -- cloud code
-- water
sndp NUMERIC ( 5 , 1 ), -- mm snow
prcp NUMERIC ( 5 , 1 ), -- mm precipitation
prcp_hour NUMERIC ( 2 ), -- precipitation duration in hour
prcp_code VARCHAR ( 1 ), -- precipitation type code
-- sky
mw_code VARCHAR ( 2 ), -- manual weather observation code
aw_code VARCHAR ( 2 ), -- auto weather observation code
pw_code VARCHAR ( 1 ), -- weather code of past period of time
pw_hour NUMERIC ( 2 ), -- duration of pw_code period
-- misc
-- remark TEXT,
-- eqd TEXT,
data JSONB -- extra data
) PARTITION BY RANGE ( ts );
解析器 NOAA ISD 提供的原始数据是高度压缩的专有格式,需要通过解析器加工,才能转换为数据库表的格式。
针对 Daily 与 Hourly 两份数据集,这里提供了两个 Parser: isdd and isdh 。
这两个解析器都以年度数据压缩包作为输入,产生 CSV 结果作为输出,以管道的方式工作,如下所示:
NAME
isd -- Intergrated Surface Dataset Parser
SYNOPSIS
isd daily [ -i <input| stdin>] [ -o <output| stout>] [ -v]
isd hourly [ -i <input| stdin>] [ -o <output| stout>] [ -v] [ -d raw| ts-first| hour-first]
DESCRIPTION
The isd program takes noaa isd daily/hourly raw tarball data as input.
and generate parsed data in csv format as output. Works in pipe mode
cat data/daily/2023.tar.gz | bin/isd daily -v | psql ${ PGURL } -AXtwqc "COPY isd.daily FROM STDIN CSV;"
isd daily -v -i data/daily/2023.tar.gz | psql ${ PGURL } -AXtwqc "COPY isd.daily FROM STDIN CSV;"
isd hourly -v -i data/hourly/2023.tar.gz | psql ${ PGURL } -AXtwqc "COPY isd.hourly FROM STDIN CSV;"
OPTIONS
-i <input> input file, stdin by default
-o <output> output file, stdout by default
-p <profpath> pprof file path, enable if specified
-d de-duplicate rows for hourly dataset ( raw, ts-first, hour-first)
-v verbose mode
-h print help
用户界面 这里提供了几个使用 Grafana 制作的 Dashboard,可以用于探索 ISD 数据集,查询气象站与历史气象数据。
ISD Overview
全局概览,总体指标与气象站导航。
ISD Country
展示单个国家/地区内所有的气象站。
ISD Station
展示单个气象站的详细信息,元数据,天/月/年度汇总指标。
ISD Station Dashboard
ISD Detail
展示一个气象站原始亚小时级观测指标数据,需要 isd.hourly 数据集。
ISD Station Dashboard
8.24 - COVID-19 数据大盘 Pigsty 自带的,用于展示世界卫生组织官方 COVID 疫情数据的一个样例 Applet
Covid 是 Pigsty 自带的,用于展示世界卫生组织官方疫情数据大盘的一个样例 Applet。
您可以查阅每个国家与地区 COVID-19 的感染与死亡案例,以及全球的疫情趋势。
概览 GitHub 仓库地址:https://github.com/Vonng/pigsty-app/tree/master/covid
在线Demo地址:https://demo.pigsty.cc/d/covid
安装 在管理节点上进入应用目录,执行make以完成安装。
其他一些子任务:
make reload # download latest data and pour it again
make ui # install grafana dashboards
make sql # install database schemas
make download # download latest data
make load # load downloaded data into database
make reload # download latest data and pour it into database
8.25 - StackOverflow 调研 分析 StackOverflow 最近七年全球开发者调研数据中关于数据库的部分
概览 GitHub 仓库地址:https://github.com/Vonng/pigsty-app/tree/master/db
在线Demo地址:https://demo.pigsty.cc/d/sf-survey
8.27 - 云上算力价格计算器 分析阿里云 / AWS 上算力与存储的价格 (ECS/ESSD)
概览 GitHub 仓库地址:https://github.com/Vonng/pigsty-app/tree/master/cloud
在线Demo地址:https://demo.pigsty.cc/d/ecs
文章地址:《剖析算力成本:阿里云真降价了吗? 》
数据源 Aliyun ECS 价格可以在 价格计算器 - 定价详情 - 价格下载 中获取 CSV 原始数据。
模式 下载 阿里云 价格明细并导入分析
CREATE EXTENSION file_fdw ;
CREATE SERVER fs FOREIGN DATA WRAPPER file_fdw ;
DROP FOREIGN TABLE IF EXISTS aliyun_ecs CASCADE ;
CREATE FOREIGN TABLE aliyun_ecs
(
"region" text ,
"system" text ,
"network" text ,
"isIO" bool ,
"instanceId" text ,
"hourlyPrice" numeric ,
"weeklyPrice" numeric ,
"standard" numeric ,
"monthlyPrice" numeric ,
"yearlyPrice" numeric ,
"2yearPrice" numeric ,
"3yearPrice" numeric ,
"4yearPrice" numeric ,
"5yearPrice" numeric ,
"id" text ,
"instanceLabel" text ,
"familyId" text ,
"serverType" text ,
"cpu" text ,
"localStorage" text ,
"NvmeSupport" text ,
"InstanceFamilyLevel" text ,
"EniTrunkSupported" text ,
"InstancePpsRx" text ,
"GPUSpec" text ,
"CpuTurboFrequency" text ,
"InstancePpsTx" text ,
"InstanceTypeId" text ,
"GPUAmount" text ,
"InstanceTypeFamily" text ,
"SecondaryEniQueueNumber" text ,
"EniQuantity" text ,
"EniPrivateIpAddressQuantity" text ,
"DiskQuantity" text ,
"EniIpv6AddressQuantity" text ,
"InstanceCategory" text ,
"CpuArchitecture" text ,
"EriQuantity" text ,
"MemorySize" numeric ,
"EniTotalQuantity" numeric ,
"PhysicalProcessorModel" text ,
"InstanceBandwidthRx" numeric ,
"CpuCoreCount" numeric ,
"Generation" text ,
"CpuSpeedFrequency" numeric ,
"PrimaryEniQueueNumber" text ,
"LocalStorageCategory" text ,
"InstanceBandwidthTx" text ,
"TotalEniQueueQuantity" text
) SERVER fs OPTIONS ( filename '/tmp/aliyun-ecs.csv' , format 'csv' , header 'true' );
AWS EC2 同理,可以从 Vantage 下载价格清单:
DROP FOREIGN TABLE IF EXISTS aws_ec2 CASCADE ;
CREATE FOREIGN TABLE aws_ec2
(
"name" TEXT ,
"id" TEXT ,
"Memory" TEXT ,
"vCPUs" TEXT ,
"GPUs" TEXT ,
"ClockSpeed" TEXT ,
"InstanceStorage" TEXT ,
"NetworkPerformance" TEXT ,
"ondemand" TEXT ,
"reserve" TEXT ,
"spot" TEXT
) SERVER fs OPTIONS ( filename '/tmp/aws-ec2.csv' , format 'csv' , header 'true' );
DROP VIEW IF EXISTS ecs ;
CREATE VIEW ecs AS
SELECT "region" AS region ,
"id" AS id ,
"instanceLabel" AS name ,
"familyId" AS family ,
"CpuCoreCount" AS cpu ,
"MemorySize" AS mem ,
round ( "5yearPrice" / "CpuCoreCount" / 60 , 2 ) AS ycm5 , -- ¥ / (core·month)
round ( "4yearPrice" / "CpuCoreCount" / 48 , 2 ) AS ycm4 , -- ¥ / (core·month)
round ( "3yearPrice" / "CpuCoreCount" / 36 , 2 ) AS ycm3 , -- ¥ / (core·month)
round ( "2yearPrice" / "CpuCoreCount" / 24 , 2 ) AS ycm2 , -- ¥ / (core·month)
round ( "yearlyPrice" / "CpuCoreCount" / 12 , 2 ) AS ycm1 , -- ¥ / (core·month)
round ( "standard" / "CpuCoreCount" , 2 ) AS ycmm , -- ¥ / (core·month)
round ( "hourlyPrice" / "CpuCoreCount" * 720 , 2 ) AS ycmh , -- ¥ / (core·month)
"CpuSpeedFrequency" :: NUMERIC AS freq ,
"CpuTurboFrequency" :: NUMERIC AS freq_turbo ,
"Generation" AS generation
FROM aliyun_ecs
WHERE system = 'linux' ;
DROP VIEW IF EXISTS ec2 ;
CREATE VIEW ec2 AS
SELECT id ,
name ,
split_part ( id , '.' , 1 ) as family ,
split_part ( id , '.' , 2 ) as spec ,
( regexp_match ( split_part ( id , '.' , 1 ), '^[a-zA-Z]+(\d)[a-z0-9]*' ))[ 1 ] as gen ,
regexp_substr ( "vCPUs" , '^[0-9]+' ):: int as cpu ,
regexp_substr ( "Memory" , '^[0-9]+' ):: int as mem ,
CASE spot
WHEN 'unavailable' THEN NULL
ELSE round (( regexp_substr ( "spot" , '([0-9]+.[0-9]+)' ):: NUMERIC * 7 . 2 ), 2 ) END AS spot ,
CASE ondemand
WHEN 'unavailable' THEN NULL
ELSE round (( regexp_substr ( "ondemand" , '([0-9]+.[0-9]+)' ):: NUMERIC * 7 . 2 ), 2 ) END AS ondemand ,
CASE reserve
WHEN 'unavailable' THEN NULL
ELSE round (( regexp_substr ( "reserve" , '([0-9]+.[0-9]+)' ):: NUMERIC * 7 . 2 ), 2 ) END AS reserve ,
"ClockSpeed" AS freq
FROM aws_ec2 ;
可视化
9 - 模板 开箱即用的配置模板,针对具体场景的配置示例,以及配置文件的详细解释。
Pigsty 提供了多种开箱即用的配置模板,适用于不同的使用场景。
您可以在 configure 时使用 -c 指定一个配置模板。如果没有指定配置模板,将会使用默认的 meta 模版。
9.1 - 单机模版 9.2 - meta Pigsty 默认使用的配置模板,单节点,覆盖核心功能,标准单机配置,在线安装,本地备份仓库。
meta 配置模板是 Pigsty 默认使用的模板,它的目标是在当前单节点上完成 Pigsty 核心功能 —— PostgreSQL 的部署。
为了实现最好的兼容性,meta 模板仅下载安装包含 最小必需 软件集合,以便在所有操作系统发行版与芯片架构上实现这一目标。
配置概览 配置名称: meta 节点数量: 单节点 配置说明:Pigsty 默认使用的单节点安装配置模板,带有较完善的关键配置参数说明,与最小可用功能集合。 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta ,slim ,fat , 使用方式:此配置模板为 Pigsty 默认配置模板,因此在 配置 时无需显式指定 -c meta 参数:
./configure [ -i <primary_ip>]
例如,如果您想要安装 PG 17,而非默认的 PostgreSQL 18,可以在 configure 中使用 -v 参数:
./configure -v 17 # or 16,15,14,13....
配置内容 源文件地址:pigsty/conf/meta.yml
---
#==============================================================#
# File : meta.yml
# Desc : Pigsty default 1-node online install config
# Ctime : 2020-05-22
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the default 1-node configuration template, with:
# INFRA, NODE, PGSQL, ETCD, MINIO, DOCKER, APP (pgadmin)
# with basic pg extensions: postgis, pgvector
#
# Work with PostgreSQL 14-18 on all supported platform
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure
# ./deploy.yml
all :
#==============================================================#
# Clusters, Nodes, and Modules
#==============================================================#
children :
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql
#----------------------------------------------#
# this is an example single-node postgres cluster with pgvector installed, with one biz database & two biz users
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary } # <---- primary instance with read-write capability
#x.xx.xx.xx: { pg_seq: 2, pg_role: replica } # <---- read only replica for read-only online traffic
#x.xx.xx.xy: { pg_seq: 3, pg_role: offline } # <---- offline instance of ETL & interactive queries
vars :
pg_cluster : pg-meta
# install, load, create pg extensions: https://doc.pgsty.com/pgsql/extension
pg_extensions : [ postgis, pgvector ]
# define business users/roles : https://doc.pgsty.com/pgsql/user
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
# define business databases : https://doc.pgsty.com/pgsql/db
pg_databases :
- name : meta
baseline : cmdb.sql
comment : "pigsty meta database"
schemas : [ pigsty]
# define extensions in database : https://doc.pgsty.com/pgsql/extension/create
extensions : [ postgis, vector ]
# define HBA rules : https://doc.pgsty.com/pgsql/hba
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
# define backup policies: https://doc.pgsty.com/pgsql/backup
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every day 1am
# define (OPTIONAL) L2 VIP that bind to primary
#pg_vip_enabled: true
#pg_vip_address: 10.10.10.2/24
#pg_vip_interface: eth1
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
vars :
repo_enabled: false # disable in 1-node mode : https://doc.pgsty.com/admin/repo
#repo_extra_packages: [ pg18-main ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# ETCD : https://doc.pgsty.com/etcd
#----------------------------------------------#
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
vars :
etcd_cluster : etcd
etcd_safeguard : false # prevent purging running etcd instance?
#----------------------------------------------#
# MINIO : https://doc.pgsty.com/minio
#----------------------------------------------#
#minio:
# hosts:
# 10.10.10.10: { minio_seq: 1 }
# vars:
# minio_cluster: minio
# minio_users: # list of minio user to be created
# - { access_key: pgbackrest ,secret_key: S3User.Backup ,policy: pgsql }
# - { access_key: s3user_meta ,secret_key: S3User.Meta ,policy: meta }
# - { access_key: s3user_data ,secret_key: S3User.Data ,policy: data }
#----------------------------------------------#
# DOCKER : https://doc.pgsty.com/docker
# APP : https://doc.pgsty.com/app
#----------------------------------------------#
# launch example pgadmin app with: ./app.yml (http://10.10.10.10:8885 admin@pigsty.cc / pigsty)
app :
hosts : { 10.10.10.10 : {} }
vars :
docker_enabled : true # enabled docker with ./docker.yml
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
app : pgadmin # specify the default app name to be installed (in the apps)
apps: # define all applications, appname : definition
pgadmin : # pgadmin app definition (app/pgadmin -> /opt/pgadmin)
conf : # override /opt/pgadmin/.env
PGADMIN_DEFAULT_EMAIL : admin@pigsty.cc
PGADMIN_DEFAULT_PASSWORD : pigsty
#==============================================================#
# Global Parameters
#==============================================================#
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: china # upstream mirror region : default|china|europe
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
pgadmin : { domain: adm.pigsty ,endpoint : "${admin_ip}:8885" }
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
node_etc_hosts : [ '${admin_ip} i.pigsty sss.pigsty' ]
node_repo_modules : 'node,infra,pgsql' # add these repos directly to the singleton node
#node_repo_modules: local # use this if you want to build & user local repo
node_repo_remove : true # remove existing node repo for node managed by pigsty
#node_packages: [openssh-server] # packages to be installed current nodes with the latest version
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # default postgres version
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_safeguard : false # prevent purging running postgres instance?
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# BACKUP : https://doc.pgsty.com/pgsql/backup
#----------------------------------------------#
# if you want to use minio as backup repo instead of 'local' fs, uncomment this, and configure `pgbackrest_repo`
# you can also use external object storage as backup repo
#pgbackrest_method: minio # if you want to use minio as backup repo instead of 'local' fs, uncomment this
#pgbackrest_repo: # pgbackrest repo: https://pgbackrest.org/configuration.html#section-repository
# local: # default pgbackrest repo with local posix fs
# path: /pg/backup # local backup directory, `/pg/backup` by default
# retention_full_type: count # retention full backups by count
# retention_full: 2 # keep 2, at most 3 full backup when using local fs repo
# minio: # optional minio repo for pgbackrest
# type: s3 # minio is s3-compatible, so s3 is used
# s3_endpoint: sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
# s3_region: us-east-1 # minio region, us-east-1 by default, useless for minio
# s3_bucket: pgsql # minio bucket name, `pgsql` by default
# s3_key: pgbackrest # minio user access key for pgbackrest
# s3_key_secret: S3User.Backup # minio user secret key for pgbackrest
# s3_uri_style: path # use path style uri for minio rather than host style
# path: /pgbackrest # minio backup path, default is `/pgbackrest`
# storage_port: 9000 # minio port, 9000 by default
# storage_ca_file: /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
# block: y # Enable block incremental backup
# bundle: y # bundle small files into a single file
# bundle_limit: 20MiB # Limit for file bundles, 20MiB for object storage
# bundle_size: 128MiB # Target size for file bundles, 128MiB for object storage
# cipher_type: aes-256-cbc # enable AES encryption for remote backup repo
# cipher_pass: pgBackRest # AES encryption password, default is 'pgBackRest'
# retention_full_type: time # retention full backup by time on minio repo
# retention_full: 14 # keep full backup for last 14 days
# s3: # aliyun oss (s3 compatible) object storage service
# type: s3 # oss is s3-compatible
# s3_endpoint: oss-cn-beijing-internal.aliyuncs.com
# s3_region: oss-cn-beijing
# s3_bucket: <your_bucket_name>
# s3_key: <your_access_key>
# s3_key_secret: <your_secret_key>
# s3_uri_style: host
# path: /pgbackrest
# bundle: y # bundle small files into a single file
# bundle_limit: 20MiB # Limit for file bundles, 20MiB for object storage
# bundle_size: 128MiB # Target size for file bundles, 128MiB for object storage
# cipher_type: aes-256-cbc # enable AES encryption for remote backup repo
# cipher_pass: pgBackRest # AES encryption password, default is 'pgBackRest'
# retention_full_type: time # retention full backup by time on minio repo
# retention_full: 14 # keep full backup for last 14 days
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 meta 模板是 Pigsty 的 默认入门配置 ,专为快速上手设计。
适用场景 :
首次体验 Pigsty 的用户 开发测试环境的快速部署 单机运行的小型生产环境 作为更复杂部署的基础模板 关键特性 :
在线安装模式,不构建本地软件源(repo_enabled: false) 默认安装 PostgreSQL 18,带有 postgis 和 pgvector 扩展 包含完整的监控基础设施(Grafana、Prometheus、Loki 等) 预置 Docker 与 pgAdmin 应用示例 MinIO 备份存储默认禁用,可按需启用 注意事项 :
默认密码为示例密码,生产环境 务必修改 单节点模式的 etcd 无高可用保障,适合开发测试 如需构建本地软件源,请使用 rich 模板 9.3 - rich 功能丰富的单节点配置,构建本地软件源,下载所有扩展,启用 MinIO 备份,预置完整示例
配置模板 rich 是 meta 的增强版本,专为需要完整功能体验的用户设计。
如果您希望构建本地软件源、使用 MinIO 存储备份、运行 Docker 应用,或需要预置业务数据库,可以使用此模板。
配置概览 配置名称: rich 节点数量: 单节点 配置说明:功能丰富的单节点配置,在 meta 基础上增加本地软件源、MinIO 备份、完整扩展、Docker 应用示例 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta ,slim ,fat 此模板相比 meta 的主要增强:
构建本地软件源(repo_enabled: true),下载所有 PG 扩展 启用单节点 MinIO 作为 PostgreSQL 备份存储 预置 TimescaleDB、pgvector、pg_wait_sampling 等扩展 包含详细的用户/数据库/服务定义注释示例 添加 Redis 主从实例示例 预置 pg-test 三节点高可用集群配置存根 启用方式:
./configure -c rich [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/rich.yml
---
#==============================================================#
# File : rich.yml
# Desc : Pigsty feature-rich 1-node online install config
# Ctime : 2020-05-22
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the enhanced version of default meta.yml, which has:
# - almost all available postgres extensions
# - build local software repo for entire env
# - 1 node minio used as central backup repo
# - cluster stub for 3-node pg-test / ferret / redis
# - stub for nginx, certs, and website self-hosting config
# - detailed comments for database / user / service
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c rich
# ./deploy.yml
all :
#==============================================================#
# Clusters, Nodes, and Modules
#==============================================================#
children :
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql
#----------------------------------------------#
# this is an example single-node postgres cluster with pgvector installed, with one biz database & two biz users
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary } # <---- primary instance with read-write capability
#x.xx.xx.xx: { pg_seq: 2, pg_role: replica } # <---- read only replica for read-only online traffic
#x.xx.xx.xy: { pg_seq: 3, pg_role: offline } # <---- offline instance of ETL & interactive queries
vars :
pg_cluster : pg-meta
# install, load, create pg extensions: https://doc.pgsty.com/pgsql/extension
pg_extensions : [ postgis, timescaledb, pgvector, pg_wait_sampling ]
pg_libs : 'timescaledb, pg_stat_statements, auto_explain, pg_wait_sampling'
# define business users/roles : https://doc.pgsty.com/pgsql/user
pg_users :
- name : dbuser_meta # REQUIRED, `name` is the only mandatory field of a user definition
password : DBUser.Meta # optional, the password. can be a scram-sha-256 hash string or plain text
login : true # optional, can log in, true by default (new biz ROLE should be false)
superuser : false # optional, is superuser? false by default
createdb : false # optional, can create databases? false by default
createrole : false # optional, can create role? false by default
inherit : true # optional, can this role use inherited privileges? true by default
replication : false # optional, can this role do replication? false by default
bypassrls : false # optional, can this role bypass row level security? false by default
pgbouncer : true # optional, add this user to the pgbouncer user-list? false by default (production user should be true explicitly)
connlimit : -1 # optional, user connection limit, default -1 disable limit
expire_in : 3650 # optional, now + n days when this role is expired (OVERWRITE expire_at)
expire_at : '2030-12-31' # optional, YYYY-MM-DD 'timestamp' when this role is expired (OVERWRITTEN by expire_in)
comment : pigsty admin user # optional, comment string for this user/role
roles: [dbrole_admin] # optional, belonged roles. default roles are : dbrole_{admin|readonly|readwrite|offline}
parameters : {} # optional, role level parameters with `ALTER ROLE SET`
pool_mode : transaction # optional, pgbouncer pool mode at user level, transaction by default
pool_connlimit : -1 # optional, max database connections at user level, default -1 disable limit
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly], comment : read-only viewer for meta database }
#- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for bytebase database }
# define business databases : https://doc.pgsty.com/pgsql/db
pg_databases : # define business databases on this cluster, array of database definition
- name : meta # REQUIRED, `name` is the only mandatory field of a database definition
baseline: cmdb.sql # optional, database sql baseline path, (relative path among the ansible search path, e.g. : files/)
schemas : [ pigsty ] # optional, additional schemas to be created, array of schema names
extensions: # optional, additional extensions to be installed : array of `{name[,schema]}`
- vector # install pgvector for vector similarity search
- postgis # install postgis for geospatial type & index
- timescaledb # install timescaledb for time-series data
- { name: pg_wait_sampling, schema : monitor } # install pg_wait_sampling on monitor schema
comment : pigsty meta database # optional, comment string for this database
#pgbouncer: true # optional, add this database to the pgbouncer database list? true by default
#owner: postgres # optional, database owner, postgres by default
#template: template1 # optional, which template to use, template1 by default
#encoding: UTF8 # optional, database encoding, UTF8 by default. (same as template database)
#locale: C # optional, database locale, C by default. (same as template database)
#lc_collate: C # optional, database collate, C by default. (same as template database)
#lc_ctype: C # optional, database ctype, C by default. (same as template database)
#tablespace: pg_default # optional, default tablespace, 'pg_default' by default.
#allowconn: true # optional, allow connection, true by default. false will disable connect at all
#revokeconn: false # optional, revoke public connection privilege. false by default. (leave connect with grant option to owner)
#register_datasource: true # optional, register this database to grafana datasources? true by default
#connlimit: -1 # optional, database connection limit, default -1 disable limit
#pool_auth_user: dbuser_meta # optional, all connection to this pgbouncer database will be authenticated by this user
#pool_mode: transaction # optional, pgbouncer pool mode at database level, default transaction
#pool_size: 64 # optional, pgbouncer pool size at database level, default 64
#pool_size_reserve: 32 # optional, pgbouncer pool size reserve at database level, default 32
#pool_size_min: 0 # optional, pgbouncer pool size min at database level, default 0
#pool_max_db_conn: 100 # optional, max database connections at database level, default 100
#- {name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment: bytebase primary database }
# define HBA rules : https://doc.pgsty.com/pgsql/hba
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
# define backup policies: https://doc.pgsty.com/pgsql/backup
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every day 1am
# define (OPTIONAL) L2 VIP that bind to primary
#pg_vip_enabled: true
#pg_vip_address: 10.10.10.2/24
#pg_vip_interface: eth1
#----------------------------------------------#
# PGSQL HA Cluster Example: 3-node pg-test
#----------------------------------------------#
#pg-test:
# hosts:
# 10.10.10.11: { pg_seq: 1, pg_role: primary } # primary instance, leader of cluster
# 10.10.10.12: { pg_seq: 2, pg_role: replica } # replica instance, follower of leader
# 10.10.10.13: { pg_seq: 3, pg_role: replica, pg_offline_query: true } # replica with offline access
# vars:
# pg_cluster: pg-test # define pgsql cluster name
# pg_users: [{ name: test , password: test , pgbouncer: true , roles: [ dbrole_admin ] }]
# pg_databases: [{ name: test }]
# # define business service here: https://doc.pgsty.com/pgsql/service
# pg_services: # extra services in addition to pg_default_services, array of service definition
# # standby service will route {ip|name}:5435 to sync replica's pgbouncer (5435->6432 standby)
# - name: standby # required, service name, the actual svc name will be prefixed with `pg_cluster`, e.g: pg-meta-standby
# port: 5435 # required, service exposed port (work as kubernetes service node port mode)
# ip: "*" # optional, service bind ip address, `*` for all ip by default
# selector: "[]" # required, service member selector, use JMESPath to filter inventory
# dest: default # optional, destination port, default|postgres|pgbouncer|<port_number>, 'default' by default
# check: /sync # optional, health check url path, / by default
# backup: "[? pg_role == `primary`]" # backup server selector
# maxconn: 3000 # optional, max allowed front-end connection
# balance: roundrobin # optional, haproxy load balance algorithm (roundrobin by default, other: leastconn)
# options: 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
# pg_vip_enabled: true
# pg_vip_address: 10.10.10.3/24
# pg_vip_interface: eth1
# node_crontab: # make a full backup on monday 1am, and an incremental backup during weekdays
# - '00 01 * * 1 postgres /pg/bin/pg-backup full'
# - '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
vars :
repo_enabled: true # build local repo, and install everything from it : https://doc.pgsty.com/admin/repo
# and download all extensions into local repo
repo_extra_packages : [ pg18-main ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# ETCD : https://doc.pgsty.com/etcd
#----------------------------------------------#
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
vars :
etcd_cluster : etcd
etcd_safeguard : false # prevent purging running etcd instance?
#----------------------------------------------#
# MINIO : https://doc.pgsty.com/minio
#----------------------------------------------#
minio :
hosts :
10.10.10.10 : { minio_seq : 1 }
vars :
minio_cluster : minio
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
#----------------------------------------------#
# DOCKER : https://doc.pgsty.com/docker
# APP : https://doc.pgsty.com/app
#----------------------------------------------#
# OPTIONAL, launch example pgadmin app with: ./app.yml & ./app.yml -e app=bytebase
app :
hosts : { 10.10.10.10 : {} }
vars :
docker_enabled : true # enabled docker with ./docker.yml
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
app : pgadmin # specify the default app name to be installed (in the apps)
apps: # define all applications, appname : definition
# Admin GUI for PostgreSQL, launch with: ./app.yml
pgadmin : # pgadmin app definition (app/pgadmin -> /opt/pgadmin)
conf : # override /opt/pgadmin/.env
PGADMIN_DEFAULT_EMAIL : admin@pigsty.cc # default user name
PGADMIN_DEFAULT_PASSWORD : pigsty # default password
# Schema Migration GUI for PostgreSQL, launch with: ./app.yml -e app=bytebase
bytebase :
conf :
BB_DOMAIN : http://ddl.pigsty # replace it with your public domain name and postgres database url
BB_PGURL : "postgresql://dbuser_bytebase:DBUser.Bytebase@10.10.10.10:5432/bytebase?sslmode=prefer"
#----------------------------------------------#
# REDIS : https://doc.pgsty.com/redis
#----------------------------------------------#
# OPTIONAL, launch redis clusters with: ./redis.yml
redis-ms :
hosts : { 10.10.10.10 : { redis_node: 1 , redis_instances : { 6379 : { }, 6380 : { replica_of : '10.10.10.10 6379' } } } }
vars : { redis_cluster: redis-ms ,redis_password: 'redis.ms' ,redis_max_memory : 64MB }
#==============================================================#
# Global Parameters
#==============================================================#
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
certbot_sign : false # enable certbot to sign https certificate for infra portal
certbot_email : your@email.com # replace your email address to receive expiration notice
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
pgadmin : { domain: adm.pigsty ,endpoint : "${admin_ip}:8885" }
bytebase : { domain: ddl.pigsty ,endpoint : "${admin_ip}:8887" }
minio : { domain: m.pigsty ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
#website: # static local website example stub
# domain: repo.pigsty # external domain name for static site
# certbot: repo.pigsty # use certbot to sign https certificate for this static site
# path: /www/pigsty # path to the static site directory
#supabase: # dynamic upstream service example stub
# domain: supa.pigsty # external domain name for upstream service
# certbot: supa.pigsty # use certbot to sign https certificate for this upstream server
# endpoint: "10.10.10.10:8000" # path to the static site directory
# websocket: true # add websocket support
# certbot: supa.pigsty # certbot cert name, apply with `make cert`
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
node_etc_hosts : # add static domains to all nodes /etc/hosts
- '${admin_ip} i.pigsty sss.pigsty'
- '${admin_ip} adm.pigsty ddl.pigsty repo.pigsty supa.pigsty'
node_repo_modules : local # use pre-made local repo rather than install from upstream
node_repo_remove : true # remove existing node repo for node managed by pigsty
#node_packages: [openssh-server] # packages to be installed current nodes with latest version
#node_timezone: Asia/Hong_Kong # overwrite node timezone
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # default postgres version
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_safeguard : false # prevent purging running postgres instance?
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# BACKUP : https://doc.pgsty.com/pgsql/backup
#----------------------------------------------#
# if you want to use minio as backup repo instead of 'local' fs, uncomment this, and configure `pgbackrest_repo`
# you can also use external object storage as backup repo
pgbackrest_method : minio # if you want to use minio as backup repo instead of 'local' fs, uncomment this
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backups when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest [CHANGE ACCORDING to minio_users.pgbackrest]
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest [CHANGE ACCORDING to minio_users.pgbackrest]
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the last 14 days
s3 : # you can use cloud object storage as backup repo
type : s3 # Add your object storage credentials here!
s3_endpoint : oss-cn-beijing-internal.aliyuncs.com
s3_region : oss-cn-beijing
s3_bucket : <your_bucket_name>
s3_key : <your_access_key>
s3_key_secret : <your_secret_key>
s3_uri_style : host
path : /pgbackrest
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the last 14 days
... 配置解读 rich 模板是 Pigsty 的 完整功能展示配置 ,适合需要深入体验所有功能的用户。
适用场景 :
需要构建本地软件源的离线环境 需要使用 MinIO 作为 PostgreSQL 备份存储 需要预先规划多个业务数据库和用户 需要运行 Docker 应用(pgAdmin、Bytebase 等) 希望了解配置参数完整用法的学习者 与 meta 的主要区别 :
启用本地软件源构建(repo_enabled: true) 启用 MinIO 存储备份(pgbackrest_method: minio) 预装 TimescaleDB、pg_wait_sampling 等额外扩展 包含详细的参数注释,便于理解配置含义 预置高可用集群存根配置(pg-test) 注意事项 :
ARM64 架构部分扩展不可用,请按需调整 构建本地软件源需要较长时间和较大磁盘空间 默认密码为示例密码,生产环境务必修改 9.4 - slim 精简安装配置模板,不部署监控基础设施,直接从互联网安装 PostgreSQL
slim 配置模板提供 精简安装 能力,在不部署 Infra 监控基础设施的前提下,直接从互联网安装 PostgreSQL 高可用集群。
当您只需要一个可用的数据库实例,不需要监控系统时,可以考虑使用 精简安装 模式。
配置概览 配置名称: slim 节点数量: 单节点 配置说明:精简安装配置模板,不部署监控基础设施,直接安装 PostgreSQL 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c slim [ -i <primary_ip>]
./slim.yml # 执行精简安装
配置内容 源文件地址:pigsty/conf/slim.yml
---
#==============================================================#
# File : slim.yml
# Desc : Pigsty slim installation config template
# Ctime : 2020-05-22
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for slim / minimal installation
# No monitoring & infra will be installed, just raw postgresql
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c slim
# ./slim.yml
all :
children :
etcd : # dcs service for postgres/patroni ha consensus
hosts : # 1 node for testing, 3 or 5 for production
10.10.10.10 : { etcd_seq : 1 } # etcd_seq required
#10.10.10.11: { etcd_seq: 2 } # assign from 1 ~ n
#10.10.10.12: { etcd_seq: 3 } # odd number please
vars : # cluster level parameter override roles/etcd
etcd_cluster : etcd # mark etcd cluster name etcd
#----------------------------------------------#
# PostgreSQL Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
#10.10.10.11: { pg_seq: 2, pg_role: replica } # you can add more!
#10.10.10.12: { pg_seq: 3, pg_role: replica, pg_offline_query: true }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
pg_databases :
- { name: meta, baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ vector ]}
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
vars :
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_version : 18 # Default PostgreSQL Major Version is 18
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 slim 模板是 Pigsty 的 精简安装配置 ,专为快速部署裸 PostgreSQL 集群设计。
适用场景 :
仅需要 PostgreSQL 数据库,不需要监控系统 资源有限的小型服务器或边缘设备 快速部署测试用的临时数据库 已有监控系统,只需要 PostgreSQL 高可用集群 关键特性 :
使用 slim.yml 剧本而非 install.yml 进行安装 从互联网直接安装软件,不构建本地软件源 保留核心 PostgreSQL 高可用能力(Patroni + etcd + HAProxy) 最小化软件包下载,加快安装速度 默认使用 PostgreSQL 18 与 meta 的区别 :
slim 使用专用的 slim.yml 剧本,跳过 Infra 模块安装安装速度更快,资源占用更少 适合"只要数据库"的场景 注意事项 :
精简安装后无法通过 Grafana 查看数据库状态 如需监控功能,请使用 meta 或 rich 模板 可按需添加从库实现高可用 9.5 - fat 功能全测试模板,单节点安装所有扩展,构建包含 PG 13-18 全版本的本地软件源。
fat 配置模板是 Pigsty 的 功能全测试模板 (Feature-All-Test),在单节点上安装所有扩展插件,并构建包含 PostgreSQL 13-18 全部六个大版本所有扩展的本地软件源。
这是一个用于测试与开发的全功能配置,适合需要完整软件包缓存或测试全部扩展的场景。
配置概览 配置名称: fat 节点数量: 单节点 配置说明:功能全测试模板,安装所有扩展,构建包含 PG 13-18 全版本的本地软件源 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta ,slim ,fat 启用方式:
./configure -c fat [ -i <primary_ip>]
如需指定特定 PostgreSQL 版本:
./configure -c fat -v 17 # 使用 PostgreSQL 17
配置内容 源文件地址:pigsty/conf/fat.yml
---
#==============================================================#
# File : fat.yml
# Desc : Pigsty Feature-All-Test config template
# Ctime : 2020-05-22
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the 4-node sandbox for pigsty
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c fat [-v 18|17|16|15]
# ./deploy.yml
all :
#==============================================================#
# Clusters, Nodes, and Modules
#==============================================================#
children :
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql
#----------------------------------------------#
# this is an example single-node postgres cluster with pgvector installed, with one biz database & two biz users
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary } # <---- primary instance with read-write capability
#x.xx.xx.xx: { pg_seq: 2, pg_role: replica } # <---- read only replica for read-only online traffic
#x.xx.xx.xy: { pg_seq: 3, pg_role: offline } # <---- offline instance of ETL & interactive queries
vars :
pg_cluster : pg-meta
# install, load, create pg extensions: https://doc.pgsty.com/pgsql/extension
pg_extensions : [ pg18-main ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_libs : 'timescaledb, pg_stat_statements, auto_explain, pg_wait_sampling'
# define business users/roles : https://doc.pgsty.com/pgsql/user
pg_users :
- name : dbuser_meta # REQUIRED, `name` is the only mandatory field of a user definition
password : DBUser.Meta # optional, the password. can be a scram-sha-256 hash string or plain text
login : true # optional, can log in, true by default (new biz ROLE should be false)
superuser : false # optional, is superuser? false by default
createdb : false # optional, can create databases? false by default
createrole : false # optional, can create role? false by default
inherit : true # optional, can this role use inherited privileges? true by default
replication : false # optional, can this role do replication? false by default
bypassrls : false # optional, can this role bypass row level security? false by default
pgbouncer : true # optional, add this user to the pgbouncer user-list? false by default (production user should be true explicitly)
connlimit : -1 # optional, user connection limit, default -1 disable limit
expire_in : 3650 # optional, now + n days when this role is expired (OVERWRITE expire_at)
expire_at : '2030-12-31' # optional, YYYY-MM-DD 'timestamp' when this role is expired (OVERWRITTEN by expire_in)
comment : pigsty admin user # optional, comment string for this user/role
roles: [dbrole_admin] # optional, belonged roles. default roles are : dbrole_{admin|readonly|readwrite|offline}
parameters : {} # optional, role level parameters with `ALTER ROLE SET`
pool_mode : transaction # optional, pgbouncer pool mode at user level, transaction by default
pool_connlimit : -1 # optional, max database connections at user level, default -1 disable limit
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly], comment : read-only viewer for meta database }
#- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for bytebase database }
# define business databases : https://doc.pgsty.com/pgsql/db
pg_databases : # define business databases on this cluster, array of database definition
- name : meta # REQUIRED, `name` is the only mandatory field of a database definition
baseline: cmdb.sql # optional, database sql baseline path, (relative path among the ansible search path, e.g. : files/)
schemas : [ pigsty ] # optional, additional schemas to be created, array of schema names
extensions: # optional, additional extensions to be installed : array of `{name[,schema]}`
- vector # install pgvector for vector similarity search
- postgis # install postgis for geospatial type & index
- timescaledb # install timescaledb for time-series data
- { name: pg_wait_sampling, schema : monitor } # install pg_wait_sampling on monitor schema
comment : pigsty meta database # optional, comment string for this database
#pgbouncer: true # optional, add this database to the pgbouncer database list? true by default
#owner: postgres # optional, database owner, postgres by default
#template: template1 # optional, which template to use, template1 by default
#encoding: UTF8 # optional, database encoding, UTF8 by default. (same as template database)
#locale: C # optional, database locale, C by default. (same as template database)
#lc_collate: C # optional, database collate, C by default. (same as template database)
#lc_ctype: C # optional, database ctype, C by default. (same as template database)
#tablespace: pg_default # optional, default tablespace, 'pg_default' by default.
#allowconn: true # optional, allow connection, true by default. false will disable connect at all
#revokeconn: false # optional, revoke public connection privilege. false by default. (leave connect with grant option to owner)
#register_datasource: true # optional, register this database to grafana datasources? true by default
#connlimit: -1 # optional, database connection limit, default -1 disable limit
#pool_auth_user: dbuser_meta # optional, all connection to this pgbouncer database will be authenticated by this user
#pool_mode: transaction # optional, pgbouncer pool mode at database level, default transaction
#pool_size: 64 # optional, pgbouncer pool size at database level, default 64
#pool_size_reserve: 32 # optional, pgbouncer pool size reserve at database level, default 32
#pool_size_min: 0 # optional, pgbouncer pool size min at database level, default 0
#pool_max_db_conn: 100 # optional, max database connections at database level, default 100
#- {name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment: bytebase primary database }
# define HBA rules : https://doc.pgsty.com/pgsql/hba
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
# define backup policies: https://doc.pgsty.com/pgsql/backup
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every day 1am
# define (OPTIONAL) L2 VIP that bind to primary
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
vars :
repo_enabled: true # build local repo : https://doc.pgsty.com/admin/repo
#repo_extra_packages: [ pg18-main ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
repo_packages : [
node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules,
pg18-full,pg18-time,pg18-gis,pg18-rag,pg18-fts,pg18-olap,pg18-feat,pg18-lang,pg18-type,pg18-util,pg18-func,pg18-admin,pg18-stat,pg18-sec,pg18-fdw,pg18-sim,pg18-etl,
pg17-full,pg17-time,pg17-gis,pg17-rag,pg17-fts,pg17-olap,pg17-feat,pg17-lang,pg17-type,pg17-util,pg17-func,pg17-admin,pg17-stat,pg17-sec,pg17-fdw,pg17-sim,pg17-etl,
pg16-full,pg16-time,pg16-gis,pg16-rag,pg16-fts,pg16-olap,pg16-feat,pg16-lang,pg16-type,pg16-util,pg16-func,pg16-admin,pg16-stat,pg16-sec,pg16-fdw,pg16-sim,pg16-etl,
pg15-full,pg15-time,pg15-gis,pg15-rag,pg15-fts,pg15-olap,pg15-feat,pg15-lang,pg15-type,pg15-util,pg15-func,pg15-admin,pg15-stat,pg15-sec,pg15-fdw,pg15-sim,pg15-etl,
pg14-full,pg14-time,pg14-gis,pg14-rag,pg14-fts,pg14-olap,pg14-feat,pg14-lang,pg14-type,pg14-util,pg14-func,pg14-admin,pg14-stat,pg14-sec,pg14-fdw,pg14-sim,pg14-etl,
pg13-full,pg13-time,pg13-gis,pg13-rag,pg13-fts,pg13-olap,pg13-feat,pg13-lang,pg13-type,pg13-util,pg13-func,pg13-admin,pg13-stat,pg13-sec,pg13-fdw,pg13-sim,pg13-etl,
infra-extra, kafka, java-runtime, sealos, tigerbeetle, polardb, ivorysql
]
#----------------------------------------------#
# ETCD : https://doc.pgsty.com/etcd
#----------------------------------------------#
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
vars :
etcd_cluster : etcd
etcd_safeguard : false # prevent purging running etcd instance?
#----------------------------------------------#
# MINIO : https://doc.pgsty.com/minio
#----------------------------------------------#
minio :
hosts :
10.10.10.10 : { minio_seq : 1 }
vars :
minio_cluster : minio
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
#----------------------------------------------#
# DOCKER : https://doc.pgsty.com/docker
# APP : https://doc.pgsty.com/app
#----------------------------------------------#
# OPTIONAL, launch example pgadmin app with: ./app.yml & ./app.yml -e app=bytebase
app :
hosts : { 10.10.10.10 : {} }
vars :
docker_enabled : true # enabled docker with ./docker.yml
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
app : pgadmin # specify the default app name to be installed (in the apps)
apps: # define all applications, appname : definition
# Admin GUI for PostgreSQL, launch with: ./app.yml
pgadmin : # pgadmin app definition (app/pgadmin -> /opt/pgadmin)
conf : # override /opt/pgadmin/.env
PGADMIN_DEFAULT_EMAIL : admin@pigsty.cc # default user name
PGADMIN_DEFAULT_PASSWORD : pigsty # default password
# Schema Migration GUI for PostgreSQL, launch with: ./app.yml -e app=bytebase
bytebase :
conf :
BB_DOMAIN : http://ddl.pigsty # replace it with your public domain name and postgres database url
BB_PGURL : "postgresql://dbuser_bytebase:DBUser.Bytebase@10.10.10.10:5432/bytebase?sslmode=prefer"
#==============================================================#
# Global Parameters
#==============================================================#
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
certbot_sign : false # enable certbot to sign https certificate for infra portal
certbot_email : your@email.com # replace your email address to receive expiration notice
infra_portal : # domain names and upstream servers
home : { domain : i.pigsty }
pgadmin : { domain: adm.pigsty ,endpoint : "${admin_ip}:8885" }
bytebase : { domain: ddl.pigsty ,endpoint : "${admin_ip}:8887" ,websocket : true }
minio : { domain: m.pigsty ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
#website: # static local website example stub
# domain: repo.pigsty # external domain name for static site
# certbot: repo.pigsty # use certbot to sign https certificate for this static site
# path: /www/pigsty # path to the static site directory
#supabase: # dynamic upstream service example stub
# domain: supa.pigsty # external domain name for upstream service
# certbot: supa.pigsty # use certbot to sign https certificate for this upstream server
# endpoint: "10.10.10.10:8000" # path to the static site directory
# websocket: true # add websocket support
# certbot: supa.pigsty # certbot cert name, apply with `make cert`
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : true # overwrite node hostname on multi-node template
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
node_etc_hosts : # add static domains to all nodes /etc/hosts
- 10.10.10.10 i.pigsty sss.pigsty
- 10.10.10.10 adm.pigsty ddl.pigsty repo.pigsty supa.pigsty
node_repo_modules : local,node,infra,pgsql # use pre-made local repo rather than install from upstream
node_repo_remove : true # remove existing node repo for node managed by pigsty
#node_packages: [openssh-server] # packages to be installed current nodes with latest version
#node_timezone: Asia/Hong_Kong # overwrite node timezone
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # default postgres version
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_safeguard : false # prevent purging running postgres instance?
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# BACKUP : https://doc.pgsty.com/pgsql/backup
#----------------------------------------------#
# if you want to use minio as backup repo instead of 'local' fs, uncomment this, and configure `pgbackrest_repo`
# you can also use external object storage as backup repo
pgbackrest_method : minio # if you want to use minio as backup repo instead of 'local' fs, uncomment this
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backups when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest [CHANGE ACCORDING to minio_users.pgbackrest]
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest [CHANGE ACCORDING to minio_users.pgbackrest]
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the last 14 days
s3 : # you can use cloud object storage as backup repo
type : s3 # Add your object storage credentials here!
s3_endpoint : oss-cn-beijing-internal.aliyuncs.com
s3_region : oss-cn-beijing
s3_bucket : <your_bucket_name>
s3_key : <your_access_key>
s3_key_secret : <your_secret_key>
s3_uri_style : host
path : /pgbackrest
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the last 14 days
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 fat 模板是 Pigsty 的 全功能测试配置 ,专为完整性测试和离线包构建设计。
关键特性 :
全扩展安装 :安装 PostgreSQL 18 的所有分类扩展包多版本软件源 :本地软件源包含 PostgreSQL 13-18 全部六个大版本完整组件栈 :包含 MinIO 备份、Docker 应用、VIP 等功能企业级组件 :包含 Kafka、PolarDB、IvorySQL、TigerBeetle 等软件源内容 :
分类 说明 PostgreSQL 13-18 六个大版本的内核和全部扩展 扩展分类包 time, gis, rag, fts, olap, feat, lang, type, util, func, admin, stat, sec, fdw, sim, etl企业组件 Kafka、Java 运行时、Sealos、TigerBeetle 数据库内核 PolarDB、IvorySQL
与 rich 的区别 :
fat 包含 PostgreSQL 13-18 全部六个版本,rich 只包含当前默认版本fat 包含额外的企业组件(Kafka、PolarDB、IvorySQL 等)fat 需要更大的磁盘空间和更长的构建时间适用场景 :
Pigsty 开发测试与功能验证 构建完整的多版本离线软件包 需要测试全部扩展兼容性的场景 企业环境预先缓存所有软件包 注意事项 :
需要较大磁盘空间(建议 100GB+)用于存储所有软件包 构建本地软件源需要较长时间 部分扩展在 ARM64 架构不可用 默认密码为示例密码,生产环境务必修改 9.6 - infra 仅安装可观测性基础设施,不包含 PostgreSQL 与 etcd 的专用配置模板
infra 配置模板仅部署 Pigsty 的可观测性基础设施组件(VictoriaMetrics/Grafana/Loki/Nginx 等),不包含 PostgreSQL 与 etcd。
适用于需要独立监控栈的场景,例如监控外部 PostgreSQL/RDS 实例或其他数据源。
配置概览 配置名称: infra 节点数量: 单节点或多节点 配置说明:仅安装可观测性基础设施,不包含 PostgreSQL 与 etcd 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c infra [ -i <primary_ip>]
./infra.yml # 仅执行 infra 剧本
配置内容 源文件地址:pigsty/conf/infra.yml
---
#==============================================================#
# File : infra.yml
# Desc : Infra Only Config
# Ctime : 2025-12-16
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/infra
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for deploy victoria stack alone
# tutorial: https://doc.pgsty.com/infra
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c infra
# ./infra.yml
all :
children :
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
#10.10.10.11: { infra_seq: 2 } # you can add more nodes if you want
#10.10.10.12: { infra_seq: 3 } # don't forget to assign unique infra_seq for each node
vars : # global variables
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
repo_enabled : false # online installation
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 infra 模板是 Pigsty 的 纯监控栈配置 ,专为独立部署可观测性基础设施设计。
适用场景 :
监控外部 PostgreSQL 实例(RDS、自建等) 需要独立的监控/告警平台 已有 PostgreSQL 集群,仅需添加监控 作为多集群监控的中央控制台 包含组件 :
VictoriaMetrics :时序数据库,存储监控指标VictoriaLogs :日志聚合系统VictoriaTraces :链路追踪系统Grafana :可视化仪表盘Alertmanager :告警管理Nginx :反向代理和 Web 入口不包含组件 :
PostgreSQL 数据库集群 etcd 分布式协调服务 MinIO 对象存储 监控外部实例 :
配置完成后,可通过 pgsql-monitor.yml 剧本添加外部 PostgreSQL 实例的监控:
pg_exporters :
20001 : { pg_cluster: pg-foo, pg_seq: 1, pg_host : 10.10.10.100 }
20002 : { pg_cluster: pg-bar, pg_seq: 1, pg_host : 10.10.10.101 }
注意事项 :
此模板不会安装任何数据库 如需完整功能,请使用 meta 或 rich 模板 可根据需要添加多个 infra 节点实现高可用
9.7 - 内核模版 9.8 - pgsql 原生 PostgreSQL 内核,支持 PostgreSQL 13 到 18 的多版本部署
pgsql 配置模板使用原生 PostgreSQL 内核,是 Pigsty 的默认数据库内核,支持 PostgreSQL 13 到 18 版本。
配置概览 配置名称: pgsql 节点数量: 单节点 配置说明:原生 PostgreSQL 内核配置模板 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c pgsql [ -i <primary_ip>]
如需指定特定 PostgreSQL 版本(如 17):
./configure -c pgsql -v 17
配置内容 源文件地址:pigsty/conf/pgsql.yml
---
#==============================================================#
# File : pgsql.yml
# Desc : 1-node PostgreSQL Config template
# Ctime : 2025-02-23
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for basical PostgreSQL Kernel.
# Nothing special, just a basic setup with one node.
# tutorial: https://doc.pgsty.com/pgsql/kernel/postgres
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c pgsql
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# PostgreSQL Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
pg_databases :
- { name: meta, baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ postgis, timescaledb, vector ]}
pg_extensions : [ postgis, timescaledb, pgvector, pg_wait_sampling ]
pg_libs : 'timescaledb, pg_stat_statements, auto_explain, pg_wait_sampling'
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # Default PostgreSQL Major Version is 18
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 pgsql 模板是 Pigsty 的 标准内核配置 ,使用社区原生 PostgreSQL。
版本支持 :
PostgreSQL 18(默认) PostgreSQL 17、16、15、14、13 适用场景 :
需要使用最新 PostgreSQL 特性 需要最广泛的扩展支持 标准生产环境部署 与 meta 模板功能相同,显式声明使用原生内核 与 meta 的区别 :
pgsql 模板显式声明使用原生 PostgreSQL 内核适合需要明确区分不同内核类型的场景 9.9 - citus Citus 分布式 PostgreSQL 集群,提供水平扩展与分片能力
citus 配置模板使用 Citus 扩展部署分布式 PostgreSQL 集群,提供透明的水平扩展与数据分片能力。
配置概览 配置名称: citus 节点数量: 五节点(1 协调节点 + 4 数据节点) 配置说明:Citus 分布式 PostgreSQL 集群 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64 相关配置:meta 启用方式:
./configure -c citus [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/citus.yml
---
#==============================================================#
# File : citus.yml
# Desc : 1-node Citus (Distributive) Config Template
# Ctime : 2020-05-22
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for Citus Distributive Cluster
# tutorial: https://doc.pgsty.com/pgsql/kernel/citus
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c citus
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# pg-citus: 10 node citus cluster
#----------------------------------------------#
pg-citus : # the citus group contains 5 clusters
hosts :
10.10.10.10 : { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.60/24 ,pg_seq: 0, pg_role : primary }
#10.10.10.11: { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.60/24 ,pg_seq: 1, pg_role: replica }
#10.10.10.12: { pg_group: 1, pg_cluster: pg-citus1 ,pg_vip_address: 10.10.10.61/24 ,pg_seq: 0, pg_role: primary }
#10.10.10.13: { pg_group: 1, pg_cluster: pg-citus1 ,pg_vip_address: 10.10.10.61/24 ,pg_seq: 1, pg_role: replica }
#10.10.10.14: { pg_group: 2, pg_cluster: pg-citus2 ,pg_vip_address: 10.10.10.62/24 ,pg_seq: 0, pg_role: primary }
#10.10.10.15: { pg_group: 2, pg_cluster: pg-citus2 ,pg_vip_address: 10.10.10.62/24 ,pg_seq: 1, pg_role: replica }
#10.10.10.16: { pg_group: 3, pg_cluster: pg-citus3 ,pg_vip_address: 10.10.10.63/24 ,pg_seq: 0, pg_role: primary }
#10.10.10.17: { pg_group: 3, pg_cluster: pg-citus3 ,pg_vip_address: 10.10.10.63/24 ,pg_seq: 1, pg_role: replica }
#10.10.10.18: { pg_group: 4, pg_cluster: pg-citus4 ,pg_vip_address: 10.10.10.64/24 ,pg_seq: 0, pg_role: primary }
#10.10.10.19: { pg_group: 4, pg_cluster: pg-citus4 ,pg_vip_address: 10.10.10.64/24 ,pg_seq: 1, pg_role: replica }
vars :
pg_mode: citus # pgsql cluster mode : citus
pg_shard: pg-citus # citus shard name : pg-citus
pg_primary_db : citus # primary database used by citus
pg_dbsu_password : DBUser.Postgres # enable dbsu password access for citus
pg_extensions : [ citus, postgis, pgvector, topn, pg_cron, hll ] # install these extensions
pg_libs : 'citus, pg_cron, pg_stat_statements' # citus will be added by patroni automatically
pg_users : [ { name: dbuser_citus ,password: DBUser.Citus ,pgbouncer: true ,roles : [ dbrole_admin ] }]
pg_databases : [ { name: citus ,owner: dbuser_citus ,extensions : [ citus, vector, topn, pg_cron, hll ] }]
pg_parameters :
cron.database_name : citus
citus.node_conninfo : 'sslrootcert=/pg/cert/ca.crt sslmode=verify-full'
pg_hba_rules :
- { user: 'all' ,db: all ,addr: 127.0.0.1/32 ,auth: ssl ,title : 'all user ssl access from localhost' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'all user ssl access from intranet' }
pg_vip_enabled : true # enable vip for citus cluster
pg_vip_interface : eth1 # vip interface for all members (you can override this in each host)
vars : # global variables
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : true # overwrite hostname since this is a multi-node tempalte
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 17 # Default PostgreSQL Major Version is 17
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#pg_extensions: [ pg17-time ,pg17-gis ,pg17-rag ,pg17-fts ,pg17-olap ,pg17-feat ,pg17-lang ,pg17-type ,pg17-util ,pg17-func ,pg17-admin ,pg17-stat ,pg17-sec ,pg17-fdw ,pg17-sim ,pg17-etl]
#repo_extra_packages: [ pgsql-main, citus, postgis, pgvector, pg_cron, hll, topn ]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 citus 模板部署 Citus 分布式 PostgreSQL 集群,适合需要水平扩展的大规模数据场景。
关键特性 :
透明数据分片,自动分布数据到多个节点 并行查询执行,聚合多节点结果 支持分布式事务(2PC) 保持 PostgreSQL SQL 兼容性 架构说明 :
协调节点 (pg-citus0):接收查询,路由到数据节点数据节点 (pg-citus1~3):存储分片数据适用场景 :
单表数据量超过单机容量 需要水平扩展写入和查询性能 多租户 SaaS 应用 实时分析型工作负载 注意事项 :
Citus 支持 PostgreSQL 14~17 分布式表需要指定分布列 部分 PostgreSQL 特性可能受限(如外键跨分片) 不支持 ARM64 架构 9.10 - mssql WiltonDB / Babelfish 内核,提供 Microsoft SQL Server 协议与语法兼容能力
mssql 配置模板使用 WiltonDB / Babelfish 数据库内核替代原生 PostgreSQL,提供 Microsoft SQL Server 线缆协议(TDS)与 T-SQL 语法兼容能力。
完整教程请参考:Babelfish (MSSQL) 内核使用说明
配置概览 配置名称: mssql 节点数量: 单节点 配置说明:WiltonDB / Babelfish 配置模板,提供 SQL Server 协议兼容 适用系统:el8, el9, el10, u22, u24 (Debian 不可用) 适用架构:x86_64 相关配置:meta 启用方式:
./configure -c mssql [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/mssql.yml
---
#==============================================================#
# File : mssql.yml
# Desc : Babelfish: WiltonDB (MSSQL Compatible) template
# Ctime : 2020-08-01
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for Babelfish Kernel (WiltonDB),
# Which is a PostgreSQL 15 fork with SQL Server Compatibility
# tutorial: https://doc.pgsty.com/pgsql/kernel/babelfish
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c mssql
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# Babelfish Database Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_mssql ,password: DBUser.MSSQL ,superuser: true, pgbouncer: true ,roles: [dbrole_admin], comment : superuser & owner for babelfish }
pg_databases :
- name : mssql
baseline : mssql.sql
extensions : [ uuid-ossp, babelfishpg_common, babelfishpg_tsql, babelfishpg_tds, babelfishpg_money, pg_hint_plan, system_stats, tds_fdw]
owner : dbuser_mssql
parameters : { 'babelfishpg_tsql.migration_mode' : 'multi-db' }
comment : babelfish cluster, a MSSQL compatible pg cluster
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
# Babelfish / WiltonDB Ad Hoc Settings
pg_mode : mssql # Microsoft SQL Server Compatible Mode
pg_version : 15
pg_packages : [ wiltondb, pgsql-common, sqlcmd ]
pg_libs : 'babelfishpg_tds, pg_stat_statements, auto_explain' # add timescaledb to shared_preload_libraries
pg_default_hba_rules : # overwrite default HBA rules for babelfish cluster
- { user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- { user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- { user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title : 'replicator replication from localhost' }
- { user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title : 'replicator replication from intranet' }
- { user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title : 'replicator postgres db from intranet' }
- { user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- { user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title : 'monitor from infra host with password' }
- { user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- { user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title : 'admin @ everywhere with ssl & pwd' }
- { user: dbuser_mssql ,db: mssql ,addr: intra ,auth: md5 ,title : 'allow mssql dbsu intranet access' } # <--- use md5 auth method for mssql user
- { user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title : 'pgbouncer read/write via local socket' }
- { user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title : 'read/write biz user via password' }
- { user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title : 'allow etl offline tasks from intranet' }
pg_default_services : # route primary & replica service to mssql port 1433
- { name: primary ,port: 5433 ,dest: 1433 ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: 1433 ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql,mssql # extra mssql repo is required
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 15 # Babelfish kernel is compatible with postgres 15
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 mssql 模板让您可以使用 SQL Server Management Studio (SSMS) 或其他 SQL Server 客户端工具连接 PostgreSQL。
关键特性 :
使用 TDS 协议(端口 1433),兼容 SQL Server 客户端 支持 T-SQL 语法,迁移成本低 保留 PostgreSQL 的 ACID 特性和扩展生态 支持 multi-db 和 single-db 两种迁移模式 连接方式 :
# 使用 sqlcmd 命令行工具
sqlcmd -S 10.10.10.10,1433 -U dbuser_mssql -P DBUser.MSSQL -d mssql
# 使用 SSMS 或 Azure Data Studio
# Server: 10.10.10.10,1433
# Authentication: SQL Server Authentication
# Login: dbuser_mssql
# Password: DBUser.MSSQL
适用场景 :
从 SQL Server 迁移到 PostgreSQL 需要同时支持 SQL Server 和 PostgreSQL 客户端的应用 希望利用 PostgreSQL 生态同时保持 T-SQL 兼容性 注意事项 :
WiltonDB 基于 PostgreSQL 15,不支持更高版本特性 部分 T-SQL 语法可能存在兼容性差异,请参考 Babelfish 兼容性文档 需要使用 md5 认证方式(而非 scram-sha-256) 9.11 - polar PolarDB for PostgreSQL 内核,提供 Aurora 风格的存算分离能力
polar 配置模板使用阿里云 PolarDB for PostgreSQL 数据库内核替代原生 PostgreSQL,提供"云原生" Aurora 风格的存算分离能力。
完整教程请参考:PolarDB for PostgreSQL (POLAR) 内核使用说明
配置概览 配置名称: polar 节点数量: 单节点 配置说明:使用 PolarDB for PostgreSQL 内核 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64 相关配置:meta 启用方式:
./configure -c polar [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/polar.yml
---
#==============================================================#
# File : polar.yml
# Desc : Pigsty 1-node PolarDB Kernel Config Template
# Ctime : 2020-08-05
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for PolarDB PG Kernel,
# Which is a PostgreSQL 15 fork with RAC flavor features
# tutorial: https://doc.pgsty.com/pgsql/kernel/polardb
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c polar
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# PolarDB Database Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas : [ pigsty]}
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
# PolarDB Ad Hoc Settings
pg_version : 15 # PolarDB PG is based on PG 15
pg_mode : polar # PolarDB PG Compatible mode
pg_packages : [ polardb, pgsql-common ] # Replace PG kernel with PolarDB kernel
pg_exporter_exclude_database : 'template0,template1,postgres,polardb_admin'
pg_default_roles : # PolarDB require replicator as superuser
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,superuser: true ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator } # <- superuser is required for replication
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
vars : # global variables
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 15 # PolarDB is compatible with PG 15
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 polar 模板使用阿里云开源的 PolarDB for PostgreSQL 内核,提供云原生数据库能力。
关键特性 :
存算分离架构,计算节点和存储节点可独立扩展 支持一写多读,读副本秒级扩展 兼容 PostgreSQL 生态,保持 SQL 兼容性 支持共享存储场景,适合云环境部署 适用场景 :
需要存算分离架构的云原生场景 读多写少的业务负载 需要快速扩展读副本的场景 评估 PolarDB 特性的测试环境 注意事项 :
PolarDB 基于 PostgreSQL 15,不支持更高版本特性 复制用户需要超级用户权限(与原生 PostgreSQL 不同) 部分 PostgreSQL 扩展可能存在兼容性问题 不支持 ARM64 架构 9.12 - ivory IvorySQL 内核,提供 Oracle 语法与 PL/SQL 兼容能力
ivory 配置模板使用瀚高的 IvorySQL 数据库内核替代原生 PostgreSQL,提供 Oracle 语法与 PL/SQL 兼容能力。
完整教程请参考:IvorySQL (Oracle兼容) 内核使用说明
配置概览 配置名称: ivory 节点数量: 单节点 配置说明:使用 IvorySQL Oracle 兼容内核 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c ivory [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/ivory.yml
---
#==============================================================#
# File : ivory.yml
# Desc : IvorySQL 4 (Oracle Compatible) template
# Ctime : 2024-08-05
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/pgsql/kernel/ivorysql
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for IvorySQL 5 Kernel,
# Which is a PostgreSQL 18 fork with Oracle Compatibility
# tutorial: https://doc.pgsty.com/pgsql/kernel/ivorysql
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c ivory
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# IvorySQL Database Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas : [ pigsty]}
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
# IvorySQL Ad Hoc Settings
pg_mode : ivory # Use IvorySQL Oracle Compatible Mode
pg_packages : [ ivorysql, pgsql-common ] # install IvorySQL instead of postgresql kernel
pg_libs : 'liboracle_parser, pg_stat_statements, auto_explain' # pre-load oracle parser
vars : # global variables
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # IvorySQL kernel is compatible with postgres 18
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 ivory 模板使用瀚高开源的 IvorySQL 内核,提供 Oracle 数据库兼容能力。
关键特性 :
支持 Oracle PL/SQL 语法 兼容 Oracle 数据类型(NUMBER、VARCHAR2 等) 支持 Oracle 风格的包(Package) 保留 PostgreSQL 的所有标准功能 适用场景 :
从 Oracle 迁移到 PostgreSQL 需要同时支持 Oracle 和 PostgreSQL 语法的应用 希望利用 PostgreSQL 生态同时保持 PL/SQL 兼容性 评估 IvorySQL 特性的测试环境 注意事项 :
IvorySQL 4 基于 PostgreSQL 18 使用 liboracle_parser 需要加载到 shared_preload_libraries pgbackrest 在 Oracle 兼容模式下可能存在校验问题,PITR 能力受限仅支持 EL8/EL9 系统,不支持 Debian/Ubuntu 9.13 - mysql OpenHalo 内核,提供 MySQL 协议与语法兼容能力
mysql 配置模板使用 OpenHalo 数据库内核替代原生 PostgreSQL,提供 MySQL 线缆协议与 SQL 语法兼容能力。
配置概览 配置名称: mysql 节点数量: 单节点 配置说明:OpenHalo MySQL 兼容内核配置 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64 相关配置:meta 启用方式:
./configure -c mysql [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/mysql.yml
---
#==============================================================#
# File : mysql.yml
# Desc : 1-node OpenHaloDB (MySQL Compatible) template
# Ctime : 2025-04-03
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for OpenHalo PG Kernel,
# Which is a PostgreSQL 14 fork with MySQL Wire Compatibility
# tutorial: https://doc.pgsty.com/pgsql/kernel/openhalo
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c mysql
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# OpenHalo Database Cluster
#----------------------------------------------#
# connect with mysql client: mysql -h 10.10.10.10 -u dbuser_meta -D mysql (the actual database is 'postgres', and 'mysql' is a schema)
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- {name: postgres, extensions : [ aux_mysql]} # the mysql compatible database
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas : [ pigsty]}
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
# OpenHalo Ad Hoc Setting
pg_mode : mysql # MySQL Compatible Mode by HaloDB
pg_version : 14 # The current HaloDB is compatible with PG Major Version 14
pg_packages : [ openhalodb, pgsql-common ] # install openhalodb instead of postgresql kernel
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 14 # OpenHalo is compatible with PG 14
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 mysql 模板使用 OpenHalo 内核,让您可以使用 MySQL 客户端工具连接 PostgreSQL。
关键特性 :
使用 MySQL 协议(端口 3306),兼容 MySQL 客户端 支持 MySQL SQL 语法子集 保留 PostgreSQL 的 ACID 特性和存储引擎 同时支持 PostgreSQL 和 MySQL 两种协议连接 连接方式 :
# 使用 MySQL 客户端
mysql -h 10.10.10.10 -P 3306 -u dbuser_meta -pDBUser.Meta
# 同时保留 PostgreSQL 连接能力
psql postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta
适用场景 :
从 MySQL 迁移到 PostgreSQL 需要同时支持 MySQL 和 PostgreSQL 客户端的应用 希望利用 PostgreSQL 生态同时保持 MySQL 兼容性 注意事项 :
OpenHalo 基于 PostgreSQL 14,不支持更高版本特性 部分 MySQL 语法可能存在兼容性差异 仅支持 EL8/EL9 系统 不支持 ARM64 架构 9.14 - pgtde Percona PostgreSQL 内核,提供透明数据加密 (pg_tde) 能力
pgtde 配置模板使用 Percona PostgreSQL 数据库内核,提供透明数据加密 (Transparent Data Encryption, TDE) 能力。
配置概览 配置名称: pgtde 节点数量: 单节点 配置说明:Percona PostgreSQL 透明数据加密配置 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64 相关配置:meta 启用方式:
./configure -c pgtde [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/pgtde.yml
---
#==============================================================#
# File : pgtde.yml
# Desc : PG TDE with Percona PostgreSQL 1-node template
# Ctime : 2025-07-04
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for Percona PostgreSQL Distribution
# With pg_tde extension, which is compatible with PostgreSQL 18.1
# tutorial: https://doc.pgsty.com/pgsql/kernel/percona
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c pgtde
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# Percona Postgres Database Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
pg_databases :
- name : meta
baseline : cmdb.sql
comment : pigsty tde database
schemas : [ pigsty]
extensions : [ vector, postgis, pg_tde ,pgaudit, { name: pg_stat_monitor, schema: monitor } ]
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
# Percona PostgreSQL TDE Ad Hoc Settings
pg_packages : [ percona-main, pgsql-common ] # install percona postgres packages
pg_libs : 'pg_tde, pgaudit, pg_stat_statements, pg_stat_monitor, auto_explain'
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql,percona
node_tune : oltp
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # Default Percona TDE PG Major Version is 18
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 pgtde 模板使用 Percona PostgreSQL 内核,提供企业级透明数据加密能力。
关键特性 :
透明数据加密 :数据在磁盘上自动加密,对应用透明密钥管理 :支持本地密钥和外部密钥管理系统 (KMS)表级加密 :可选择性加密敏感表完整兼容 :与原生 PostgreSQL 完全兼容适用场景 :
需要满足数据安全合规要求(如 PCI-DSS、HIPAA) 存储敏感数据(如个人信息、金融数据) 需要静态数据加密的场景 对数据安全有严格要求的企业环境 使用方法 :
-- 创建加密表
CREATE TABLE sensitive_data (
id SERIAL PRIMARY KEY ,
ssn VARCHAR ( 11 )
) USING pg_tde ;
-- 或对现有表启用加密
ALTER TABLE existing_table SET ACCESS METHOD pg_tde ;
注意事项 :
Percona PostgreSQL 基于 PostgreSQL 18 加密会带来一定性能开销(通常 5-15%) 需要妥善管理加密密钥 不支持 ARM64 架构 9.15 - oriole OrioleDB 内核,提供无膨胀的 OLTP 增强存储引擎
oriole 配置模板使用 OrioleDB 存储引擎替代 PostgreSQL 默认的 Heap 存储,提供无膨胀、高性能的 OLTP 能力。
配置概览 配置名称: oriole 节点数量: 单节点 配置说明:OrioleDB 无膨胀存储引擎配置 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64 相关配置:meta 启用方式:
./configure -c oriole [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/oriole.yml
---
#==============================================================#
# File : oriole.yml
# Desc : 1-node OrioleDB (OLTP Enhancement) template
# Ctime : 2025-04-05
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# This is the config template for OrioleDB Kernel,
# Which is a Patched PostgreSQL 17 fork without bloat
# tutorial: https://doc.pgsty.com/pgsql/kernel/oriole
#
# Usage:
# curl https://repo.pigsty.io/get | bash
# ./configure -c oriole
# ./deploy.yml
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq: 1 }} ,vars : { repo_enabled : false }}
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 }} ,vars : { etcd_cluster : etcd }}
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 }} ,vars: { minio_cluster: minio }}
#----------------------------------------------#
# OrioleDB Database Cluster
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty], extensions : [ orioledb]}
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
# OrioleDB Ad Hoc Settings
pg_mode : oriole # oriole compatible mode
pg_packages : [ oriole, pgsql-common ] # install OrioleDB kernel
pg_libs : 'orioledb, pg_stat_statements, auto_explain' # Load OrioleDB Extension
vars : # global variables
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_repo_modules : node,infra,pgsql # add these repos directly to the singleton node
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 17 # OrioleDB Kernel is based on PG 17
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 oriole 模板使用 OrioleDB 存储引擎,从根本上解决 PostgreSQL 表膨胀问题。
关键特性 :
无膨胀设计 :使用 UNDO 日志而非多版本并发控制 (MVCC)无需 VACUUM :消除 autovacuum 带来的性能抖动行级 WAL :更高效的日志记录和复制压缩存储 :内置数据压缩,减少存储空间适用场景 :
高频更新的 OLTP 工作负载 对写入延迟敏感的应用 需要稳定响应时间(消除 VACUUM 影响) 大表频繁更新导致膨胀的场景 使用方法 :
-- 创建使用 OrioleDB 存储的表
CREATE TABLE orders (
id SERIAL PRIMARY KEY ,
customer_id INT ,
amount DECIMAL ( 10 , 2 )
) USING orioledb ;
-- 对现有表无法直接转换,需要重建
注意事项 :
OrioleDB 基于 PostgreSQL 17 需要将 orioledb 添加到 shared_preload_libraries 部分 PostgreSQL 特性可能不完全支持 不支持 ARM64 架构 9.16 - supabase 使用 Pigsty 托管的 PostgreSQL 自建 Supabase 开源 Firebase 替代方案
supabase 配置模板提供了自建 Supabase 的参考配置,使用 Pigsty 托管的 PostgreSQL 作为底层存储。
更多细节,请参考 Supabase 自建教程
配置概览 配置名称: supabase 节点数量: 单节点 配置说明:使用 Pigsty 托管的 PostgreSQL 自建 Supabase 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta ,rich 启用方式:
./configure -c supabase [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/supabase.yml
---
#==============================================================#
# File : supabase.yml
# Desc : Pigsty configuration for self-hosting supabase
# Ctime : 2023-09-19
# Mtime : 2025-12-28
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# supabase is available on el8/el9/u22/u24/d12 with pg15,16,17,18
# tutorial: https://doc.pgsty.com/app/supabase
# Usage:
# curl https://repo.pigsty.io/get | bash # install pigsty
# ./configure -c supabase # use this supabase conf template
# ./deploy.yml # install pigsty & pgsql & minio
# ./docker.yml # install docker & docker compose
# ./app.yml # launch supabase with docker compose
all :
children :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
vars :
repo_enabled : false # disable local repo
#----------------------------------------------#
# ETCD : https://doc.pgsty.com/etcd
#----------------------------------------------#
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
vars :
etcd_cluster : etcd
etcd_safeguard : false # enable to prevent purging running etcd instance
#----------------------------------------------#
# MINIO : https://doc.pgsty.com/minio
#----------------------------------------------#
minio :
hosts :
10.10.10.10 : { minio_seq : 1 }
vars :
minio_cluster : minio
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
#----------------------------------------------#
# PostgreSQL cluster for Supabase self-hosting
#----------------------------------------------#
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
# supabase roles: anon, authenticated, dashboard_user
- { name: anon ,login : false }
- { name: authenticated ,login : false }
- { name: dashboard_user ,login: false ,replication: true ,createdb: true ,createrole : true }
- { name: service_role ,login: false ,bypassrls : true }
# supabase users: please use the same password
- { name: supabase_admin ,password: 'DBUser.Supa' ,pgbouncer: true ,inherit: true ,roles: [ dbrole_admin ] ,superuser: true ,replication: true ,createdb: true ,createrole: true ,bypassrls : true }
- { name: authenticator ,password: 'DBUser.Supa' ,pgbouncer: true ,inherit: false ,roles : [ dbrole_admin, authenticated ,anon ,service_role ] }
- { name: supabase_auth_admin ,password: 'DBUser.Supa' ,pgbouncer: true ,inherit: false ,roles: [ dbrole_admin ] ,createrole : true }
- { name: supabase_storage_admin ,password: 'DBUser.Supa' ,pgbouncer: true ,inherit: false ,roles: [ dbrole_admin, authenticated ,anon ,service_role ] ,createrole : true }
- { name: supabase_functions_admin ,password: 'DBUser.Supa' ,pgbouncer: true ,inherit: false ,roles: [ dbrole_admin ] ,createrole : true }
- { name: supabase_replication_admin ,password: 'DBUser.Supa' ,replication: true ,roles : [ dbrole_admin ]}
- { name: supabase_etl_admin ,password: 'DBUser.Supa' ,replication: true ,roles : [ pg_read_all_data ]}
- { name: supabase_read_only_user ,password: 'DBUser.Supa' ,bypassrls: true ,roles : [ pg_read_all_data, dbrole_readonly ]}
pg_databases :
- name : postgres
baseline : supabase.sql
owner : supabase_admin
comment : supabase postgres database
schemas : [ extensions ,auth ,realtime ,storage ,graphql_public ,supabase_functions ,_analytics ,_realtime ]
extensions :
- { name: pgcrypto ,schema : extensions } # cryptographic functions
- { name: pg_net ,schema : extensions } # async HTTP
- { name: pgjwt ,schema : extensions } # json web token API for postgres
- { name: uuid-ossp ,schema : extensions } # generate universally unique identifiers (UUIDs)
- { name: pgsodium ,schema : extensions } # pgsodium is a modern cryptography library for Postgres.
- { name: supabase_vault ,schema : extensions } # Supabase Vault Extension
- { name: pg_graphql ,schema: extensions } # pg_graphql : GraphQL support
- { name: pg_jsonschema ,schema: extensions } # pg_jsonschema : Validate json schema
- { name: wrappers ,schema: extensions } # wrappers : FDW collections
- { name: http ,schema: extensions } # http : allows web page retrieval inside the database.
- { name: pg_cron ,schema: extensions } # pg_cron : Job scheduler for PostgreSQL
- { name: timescaledb ,schema: extensions } # timescaledb : Enables scalable inserts and complex queries for time-series data
- { name: pg_tle ,schema: extensions } # pg_tle : Trusted Language Extensions for PostgreSQL
- { name: vector ,schema: extensions } # pgvector : the vector similarity search
- { name: pgmq ,schema: extensions } # pgmq : A lightweight message queue like AWS SQS and RSMQ
- { name: supabase ,owner: supabase_admin ,comment: supabase analytics database ,schemas : [ extensions, _analytics ] }
# supabase required extensions
pg_libs : 'timescaledb, pgsodium, plpgsql, plpgsql_check, pg_cron, pg_net, pg_stat_statements, auto_explain, pg_wait_sampling, pg_tle, plan_filter'
pg_extensions : [ pg18-main ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_parameters : { cron.database_name : postgres }
pg_hba_rules : # supabase hba rules, require access from docker network
- { user: all ,db: postgres ,addr: intra ,auth: pwd ,title : 'allow supabase access from intranet' }
- { user: all ,db: postgres ,addr: 172.17.0.0/16 ,auth: pwd ,title : 'allow access from local docker network' }
node_crontab :
- '00 01 * * * postgres /pg/bin/pg-backup full' # make a full backup every 1am
- '* * * * * postgres /pg/bin/supa-kick' # kick supabase _analytics lag per minute : https://github.com/pgsty/pigsty/issues/581
#----------------------------------------------#
# Supabase
#----------------------------------------------#
# ./docker.yml
# ./app.yml
# the supabase stateless containers (default username & password: supabase/pigsty)
supabase :
hosts :
10.10.10.10 : {}
vars :
docker_enabled : true # enable docker on this group
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
app : supabase # specify app name (supa) to be installed (in the apps)
apps : # define all applications
supabase : # the definition of supabase app
conf : # override /opt/supabase/.env
# IMPORTANT: CHANGE JWT_SECRET AND REGENERATE CREDENTIAL ACCORDING!!!!!!!!!!!
# https://supabase.com/docs/guides/self-hosting/docker#securing-your-services
JWT_SECRET : your-super-secret-jwt-token-with-at-least-32-characters-long
ANON_KEY : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE
SERVICE_ROLE_KEY : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q
PG_META_CRYPTO_KEY : your-encryption-key-32-chars-min
DASHBOARD_USERNAME : supabase
DASHBOARD_PASSWORD : pigsty
# 32~64 random characters string for logflare
LOGFLARE_PUBLIC_ACCESS_TOKEN : 1234567890abcdef1234567890abcdef
LOGFLARE_PRIVATE_ACCESS_TOKEN : fedcba0987654321fedcba0987654321
# postgres connection string (use the correct ip and port)
POSTGRES_HOST : 10.10.10.10 # point to the local postgres node
POSTGRES_PORT : 5436 # access via the 'default' service, which always route to the primary postgres
POSTGRES_DB : postgres # the supabase underlying database
POSTGRES_PASSWORD : DBUser.Supa # password for supabase_admin and multiple supabase users
# expose supabase via domain name
SITE_URL : https://supa.pigsty # <------- Change This to your external domain name
API_EXTERNAL_URL : https://supa.pigsty # <------- Otherwise the storage api may not work!
SUPABASE_PUBLIC_URL : https://supa.pigsty # <------- DO NOT FORGET TO PUT IT IN infra_portal!
# if using s3/minio as file storage
S3_BUCKET : data
S3_ENDPOINT : https://sss.pigsty:9000
S3_ACCESS_KEY : s3user_data
S3_SECRET_KEY : S3User.Data
S3_FORCE_PATH_STYLE : true
S3_PROTOCOL : https
S3_REGION : stub
MINIO_DOMAIN_IP : 10.10.10.10 # sss.pigsty domain name will resolve to this ip statically
# if using SMTP (optional)
#SMTP_ADMIN_EMAIL: admin@example.com
#SMTP_HOST: supabase-mail
#SMTP_PORT: 2500
#SMTP_USER: fake_mail_user
#SMTP_PASS: fake_mail_password
#SMTP_SENDER_NAME: fake_sender
#ENABLE_ANONYMOUS_USERS: false
#==============================================================#
# Global Parameters
#==============================================================#
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
certbot_sign : false # enable certbot to sign https certificate for infra portal
certbot_email : your@email.com # replace your email address to receive expiration notice
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
pgadmin : { domain: adm.pigsty ,endpoint : "${admin_ip}:8885" }
bytebase : { domain: ddl.pigsty ,endpoint : "${admin_ip}:8887" }
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
# Nginx / Domain / HTTPS : https://doc.pgsty.com/admin/portal
supa : # nginx server config for supabase
domain : supa.pigsty # REPLACE IT WITH YOUR OWN DOMAIN!
endpoint : "10.10.10.10:8000" # supabase service endpoint: IP:PORT
websocket : true # add websocket support
certbot : supa.pigsty # certbot cert name, apply with `make cert`
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
nodename_overwrite : false # do not overwrite node hostname on single node mode
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
node_etc_hosts : # add static domains to all nodes /etc/hosts
- 10.10.10.10 i.pigsty sss.pigsty supa.pigsty
node_repo_modules : node,pgsql,infra # use pre-made local repo rather than install from upstream
node_repo_remove : true # remove existing node repo for node managed by pigsty
#node_packages: [openssh-server] # packages to be installed current nodes with latest version
#node_timezone: Asia/Hong_Kong # overwrite node timezone
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # default postgres version
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_safeguard : false # prevent purging running postgres instance?
pg_default_schemas: [ monitor, extensions ] # add new schema : exxtensions
pg_default_extensions : # default extensions to be created
- { name: pg_stat_statements ,schema : monitor }
- { name: pgstattuple ,schema : monitor }
- { name: pg_buffercache ,schema : monitor }
- { name: pageinspect ,schema : monitor }
- { name: pg_prewarm ,schema : monitor }
- { name: pg_visibility ,schema : monitor }
- { name: pg_freespacemap ,schema : monitor }
- { name: pg_wait_sampling ,schema : monitor }
# move default extensions to `extensions` schema for supabase
- { name: postgres_fdw ,schema : extensions }
- { name: file_fdw ,schema : extensions }
- { name: btree_gist ,schema : extensions }
- { name: btree_gin ,schema : extensions }
- { name: pg_trgm ,schema : extensions }
- { name: intagg ,schema : extensions }
- { name: intarray ,schema : extensions }
- { name: pg_repack ,schema : extensions }
#----------------------------------------------#
# BACKUP : https://doc.pgsty.com/pgsql/backup
#----------------------------------------------#
minio_endpoint : https://sss.pigsty:9000 # explicit overwrite minio endpoint with haproxy port
pgbackrest_method: minio # pgbackrest repo method : local,minio,[user-defined...]
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backups when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest <------------------ HEY, DID YOU CHANGE THIS?
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest' <----- HEY, DID YOU CHANGE THIS?
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the last 14 days
s3 : # you can use cloud object storage as backup repo
type : s3 # Add your object storage credentials here!
s3_endpoint : oss-cn-beijing-internal.aliyuncs.com
s3_region : oss-cn-beijing
s3_bucket : <your_bucket_name>
s3_key : <your_access_key>
s3_key_secret : <your_secret_key>
s3_uri_style : host
path : /pgbackrest
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the last 14 days
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 supabase 模板提供了完整的 Supabase 自建方案,让您可以在自己的基础设施上运行这个开源 Firebase 替代品。
架构组成 :
PostgreSQL :Pigsty 托管的生产级 PostgreSQL(支持高可用)Docker 容器 :Supabase 无状态服务(Auth、Storage、Realtime、Edge Functions 等)MinIO :S3 兼容的对象存储,用于文件存储和 PostgreSQL 备份Nginx :反向代理和 HTTPS 终止关键特性 :
使用 Pigsty 管理的 PostgreSQL 替代 Supabase 自带的数据库容器 支持 PostgreSQL 高可用(可扩展为三节点集群) 安装全部 Supabase 所需扩展(pg_net、pgjwt、pg_graphql、vector 等) 集成 MinIO 对象存储用于文件上传和备份 支持 HTTPS 和 Let’s Encrypt 自动证书 部署步骤 :
curl https://repo.pigsty.io/get | bash # 下载 Pigsty
./configure -c supabase # 使用 supabase 配置模板
./install.yml # 安装 Pigsty、PostgreSQL、MinIO
./docker.yml # 安装 Docker
./app.yml # 启动 Supabase 容器
访问方式 :
# Supabase Studio
https://supa.pigsty ( 用户名: supabase, 密码: pigsty)
# 直接连接 PostgreSQL
psql postgres://supabase_admin:DBUser.Supa@10.10.10.10:5432/postgres
适用场景 :
需要自建 BaaS (Backend as a Service) 平台 希望完全掌控数据和基础设施 需要企业级 PostgreSQL 高可用和备份 对 Supabase 云服务有合规或成本考虑 注意事项 :
必须修改 JWT_SECRET :使用至少 32 字符的随机字符串,并重新生成 ANON_KEY 和 SERVICE_ROLE_KEY需要配置正确的域名(SITE_URL、API_EXTERNAL_URL) 生产环境建议启用 HTTPS(可使用 certbot 自动签发证书) Docker 网络需要能访问 PostgreSQL(已配置 172.17.0.0/16 HBA 规则)
9.17 - 高可用模板 9.18 - ha/simu 20 节点生产环境仿真配置,用于大规模部署测试
ha/simu 配置模板是一个 20 节点的生产环境仿真配置,需要强大的宿主机方可运行。
配置概览 配置名称: ha/simu 节点数量: 20 节点,pigsty/vagrant/spec/simu.rb 配置说明:20 节点的生产环境仿真配置,需要强大的宿主机方可运行。 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 启用方式:
./configure -c ha/simu [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/ha/simu.yml
---
#==============================================================#
# File : simu.yml
# Desc : Pigsty Simubox: a 20 node prod simulation env
# Ctime : 2023-07-20
# Mtime : 2025-12-23
# Docs : https://doc.pgsty.com/config
# License : AGPLv3 @ https://doc.pgsty.com/about/license
# Copyright : 2018-2025 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
all :
children :
#==========================================================#
# infra: 3 nodes
#==========================================================#
# ./infra.yml -l infra
# ./docker.yml -l infra (optional)
infra :
hosts :
10.10.10.10 : {}
10.10.10.11 : { repo_enabled : false }
10.10.10.12 : { repo_enabled : false }
vars :
docker_enabled : true
node_conf : oltp # use oltp template for infra nodes
pg_conf : oltp.yml # use oltp template for infra pgsql
pg_exporters : # bin/pgmon-add pg-meta2/pg-src2/pg-dst2
20001 : {pg_cluster: pg-meta2 ,pg_seq: 1 ,pg_host: 10.10.10.10, pg_databases : [ { name : meta }]}
20002 : {pg_cluster: pg-meta2 ,pg_seq: 2 ,pg_host: 10.10.10.11, pg_databases : [ { name : meta }]}
20003 : {pg_cluster: pg-meta2 ,pg_seq: 3 ,pg_host: 10.10.10.12, pg_databases : [ { name : meta }]}
20004 : {pg_cluster: pg-src2 ,pg_seq: 1 ,pg_host: 10.10.10.31, pg_databases : [ { name : src }]}
20005 : {pg_cluster: pg-src2 ,pg_seq: 2 ,pg_host: 10.10.10.32, pg_databases : [ { name : src }]}
20006 : {pg_cluster: pg-src2 ,pg_seq: 3 ,pg_host: 10.10.10.33, pg_databases : [ { name : src }]}
20007 : {pg_cluster: pg-dst2 ,pg_seq: 1 ,pg_host: 10.10.10.41, pg_databases : [ { name : dst }]}
20008 : {pg_cluster: pg-dst2 ,pg_seq: 2 ,pg_host: 10.10.10.42, pg_databases : [ { name : dst }]}
20009 : {pg_cluster: pg-dst2 ,pg_seq: 3 ,pg_host: 10.10.10.43, pg_databases : [ { name : dst }]}
#==========================================================#
# nodes: 23 nodes
#==========================================================#
# ./node.yml
nodes :
hosts :
10.10.10.10 : { nodename: meta1 ,node_cluster: meta ,pg_cluster: pg-meta ,pg_seq: 1 ,pg_role: primary, infra_seq : 1 }
10.10.10.11 : { nodename: meta2 ,node_cluster: meta ,pg_cluster: pg-meta ,pg_seq: 2 ,pg_role: replica, infra_seq : 2 }
10.10.10.12 : { nodename: meta3 ,node_cluster: meta ,pg_cluster: pg-meta ,pg_seq: 3 ,pg_role: replica, infra_seq : 3 }
10.10.10.18 : { nodename: proxy1 ,node_cluster: proxy ,vip_address: 10.10.10.20 ,vip_vrid: 20 ,vip_interface: eth1 ,vip_role : master }
10.10.10.19 : { nodename: proxy2 ,node_cluster: proxy ,vip_address: 10.10.10.20 ,vip_vrid: 20 ,vip_interface: eth1 ,vip_role : backup }
10.10.10.21 : { nodename: minio1 ,node_cluster: minio ,minio_cluster: minio ,minio_seq : 1 }
10.10.10.22 : { nodename: minio2 ,node_cluster: minio ,minio_cluster: minio ,minio_seq : 2 }
10.10.10.23 : { nodename: minio3 ,node_cluster: minio ,minio_cluster: minio ,minio_seq : 3 }
10.10.10.24 : { nodename: minio4 ,node_cluster: minio ,minio_cluster: minio ,minio_seq : 4 }
10.10.10.25 : { nodename: etcd1 ,node_cluster: etcd ,etcd_cluster: etcd ,etcd_seq : 1 }
10.10.10.26 : { nodename: etcd2 ,node_cluster: etcd ,etcd_cluster: etcd ,etcd_seq : 2 }
10.10.10.27 : { nodename: etcd3 ,node_cluster: etcd ,etcd_cluster: etcd ,etcd_seq : 3 }
10.10.10.28 : { nodename: etcd4 ,node_cluster: etcd ,etcd_cluster: etcd ,etcd_seq : 4 }
10.10.10.29 : { nodename: etcd5 ,node_cluster: etcd ,etcd_cluster: etcd ,etcd_seq : 5 }
10.10.10.31 : { nodename: pg-src-1 ,node_cluster: pg-src ,node_id_from_pg : true }
10.10.10.32 : { nodename: pg-src-2 ,node_cluster: pg-src ,node_id_from_pg : true }
10.10.10.33 : { nodename: pg-src-3 ,node_cluster: pg-src ,node_id_from_pg : true }
10.10.10.41 : { nodename: pg-dst-1 ,node_cluster: pg-dst ,node_id_from_pg : true }
10.10.10.42 : { nodename: pg-dst-2 ,node_cluster: pg-dst ,node_id_from_pg : true }
10.10.10.43 : { nodename: pg-dst-3 ,node_cluster: pg-dst ,node_id_from_pg : true }
#==========================================================#
# etcd: 5 nodes dedicated etcd cluster
#==========================================================#
# ./etcd.yml -l etcd;
etcd :
hosts :
10.10.10.25 : {}
10.10.10.26 : {}
10.10.10.27 : {}
10.10.10.28 : {}
10.10.10.29 : {}
vars : {}
#==========================================================#
# minio: 4 nodes dedicated minio cluster
#==========================================================#
# ./minio.yml -l minio;
minio :
hosts :
10.10.10.21 : {}
10.10.10.22 : {}
10.10.10.23 : {}
10.10.10.24 : {}
vars :
minio_data : '/data{1...4}' # 4 node x 4 disk
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
#==========================================================#
# proxy: 2 nodes used as dedicated haproxy server
#==========================================================#
# ./node.yml -l proxy
proxy :
hosts :
10.10.10.18 : {}
10.10.10.19 : {}
vars :
vip_enabled : true
haproxy_services: # expose minio service : sss.pigsty:9000
- name : minio # [REQUIRED] service name, unique
port : 9000 # [REQUIRED] service port, unique
balance : leastconn # Use leastconn algorithm and minio health check
options : [ "option httpchk" , "option http-keep-alive" , "http-check send meth OPTIONS uri /minio/health/live" , "http-check expect status 200" ]
servers : # reload service with ./node.yml -t haproxy_config,haproxy_reload
- { name: minio-1 ,ip: 10.10.10.21 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-2 ,ip: 10.10.10.22 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-3 ,ip: 10.10.10.23 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-4 ,ip: 10.10.10.24 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
#==========================================================#
# pg-meta: reuse infra node as meta cmdb
#==========================================================#
# ./pgsql.yml -l pg-meta
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1 , pg_role : primary }
10.10.10.11 : { pg_seq: 2 , pg_role : replica }
10.10.10.12 : { pg_seq: 3 , pg_role : replica }
vars :
pg_cluster : pg-meta
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
- {name: dbuser_grafana ,password: DBUser.Grafana ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for grafana database }
- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for bytebase database }
- {name: dbuser_kong ,password: DBUser.Kong ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for kong api gateway }
- {name: dbuser_gitea ,password: DBUser.Gitea ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for gitea service }
- {name: dbuser_wiki ,password: DBUser.Wiki ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for wiki.js service }
- {name: dbuser_noco ,password: DBUser.Noco ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for nocodb service }
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name : vector}]}
- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment : grafana primary database }
- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment : bytebase primary database }
- { name: kong ,owner: dbuser_kong ,revokeconn: true ,comment : kong the api gateway database }
- { name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment : gitea meta database }
- { name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment : wiki meta database }
- { name: noco ,owner: dbuser_noco ,revokeconn: true ,comment : nocodb database }
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
pg_libs : 'pg_stat_statements, auto_explain' # add timescaledb to shared_preload_libraries
node_crontab : # make a full backup on monday 1am, and an incremental backup during weekdays
- '00 01 * * 1 postgres /pg/bin/pg-backup full'
- '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
#==========================================================#
# pg-src: dedicate 3 node source cluster
#==========================================================#
# ./pgsql.yml -l pg-src
pg-src :
hosts :
10.10.10.31 : { pg_seq: 1 ,pg_role : primary }
10.10.10.32 : { pg_seq: 2 ,pg_role : replica }
10.10.10.33 : { pg_seq: 3 ,pg_role : replica }
vars :
pg_cluster : pg-src
pg_vip_enabled : true
pg_vip_address : 10.10.10.3 /24
pg_vip_interface : eth1
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] }]
pg_databases : [ { name : src }]
#==========================================================#
# pg-dst: dedicate 3 node destination cluster
#==========================================================#
# ./pgsql.yml -l pg-dst
pg-dst :
hosts :
10.10.10.41 : { pg_seq: 1 ,pg_role : primary }
10.10.10.42 : { pg_seq: 2 ,pg_role : replica }
10.10.10.43 : { pg_seq: 3 ,pg_role : replica }
vars :
pg_cluster : pg-dst
pg_vip_enabled : true
pg_vip_address : 10.10.10.4 /24
pg_vip_interface : eth1
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] } ]
pg_databases : [ { name : dst } ]
#==========================================================#
# redis-meta: reuse the 5 etcd nodes as redis sentinel
#==========================================================#
# ./redis.yml -l redis-meta
redis-meta :
hosts :
10.10.10.25 : { redis_node: 1 , redis_instances : { 26379 : {} } }
10.10.10.26 : { redis_node: 2 , redis_instances : { 26379 : {} } }
10.10.10.27 : { redis_node: 3 , redis_instances : { 26379 : {} } }
10.10.10.28 : { redis_node: 4 , redis_instances : { 26379 : {} } }
10.10.10.29 : { redis_node: 5 , redis_instances : { 26379 : {} } }
vars :
redis_cluster : redis-meta
redis_password : 'redis.meta'
redis_mode : sentinel
redis_max_memory : 256MB
redis_sentinel_monitor : # primary list for redis sentinel, use cls as name, primary ip:port
- { name: redis-src, host: 10.10.10.31, port: 6379 ,password: redis.src, quorum : 1 }
- { name: redis-dst, host: 10.10.10.41, port: 6379 ,password: redis.dst, quorum : 1 }
#==========================================================#
# redis-src: reuse pg-src 3 nodes for redis
#==========================================================#
# ./redis.yml -l redis-src
redis-src :
hosts :
10.10.10.31 : { redis_node: 1 , redis_instances : {6379 : { } }}
10.10.10.32 : { redis_node: 2 , redis_instances : {6379 : { replica_of: '10.10.10.31 6379' }, 6380 : { replica_of : '10.10.10.32 6379' } }}
10.10.10.33 : { redis_node: 3 , redis_instances : {6379 : { replica_of: '10.10.10.31 6379' }, 6380 : { replica_of : '10.10.10.33 6379' } }}
vars :
redis_cluster : redis-src
redis_password : 'redis.src'
redis_max_memory : 64MB
#==========================================================#
# redis-dst: reuse pg-dst 3 nodes for redis
#==========================================================#
# ./redis.yml -l redis-dst
redis-dst :
hosts :
10.10.10.41 : { redis_node: 1 , redis_instances : {6379 : { } }}
10.10.10.42 : { redis_node: 2 , redis_instances : {6379 : { replica_of : '10.10.10.41 6379' } }}
10.10.10.43 : { redis_node: 3 , redis_instances : {6379 : { replica_of : '10.10.10.41 6379' } }}
vars :
redis_cluster : redis-dst
redis_password : 'redis.dst'
redis_max_memory : 64MB
#==========================================================#
# pg-tmp: reuse proxy nodes as pgsql cluster
#==========================================================#
# ./pgsql.yml -l pg-tmp
pg-tmp :
hosts :
10.10.10.18 : { pg_seq: 1 ,pg_role : primary }
10.10.10.19 : { pg_seq: 2 ,pg_role : replica }
vars :
pg_cluster : pg-tmp
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] } ]
pg_databases : [ { name : tmp } ]
#==========================================================#
# pg-etcd: reuse etcd nodes as pgsql cluster
#==========================================================#
# ./pgsql.yml -l pg-etcd
pg-etcd :
hosts :
10.10.10.25 : { pg_seq: 1 ,pg_role : primary }
10.10.10.26 : { pg_seq: 2 ,pg_role : replica }
10.10.10.27 : { pg_seq: 3 ,pg_role : replica }
10.10.10.28 : { pg_seq: 4 ,pg_role : replica }
10.10.10.29 : { pg_seq: 5 ,pg_role : offline }
vars :
pg_cluster : pg-etcd
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] } ]
pg_databases : [ { name : etcd } ]
#==========================================================#
# pg-minio: reuse minio nodes as pgsql cluster
#==========================================================#
# ./pgsql.yml -l pg-minio
pg-minio :
hosts :
10.10.10.21 : { pg_seq: 1 ,pg_role : primary }
10.10.10.22 : { pg_seq: 2 ,pg_role : replica }
10.10.10.23 : { pg_seq: 3 ,pg_role : replica }
10.10.10.24 : { pg_seq: 4 ,pg_role : replica }
vars :
pg_cluster : pg-minio
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] } ]
pg_databases : [ { name : minio } ]
#==========================================================#
# ferret: reuse pg-src as mongo (ferretdb)
#==========================================================#
# ./mongo.yml -l ferret
ferret :
hosts :
10.10.10.31 : { mongo_seq : 1 }
10.10.10.32 : { mongo_seq : 2 }
10.10.10.33 : { mongo_seq : 3 }
vars :
mongo_cluster : ferret
mongo_pgurl : 'postgres://test:test@10.10.10.31:5432/src'
#============================================================#
# Global Variables
#============================================================#
vars :
#==========================================================#
# INFRA
#==========================================================#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: china # upstream mirror region : default|china|europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
minio : { domain: m.pigsty ,endpoint : "10.10.10.21:9001" ,scheme: https ,websocket : true }
postgrest : { domain: api.pigsty ,endpoint : "127.0.0.1:8884" }
pgadmin : { domain: adm.pigsty ,endpoint : "127.0.0.1:8885" }
pgweb : { domain: cli.pigsty ,endpoint : "127.0.0.1:8886" }
bytebase : { domain: ddl.pigsty ,endpoint : "127.0.0.1:8887" }
jupyter : { domain: lab.pigsty ,endpoint : "127.0.0.1:8888" , websocket : true }
supa : { domain: supa.pigsty ,endpoint : "10.10.10.10:8000" , websocket : true }
#==========================================================#
# NODE
#==========================================================#
node_id_from_pg : false # use nodename rather than pg identity as hostname
node_conf : tiny # use small node template
node_timezone : Asia/Hong_Kong # use Asia/Hong_Kong Timezone
node_dns_servers : # DNS servers in /etc/resolv.conf
- 10.10.10.10
- 10.10.10.11
node_etc_hosts :
- 10.10.10.10 i.pigsty
- 10.10.10.20 sss.pigsty # point minio service domain to the L2 VIP of proxy cluster
node_ntp_servers : # NTP servers in /etc/chrony.conf
- pool cn.pool.ntp.org iburst
- pool 10.10.10.10 iburst
node_admin_ssh_exchange : false # exchange admin ssh key among node cluster
#==========================================================#
# PGSQL
#==========================================================#
pg_conf : tiny.yml
pgbackrest_method : minio # USE THE HA MINIO THROUGH A LOAD BALANCER
pg_dbsu_ssh_exchange : false # do not exchange dbsu ssh key among pgsql cluster
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backup when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `//pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for last 14 days
#==========================================================#
# Repo
#==========================================================#
repo_packages : [
node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules,
pg18-core ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl
]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 ha/simu 模板是一个 大规模生产环境仿真配置 ,用于测试和验证复杂场景。
架构组成 :
2 节点高可用 INFRA(监控/告警/Nginx/DNS) 5 节点高可用 ETCD 和 MinIO(多磁盘) 2 节点 Proxy(HAProxy + Keepalived VIP) 多套 PostgreSQL 集群:pg-meta:2 节点高可用 pg-v12~v17:单节点多版本测试 pg-pitr:单节点 PITR 测试 pg-test:4 节点高可用 pg-src/pg-dst:3+2 节点复制测试 pg-citus:10 节点分布式集群 多种 Redis 模式:主从、哨兵、集群 适用场景 :
大规模部署测试与验证 高可用故障演练 性能基准测试 新功能预览与评估 注意事项 :
需要强大的宿主机(推荐 64GB+ 内存) 使用 Vagrant 虚拟机模拟 9.19 - ha/full 四节点完整功能演示环境,带有两套 PostgreSQL 集群、MinIO、Redis 等组件示例
ha/full 配置模板是 Pigsty 推荐的沙箱演示环境,使用四个节点部署两套 PostgreSQL 集群,用于测试和演示 Pigsty 各方面的能力。
Pigsty 大部分教程和示例都基于此模板的沙箱环境。
配置概览 配置名称: ha/full 节点数量: 四节点 配置说明:四节点完整功能演示环境,带有两套 PostgreSQL 集群、MinIO、Redis 等组件示例 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:ha/trio ,ha/safe ,demo/demo 启用方式:
./configure -c ha/full [ -i <primary_ip>]
配置生成后,需要修改其他三个节点的 IP 地址。
配置内容 源文件地址:pigsty/conf/ha/full.yml
---
#==============================================================#
# File : full.yml
# Desc : Pigsty Local Sandbox 4-node Demo Config
# Ctime : 2020-05-22
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
all :
#==============================================================#
# Clusters, Nodes, and Modules
#==============================================================#
children :
# infra: monitor, alert, repo, etc..
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
vars :
docker_enabled : true # enabled docker with ./docker.yml
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
# etcd cluster for HA postgres DCS
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
vars :
etcd_cluster : etcd
# minio (single node, used as backup repo)
minio :
hosts :
10.10.10.10 : { minio_seq : 1 }
vars :
minio_cluster : minio
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
# postgres cluster: pg-meta
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [ dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [ dbrole_readonly ] ,comment : read-only viewer for meta database }
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas : [ pigsty ] }
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
node_crontab : # make a full backup 1 am everyday
- '00 01 * * * postgres /pg/bin/pg-backup full'
# pgsql 3 node ha cluster: pg-test
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary } # primary instance, leader of cluster
10.10.10.12 : { pg_seq: 2, pg_role : replica } # replica instance, follower of leader
10.10.10.13 : { pg_seq: 3, pg_role: replica, pg_offline_query : true } # replica with offline access
vars :
pg_cluster : pg-test # define pgsql cluster name
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] }]
pg_databases : [ { name : test }]
pg_vip_enabled : true
pg_vip_address : 10.10.10.3 /24
pg_vip_interface : eth1
node_crontab : # make a full backup on monday 1am, and an incremental backup during weekdays
- '00 01 * * 1 postgres /pg/bin/pg-backup full'
- '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
#----------------------------------#
# redis ms, sentinel, native cluster
#----------------------------------#
redis-ms : # redis classic primary & replica
hosts : { 10.10.10.10 : { redis_node: 1 , redis_instances : { 6379 : { }, 6380 : { replica_of : '10.10.10.10 6379' } } } }
vars : { redis_cluster: redis-ms ,redis_password: 'redis.ms' ,redis_max_memory : 64MB }
redis-meta : # redis sentinel x 3
hosts : { 10.10.10.11 : { redis_node: 1 , redis_instances : { 26379 : { } ,26380 : { } ,26381 : { } } } }
vars :
redis_cluster : redis-meta
redis_password : 'redis.meta'
redis_mode : sentinel
redis_max_memory : 16MB
redis_sentinel_monitor : # primary list for redis sentinel, use cls as name, primary ip:port
- { name: redis-ms, host: 10.10.10.10, port: 6379 ,password: redis.ms, quorum : 2 }
redis-test: # redis native cluster : 3m x 3s
hosts :
10.10.10.12 : { redis_node: 1 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
10.10.10.13 : { redis_node: 2 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
vars : { redis_cluster: redis-test ,redis_password: 'redis.test' ,redis_mode: cluster, redis_max_memory : 32MB }
#==============================================================#
# Global Parameters
#==============================================================#
vars :
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
#----------------------------------#
# MinIO Related Options
#----------------------------------#
node_etc_hosts : [ '${admin_ip} i.pigsty sss.pigsty' ]
pgbackrest_method : minio # if you want to use minio as backup repo instead of 'local' fs, uncomment this
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backup when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for last 14 days
#----------------------------------#
# Repo, Node, Packages
#----------------------------------#
repo_remove : true # remove existing repo on admin node during repo bootstrap
node_repo_remove : true # remove existing node repo for node managed by pigsty
repo_extra_packages : [ pg18-main ] #,pg18-core ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_version : 18 # default postgres version
#pg_extensions: [pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl ,pg18-olap]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 ha/full 模板是 Pigsty 的 完整功能演示配置 ,展示了多种组件的协同工作。
组件概览 :
组件 节点分布 说明 INFRA 节点1 监控/告警/Nginx/DNS ETCD 节点1 DCS 服务 MinIO 节点1 S3 兼容存储 pg-meta 节点1 单节点 PostgreSQL pg-test 节点2-4 三节点高可用 PostgreSQL redis-ms 节点1 Redis 主从模式 redis-meta 节点2 Redis 哨兵模式 redis-test 节点3-4 Redis 原生集群模式
适用场景 :
Pigsty 功能演示与学习 开发测试环境 评估高可用架构 Redis 不同模式对比测试 与 ha/trio 的区别 :
增加了第二套 PostgreSQL 集群(pg-test) 增加了三种模式的 Redis 集群示例 基础设施使用单节点(而非三节点) 注意事项 :
9.20 - ha/safe 安全加固的高可用配置模板,采用高标准的安全最佳实践
ha/safe 配置模板基于 ha/trio 模板修改,是一个安全加固的专用配置模板,采用高标准的安全最佳实践。
配置概览 配置名称: ha/safe 节点数量: 三节点(可选添加延迟副本) 配置说明:安全加固的高可用配置模板,采用高标准的安全最佳实践 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64(部分安全扩展在 ARM64 不可用) 相关配置:ha/trio ,ha/full 启用方式:
./configure -c ha/safe [ -i <primary_ip>]
安全加固措施 ha/safe 模板实现了以下安全加固:
强制 SSL 加密 :PostgreSQL 和 PgBouncer 均启用 SSL强密码策略 :使用 passwordcheck 扩展强制密码复杂度用户过期时间 :所有用户设置 20 年过期时间最小化连接范围 :限制 PostgreSQL/Patroni/PgBouncer 监听地址严格 HBA 规则 :强制 SSL 认证,管理员需证书认证审计日志 :记录连接和断开事件延迟副本 :可选的 1 小时延迟副本,用于误操作恢复关键模板 :使用 crit.yml 调优模板,零数据丢失配置内容 源文件地址:pigsty/conf/ha/safe.yml
---
#==============================================================#
# File : safe.yml
# Desc : Pigsty 3-node security enhance template
# Ctime : 2020-05-22
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
#===== SECURITY ENHANCEMENT CONFIG TEMPLATE WITH 3 NODES ======#
# * 3 infra nodes, 3 etcd nodes, single minio node
# * 3-instance pgsql cluster with an extra delayed instance
# * crit.yml templates, no data loss, checksum enforced
# * enforce ssl on postgres & pgbouncer, use postgres by default
# * enforce an expiration date for all users (20 years by default)
# * enforce strong password policy with passwordcheck extension
# * enforce changing default password for all users
# * log connections and disconnections
# * restrict listen ip address for postgres/patroni/pgbouncer
all :
children :
infra : # infra cluster for proxy, monitor, alert, etc
hosts : # 1 for common usage, 3 nodes for production
10.10.10.10 : { infra_seq : 1 } # identity required
10.10.10.11 : { infra_seq: 2, repo_enabled : false }
10.10.10.12 : { infra_seq: 3, repo_enabled : false }
vars : { patroni_watchdog_mode : off }
minio : # minio cluster, s3 compatible object storage
hosts : { 10.10.10.10 : { minio_seq : 1 } }
vars : { minio_cluster : minio }
etcd : # dcs service for postgres/patroni ha consensus
hosts : # 1 node for testing, 3 or 5 for production
10.10.10.10 : { etcd_seq : 1 } # etcd_seq required
10.10.10.11 : { etcd_seq : 2 } # assign from 1 ~ n
10.10.10.12 : { etcd_seq : 3 } # odd number please
vars : # cluster level parameter override roles/etcd
etcd_cluster : etcd # mark etcd cluster name etcd
etcd_safeguard : false # safeguard against purging
etcd_clean : true # purge etcd during init process
pg-meta : # 3 instance postgres cluster `pg-meta`
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
10.10.10.11 : { pg_seq: 2, pg_role : replica }
10.10.10.12 : { pg_seq: 3, pg_role: replica , pg_offline_query : true }
vars :
pg_cluster : pg-meta
pg_conf : crit.yml
pg_users :
- { name: dbuser_meta , password: Pleas3-ChangeThisPwd ,expire_in: 7300 ,pgbouncer: true ,roles: [ dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view , password: Make.3ure-Compl1ance ,expire_in: 7300 ,pgbouncer: true ,roles: [ dbrole_readonly ] ,comment : read-only viewer for meta database }
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [ pigsty ] ,extensions : [ { name : vector } ] }
pg_services :
- { name: standby , ip : "*" ,port: 5435 , dest: default ,selector : "[]" , backup : "[? pg_role == `primary`]" }
pg_listen : '${ip},${vip},${lo}'
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
# OPTIONAL delayed cluster for pg-meta
#pg-meta-delay: # delayed instance for pg-meta (1 hour ago)
# hosts: { 10.10.10.13: { pg_seq: 1, pg_role: primary, pg_upstream: 10.10.10.10, pg_delay: 1h } }
# vars: { pg_cluster: pg-meta-delay }
####################################################################
# Parameters #
####################################################################
vars : # global variables
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
patroni_ssl_enabled : true # secure patroni RestAPI communications with SSL?
pgbouncer_sslmode: require # pgbouncer client ssl mode : disable|allow|prefer|require|verify-ca|verify-full, disable by default
pg_default_service_dest : postgres # default service destination to postgres instead of pgbouncer
pgbackrest_method: minio # pgbackrest repo method : local,minio,[user-defined...]
#----------------------------------#
# MinIO Related Options
#----------------------------------#
minio_users : # and configure `pgbackrest_repo` & `minio_users` accordingly
- { access_key: dba , secret_key: S3User.DBA.Strong.Password, policy : consoleAdmin }
- { access_key: pgbackrest , secret_key: Min10.bAckup ,policy : readwrite }
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backup when using local fs repo
minio : # optional minio repo for pgbackrest
s3_key : pgbackrest # <-------- CHANGE THIS, SAME AS `minio_users` access_key
s3_key_secret : Min10.bAckup # <-------- CHANGE THIS, SAME AS `minio_users` secret_key
cipher_pass : 'pgBR.${pg_cluster}' # <-------- CHANGE THIS, you can use cluster name as part of password
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for last 14 days
#----------------------------------#
# Access Control
#----------------------------------#
# add passwordcheck extension to enforce strong password policy
pg_libs : '$libdir/passwordcheck, pg_stat_statements, auto_explain'
pg_extensions :
- passwordcheck, supautils, pgsodium, pg_vault, pg_session_jwt, anonymizer, pgsmcrypto, pgauditlogtofile, pgaudit #, pgaudit17, pgaudit16, pgaudit15, pgaudit14
- pg_auth_mon, credcheck, pgcryptokey, pg_jobmon, logerrors, login_hook, set_user, pgextwlist, pg_auditor, sslutils, noset #pg_tde #pg_snakeoil
pg_default_roles : # default roles and users in postgres cluster
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [ dbrole_readonly ] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [ pg_monitor, dbrole_readwrite ] ,comment : role for object creation }
- { name: postgres ,superuser: true ,expire_in: 7300 ,comment : system superuser }
- { name: replicator ,replication: true ,expire_in: 7300 ,roles: [ pg_monitor, dbrole_readonly ] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,expire_in: 7300 ,roles: [ dbrole_admin ] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 , comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [ pg_monitor ] ,expire_in: 7300 ,pgbouncer: true ,parameters : { log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
pg_default_hba_rules : # postgres host-based auth rules by default
- { user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- { user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- { user : '${repl}' ,db: replication ,addr: localhost ,auth: ssl ,title : 'replicator replication from localhost' }
- { user : '${repl}' ,db: replication ,addr: intra ,auth: ssl ,title : 'replicator replication from intranet' }
- { user : '${repl}' ,db: postgres ,addr: intra ,auth: ssl ,title : 'replicator postgres db from intranet' }
- { user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- { user : '${monitor}' ,db: all ,addr: infra ,auth: ssl ,title : 'monitor from infra host with password' }
- { user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- { user : '${admin}' ,db: all ,addr: world ,auth: cert ,title : 'admin @ everywhere with ssl & cert' }
- { user: '+dbrole_readonly',db: all ,addr: localhost ,auth: ssl ,title : 'pgbouncer read/write via local socket' }
- { user: '+dbrole_readonly',db: all ,addr: intra ,auth: ssl ,title : 'read/write biz user via password' }
- { user: '+dbrole_offline' ,db: all ,addr: intra ,auth: ssl ,title : 'allow etl offline tasks from intranet' }
pgb_default_hba_rules : # pgbouncer host-based authentication rules
- { user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title : 'dbsu local admin access with os ident' }
- { user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title : 'allow all user local access with pwd' }
- { user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: ssl ,title : 'monitor access via intranet with pwd' }
- { user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other monitor access addr' }
- { user : '${admin}' ,db: all ,addr: intra ,auth: ssl ,title : 'admin access via intranet with pwd' }
- { user : '${admin}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other admin access addr' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'allow all user intra access with pwd' }
#----------------------------------#
# Repo, Node, Packages
#----------------------------------#
repo_remove : true # remove existing repo on admin node during repo bootstrap
node_repo_remove : true # remove existing node repo for node managed by pigsty
#node_selinux_mode: enforcing # set selinux mode: enforcing,permissive,disabled
node_firewall_mode: zone # firewall mode : off , none, zone, zone by default
repo_extra_packages : [ pg18-main ] #,pg18-core ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_version : 18 # default postgres version
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
#grafana_admin_username: admin
grafana_admin_password : You.Have2Use-A_VeryStrongPassword
grafana_view_password : DBUser.Viewer
#pg_admin_username: dbuser_dba
pg_admin_password : PessWorb.Should8eStrong-eNough
#pg_monitor_username: dbuser_monitor
pg_monitor_password : MekeSuerYour.PassWordI5secured
#pg_replication_username: replicator
pg_replication_password : doNotUseThis-PasswordFor.AnythingElse
#patroni_username: postgres
patroni_password : don.t-forget-to-change-thEs3-password
#haproxy_admin_username: admin
haproxy_admin_password : GneratePasswordWith-pwgen-s-16-1
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 ha/safe 模板是 Pigsty 的 安全加固配置 ,专为对安全性有较高要求的生产环境设计。
安全特性汇总 :
安全措施 说明 SSL 加密 PostgreSQL/PgBouncer/Patroni 全链路 SSL 强密码策略 passwordcheck 扩展强制密码复杂度用户过期 所有用户 20 年过期(expire_in: 7300) 严格 HBA 管理员远程访问需要证书认证 备份加密 MinIO 备份启用 AES-256-CBC 加密 审计日志 pgaudit 扩展记录 SQL 审计日志延迟副本 1 小时延迟副本用于误操作恢复
适用场景 :
金融、医疗、政务等高安全要求行业 需要满足合规审计要求的环境 对数据安全有极高要求的关键业务 注意事项 :
部分安全扩展在 ARM64 架构不可用,请酌情启用 所有默认密码必须修改为强密码 建议配合定期安全审计使用 9.21 - ha/trio 三节点标准高可用配置模板,允许任意一台服务器宕机。
三节点是实现真正高可用的最小规格。ha/trio 模板使用三节点标准 HA 架构,INFRA、ETCD、PGSQL 三个核心模块均采用三节点部署,允许任意一台服务器宕机。
配置概览 配置名称: ha/trio 节点数量: 三节点 配置说明:三节点标准高可用架构,允许任意一台服务器宕机 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:ha/dual ,ha/full ,ha/safe 启用方式:
./configure -c ha/trio [ -i <primary_ip>]
配置生成后,需要将占位 IP 10.10.10.11 和 10.10.10.12 修改为实际的节点 IP 地址。
配置内容 源文件地址:pigsty/conf/ha/trio.yml
---
#==============================================================#
# File : trio.yml
# Desc : Pigsty 3-node security enhance template
# Ctime : 2020-05-22
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# 3 infra node, 3 etcd node, 3 pgsql node, and 1 minio node
all :
#==============================================================#
# Clusters, Nodes, and Modules
#==============================================================#
children :
#----------------------------------#
# infra: monitor, alert, repo, etc..
#----------------------------------#
infra : # infra cluster for proxy, monitor, alert, etc
hosts : # 1 for common usage, 3 nodes for production
10.10.10.10 : { infra_seq : 1 } # identity required
10.10.10.11 : { infra_seq: 2, repo_enabled : false }
10.10.10.12 : { infra_seq: 3, repo_enabled : false }
vars :
patroni_watchdog_mode : off # do not fencing infra
etcd : # dcs service for postgres/patroni ha consensus
hosts : # 1 node for testing, 3 or 5 for production
10.10.10.10 : { etcd_seq : 1 } # etcd_seq required
10.10.10.11 : { etcd_seq : 2 } # assign from 1 ~ n
10.10.10.12 : { etcd_seq : 3 } # odd number please
vars : # cluster level parameter override roles/etcd
etcd_cluster : etcd # mark etcd cluster name etcd
etcd_safeguard : false # safeguard against purging
etcd_clean : true # purge etcd during init process
minio : # minio cluster, s3 compatible object storage
hosts : { 10.10.10.10 : { minio_seq : 1 } }
vars : { minio_cluster : minio }
pg-meta : # 3 instance postgres cluster `pg-meta`
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
10.10.10.11 : { pg_seq: 2, pg_role : replica }
10.10.10.12 : { pg_seq: 3, pg_role: replica , pg_offline_query : true }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta , password: DBUser.Meta ,pgbouncer: true ,roles: [ dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view , password: DBUser.View ,pgbouncer: true ,roles: [ dbrole_readonly ] ,comment : read-only viewer for meta database }
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [ pigsty ] ,extensions : [ { name : vector } ] }
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
#==============================================================#
# Global Parameters
#==============================================================#
vars :
#----------------------------------#
# Meta Data
#----------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
#----------------------------------#
# Repo, Node, Packages
#----------------------------------#
repo_remove : true # remove existing repo on admin node during repo bootstrap
node_repo_remove : true # remove existing node repo for node managed by pigsty
repo_extra_packages : [ pg18-main ] #,pg18-core ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_version : 18 # default postgres version
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 ha/trio 模板是 Pigsty 的 标准高可用配置 ,提供真正的故障自动恢复能力。
架构说明 :
三节点 INFRA:Prometheus/Grafana/Nginx 分布式部署 三节点 ETCD:DCS 多数派选举,容忍单点故障 三节点 PostgreSQL:一主两从,自动故障转移 单节点 MinIO:可按需扩展为多节点 高可用保障 :
ETCD 三节点可容忍一节点故障,保持多数派 PostgreSQL 主库故障时,Patroni 自动选举新主 L2 VIP 随主库漂移,应用无需修改连接配置 适用场景 :
生产环境最小高可用部署 需要自动故障转移的关键业务 作为更大规模部署的基础架构 扩展建议 :
需要更强数据安全性,参考 ha/safe 模板 需要更多演示功能,参考 ha/full 模板 生产环境建议启用 pgbackrest_method: minio 远程备份 9.22 - ha/dual 双节点配置模板,有限高可用部署,允许宕机特定一台服务器。
ha/dual 模板使用双节点部署,实现一主一备的"半高可用"架构。如果您只有两台服务器,这是一个务实的选择。
配置概览 配置名称: ha/dual 节点数量: 双节点 配置说明:两节点有限高可用部署,允许特定一台服务器宕机 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:ha/trio ,slim 启用方式:
./configure -c ha/dual [ -i <primary_ip>]
配置生成后,需要将占位 IP 10.10.10.11 修改为实际的备库节点 IP 地址。
配置内容 源文件地址:pigsty/conf/ha/dual.yml
---
#==============================================================#
# File : dual.yml
# Desc : Pigsty deployment example for two nodes
# Ctime : 2020-05-22
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# It is recommended to use at least three nodes in production deployment.
# But sometimes, there are only two nodes available, that's dual.yml for
#
# In this setup, we have two nodes, .10 (admin_node) and .11 (pgsql_priamry):
#
# If .11 is down, .10 will take over since the dcs:etcd is still alive
# If .10 is down, .11 (pgsql primary) will still be functioning as a primary if:
# - Only dcs:etcd is down
# - Only pgsql is down
# if both etcd & pgsql are down (e.g. node down), the primary will still demote itself.
all :
children :
# infra cluster for proxy, monitor, alert, etc..
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
# etcd cluster for ha postgres
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
# minio cluster, optional backup repo for pgbackrest
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 } }, vars: { minio_cluster: minio } }
# postgres cluster 'pg-meta' with single primary instance
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : replica }
10.10.10.11 : { pg_seq: 2, pg_role : primary } # <----- use this as primary by default
vars :
pg_cluster : pg-meta
pg_databases : [ { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [ pigsty ] ,extensions : [ { name : vector }] } ]
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [ dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [ dbrole_readonly ] ,comment : read-only viewer for meta database }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
vars : # global parameters
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
infra_portal : # domain names and upstream servers
home : { domain : i.pigsty }
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
#----------------------------------#
# Repo, Node, Packages
#----------------------------------#
repo_remove : true # remove existing repo on admin node during repo bootstrap
node_repo_remove : true # remove existing node repo for node managed by pigsty
repo_extra_packages : [ pg18-main ] #,pg18-core ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_version : 18 # default postgres version
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 ha/dual 模板是 Pigsty 的 双节点有限高可用配置 ,专为只有两台服务器的场景设计。
架构说明 :
节点A (10.10.10.10):管理节点,运行 Infra + etcd + PostgreSQL 备库节点B (10.10.10.11):数据节点,仅运行 PostgreSQL 主库故障场景分析 :
故障节点 影响 是否自动恢复 节点B 宕机 主库切换到节点A 自动 节点A etcd 宕机 主库继续运行(无 DCS) 需人工 节点A pgsql 宕机 主库继续运行 需人工 节点A 完全宕机 主库降级为单机 需人工
适用场景 :
仅有两台服务器的预算受限环境 可接受部分故障场景需要人工介入 作为三节点高可用的过渡方案 注意事项 :
真正的高可用需要至少三节点(DCS 需要多数派) 建议尽快升级到三节点架构 L2 VIP 需要网络环境支持(同一广播域)
9.23 - 应用模版 9.24 - app/odoo 使用 Pigsty 托管的 PostgreSQL 部署 Odoo 开源 ERP 系统
app/odoo 配置模板提供了自建 Odoo 开源 ERP 系统的参考配置,使用 Pigsty 托管的 PostgreSQL 作为数据库。
更多细节,请参考 Odoo 部署教程
配置概览 配置名称: app/odoo 节点数量: 单节点 配置说明:使用 Pigsty 托管的 PostgreSQL 部署 Odoo ERP 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c app/odoo [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/app/odoo.yml
---
#==============================================================#
# File : odoo.yml
# Desc : pigsty config for running 1-node odoo app
# Ctime : 2025-01-11
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/app/odoo
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# tutorial: https://doc.pgsty.com/app/odoo
# how to use this template:
#
# curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
# ./bootstrap # prepare local repo & ansible
# ./configure -c app/odoo # Use this odoo config template
# vi pigsty.yml # IMPORTANT: CHANGE CREDENTIALS!!
# ./deploy.yml # install pigsty & pgsql & minio
# ./docker.yml # install docker & docker-compose
# ./app.yml # install odoo
all :
children :
# the odoo application (default username & password: admin/admin)
odoo :
hosts : { 10.10.10.10 : {} }
vars :
app : odoo # specify app name to be installed (in the apps)
apps : # define all applications
odoo : # app name, should have corresponding ~/pigsty/app/odoo folder
file : # optional directory to be created
- { path: /data/odoo ,state: directory, owner: 100, group : 101 }
- { path: /data/odoo/webdata ,state: directory, owner: 100, group : 101 }
- { path: /data/odoo/addons ,state: directory, owner: 100, group : 101 }
conf : # override /opt/<app>/.env config file
PG_HOST : 10.10.10.10 # postgres host
PG_PORT : 5432 # postgres port
PG_USERNAME : odoo # postgres user
PG_PASSWORD : DBUser.Odoo # postgres password
ODOO_PORT : 8069 # odoo app port
ODOO_DATA : /data/odoo/webdata # odoo webdata
ODOO_ADDONS : /data/odoo/addons # odoo plugins
ODOO_DBNAME : odoo # odoo database name
ODOO_VERSION : 19.0 # odoo image version
# the odoo database
pg-odoo :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-odoo
pg_users :
- { name: odoo ,password: DBUser.Odoo ,pgbouncer: true ,roles: [ dbrole_admin ] ,createdb: true ,comment : admin user for odoo service }
- { name: odoo_ro ,password: DBUser.Odoo ,pgbouncer: true ,roles: [ dbrole_readonly ] ,comment : read only user for odoo service }
- { name: odoo_rw ,password: DBUser.Odoo ,pgbouncer: true ,roles: [ dbrole_readwrite ] ,comment : read write user for odoo service }
pg_databases :
- { name: odoo ,owner: odoo ,revokeconn: true ,comment : odoo main database }
pg_hba_rules :
- { user: all ,db: all ,addr: 172.17.0.0/16 ,auth: pwd ,title : 'allow access from local docker network' }
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 } }, vars: { minio_cluster: minio } }
vars : # global variables
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
docker_enabled : true # enable docker on app group
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
proxy_env : # global proxy env when downloading packages & pull docker images
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.tsinghua.edu.cn"
#http_proxy: 127.0.0.1:12345 # add your proxy env here for downloading packages or pull images
#https_proxy: 127.0.0.1:12345 # usually the proxy is format as http://user:pass@proxy.xxx.com
#all_proxy: 127.0.0.1:12345
infra_portal : # domain names and upstream servers
home : { domain : i.pigsty }
minio : { domain: m.pigsty ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
odoo : # nginx server config for odoo
domain : odoo.pigsty # REPLACE WITH YOUR OWN DOMAIN!
endpoint : "10.10.10.10:8069" # odoo service endpoint: IP:PORT
websocket : true # add websocket support
certbot : odoo.pigsty # certbot cert name, apply with `make cert`
repo_enabled : false
node_repo_modules : node,infra,pgsql
pg_version : 18
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 app/odoo 模板提供了 Odoo 开源 ERP 系统的一键部署方案。
Odoo 是什么 :
全球最流行的开源 ERP 系统 覆盖 CRM、销售、采购、库存、财务、HR 等企业管理模块 支持数千个社区和官方应用扩展 提供 Web 界面和移动端支持 关键特性 :
使用 Pigsty 管理的 PostgreSQL 替代 Odoo 自带的数据库 支持 Odoo 19.0 最新版本 数据持久化到独立目录 /data/odoo 支持自定义插件目录 /data/odoo/addons 访问方式 :
# Odoo Web 界面
http://odoo.pigsty:8069
# 默认管理员账号
用户名: admin
密码: admin ( 首次登录时设置)
适用场景 :
中小企业 ERP 系统 替代 SAP、Oracle ERP 等商业解决方案 需要自定义业务流程的企业应用 注意事项 :
Odoo 容器以 uid=100, gid=101 运行,数据目录需要正确的权限 首次访问时需要创建数据库和设置管理员密码 生产环境建议启用 HTTPS 可通过 /data/odoo/addons 安装自定义模块 9.25 - app/dify 使用 Pigsty 托管的 PostgreSQL 部署 Dify AI 应用开发平台
app/dify 配置模板提供了自建 Dify AI 应用开发平台的参考配置,使用 Pigsty 托管的 PostgreSQL 和 pgvector 作为向量存储。
更多细节,请参考 Dify 部署教程
配置概览 配置名称: app/dify 节点数量: 单节点 配置说明:使用 Pigsty 托管的 PostgreSQL 部署 Dify 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c app/dify [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/app/dify.yml
---
#==============================================================#
# File : dify.yml
# Desc : pigsty config for running 1-node dify app
# Ctime : 2025-02-24
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/app/odoo
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# Last Verified Dify Version: v1.8.1 on 2025-0908
# tutorial: https://doc.pgsty.com/app/dify
# how to use this template:
#
# curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
# ./bootstrap # prepare local repo & ansible
# ./configure -c app/dify # use this dify config template
# vi pigsty.yml # IMPORTANT: CHANGE CREDENTIALS!!
# ./deploy.yml # install pigsty & pgsql & minio
# ./docker.yml # install docker & docker-compose
# ./app.yml # install dify with docker-compose
#
# To replace domain name:
# sed -ie 's/dify.pigsty/dify.pigsty.cc/g' pigsty.yml
all :
children :
# the dify application
dify :
hosts : { 10.10.10.10 : {} }
vars :
app : dify # specify app name to be installed (in the apps)
apps : # define all applications
dify : # app name, should have corresponding ~/pigsty/app/dify folder
file : # data directory to be created
- { path: /data/dify ,state: directory ,mode : 0755 }
conf : # override /opt/dify/.env config file
# change domain, mirror, proxy, secret key
NGINX_SERVER_NAME : dify.pigsty
# A secret key for signing and encryption, gen with `openssl rand -base64 42` (CHANGE PASSWORD!)
SECRET_KEY : sk-9f73s3ljTXVcMT3Blb3ljTqtsKiGHXVcMT3BlbkFJLK7U
# expose DIFY nginx service with port 5001 by default
DIFY_PORT : 5001
# where to store dify files? the default is ./volume, we'll use another volume created above
DIFY_DATA : /data/dify
# proxy and mirror settings
#PIP_MIRROR_URL: https://pypi.tuna.tsinghua.edu.cn/simple
#SANDBOX_HTTP_PROXY: http://10.10.10.10:12345
#SANDBOX_HTTPS_PROXY: http://10.10.10.10:12345
# database credentials
DB_USERNAME : dify
DB_PASSWORD : difyai123456
DB_HOST : 10.10.10.10
DB_PORT : 5432
DB_DATABASE : dify
VECTOR_STORE : pgvector
PGVECTOR_HOST : 10.10.10.10
PGVECTOR_PORT : 5432
PGVECTOR_USER : dify
PGVECTOR_PASSWORD : difyai123456
PGVECTOR_DATABASE : dify
PGVECTOR_MIN_CONNECTION : 2
PGVECTOR_MAX_CONNECTION : 10
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dify ,password: difyai123456 ,pgbouncer: true ,roles: [ dbrole_admin ] ,superuser: true ,comment : dify superuser }
pg_databases :
- { name: dify ,owner: dify ,revokeconn: true ,comment : dify main database }
- { name: dify_plugin ,owner: dify ,revokeconn: true ,comment : dify plugin_daemon database }
pg_hba_rules :
- { user: dify ,db: all ,addr: 172.17.0.0/16 ,auth: pwd ,title : 'allow dify access from local docker network' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 } }, vars: { minio_cluster: minio } }
vars : # global variables
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
docker_enabled : true # enable docker on app group
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
proxy_env : # global proxy env when downloading packages & pull docker images
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.tsinghua.edu.cn"
#http_proxy: 127.0.0.1:12345 # add your proxy env here for downloading packages or pull images
#https_proxy: 127.0.0.1:12345 # usually the proxy is format as http://user:pass@proxy.xxx.com
#all_proxy: 127.0.0.1:12345
infra_portal : # domain names and upstream servers
home : { domain : i.pigsty }
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
dify : # nginx server config for dify
domain : dify.pigsty # REPLACE WITH YOUR OWN DOMAIN!
endpoint : "10.10.10.10:5001" # dify service endpoint: IP:PORT
websocket : true # add websocket support
certbot : dify.pigsty # certbot cert name, apply with `make cert`
repo_enabled : false
node_repo_modules : node,infra,pgsql
pg_version : 18
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 app/dify 模板提供了 Dify AI 应用开发平台的一键部署方案。
Dify 是什么 :
开源的 LLM 应用开发平台 支持 RAG、Agent、Workflow 等 AI 应用模式 提供可视化的 Prompt 编排和应用构建界面 支持多种 LLM 后端(OpenAI、Claude、本地模型等) 关键特性 :
使用 Pigsty 管理的 PostgreSQL 替代 Dify 自带的数据库 使用 pgvector 作为向量存储(替代 Weaviate/Qdrant) 支持 HTTPS 和自定义域名 数据持久化到独立目录 /data/dify 访问方式 :
# Dify Web 界面
http://dify.pigsty:5001
# 或通过 Nginx 代理
https://dify.pigsty
适用场景 :
企业内部 AI 应用开发平台 RAG 知识库问答系统 LLM 驱动的自动化工作流 AI Agent 开发与部署 注意事项 :
必须修改 SECRET_KEY,使用 openssl rand -base64 42 生成 需要配置 LLM API 密钥(如 OpenAI API Key) Docker 网络需要能访问 PostgreSQL(已配置 172.17.0.0/16 HBA 规则) 建议配置代理以加速 Python 包下载 9.26 - app/electric 使用 Pigsty 托管的 PostgreSQL 部署 Electric 实时同步服务
app/electric 配置模板提供了部署 Electric SQL 实时同步服务的参考配置,实现 PostgreSQL 到客户端的实时数据同步。
配置概览 配置名称: app/electric 节点数量: 单节点 配置说明:使用 Pigsty 托管的 PostgreSQL 部署 Electric 实时同步 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c app/electric [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/app/electric.yml
---
#==============================================================#
# File : electric.yml
# Desc : pigsty config for running 1-node electric app
# Ctime : 2025-03-29
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/app/odoo
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# tutorial: https://doc.pgsty.com/app/electric
# quick start: https://electric-sql.com/docs/quickstart
# how to use this template:
#
# curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
# ./bootstrap # prepare local repo & ansible
# ./configure -c app/electric # use this dify config template
# vi pigsty.yml # IMPORTANT: CHANGE CREDENTIALS!!
# ./deploy.yml # install pigsty & pgsql & minio
# ./docker.yml # install docker & docker-compose
# ./app.yml # install dify with docker-compose
all :
children :
# infra cluster for proxy, monitor, alert, etc..
infra :
hosts : { 10.10.10.10 : { infra_seq : 1 } }
vars :
app : electric
apps : # define all applications
electric : # app name, should have corresponding ~/pigsty/app/electric folder
conf: # override /opt/electric/.env config file : https://electric-sql.com/docs/api/config
DATABASE_URL : 'postgresql://electric:DBUser.Electric@10.10.10.10:5432/electric?sslmode=require'
ELECTRIC_PORT : 8002
ELECTRIC_PROMETHEUS_PORT : 8003
ELECTRIC_INSECURE : true
#ELECTRIC_SECRET: 1U6ItbhoQb4kGUU5wXBLbxvNf
# etcd cluster for ha postgres
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
# minio cluster, s3 compatible object storage
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 } }, vars: { minio_cluster: minio } }
# postgres example cluster: pg-meta
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- {name: electric ,password: DBUser.Electric ,pgbouncer: true , replication: true ,roles: [dbrole_admin] ,comment : electric main user }
pg_databases : [ { name: electric , owner : electric }]
pg_hba_rules :
- { user: electric , db: replication ,addr: infra ,auth: ssl ,title : 'allow electric intranet/docker ssl access' }
#==============================================================#
# Global Parameters
#==============================================================#
vars :
#----------------------------------#
# Meta Data
#----------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
docker_enabled : true # enable docker on app group
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
infra_portal : # domain names and upstream servers
home : { domain : i.pigsty }
electric :
domain : elec.pigsty
endpoint : "${admin_ip}:8002"
websocket: true # apply free ssl cert with certbot : make cert
certbot : odoo.pigsty # <----- replace with your own domain name!
#----------------------------------#
# Safe Guard
#----------------------------------#
# you can enable these flags after bootstrap, to prevent purging running etcd / pgsql instances
etcd_safeguard : false # prevent purging running etcd instance?
pg_safeguard : false # prevent purging running postgres instance? false by default
#----------------------------------#
# Repo, Node, Packages
#----------------------------------#
repo_enabled : false
node_repo_modules : node,infra,pgsql
pg_version : 18 # default postgres version
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 app/electric 模板提供了 Electric SQL 实时同步服务的一键部署方案。
Electric 是什么 :
PostgreSQL 到客户端的实时数据同步服务 支持离线优先 (Local-first) 应用架构 通过逻辑复制实时同步数据变更 提供 HTTP API 供前端应用消费 关键特性 :
使用 Pigsty 管理的 PostgreSQL 作为数据源 通过逻辑复制 (Logical Replication) 捕获数据变更 支持 SSL 加密连接 内置 Prometheus 指标端点 访问方式 :
# Electric API 端点
http://elec.pigsty:8002
# Prometheus 指标
http://elec.pigsty:8003/metrics
适用场景 :
构建离线优先 (Local-first) 应用 需要实时数据同步到客户端 移动应用和 PWA 的数据同步 协作应用的实时更新 注意事项 :
Electric 用户需要 replication 权限 需要启用 PostgreSQL 逻辑复制 生产环境建议使用 SSL 连接(已配置 sslmode=require) 9.27 - app/maybe 使用 Pigsty 托管的 PostgreSQL 部署 Maybe 个人财务管理系统
app/maybe 配置模板提供了部署 Maybe 开源个人财务管理系统的参考配置,使用 Pigsty 托管的 PostgreSQL 作为数据库。
配置概览 配置名称: app/maybe 节点数量: 单节点 配置说明:使用 Pigsty 托管的 PostgreSQL 部署 Maybe 财务管理 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c app/maybe [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/app/maybe.yml
---
#==============================================================#
# File : maybe.yml
# Desc : pigsty config for running 1-node maybe app
# Ctime : 2025-09-08
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/app/maybe
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# tutorial: https://doc.pgsty.com/app/maybe
# how to use this template:
#
# curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
# ./bootstrap # prepare local repo & ansible
# ./configure -c app/maybe # Use this maybe config template
# vi pigsty.yml # IMPORTANT: CHANGE CREDENTIALS!!
# ./deploy.yml # install pigsty & pgsql
# ./docker.yml # install docker & docker-compose
# ./app.yml # install maybe
all :
children :
# the maybe application (personal finance management)
maybe :
hosts : { 10.10.10.10 : {} }
vars :
app : maybe # specify app name to be installed (in the apps)
apps : # define all applications
maybe : # app name, should have corresponding ~/pigsty/app/maybe folder
file : # optional directory to be created
- { path: /data/maybe ,state: directory ,mode : 0755 }
- { path: /data/maybe/storage ,state: directory ,mode : 0755 }
conf : # override /opt/<app>/.env config file
# Core Configuration
MAYBE_VERSION : latest # Maybe image version
MAYBE_PORT : 5002 # Port to expose Maybe service
MAYBE_DATA : /data/maybe # Data directory for Maybe
APP_DOMAIN : maybe.pigsty # Domain name for Maybe
# REQUIRED: Generate with: openssl rand -hex 64
SECRET_KEY_BASE : sk-9f73s3ljTXVcMT3Blb3ljTqtsKiGHXVcMT3BlbkFJLK7U
# Database Configuration
DB_HOST : 10.10.10.10 # PostgreSQL host
DB_PORT : 5432 # PostgreSQL port
DB_USERNAME : maybe # PostgreSQL username
DB_PASSWORD : MaybeFinance2025 # PostgreSQL password (CHANGE THIS!)
DB_DATABASE : maybe_production # PostgreSQL database name
# Optional: API Integration
#SYNTH_API_KEY: # Get from synthfinance.com
# the maybe database
pg-maybe :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-maybe
pg_users :
- { name: maybe ,password: MaybeFinance2025 ,pgbouncer: true ,roles: [ dbrole_admin ] ,createdb: true ,comment : admin user for maybe service }
- { name: maybe_ro ,password: MaybeFinance2025 ,pgbouncer: true ,roles: [ dbrole_readonly ] ,comment : read only user for maybe service }
- { name: maybe_rw ,password: MaybeFinance2025 ,pgbouncer: true ,roles: [ dbrole_readwrite ] ,comment : read write user for maybe service }
pg_databases :
- { name: maybe_production ,owner: maybe ,revokeconn: true ,comment : maybe main database }
pg_hba_rules :
- { user: maybe ,db: all ,addr: 172.17.0.0/16 ,auth: pwd ,title : 'allow maybe access from local docker network' }
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
#minio: { hosts: { 10.10.10.10: { minio_seq: 1 } }, vars: { minio_cluster: minio } }
vars : # global variables
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
docker_enabled : true # enable docker on app group
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
proxy_env : # global proxy env when downloading packages & pull docker images
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.tsinghua.edu.cn"
#http_proxy: 127.0.0.1:12345 # add your proxy env here for downloading packages or pull images
#https_proxy: 127.0.0.1:12345 # usually the proxy is format as http://user:pass@proxy.xxx.com
#all_proxy: 127.0.0.1:12345
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
minio : { domain: m.pigsty ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
maybe : # nginx server config for maybe
domain : maybe.pigsty # REPLACE WITH YOUR OWN DOMAIN!
endpoint : "10.10.10.10:5002" # maybe service endpoint: IP:PORT
websocket : true # add websocket support
repo_enabled : false
node_repo_modules : node,infra,pgsql
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 app/maybe 模板提供了 Maybe 开源个人财务管理系统的一键部署方案。
Maybe 是什么 :
开源的个人和家庭财务管理系统 支持多账户、多币种资产追踪 提供投资组合分析和净值计算 美观现代的 Web 界面 关键特性 :
使用 Pigsty 管理的 PostgreSQL 替代 Maybe 自带的数据库 数据持久化到独立目录 /data/maybe 支持 HTTPS 和自定义域名 提供多用户权限管理 访问方式 :
# Maybe Web 界面
http://maybe.pigsty:5002
# 或通过 Nginx 代理
https://maybe.pigsty
适用场景 :
个人或家庭财务管理 投资组合追踪和分析 多账户资产汇总 替代 Mint、YNAB 等商业服务 注意事项 :
必须修改 SECRET_KEY_BASE,使用 openssl rand -hex 64 生成 首次访问时需要注册管理员账号 可选配置 Synth API 以获取股票价格数据 9.28 - app/teable 使用 Pigsty 托管的 PostgreSQL 部署 Teable 开源 Airtable 替代品
app/teable 配置模板提供了部署 Teable 开源无代码数据库的参考配置,使用 Pigsty 托管的 PostgreSQL 作为数据库。
配置概览 配置名称: app/teable 节点数量: 单节点 配置说明:使用 Pigsty 托管的 PostgreSQL 部署 Teable 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c app/teable [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/app/teable.yml
---
#==============================================================#
# File : teable.yml
# Desc : pigsty config for running 1-node teable app
# Ctime : 2025-02-24
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/app/odoo
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# tutorial: https://doc.pgsty.com/app/teable
# how to use this template:
#
# curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
# ./bootstrap # prepare local repo & ansible
# ./configure -c app/teable # use this teable config template
# vi pigsty.yml # IMPORTANT: CHANGE CREDENTIALS!!
# ./deploy.yml # install pigsty & pgsql & minio
# ./docker.yml # install docker & docker-compose
# ./app.yml # install teable with docker-compose
#
# To replace domain name:
# sed -ie 's/teable.pigsty/teable.pigsty.cc/g' pigsty.yml
all :
children :
# the teable application
teable :
hosts : { 10.10.10.10 : {} }
vars :
app : teable # specify app name to be installed (in the apps)
apps : # define all applications
teable : # app name, ~/pigsty/app/teable folder
conf : # override /opt/teable/.env config file
# https://github.com/teableio/teable/blob/develop/dockers/examples/standalone/.env
# https://help.teable.io/en/deploy/env
POSTGRES_HOST : "10.10.10.10"
POSTGRES_PORT : "5432"
POSTGRES_DB : "teable"
POSTGRES_USER : "dbuser_teable"
POSTGRES_PASSWORD : "DBUser.Teable"
PRISMA_DATABASE_URL : "postgresql://dbuser_teable:DBUser.Teable@10.10.10.10:5432/teable"
PUBLIC_ORIGIN : "http://tea.pigsty"
PUBLIC_DATABASE_PROXY : "10.10.10.10:5432"
TIMEZONE : "UTC"
# Need to support sending emails to enable the following configurations
#BACKEND_MAIL_HOST: smtp.teable.io
#BACKEND_MAIL_PORT: 465
#BACKEND_MAIL_SECURE: true
#BACKEND_MAIL_SENDER: noreply.teable.io
#BACKEND_MAIL_SENDER_NAME: Teable
#BACKEND_MAIL_AUTH_USER: username
#BACKEND_MAIL_AUTH_PASS: password
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_teable ,password: DBUser.Teable ,pgbouncer: true ,roles: [ dbrole_admin ] ,superuser: true ,comment : teable superuser }
pg_databases :
- { name: teable ,owner: dbuser_teable ,comment : teable database }
pg_hba_rules :
- { user: teable ,db: all ,addr: 172.17.0.0/16 ,auth: pwd ,title : 'allow teable access from local docker network' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
vars : # global variables
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
docker_enabled : true # enable docker on app group
#docker_registry_mirrors: ["https://docker.1panel.live","https://docker.1ms.run","https://docker.xuanyuan.me","https://registry-1.docker.io"]
proxy_env : # global proxy env when downloading packages & pull docker images
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.tsinghua.edu.cn"
#http_proxy: 127.0.0.1:12345 # add your proxy env here for downloading packages or pull images
#https_proxy: 127.0.0.1:12345 # usually the proxy is format as http://user:pass@proxy.xxx.com
#all_proxy: 127.0.0.1:12345
infra_portal : # domain names and upstream servers
home : { domain : i.pigsty }
#minio : { domain: m.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
teable : # nginx server config for teable
domain : tea.pigsty # REPLACE IT WITH YOUR OWN DOMAIN!
endpoint : "10.10.10.10:8890" # teable service endpoint: IP:PORT
websocket : true # add websocket support
certbot : tea.pigsty # certbot cert name, apply with `make cert`
repo_enabled : false
node_repo_modules : node,infra,pgsql
pg_version : 18
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 app/teable 模板提供了 Teable 开源无代码数据库的一键部署方案。
Teable 是什么 :
开源的 Airtable 替代品 基于 PostgreSQL 的无代码数据库 支持表格、看板、日历、表单等多种视图 提供 API 和自动化工作流 关键特性 :
使用 Pigsty 管理的 PostgreSQL 作为底层存储 数据实际存储在真实的 PostgreSQL 表中 支持 SQL 直接查询数据 可与其他 PostgreSQL 工具和扩展集成 访问方式 :
# Teable Web 界面
http://tea.pigsty:8890
# 或通过 Nginx 代理
https://tea.pigsty
# 同时可以直接 SQL 访问底层数据
psql postgresql://dbuser_teable:DBUser.Teable@10.10.10.10:5432/teable
适用场景 :
需要 Airtable 类似功能但希望自建 团队协作数据管理 需要同时支持 API 和 SQL 访问 希望数据存储在真实 PostgreSQL 中 注意事项 :
Teable 用户需要 superuser 权限 需要正确配置 PUBLIC_ORIGIN 为外部访问地址 支持邮件通知(可选配置 SMTP) 9.29 - app/registry 使用 Pigsty 部署 Docker Registry 镜像代理和私有仓库
app/registry 配置模板提供了部署 Docker Registry 镜像代理的参考配置,可用作 Docker Hub 镜像加速或私有镜像仓库。
配置概览 配置名称: app/registry 节点数量: 单节点 配置说明:部署 Docker Registry 镜像代理和私有仓库 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c app/registry [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/app/registry.yml
---
#==============================================================#
# File : registry.yml
# Desc : pigsty config for running Docker Registry Mirror
# Ctime : 2025-07-01
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/app/registry
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# tutorial: https://doc.pgsty.com/app/registry
# how to use this template:
#
# curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty
# ./configure -c app/registry # use this registry config template
# vi pigsty.yml # IMPORTANT: CHANGE DOMAIN & CREDENTIALS!
# ./deploy.yml # install pigsty
# ./docker.yml # install docker & docker-compose
# ./app.yml # install registry with docker-compose
#
# To replace domain name:
# sed -ie 's/registry.pigsty/registry.your-domain.com/g' pigsty.yml
#==============================================================#
# Usage Instructions:
#==============================================================#
#
# 1. Deploy the registry:
# ./configure -c conf/app/registry.yml && ./deploy.yml && ./docker.yml && ./app.yml
#
# 2. Configure Docker clients to use the mirror:
# Edit /etc/docker/daemon.json:
# {
# "registry-mirrors": ["https://registry.your-domain.com"],
# "insecure-registries": ["registry.your-domain.com"]
# }
#
# 3. Restart Docker daemon:
# sudo systemctl restart docker
#
# 4. Test the registry:
# docker pull nginx:latest # This will now use your mirror
#
# 5. Access the web UI (optional):
# https://registry-ui.your-domain.com
#
# 6. Monitor the registry:
# curl https://registry.your-domain.com/v2/_catalog
# curl https://registry.your-domain.com/v2/nginx/tags/list
#
#==============================================================#
all :
children :
# the docker registry mirror application
registry :
hosts : { 10.10.10.10 : {} }
vars :
app : registry # specify app name to be installed
apps : # define all applications
registry :
file : # create data directory for registry
- { path: /data/registry ,state: directory ,mode : 0755 }
conf : # environment variables for registry
REGISTRY_DATA : /data/registry
REGISTRY_PORT : 5000
REGISTRY_UI_PORT : 5080
REGISTRY_STORAGE_DELETE_ENABLED : true
REGISTRY_LOG_LEVEL : info
REGISTRY_PROXY_REMOTEURL : https://registry-1.docker.io
REGISTRY_PROXY_TTL : 168h
# basic infrastructure
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
vars :
#----------------------------------------------#
# INFRA : https://doc.pgsty.com/infra/param
#----------------------------------------------#
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
# Docker Registry Mirror service configuration
registry : # nginx server config for registry
domain : d.pigsty # REPLACE IT WITH YOUR OWN DOMAIN!
endpoint : "10.10.10.10:5000" # registry service endpoint: IP:PORT
websocket : false # registry doesn't need websocket
certbot : d.pigsty # certbot cert name, apply with `make cert`
# Optional: Registry Web UI
registry-ui : # nginx server config for registry UI
domain : dui.pigsty # REPLACE IT WITH YOUR OWN DOMAIN!
endpoint : "10.10.10.10:5080" # registry UI endpoint: IP:PORT
websocket : false # UI doesn't need websocket
certbot : d.pigsty # certbot cert name for UI
#----------------------------------------------#
# NODE : https://doc.pgsty.com/node/param
#----------------------------------------------#
repo_enabled : false
node_repo_modules : node,infra,pgsql
node_tune: oltp # node tuning specs : oltp,olap,tiny,crit
#----------------------------------------------#
# PGSQL : https://doc.pgsty.com/pgsql/param
#----------------------------------------------#
pg_version : 18 # Default PostgreSQL Major Version is 18
pg_conf: oltp.yml # pgsql tuning specs : {oltp,olap,tiny,crit}.yml
pg_packages : [ pgsql-main, pgsql-common ] # pg kernel and common utils
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
...
配置解读 app/registry 模板提供了 Docker Registry 镜像代理的一键部署方案。
Registry 是什么 :
Docker 官方的镜像仓库实现 可作为 Docker Hub 的拉取代理(Pull-through Cache) 也可作为私有镜像仓库使用 支持镜像缓存和本地存储 关键特性 :
作为 Docker Hub 的代理缓存,加速镜像拉取 缓存镜像到本地存储 /data/registry 提供 Web UI 界面查看缓存的镜像 支持自定义缓存过期时间 配置 Docker 客户端 :
# 编辑 /etc/docker/daemon.json
{
"registry-mirrors" : [ "https://d.pigsty" ] ,
"insecure-registries" : [ "d.pigsty" ]
}
# 重启 Docker
sudo systemctl restart docker
访问方式 :
# Registry API
https://d.pigsty/v2/_catalog
# Web UI
http://dui.pigsty:5080
# 拉取镜像(自动使用代理)
docker pull nginx:latest
适用场景 :
加速 Docker 镜像拉取(尤其在中国大陆) 减少对外网络依赖 企业内部私有镜像仓库 离线环境镜像分发 注意事项 :
需要足够的磁盘空间存储缓存镜像 默认缓存 7 天(REGISTRY_PROXY_TTL: 168h) 可配置 HTTPS 证书(通过 certbot)
9.30 - 其他模版 9.31 - demo/el Enterprise Linux (RHEL/Rocky/Alma) 专用配置模板
demo/el 配置模板是针对 Enterprise Linux 系列发行版(RHEL、Rocky Linux、Alma Linux、Oracle Linux)优化的配置模板。
配置概览 配置名称: demo/el 节点数量: 单节点 配置说明:Enterprise Linux 专用配置模板 适用系统:el8, el9, el10 适用架构:x86_64, aarch64 相关配置:meta ,demo/debian 启用方式:
./configure -c demo/el [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/demo/el.yml
---
#==============================================================#
# File : el.yml
# Desc : Default parameters for EL System in Pigsty
# Ctime : 2020-05-22
# Mtime : 2025-12-27
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
#==============================================================#
# Sandbox (4-node) #
#==============================================================#
# admin user : vagrant (nopass ssh & sudo already set) #
# 1. meta : 10.10.10.10 (2 Core | 4GB) pg-meta #
# 2. node-1 : 10.10.10.11 (1 Core | 1GB) pg-test-1 #
# 3. node-2 : 10.10.10.12 (1 Core | 1GB) pg-test-2 #
# 4. node-3 : 10.10.10.13 (1 Core | 1GB) pg-test-3 #
# (replace these ip if your 4-node env have different ip addr) #
# VIP 2: (l2 vip is available inside same LAN ) #
# pg-meta ---> 10.10.10.2 ---> 10.10.10.10 #
# pg-test ---> 10.10.10.3 ---> 10.10.10.1{1,2,3} #
#==============================================================#
all :
##################################################################
# CLUSTERS #
##################################################################
# meta nodes, nodes, pgsql, redis, pgsql clusters are defined as
# k:v pair inside `all.children`. Where the key is cluster name
# and value is cluster definition consist of two parts:
# `hosts`: cluster members ip and instance level variables
# `vars` : cluster level variables
##################################################################
children : # groups definition
# infra cluster for proxy, monitor, alert, etc..
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
# etcd cluster for ha postgres
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
# minio cluster, s3 compatible object storage
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
#----------------------------------#
# pgsql cluster: pg-meta (CMDB) #
#----------------------------------#
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role: primary , pg_offline_query : true } }
vars :
pg_cluster : pg-meta
# define business databases here: https://doc.pgsty.com/pgsql/db
pg_databases : # define business databases on this cluster, array of database definition
- name : meta # REQUIRED, `name` is the only mandatory field of a database definition
baseline: cmdb.sql # optional, database sql baseline path, (relative path among ansible search path, e.g : files/)
schemas : [ pigsty] # optional, additional schemas to be created, array of schema names
extensions: # optional, additional extensions to be installed : array of `{name[,schema]}`
- { name : vector } # install pgvector extension on this database by default
comment : pigsty meta database # optional, comment string for this database
#pgbouncer: true # optional, add this database to pgbouncer database list? true by default
#owner: postgres # optional, database owner, postgres by default
#template: template1 # optional, which template to use, template1 by default
#encoding: UTF8 # optional, database encoding, UTF8 by default. (MUST same as template database)
#locale: C # optional, database locale, C by default. (MUST same as template database)
#lc_collate: C # optional, database collate, C by default. (MUST same as template database)
#lc_ctype: C # optional, database ctype, C by default. (MUST same as template database)
#tablespace: pg_default # optional, default tablespace, 'pg_default' by default.
#allowconn: true # optional, allow connection, true by default. false will disable connect at all
#revokeconn: false # optional, revoke public connection privilege. false by default. (leave connect with grant option to owner)
#register_datasource: true # optional, register this database to grafana datasources? true by default
#connlimit: -1 # optional, database connection limit, default -1 disable limit
#pool_auth_user: dbuser_meta # optional, all connection to this pgbouncer database will be authenticated by this user
#pool_mode: transaction # optional, pgbouncer pool mode at database level, default transaction
#pool_size: 64 # optional, pgbouncer pool size at database level, default 64
#pool_size_reserve: 32 # optional, pgbouncer pool size reserve at database level, default 32
#pool_size_min: 0 # optional, pgbouncer pool size min at database level, default 0
#pool_max_db_conn: 100 # optional, max database connections at database level, default 100
#- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment: grafana primary database }
#- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment: bytebase primary database }
#- { name: kong ,owner: dbuser_kong ,revokeconn: true ,comment: kong the api gateway database }
#- { name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment: gitea meta database }
#- { name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment: wiki meta database }
# define business users here: https://doc.pgsty.com/pgsql/user
pg_users : # define business users/roles on this cluster, array of user definition
- name : dbuser_meta # REQUIRED, `name` is the only mandatory field of a user definition
password : DBUser.Meta # optional, password, can be a scram-sha-256 hash string or plain text
login : true # optional, can log in, true by default (new biz ROLE should be false)
superuser : false # optional, is superuser? false by default
createdb : false # optional, can create database? false by default
createrole : false # optional, can create role? false by default
inherit : true # optional, can this role use inherited privileges? true by default
replication : false # optional, can this role do replication? false by default
bypassrls : false # optional, can this role bypass row level security? false by default
pgbouncer : true # optional, add this user to pgbouncer user-list? false by default (production user should be true explicitly)
connlimit : -1 # optional, user connection limit, default -1 disable limit
expire_in : 3650 # optional, now + n days when this role is expired (OVERWRITE expire_at)
expire_at : '2030-12-31' # optional, YYYY-MM-DD 'timestamp' when this role is expired (OVERWRITTEN by expire_in)
comment : pigsty admin user # optional, comment string for this user/role
roles: [dbrole_admin] # optional, belonged roles. default roles are : dbrole_{admin,readonly,readwrite,offline}
parameters : {} # optional, role level parameters with `ALTER ROLE SET`
pool_mode : transaction # optional, pgbouncer pool mode at user level, transaction by default
pool_connlimit : -1 # optional, max database connections at user level, default -1 disable limit
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly], comment : read-only viewer for meta database}
#- {name: dbuser_grafana ,password: DBUser.Grafana ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for grafana database }
#- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for bytebase database }
#- {name: dbuser_gitea ,password: DBUser.Gitea ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for gitea service }
#- {name: dbuser_wiki ,password: DBUser.Wiki ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for wiki.js service }
# define business service here: https://doc.pgsty.com/pgsql/service
pg_services : # extra services in addition to pg_default_services, array of service definition
# standby service will route {ip|name}:5435 to sync replica's pgbouncer (5435->6432 standby)
- name: standby # required, service name, the actual svc name will be prefixed with `pg_cluster`, e.g : pg-meta-standby
port : 5435 # required, service exposed port (work as kubernetes service node port mode)
ip : "*" # optional, service bind ip address, `*` for all ip by default
selector : "[]" # required, service member selector, use JMESPath to filter inventory
dest : default # optional, destination port, default|postgres|pgbouncer|<port_number>, 'default' by default
check : /sync # optional, health check url path, / by default
backup : "[? pg_role == `primary`]" # backup server selector
maxconn : 3000 # optional, max allowed front-end connection
balance: roundrobin # optional, haproxy load balance algorithm (roundrobin by default, other : leastconn)
options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
# define pg extensions: https://doc.pgsty.com/pgsql/extension
pg_libs : 'pg_stat_statements, auto_explain' # add timescaledb to shared_preload_libraries
#pg_extensions: [] # extensions to be installed on this cluster
# define HBA rules here: https://doc.pgsty.com/pgsql/hba
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
node_crontab : # make a full backup 1 am everyday
- '00 01 * * * postgres /pg/bin/pg-backup full'
#----------------------------------#
# pgsql cluster: pg-test (3 nodes) #
#----------------------------------#
# pg-test ---> 10.10.10.3 ---> 10.10.10.1{1,2,3}
pg-test : # define the new 3-node cluster pg-test
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary } # primary instance, leader of cluster
10.10.10.12 : { pg_seq: 2, pg_role : replica } # replica instance, follower of leader
10.10.10.13 : { pg_seq: 3, pg_role: replica, pg_offline_query : true } # replica with offline access
vars :
pg_cluster : pg-test # define pgsql cluster name
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] }]
pg_databases : [ { name : test }] # create a database and user named 'test'
node_tune : tiny
pg_conf : tiny.yml
pg_vip_enabled : true
pg_vip_address : 10.10.10.3 /24
pg_vip_interface : eth1
node_crontab : # make a full backup on monday 1am, and an incremental backup during weekdays
- '00 01 * * 1 postgres /pg/bin/pg-backup full'
- '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
#----------------------------------#
# redis ms, sentinel, native cluster
#----------------------------------#
redis-ms : # redis classic primary & replica
hosts : { 10.10.10.10 : { redis_node: 1 , redis_instances : { 6379 : { }, 6380 : { replica_of : '10.10.10.10 6379' } } } }
vars : { redis_cluster: redis-ms ,redis_password: 'redis.ms' ,redis_max_memory : 64MB }
redis-meta : # redis sentinel x 3
hosts : { 10.10.10.11 : { redis_node: 1 , redis_instances : { 26379 : { } ,26380 : { } ,26381 : { } } } }
vars :
redis_cluster : redis-meta
redis_password : 'redis.meta'
redis_mode : sentinel
redis_max_memory : 16MB
redis_sentinel_monitor : # primary list for redis sentinel, use cls as name, primary ip:port
- { name: redis-ms, host: 10.10.10.10, port: 6379 ,password: redis.ms, quorum : 2 }
redis-test: # redis native cluster : 3m x 3s
hosts :
10.10.10.12 : { redis_node: 1 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
10.10.10.13 : { redis_node: 2 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
vars : { redis_cluster: redis-test ,redis_password: 'redis.test' ,redis_mode: cluster, redis_max_memory : 32MB }
####################################################################
# VARS #
####################################################################
vars : # global variables
#================================================================#
# VARS: INFRA #
#================================================================#
#-----------------------------------------------------------------
# META
#-----------------------------------------------------------------
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
language: en # default language : en, zh
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
#-----------------------------------------------------------------
# CA
#-----------------------------------------------------------------
ca_create : true # create ca if not exists? or just abort
ca_cn : pigsty-ca # ca common name, fixed as pigsty-ca
cert_validity : 7300d # cert validity, 20 years by default
#-----------------------------------------------------------------
# INFRA_IDENTITY
#-----------------------------------------------------------------
#infra_seq: 1 # infra node identity, explicitly required
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
infra_data : /data/infra # default data path for infrastructure data
#-----------------------------------------------------------------
# REPO
#-----------------------------------------------------------------
repo_enabled : true # create a yum repo on this infra node?
repo_home : /www # repo home dir, `/www` by default
repo_name : pigsty # repo name, pigsty by default
repo_endpoint : http://${admin_ip}:80 # access point to this repo by domain or ip:port
repo_remove : true # remove existing upstream repo
repo_modules : infra,node,pgsql # which repo modules are installed in repo_upstream
repo_upstream : # where to download
- { name: pigsty-local ,description: 'Pigsty Local' ,module: local ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://${admin_ip}/pigsty' }} # used by intranet nodes
- { name: pigsty-infra ,description: 'Pigsty INFRA' ,module: infra ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://repo.pigsty.io/yum/infra/$basearch' ,china : 'https://repo.pigsty.cc/yum/infra/$basearch' }}
- { name: pigsty-pgsql ,description: 'Pigsty PGSQL' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://repo.pigsty.io/yum/pgsql/el$releasever.$basearch' ,china : 'https://repo.pigsty.cc/yum/pgsql/el$releasever.$basearch' }}
- { name: nginx ,description: 'Nginx Repo' ,module: infra ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://nginx.org/packages/rhel/$releasever/$basearch/' }}
- { name: docker-ce ,description: 'Docker CE' ,module: infra ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.docker.com/linux/centos/$releasever/$basearch/stable' ,china: 'https://mirrors.aliyun.com/docker-ce/linux/centos/$releasever/$basearch/stable' ,europe : 'https://mirrors.xtom.de/docker-ce/linux/centos/$releasever/$basearch/stable' }}
- { name: baseos ,description: 'EL 8+ BaseOS' ,module: node ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/BaseOS/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/BaseOS/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/BaseOS/$basearch/os/' }}
- { name: appstream ,description: 'EL 8+ AppStream' ,module: node ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/AppStream/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/AppStream/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/AppStream/$basearch/os/' }}
- { name: extras ,description: 'EL 8+ Extras' ,module: node ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/extras/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/extras/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/extras/$basearch/os/' }}
- { name: powertools ,description: 'EL 8 PowerTools' ,module: node ,releases: [8 ] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/PowerTools/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/PowerTools/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/PowerTools/$basearch/os/' }}
- { name: crb ,description: 'EL 9 CRB' ,module: node ,releases: [ 9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://dl.rockylinux.org/pub/rocky/$releasever/CRB/$basearch/os/' ,china: 'https://mirrors.aliyun.com/rockylinux/$releasever/CRB/$basearch/os/' ,europe : 'https://mirrors.xtom.de/rocky/$releasever/CRB/$basearch/os/' }}
- { name: epel ,description: 'EL 8+ EPEL' ,module: node ,releases: [8,9 ] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://mirrors.edge.kernel.org/fedora-epel/$releasever/Everything/$basearch/' ,china: 'https://mirrors.aliyun.com/epel/$releasever/Everything/$basearch/' ,europe : 'https://mirrors.xtom.de/epel/$releasever/Everything/$basearch/' }}
- { name: epel ,description: 'EL 10 EPEL' ,module: node ,releases: [ 10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://mirrors.edge.kernel.org/fedora-epel/$releasever.0/Everything/$basearch/' ,china: 'https://mirrors.aliyun.com/epel/$releasever.0/Everything/$basearch/' ,europe : 'https://mirrors.xtom.de/epel/$releasever.0/Everything/$basearch/' }}
- { name: pgdg-common ,description: 'PostgreSQL Common' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/common/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg-el8fix ,description: 'PostgreSQL EL8FIX' ,module: pgsql ,releases: [8 ] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-$basearch/' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-$basearch/' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-centos8-sysupdates/redhat/rhel-8-$basearch/' }}
- { name: pgdg-el9fix ,description: 'PostgreSQL EL9FIX' ,module: pgsql ,releases: [ 9 ] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-$basearch/' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-$basearch/' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-rocky9-sysupdates/redhat/rhel-9-$basearch/' }}
- { name: pgdg-el10fix ,description: 'PostgreSQL EL10FIX' ,module: pgsql ,releases: [ 10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/common/pgdg-rocky10-sysupdates/redhat/rhel-10-$basearch/' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/common/pgdg-rocky10-sysupdates/redhat/rhel-10-$basearch/' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/common/pgdg-rocky10-sysupdates/redhat/rhel-10-$basearch/' }}
- { name: pgdg13 ,description: 'PostgreSQL 13' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/13/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/13/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/13/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg14 ,description: 'PostgreSQL 14' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/14/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/14/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/14/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg15 ,description: 'PostgreSQL 15' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/15/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/15/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/15/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg16 ,description: 'PostgreSQL 16' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/16/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/16/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/16/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg17 ,description: 'PostgreSQL 17' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/17/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/17/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/17/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg18 ,description: 'PostgreSQL 18' ,module: pgsql ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/18/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/18/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/18/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg-beta ,description: 'PostgreSQL Testing' ,module: beta ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/testing/19/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/testing/19/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/testing/19/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg-extras ,description: 'PostgreSQL Extra' ,module: extra ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/extras/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/extras/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/extras/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg13-nonfree ,description: 'PostgreSQL 13+' ,module: extra ,releases: [8,9,10] ,arch: [x86_64 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/non-free/13/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/non-free/13/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/non-free/13/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg14-nonfree ,description: 'PostgreSQL 14+' ,module: extra ,releases: [8,9,10] ,arch: [x86_64 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/non-free/14/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/non-free/14/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/non-free/14/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg15-nonfree ,description: 'PostgreSQL 15+' ,module: extra ,releases: [8,9,10] ,arch: [x86_64 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/non-free/15/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/non-free/15/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/non-free/15/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg16-nonfree ,description: 'PostgreSQL 16+' ,module: extra ,releases: [8,9,10] ,arch: [x86_64 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/non-free/16/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/non-free/16/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/non-free/16/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg17-nonfree ,description: 'PostgreSQL 17+' ,module: extra ,releases: [8,9,10] ,arch: [x86_64 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/non-free/17/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/non-free/17/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/non-free/17/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg18-nonfree ,description: 'PostgreSQL 18+' ,module: extra ,releases: [8,9,10] ,arch: [x86_64 ] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/non-free/18/redhat/rhel-$releasever-$basearch' ,china: 'https://mirrors.aliyun.com/postgresql/repos/yum/non-free/18/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/non-free/18/redhat/rhel-$releasever-$basearch' }}
- { name: timescaledb ,description: 'TimescaleDB' ,module: extra ,releases: [8,9 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packagecloud.io/timescale/timescaledb/el/$releasever/$basearch' }}
- { name: percona ,description: 'Percona TDE' ,module: percona ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://repo.pigsty.io/yum/percona/el$releasever.$basearch' ,china: 'https://repo.pigsty.cc/yum/percona/el$releasever.$basearch' ,origin : 'http://repo.percona.com/ppg-18.1/yum/release/$releasever/RPMS/$basearch' }}
- { name: wiltondb ,description: 'WiltonDB' ,module: mssql ,releases: [8,9 ] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://repo.pigsty.io/yum/mssql/el$releasever.$basearch', china: 'https://repo.pigsty.cc/yum/mssql/el$releasever.$basearch' , origin : 'https://download.copr.fedorainfracloud.org/results/wiltondb/wiltondb/epel-$releasever-$basearch/' }}
- { name: groonga ,description: 'Groonga' ,module: groonga ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packages.groonga.org/almalinux/$releasever/$basearch/' }}
- { name: mysql ,description: 'MySQL' ,module: mysql ,releases: [8,9 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://repo.mysql.com/yum/mysql-8.4-community/el/$releasever/$basearch/' }}
- { name: mongo ,description: 'MongoDB' ,module: mongo ,releases: [8,9 ] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/8.0/$basearch/' ,china : 'https://mirrors.aliyun.com/mongodb/yum/redhat/$releasever/mongodb-org/8.0/$basearch/' }}
- { name: redis ,description: 'Redis' ,module: redis ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://rpmfind.net/linux/remi/enterprise/$releasever/redis72/$basearch/' }}
- { name: grafana ,description: 'Grafana' ,module: grafana ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://rpm.grafana.com', china : 'https://mirrors.aliyun.com/grafana/yum/' }}
- { name: kubernetes ,description: 'Kubernetes' ,module: kube ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://pkgs.k8s.io/core:/stable:/v1.33/rpm/', china : 'https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.33/rpm/' }}
- { name: gitlab-ee ,description: 'Gitlab EE' ,module: gitlab ,releases: [8,9 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packages.gitlab.com/gitlab/gitlab-ee/el/$releasever/$basearch' }}
- { name: gitlab-ce ,description: 'Gitlab CE' ,module: gitlab ,releases: [8,9 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packages.gitlab.com/gitlab/gitlab-ce/el/$releasever/$basearch' }}
- { name: clickhouse ,description: 'ClickHouse' ,module: click ,releases: [8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://packages.clickhouse.com/rpm/stable/', china : 'https://mirrors.aliyun.com/clickhouse/rpm/stable/' }}
repo_packages : [ node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules ]
repo_extra_packages : [ pgsql-main ]
repo_url_packages : []
#-----------------------------------------------------------------
# INFRA_PACKAGE
#-----------------------------------------------------------------
infra_packages : # packages to be installed on infra nodes
- grafana,grafana-plugins,grafana-victorialogs-ds,grafana-victoriametrics-ds,victoria-metrics,victoria-logs,victoria-traces,vmutils,vlogscli,alertmanager
- node_exporter,blackbox_exporter,nginx_exporter,pg_exporter,pev2,nginx,dnsmasq,ansible,etcd,python3-requests,redis,mcli,restic,certbot,python3-certbot-nginx
infra_packages_pip : '' # pip installed packages for infra nodes
#-----------------------------------------------------------------
# NGINX
#-----------------------------------------------------------------
nginx_enabled : true # enable nginx on this infra node?
nginx_clean : false # clean existing nginx config during init?
nginx_exporter_enabled : true # enable nginx_exporter on this infra node?
nginx_exporter_port : 9113 # nginx_exporter listen port, 9113 by default
nginx_sslmode : enable # nginx ssl mode? disable,enable,enforce
nginx_cert_validity : 397d # nginx self-signed cert validity, 397d by default
nginx_home : /www # nginx content dir, `/www` by default (soft link to nginx_data)
nginx_data : /data/nginx # nginx actual data dir, /data/nginx by default
nginx_users : { admin : pigsty } # nginx basic auth users : name and pass dict
nginx_port : 80 # nginx listen port, 80 by default
nginx_ssl_port : 443 # nginx ssl listen port, 443 by default
certbot_sign : false # sign nginx cert with certbot during setup?
certbot_email : your@email.com # certbot email address, used for free ssl
certbot_options : '' # certbot extra options
#-----------------------------------------------------------------
# DNS
#-----------------------------------------------------------------
dns_enabled : true # setup dnsmasq on this infra node?
dns_port : 53 # dns server listen port, 53 by default
dns_records : # dynamic dns records resolved by dnsmasq
- "${admin_ip} i.pigsty"
- "${admin_ip} m.pigsty supa.pigsty api.pigsty adm.pigsty cli.pigsty ddl.pigsty"
#-----------------------------------------------------------------
# VICTORIA
#-----------------------------------------------------------------
vmetrics_enabled : true # enable victoria-metrics on this infra node?
vmetrics_clean : false # whether clean existing victoria metrics data during init?
vmetrics_port : 8428 # victoria-metrics listen port, 8428 by default
vmetrics_scrape_interval : 10s # victoria global scrape interval, 10s by default
vmetrics_scrape_timeout : 8s # victoria global scrape timeout, 8s by default
vmetrics_options : >-
-retentionPeriod=15d
-promscrape.fileSDCheckInterval=5s
vlogs_enabled : true # enable victoria-logs on this infra node?
vlogs_clean : false # clean victoria-logs data during init?
vlogs_port : 9428 # victoria-logs listen port, 9428 by default
vlogs_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
-insert.maxLineSizeBytes=1MB
-search.maxQueryDuration=120s
vtraces_enabled : true # enable victoria-traces on this infra node?
vtraces_clean : false # clean victoria-trace data during inti?
vtraces_port : 10428 # victoria-traces listen port, 10428 by default
vtraces_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
vmalert_enabled : true # enable vmalert on this infra node?
vmalert_port : 8880 # vmalert listen port, 8880 by default
vmalert_options : '' # vmalert extra server options
#-----------------------------------------------------------------
# PROMETHEUS
#-----------------------------------------------------------------
blackbox_enabled : true # setup blackbox_exporter on this infra node?
blackbox_port : 9115 # blackbox_exporter listen port, 9115 by default
blackbox_options : '' # blackbox_exporter extra server options
alertmanager_enabled : true # setup alertmanager on this infra node?
alertmanager_port : 9059 # alertmanager listen port, 9059 by default
alertmanager_options : '' # alertmanager extra server options
exporter_metrics_path : /metrics # exporter metric path, `/metrics` by default
#-----------------------------------------------------------------
# GRAFANA
#-----------------------------------------------------------------
grafana_enabled : true # enable grafana on this infra node?
grafana_port : 3000 # default listen port for grafana
grafana_clean : true # clean grafana data during init?
grafana_admin_username : admin # grafana admin username, `admin` by default
grafana_admin_password : pigsty # grafana admin password, `pigsty` by default
grafana_auth_proxy : false # enable grafana auth proxy?
grafana_pgurl : '' # external postgres database url for grafana if given
grafana_view_password : DBUser.Viewer # password for grafana meta pg datasource
#================================================================#
# VARS: NODE #
#================================================================#
#-----------------------------------------------------------------
# NODE_IDENTITY
#-----------------------------------------------------------------
#nodename: # [INSTANCE] # node instance identity, use hostname if missing, optional
node_cluster : nodes # [CLUSTER] # node cluster identity, use 'nodes' if missing, optional
nodename_overwrite : true # overwrite node's hostname with nodename?
nodename_exchange : false # exchange nodename among play hosts?
node_id_from_pg : true # use postgres identity as node identity if applicable?
#-----------------------------------------------------------------
# NODE_DNS
#-----------------------------------------------------------------
node_write_etc_hosts : true # modify `/etc/hosts` on target node?
node_default_etc_hosts : # static dns records in `/etc/hosts`
- "${admin_ip} i.pigsty"
node_etc_hosts : [] # extra static dns records in `/etc/hosts`
node_dns_method: add # how to handle dns servers : add,none,overwrite
node_dns_servers : [ '${admin_ip}' ] # dynamic nameserver in `/etc/resolv.conf`
node_dns_options : # dns resolv options in `/etc/resolv.conf`
- options single-request-reopen timeout:1
#-----------------------------------------------------------------
# NODE_PACKAGE
#-----------------------------------------------------------------
node_repo_modules : local # upstream repo to be added on node, local by default
node_repo_remove : true # remove existing repo on node?
node_packages : [ openssh-server] # packages to be installed current nodes with latest version
node_default_packages : # default packages to be installed on all nodes
- lz4,unzip,bzip2,pv,jq,git,ncdu,make,patch,bash,lsof,wget,uuid,tuned,nvme-cli,numactl,sysstat,iotop,htop,rsync,tcpdump
- python3,python3-pip,socat,lrzsz,net-tools,ipvsadm,telnet,ca-certificates,openssl,keepalived,etcd,haproxy,chrony,pig
- zlib,yum,audit,bind-utils,readline,vim-minimal,node_exporter,grubby,openssh-server,openssh-clients,chkconfig,vector
#-----------------------------------------------------------------
# NODE_SEC
#-----------------------------------------------------------------
node_selinux_mode: permissive # set selinux mode : enforcing,permissive,disabled
node_firewall_mode: zone # firewall mode : off , none, zone, zone by default
node_firewall_intranet : # which intranet cidr considered as internal network
- 10.0.0.0 /8
- 192.168.0.0 /16
- 172.16.0.0 /12
node_firewall_public_port : # expose these ports to public network in (zone, strict) mode
- 22 # enable ssh access
- 80 # enable http access
- 443 # enable https access
- 5432 # enable postgresql access (think twice before exposing it!)
#-----------------------------------------------------------------
# NODE_TUNE
#-----------------------------------------------------------------
node_disable_numa : false # disable node numa, reboot required
node_disable_swap : false # disable node swap, use with caution
node_static_network : true # preserve dns resolver settings after reboot
node_disk_prefetch : false # setup disk prefetch on HDD to increase performance
node_kernel_modules : [ softdog, ip_vs, ip_vs_rr, ip_vs_wrr, ip_vs_sh ]
node_hugepage_count : 0 # number of 2MB hugepage, take precedence over ratio
node_hugepage_ratio : 0 # node mem hugepage ratio, 0 disable it by default
node_overcommit_ratio : 0 # node mem overcommit ratio, 0 disable it by default
node_tune: oltp # node tuned profile : none,oltp,olap,crit,tiny
node_sysctl_params : { } # sysctl parameters in k:v format in addition to tuned
#-----------------------------------------------------------------
# NODE_ADMIN
#-----------------------------------------------------------------
node_data : /data # node main data directory, `/data` by default
node_admin_enabled : true # create a admin user on target node?
node_admin_uid : 88 # uid and gid for node admin user
node_admin_username : dba # name of node admin user, `dba` by default
node_admin_sudo : nopass # admin sudo privilege, all,nopass. nopass by default
node_admin_ssh_exchange : true # exchange admin ssh key among node cluster
node_admin_pk_current : true # add current user's ssh pk to admin authorized_keys
node_admin_pk_list : [] # ssh public keys to be added to admin user
node_aliases : {} # extra shell aliases to be added, k:v dict
#-----------------------------------------------------------------
# NODE_TIME
#-----------------------------------------------------------------
node_timezone : '' # setup node timezone, empty string to skip
node_ntp_enabled : true # enable chronyd time sync service?
node_ntp_servers : # ntp servers in `/etc/chrony.conf`
- pool pool.ntp.org iburst
node_crontab_overwrite : true # overwrite or append to `/etc/crontab`?
node_crontab : [ ] # crontab entries in `/etc/crontab`
#-----------------------------------------------------------------
# NODE_VIP
#-----------------------------------------------------------------
vip_enabled : false # enable vip on this node cluster?
# vip_address: [IDENTITY] # node vip address in ipv4 format, required if vip is enabled
# vip_vrid: [IDENTITY] # required, integer, 1-254, should be unique among same VLAN
vip_role : backup # optional, `master|backup`, backup by default, use as init role
vip_preempt : false # optional, `true/false`, false by default, enable vip preemption
vip_interface : eth0 # node vip network interface to listen, `eth0` by default
vip_dns_suffix : '' # node vip dns name suffix, empty string by default
vip_exporter_port : 9650 # keepalived exporter listen port, 9650 by default
#-----------------------------------------------------------------
# HAPROXY
#-----------------------------------------------------------------
haproxy_enabled : true # enable haproxy on this node?
haproxy_clean : false # cleanup all existing haproxy config?
haproxy_reload : true # reload haproxy after config?
haproxy_auth_enabled : true # enable authentication for haproxy admin page
haproxy_admin_username : admin # haproxy admin username, `admin` by default
haproxy_admin_password : pigsty # haproxy admin password, `pigsty` by default
haproxy_exporter_port : 9101 # haproxy admin/exporter port, 9101 by default
haproxy_client_timeout : 24h # client side connection timeout, 24h by default
haproxy_server_timeout : 24h # server side connection timeout, 24h by default
haproxy_services : [] # list of haproxy service to be exposed on node
#-----------------------------------------------------------------
# NODE_EXPORTER
#-----------------------------------------------------------------
node_exporter_enabled : true # setup node_exporter on this node?
node_exporter_port : 9100 # node exporter listen port, 9100 by default
node_exporter_options : '--no-collector.softnet --no-collector.nvme --collector.tcpstat --collector.processes'
#-----------------------------------------------------------------
# VECTOR
#-----------------------------------------------------------------
vector_enabled : true # enable vector log collector?
vector_clean : false # purge vector data dir during init?
vector_data : /data/vector # vector data dir, /data/vector by default
vector_port : 9598 # vector metrics port, 9598 by default
vector_read_from : beginning # vector read from beginning or end
vector_log_endpoint : [ infra ] # if defined, sending vector log to this endpoint.
#================================================================#
# VARS: DOCKER #
#================================================================#
docker_enabled : false # enable docker on this node?
docker_data : /var/lib/docker # docker data directory, /var/lib/docker by default
docker_storage_driver : overlay2 # docker storage driver, can be zfs, btrfs
docker_cgroups_driver: systemd # docker cgroup fs driver : cgroupfs,systemd
docker_registry_mirrors : [] # docker registry mirror list
docker_exporter_port : 9323 # docker metrics exporter port, 9323 by default
docker_image : [] # docker image to be pulled after bootstrap
docker_image_cache : /tmp/docker/*.tgz # docker image cache glob pattern
#================================================================#
# VARS: ETCD #
#================================================================#
#etcd_seq: 1 # etcd instance identifier, explicitly required
etcd_cluster : etcd # etcd cluster & group name, etcd by default
etcd_safeguard : false # prevent purging running etcd instance?
etcd_clean : true # purging existing etcd during initialization?
etcd_data : /data/etcd # etcd data directory, /data/etcd by default
etcd_port : 2379 # etcd client port, 2379 by default
etcd_peer_port : 2380 # etcd peer port, 2380 by default
etcd_init : new # etcd initial cluster state, new or existing
etcd_election_timeout : 1000 # etcd election timeout, 1000ms by default
etcd_heartbeat_interval : 100 # etcd heartbeat interval, 100ms by default
etcd_root_password : Etcd.Root # etcd root password for RBAC, change it!
#================================================================#
# VARS: MINIO #
#================================================================#
#minio_seq: 1 # minio instance identifier, REQUIRED
minio_cluster : minio # minio cluster identifier, REQUIRED
minio_clean : false # cleanup minio during init?, false by default
minio_user : minio # minio os user, `minio` by default
minio_https : true # use https for minio, true by default
minio_node : '${minio_cluster}-${minio_seq}.pigsty' # minio node name pattern
minio_data : '/data/minio' # minio data dir(s), use {x...y} to specify multi drivers
#minio_volumes: # minio data volumes, override defaults if specified
minio_domain : sss.pigsty # minio external domain name, `sss.pigsty` by default
minio_port : 9000 # minio service port, 9000 by default
minio_admin_port : 9001 # minio console port, 9001 by default
minio_access_key : minioadmin # root access key, `minioadmin` by default
minio_secret_key : S3User.MinIO # root secret key, `S3User.MinIO` by default
minio_extra_vars : '' # extra environment variables
minio_provision : true # run minio provisioning tasks?
minio_alias : sss # alias name for local minio deployment
#minio_endpoint: https://sss.pigsty:9000 # if not specified, overwritten by defaults
minio_buckets : # list of minio bucket to be created
- { name : pgsql }
- { name: meta ,versioning : true }
- { name : data }
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
#================================================================#
# VARS: REDIS #
#================================================================#
#redis_cluster: <CLUSTER> # redis cluster name, required identity parameter
#redis_node: 1 <NODE> # redis node sequence number, node int id required
#redis_instances: {} <NODE> # redis instances definition on this redis node
redis_fs_main : /data # redis main data mountpoint, `/data` by default
redis_exporter_enabled : true # install redis exporter on redis nodes?
redis_exporter_port : 9121 # redis exporter listen port, 9121 by default
redis_exporter_options : '' # cli args and extra options for redis exporter
redis_safeguard : false # prevent purging running redis instance?
redis_clean : true # purging existing redis during init?
redis_rmdata : true # remove redis data when purging redis server?
redis_mode: standalone # redis mode : standalone,cluster,sentinel
redis_conf : redis.conf # redis config template path, except sentinel
redis_bind_address : '0.0.0.0' # redis bind address, empty string will use host ip
redis_max_memory : 1GB # max memory used by each redis instance
redis_mem_policy : allkeys-lru # redis memory eviction policy
redis_password : '' # redis password, empty string will disable password
redis_rdb_save : [ '1200 1' ] # redis rdb save directives, disable with empty list
redis_aof_enabled : false # enable redis append only file?
redis_rename_commands : {} # rename redis dangerous commands
redis_cluster_replicas : 1 # replica number for one master in redis cluster
redis_sentinel_monitor : [] # sentinel master list, works on sentinel cluster only
#================================================================#
# VARS: PGSQL #
#================================================================#
#-----------------------------------------------------------------
# PG_IDENTITY
#-----------------------------------------------------------------
pg_mode: pgsql #CLUSTER # pgsql cluster mode : pgsql,citus,gpsql,mssql,mysql,ivory,polar
# pg_cluster: #CLUSTER # pgsql cluster name, required identity parameter
# pg_seq: 0 #INSTANCE # pgsql instance seq number, required identity parameter
# pg_role: replica #INSTANCE # pgsql role, required, could be primary,replica,offline
# pg_instances: {} #INSTANCE # define multiple pg instances on node in `{port:ins_vars}` format
# pg_upstream: #INSTANCE # repl upstream ip addr for standby cluster or cascade replica
# pg_shard: #CLUSTER # pgsql shard name, optional identity for sharding clusters
# pg_group: 0 #CLUSTER # pgsql shard index number, optional identity for sharding clusters
# gp_role: master #CLUSTER # greenplum role of this cluster, could be master or segment
pg_offline_query : false #INSTANCE # set to true to enable offline queries on this instance
#-----------------------------------------------------------------
# PG_BUSINESS
#-----------------------------------------------------------------
# postgres business object definition, overwrite in group vars
pg_users : [] # postgres business users
pg_databases : [] # postgres business databases
pg_services : [] # postgres business services
pg_hba_rules : [] # business hba rules for postgres
pgb_hba_rules : [] # business hba rules for pgbouncer
# global credentials, overwrite in global vars
pg_dbsu_password : '' # dbsu password, empty string means no dbsu password by default
pg_replication_username : replicator
pg_replication_password : DBUser.Replicator
pg_admin_username : dbuser_dba
pg_admin_password : DBUser.DBA
pg_monitor_username : dbuser_monitor
pg_monitor_password : DBUser.Monitor
#-----------------------------------------------------------------
# PG_INSTALL
#-----------------------------------------------------------------
pg_dbsu : postgres # os dbsu name, postgres by default, better not change it
pg_dbsu_uid : 26 # os dbsu uid and gid, 26 for default postgres users and groups
pg_dbsu_sudo : limit # dbsu sudo privilege, none,limit,all,nopass. limit by default
pg_dbsu_home : /var/lib/pgsql # postgresql home directory, `/var/lib/pgsql` by default
pg_dbsu_ssh_exchange : true # exchange postgres dbsu ssh key among same pgsql cluster
pg_version : 18 # postgres major version to be installed, 17 by default
pg_bin_dir : /usr/pgsql/bin # postgres binary dir, `/usr/pgsql/bin` by default
pg_log_dir : /pg/log/postgres # postgres log dir, `/pg/log/postgres` by default
pg_packages : # pg packages to be installed, alias can be used
- pgsql-main pgsql-common
pg_extensions : [] # pg extensions to be installed, alias can be used
#-----------------------------------------------------------------
# PG_BOOTSTRAP
#-----------------------------------------------------------------
pg_data : /pg/data # postgres data directory, `/pg/data` by default
pg_fs_main : /data/postgres # postgres main data directory, `/data/postgres` by default
pg_fs_backup : /data/backups # postgres backup data directory, `/data/backups` by default
pg_storage_type : SSD # storage type for pg main data, SSD,HDD, SSD by default
pg_dummy_filesize : 64MiB # size of `/pg/dummy`, hold 64MB disk space for emergency use
pg_listen : '0.0.0.0' # postgres/pgbouncer listen addresses, comma separated list
pg_port : 5432 # postgres listen port, 5432 by default
pg_localhost : /var/run/postgresql # postgres unix socket dir for localhost connection
patroni_enabled : true # if disabled, no postgres cluster will be created during init
patroni_mode: default # patroni working mode : default,pause,remove
pg_namespace : /pg # top level key namespace in etcd, used by patroni & vip
patroni_port : 8008 # patroni listen port, 8008 by default
patroni_log_dir : /pg/log/patroni # patroni log dir, `/pg/log/patroni` by default
patroni_ssl_enabled : false # secure patroni RestAPI communications with SSL?
patroni_watchdog_mode: off # patroni watchdog mode : automatic,required,off. off by default
patroni_username : postgres # patroni restapi username, `postgres` by default
patroni_password : Patroni.API # patroni restapi password, `Patroni.API` by default
pg_etcd_password : '' # etcd password for this pg cluster, '' to use pg_cluster
pg_primary_db : postgres # primary database name, used by citus,etc... ,postgres by default
pg_parameters : {} # extra parameters in postgresql.auto.conf
pg_files : [] # extra files to be copied to postgres data directory (e.g. license)
pg_conf: oltp.yml # config template : oltp,olap,crit,tiny. `oltp.yml` by default
pg_max_conn : auto # postgres max connections, `auto` will use recommended value
pg_shared_buffer_ratio : 0.25 # postgres shared buffers ratio, 0.25 by default, 0.1~0.4
pg_io_method : worker # io method for postgres, auto,fsync,worker,io_uring, auto by default
pg_rto : 30 # recovery time objective in seconds, `30s` by default
pg_rpo : 1048576 # recovery point objective in bytes, `1MiB` at most by default
pg_libs : 'pg_stat_statements, auto_explain' # preloaded libraries, `pg_stat_statements,auto_explain` by default
pg_delay : 0 # replication apply delay for standby cluster leader
pg_checksum : true # enable data checksum for postgres cluster?
pg_encoding : UTF8 # database cluster encoding, `UTF8` by default
pg_locale : C # database cluster local, `C` by default
pg_lc_collate : C # database cluster collate, `C` by default
pg_lc_ctype : C # database character type, `C` by default
#pgsodium_key: "" # pgsodium key, 64 hex digit, default to sha256(pg_cluster)
#pgsodium_getkey_script: "" # pgsodium getkey script path, pgsodium_getkey by default
#-----------------------------------------------------------------
# PG_PROVISION
#-----------------------------------------------------------------
pg_provision : true # provision postgres cluster after bootstrap
pg_init : pg-init # provision init script for cluster template, `pg-init` by default
pg_default_roles : # default roles and users in postgres cluster
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
pg_default_privileges : # default privileges when created by admin user
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
pg_default_schemas : [ monitor ] # default schemas to be created
pg_default_extensions : # default extensions to be created
- { name: pg_stat_statements ,schema : monitor }
- { name: pgstattuple ,schema : monitor }
- { name: pg_buffercache ,schema : monitor }
- { name: pageinspect ,schema : monitor }
- { name: pg_prewarm ,schema : monitor }
- { name: pg_visibility ,schema : monitor }
- { name: pg_freespacemap ,schema : monitor }
- { name: postgres_fdw ,schema : public }
- { name: file_fdw ,schema : public }
- { name: btree_gist ,schema : public }
- { name: btree_gin ,schema : public }
- { name: pg_trgm ,schema : public }
- { name: intagg ,schema : public }
- { name: intarray ,schema : public }
- { name : pg_repack }
pg_reload : true # reload postgres after hba changes
pg_default_hba_rules : # postgres default host-based authentication rules
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title : 'replicator replication from localhost' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title : 'replicator replication from intranet' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title : 'replicator postgres db from intranet' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title : 'monitor from infra host with password' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title : 'admin @ everywhere with ssl & pwd' }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title : 'pgbouncer read/write via local socket' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title : 'read/write biz user via password' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title : 'allow etl offline tasks from intranet' }
pgb_default_hba_rules : # pgbouncer default host-based authentication rules
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title : 'dbsu local admin access with os ident' }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title : 'allow all user local access with pwd' }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: pwd ,title : 'monitor access via intranet with pwd' }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other monitor access addr' }
- {user : '${admin}' ,db: all ,addr: intra ,auth: pwd ,title : 'admin access via intranet with pwd' }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other admin access addr' }
- {user: 'all' ,db: all ,addr: intra ,auth: pwd ,title : 'allow all user intra access with pwd' }
#-----------------------------------------------------------------
# PG_BACKUP
#-----------------------------------------------------------------
pgbackrest_enabled : true # enable pgbackrest on pgsql host?
pgbackrest_log_dir : /pg/log/pgbackrest # pgbackrest log dir, `/pg/log/pgbackrest` by default
pgbackrest_method: local # pgbackrest repo method : local,minio,[user-defined...]
pgbackrest_init_backup : true # take a full backup after pgbackrest is initialized?
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backups when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the the last 14 days
#-----------------------------------------------------------------
# PG_ACCESS
#-----------------------------------------------------------------
pgbouncer_enabled : true # if disabled, pgbouncer will not be launched on pgsql host
pgbouncer_port : 6432 # pgbouncer listen port, 6432 by default
pgbouncer_log_dir : /pg/log/pgbouncer # pgbouncer log dir, `/pg/log/pgbouncer` by default
pgbouncer_auth_query : false # query postgres to retrieve unlisted business users?
pgbouncer_poolmode: transaction # pooling mode : transaction,session,statement, transaction by default
pgbouncer_sslmode : disable # pgbouncer client ssl mode, disable by default
pgbouncer_ignore_param : [ extra_float_digits, application_name, TimeZone, DateStyle, IntervalStyle, search_path ]
pg_weight : 100 #INSTANCE # relative load balance weight in service, 100 by default, 0-255
pg_service_provider : '' # dedicate haproxy node group name, or empty string for local nodes by default
pg_default_service_dest : pgbouncer # default service destination if svc.dest='default'
pg_default_services : # postgres default service definitions
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
pg_vip_enabled : false # enable a l2 vip for pgsql primary? false by default
pg_vip_address : 127.0.0.1 /24 # vip address in `<ipv4>/<mask>` format, require if vip is enabled
pg_vip_interface : eth0 # vip network interface to listen, eth0 by default
pg_dns_suffix : '' # pgsql dns suffix, '' by default
pg_dns_target : auto # auto, primary, vip, none, or ad hoc ip
#-----------------------------------------------------------------
# PG_MONITOR
#-----------------------------------------------------------------
pg_exporter_enabled : true # enable pg_exporter on pgsql hosts?
pg_exporter_config : pg_exporter.yml # pg_exporter configuration file name
pg_exporter_cache_ttls : '1,10,60,300' # pg_exporter collector ttl stage in seconds, '1,10,60,300' by default
pg_exporter_port : 9630 # pg_exporter listen port, 9630 by default
pg_exporter_params : 'sslmode=disable' # extra url parameters for pg_exporter dsn
pg_exporter_url : '' # overwrite auto-generate pg dsn if specified
pg_exporter_auto_discovery : true # enable auto database discovery? enabled by default
pg_exporter_exclude_database : 'template0,template1,postgres' # csv of database that WILL NOT be monitored during auto-discovery
pg_exporter_include_database : '' # csv of database that WILL BE monitored during auto-discovery
pg_exporter_connect_timeout : 200 # pg_exporter connect timeout in ms, 200 by default
pg_exporter_options : '' # overwrite extra options for pg_exporter
pgbouncer_exporter_enabled : true # enable pgbouncer_exporter on pgsql hosts?
pgbouncer_exporter_port : 9631 # pgbouncer_exporter listen port, 9631 by default
pgbouncer_exporter_url : '' # overwrite auto-generate pgbouncer dsn if specified
pgbouncer_exporter_options : '' # overwrite extra options for pgbouncer_exporter
pgbackrest_exporter_enabled : true # enable pgbackrest_exporter on pgsql hosts?
pgbackrest_exporter_port : 9854 # pgbackrest_exporter listen port, 9854 by default
pgbackrest_exporter_options : >
--collect.interval=120
--log.level=info
#-----------------------------------------------------------------
# PG_REMOVE
#-----------------------------------------------------------------
pg_safeguard : false # stop pg_remove running if pg_safeguard is enabled, false by default
pg_rm_data : true # remove postgres data during remove? true by default
pg_rm_backup : true # remove pgbackrest backup during primary remove? true by default
pg_rm_pkg : true # uninstall postgres packages during remove? true by default
... 配置解读 demo/el 模板是针对 Enterprise Linux 系列发行版优化的配置。
支持的发行版 :
RHEL 8/9/10 Rocky Linux 8/9/10 Alma Linux 8/9/10 Oracle Linux 8/9 关键特性 :
使用 EPEL 和 PGDG 软件源 针对 YUM/DNF 包管理器优化 支持 EL 系列特定的软件包名称 适用场景 :
企业生产环境(推荐 RHEL/Rocky/Alma) 需要长期支持和稳定性保障 使用红帽生态系统的环境 9.32 - demo/debian Debian/Ubuntu 专用配置模板
demo/debian 配置模板是针对 Debian 和 Ubuntu 发行版优化的配置模板。
配置概览 配置名称: demo/debian 节点数量: 单节点 配置说明:Debian/Ubuntu 专用配置模板 适用系统:d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta ,demo/el 启用方式:
./configure -c demo/debian [ -i <primary_ip>]
配置内容 源文件地址:pigsty/conf/demo/debian.yml
---
#==============================================================#
# File : debian.yml
# Desc : Default parameters for Debian/Ubuntu in Pigsty
# Ctime : 2020-05-22
# Mtime : 2025-12-27
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
#==============================================================#
# Sandbox (4-node) #
#==============================================================#
# admin user : vagrant (nopass ssh & sudo already set) #
# 1. meta : 10.10.10.10 (2 Core | 4GB) pg-meta #
# 2. node-1 : 10.10.10.11 (1 Core | 1GB) pg-test-1 #
# 3. node-2 : 10.10.10.12 (1 Core | 1GB) pg-test-2 #
# 4. node-3 : 10.10.10.13 (1 Core | 1GB) pg-test-3 #
# (replace these ip if your 4-node env have different ip addr) #
# VIP 2: (l2 vip is available inside same LAN ) #
# pg-meta ---> 10.10.10.2 ---> 10.10.10.10 #
# pg-test ---> 10.10.10.3 ---> 10.10.10.1{1,2,3} #
#==============================================================#
all :
##################################################################
# CLUSTERS #
##################################################################
# meta nodes, nodes, pgsql, redis, pgsql clusters are defined as
# k:v pair inside `all.children`. Where the key is cluster name
# and value is cluster definition consist of two parts:
# `hosts`: cluster members ip and instance level variables
# `vars` : cluster level variables
##################################################################
children : # groups definition
# infra cluster for proxy, monitor, alert, etc..
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
# etcd cluster for ha postgres
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
# minio cluster, s3 compatible object storage
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
#----------------------------------#
# pgsql cluster: pg-meta (CMDB) #
#----------------------------------#
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role: primary , pg_offline_query : true } }
vars :
pg_cluster : pg-meta
# define business databases here: https://doc.pgsty.com/pgsql/db
pg_databases : # define business databases on this cluster, array of database definition
- name : meta # REQUIRED, `name` is the only mandatory field of a database definition
baseline: cmdb.sql # optional, database sql baseline path, (relative path among ansible search path, e.g : files/)
schemas : [ pigsty] # optional, additional schemas to be created, array of schema names
extensions: # optional, additional extensions to be installed : array of `{name[,schema]}`
- { name : vector } # install pgvector extension on this database by default
comment : pigsty meta database # optional, comment string for this database
#pgbouncer: true # optional, add this database to pgbouncer database list? true by default
#owner: postgres # optional, database owner, postgres by default
#template: template1 # optional, which template to use, template1 by default
#encoding: UTF8 # optional, database encoding, UTF8 by default. (MUST same as template database)
#locale: C # optional, database locale, C by default. (MUST same as template database)
#lc_collate: C # optional, database collate, C by default. (MUST same as template database)
#lc_ctype: C # optional, database ctype, C by default. (MUST same as template database)
#tablespace: pg_default # optional, default tablespace, 'pg_default' by default.
#allowconn: true # optional, allow connection, true by default. false will disable connect at all
#revokeconn: false # optional, revoke public connection privilege. false by default. (leave connect with grant option to owner)
#register_datasource: true # optional, register this database to grafana datasources? true by default
#connlimit: -1 # optional, database connection limit, default -1 disable limit
#pool_auth_user: dbuser_meta # optional, all connection to this pgbouncer database will be authenticated by this user
#pool_mode: transaction # optional, pgbouncer pool mode at database level, default transaction
#pool_size: 64 # optional, pgbouncer pool size at database level, default 64
#pool_size_reserve: 32 # optional, pgbouncer pool size reserve at database level, default 32
#pool_size_min: 0 # optional, pgbouncer pool size min at database level, default 0
#pool_max_db_conn: 100 # optional, max database connections at database level, default 100
#- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment: grafana primary database }
#- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment: bytebase primary database }
#- { name: kong ,owner: dbuser_kong ,revokeconn: true ,comment: kong the api gateway database }
#- { name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment: gitea meta database }
#- { name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment: wiki meta database }
# define business users here: https://doc.pgsty.com/pgsql/user
pg_users : # define business users/roles on this cluster, array of user definition
- name : dbuser_meta # REQUIRED, `name` is the only mandatory field of a user definition
password : DBUser.Meta # optional, password, can be a scram-sha-256 hash string or plain text
login : true # optional, can log in, true by default (new biz ROLE should be false)
superuser : false # optional, is superuser? false by default
createdb : false # optional, can create database? false by default
createrole : false # optional, can create role? false by default
inherit : true # optional, can this role use inherited privileges? true by default
replication : false # optional, can this role do replication? false by default
bypassrls : false # optional, can this role bypass row level security? false by default
pgbouncer : true # optional, add this user to pgbouncer user-list? false by default (production user should be true explicitly)
connlimit : -1 # optional, user connection limit, default -1 disable limit
expire_in : 3650 # optional, now + n days when this role is expired (OVERWRITE expire_at)
expire_at : '2030-12-31' # optional, YYYY-MM-DD 'timestamp' when this role is expired (OVERWRITTEN by expire_in)
comment : pigsty admin user # optional, comment string for this user/role
roles: [dbrole_admin] # optional, belonged roles. default roles are : dbrole_{admin,readonly,readwrite,offline}
parameters : {} # optional, role level parameters with `ALTER ROLE SET`
pool_mode : transaction # optional, pgbouncer pool mode at user level, transaction by default
pool_connlimit : -1 # optional, max database connections at user level, default -1 disable limit
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly], comment : read-only viewer for meta database}
#- {name: dbuser_grafana ,password: DBUser.Grafana ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for grafana database }
#- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for bytebase database }
#- {name: dbuser_gitea ,password: DBUser.Gitea ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for gitea service }
#- {name: dbuser_wiki ,password: DBUser.Wiki ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for wiki.js service }
# define business service here: https://doc.pgsty.com/pgsql/service
pg_services : # extra services in addition to pg_default_services, array of service definition
# standby service will route {ip|name}:5435 to sync replica's pgbouncer (5435->6432 standby)
- name: standby # required, service name, the actual svc name will be prefixed with `pg_cluster`, e.g : pg-meta-standby
port : 5435 # required, service exposed port (work as kubernetes service node port mode)
ip : "*" # optional, service bind ip address, `*` for all ip by default
selector : "[]" # required, service member selector, use JMESPath to filter inventory
dest : default # optional, destination port, default|postgres|pgbouncer|<port_number>, 'default' by default
check : /sync # optional, health check url path, / by default
backup : "[? pg_role == `primary`]" # backup server selector
maxconn : 3000 # optional, max allowed front-end connection
balance: roundrobin # optional, haproxy load balance algorithm (roundrobin by default, other : leastconn)
options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
# define pg extensions: https://doc.pgsty.com/pgsql/extension
pg_libs : 'pg_stat_statements, auto_explain' # add timescaledb to shared_preload_libraries
#pg_extensions: [] # extensions to be installed on this cluster
# define HBA rules here: https://doc.pgsty.com/pgsql/hba
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
pg_vip_enabled : true
pg_vip_address : 10.10.10.2 /24
pg_vip_interface : eth1
node_crontab : # make a full backup 1 am everyday
- '00 01 * * * postgres /pg/bin/pg-backup full'
#----------------------------------#
# pgsql cluster: pg-test (3 nodes) #
#----------------------------------#
# pg-test ---> 10.10.10.3 ---> 10.10.10.1{1,2,3}
pg-test : # define the new 3-node cluster pg-test
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary } # primary instance, leader of cluster
10.10.10.12 : { pg_seq: 2, pg_role : replica } # replica instance, follower of leader
10.10.10.13 : { pg_seq: 3, pg_role: replica, pg_offline_query : true } # replica with offline access
vars :
pg_cluster : pg-test # define pgsql cluster name
pg_users : [ { name: test , password: test , pgbouncer: true , roles : [ dbrole_admin ] }]
pg_databases : [ { name : test }] # create a database and user named 'test'
node_tune : tiny
pg_conf : tiny.yml
pg_vip_enabled : true
pg_vip_address : 10.10.10.3 /24
pg_vip_interface : eth1
node_crontab : # make a full backup on monday 1am, and an incremental backup during weekdays
- '00 01 * * 1 postgres /pg/bin/pg-backup full'
- '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
#----------------------------------#
# redis ms, sentinel, native cluster
#----------------------------------#
redis-ms : # redis classic primary & replica
hosts : { 10.10.10.10 : { redis_node: 1 , redis_instances : { 6379 : { }, 6380 : { replica_of : '10.10.10.10 6379' } } } }
vars : { redis_cluster: redis-ms ,redis_password: 'redis.ms' ,redis_max_memory : 64MB }
redis-meta : # redis sentinel x 3
hosts : { 10.10.10.11 : { redis_node: 1 , redis_instances : { 26379 : { } ,26380 : { } ,26381 : { } } } }
vars :
redis_cluster : redis-meta
redis_password : 'redis.meta'
redis_mode : sentinel
redis_max_memory : 16MB
redis_sentinel_monitor : # primary list for redis sentinel, use cls as name, primary ip:port
- { name: redis-ms, host: 10.10.10.10, port: 6379 ,password: redis.ms, quorum : 2 }
redis-test: # redis native cluster : 3m x 3s
hosts :
10.10.10.12 : { redis_node: 1 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
10.10.10.13 : { redis_node: 2 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
vars : { redis_cluster: redis-test ,redis_password: 'redis.test' ,redis_mode: cluster, redis_max_memory : 32MB }
####################################################################
# VARS #
####################################################################
vars : # global variables
#================================================================#
# VARS: INFRA #
#================================================================#
#-----------------------------------------------------------------
# META
#-----------------------------------------------------------------
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default,china,europe
language: en # default language : en, zh
proxy_env : # global proxy env when downloading packages
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
#-----------------------------------------------------------------
# CA
#-----------------------------------------------------------------
ca_create : true # create ca if not exists? or just abort
ca_cn : pigsty-ca # ca common name, fixed as pigsty-ca
cert_validity : 7300d # cert validity, 20 years by default
#-----------------------------------------------------------------
# INFRA_IDENTITY
#-----------------------------------------------------------------
#infra_seq: 1 # infra node identity, explicitly required
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
infra_data : /data/infra # default data path for infrastructure data
#-----------------------------------------------------------------
# REPO
#-----------------------------------------------------------------
repo_enabled : true # create a yum repo on this infra node?
repo_home : /www # repo home dir, `/www` by default
repo_name : pigsty # repo name, pigsty by default
repo_endpoint : http://${admin_ip}:80 # access point to this repo by domain or ip:port
repo_remove : true # remove existing upstream repo
repo_modules : infra,node,pgsql # which repo modules are installed in repo_upstream
repo_upstream : # where to download
- { name: pigsty-local ,description: 'Pigsty Local' ,module: local ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://${admin_ip}/pigsty ./' }}
- { name: pigsty-pgsql ,description: 'Pigsty PgSQL' ,module: pgsql ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://repo.pigsty.io/apt/pgsql/${distro_codename} ${distro_codename} main' , china : 'https://repo.pigsty.cc/apt/pgsql/${distro_codename} ${distro_codename} main' }}
- { name: pigsty-infra ,description: 'Pigsty Infra' ,module: infra ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://repo.pigsty.io/apt/infra/ generic main' ,china : 'https://repo.pigsty.cc/apt/infra/ generic main' }}
- { name: nginx ,description: 'Nginx' ,module: infra ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://nginx.org/packages/${distro_name} ${distro_codename} nginx' }}
- { name: docker-ce ,description: 'Docker' ,module: infra ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://download.docker.com/linux/${distro_name} ${distro_codename} stable' ,china : 'https://mirrors.aliyun.com/docker-ce/linux/${distro_name} ${distro_codename} stable' }}
- { name: base ,description: 'Debian Basic' ,module: node ,releases: [11,12,13 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://deb.debian.org/debian/ ${distro_codename} main non-free-firmware' ,china : 'https://mirrors.aliyun.com/debian/ ${distro_codename} main restricted universe multiverse' }}
- { name: updates ,description: 'Debian Updates' ,module: node ,releases: [11,12,13 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://deb.debian.org/debian/ ${distro_codename}-updates main non-free-firmware' ,china : 'https://mirrors.aliyun.com/debian/ ${distro_codename}-updates main restricted universe multiverse' }}
- { name: security ,description: 'Debian Security' ,module: node ,releases: [11,12,13 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://security.debian.org/debian-security ${distro_codename}-security main non-free-firmware' ,china : 'https://mirrors.aliyun.com/debian-security/ ${distro_codename}-security main non-free-firmware' }}
- { name: base ,description: 'Ubuntu Basic' ,module: node ,releases: [ 20,22,24] ,arch: [x86_64 ] ,baseurl : { default : 'https://mirrors.edge.kernel.org/ubuntu/ ${distro_codename} main universe multiverse restricted' ,china : 'https://mirrors.aliyun.com/ubuntu/ ${distro_codename} main restricted universe multiverse' }}
- { name: updates ,description: 'Ubuntu Updates' ,module: node ,releases: [ 20,22,24] ,arch: [x86_64 ] ,baseurl : { default : 'https://mirrors.edge.kernel.org/ubuntu/ ${distro_codename}-backports main restricted universe multiverse' ,china : 'https://mirrors.aliyun.com/ubuntu/ ${distro_codename}-updates main restricted universe multiverse' }}
- { name: backports ,description: 'Ubuntu Backports' ,module: node ,releases: [ 20,22,24] ,arch: [x86_64 ] ,baseurl : { default : 'https://mirrors.edge.kernel.org/ubuntu/ ${distro_codename}-security main restricted universe multiverse' ,china : 'https://mirrors.aliyun.com/ubuntu/ ${distro_codename}-backports main restricted universe multiverse' }}
- { name: security ,description: 'Ubuntu Security' ,module: node ,releases: [ 20,22,24] ,arch: [x86_64 ] ,baseurl : { default : 'https://mirrors.edge.kernel.org/ubuntu/ ${distro_codename}-updates main restricted universe multiverse' ,china : 'https://mirrors.aliyun.com/ubuntu/ ${distro_codename}-security main restricted universe multiverse' }}
- { name: base ,description: 'Ubuntu Basic' ,module: node ,releases: [ 20,22,24] ,arch: [ aarch64] ,baseurl : { default : 'http://ports.ubuntu.com/ubuntu-ports/ ${distro_codename} main universe multiverse restricted' ,china : 'https://mirrors.aliyun.com/ubuntu-ports/ ${distro_codename} main restricted universe multiverse' }}
- { name: updates ,description: 'Ubuntu Updates' ,module: node ,releases: [ 20,22,24] ,arch: [ aarch64] ,baseurl : { default : 'http://ports.ubuntu.com/ubuntu-ports/ ${distro_codename}-backports main restricted universe multiverse' ,china : 'https://mirrors.aliyun.com/ubuntu-ports/ ${distro_codename}-updates main restricted universe multiverse' }}
- { name: backports ,description: 'Ubuntu Backports' ,module: node ,releases: [ 20,22,24] ,arch: [ aarch64] ,baseurl : { default : 'http://ports.ubuntu.com/ubuntu-ports/ ${distro_codename}-security main restricted universe multiverse' ,china : 'https://mirrors.aliyun.com/ubuntu-ports/ ${distro_codename}-backports main restricted universe multiverse' }}
- { name: security ,description: 'Ubuntu Security' ,module: node ,releases: [ 20,22,24] ,arch: [ aarch64] ,baseurl : { default : 'http://ports.ubuntu.com/ubuntu-ports/ ${distro_codename}-updates main restricted universe multiverse' ,china : 'https://mirrors.aliyun.com/ubuntu-ports/ ${distro_codename}-security main restricted universe multiverse' }}
- { name: pgdg ,description: 'PGDG' ,module: pgsql ,releases: [11,12,13, 22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://apt.postgresql.org/pub/repos/apt/ ${distro_codename}-pgdg main' ,china : 'https://mirrors.aliyun.com/postgresql/repos/apt/ ${distro_codename}-pgdg main' }}
- { name: pgdg-beta ,description: 'PGDG Beta' ,module: beta ,releases: [11,12,13, 22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://apt.postgresql.org/pub/repos/apt/ ${distro_codename}-pgdg-testing main 19' ,china : 'https://mirrors.aliyun.com/postgresql/repos/apt/ ${distro_codename}-pgdg-testing main 19' }}
- { name: timescaledb ,description: 'TimescaleDB' ,module: extra ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packagecloud.io/timescale/timescaledb/${distro_name}/ ${distro_codename} main' }}
- { name: citus ,description: 'Citus' ,module: extra ,releases: [11,12, 20,22 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packagecloud.io/citusdata/community/${distro_name}/ ${distro_codename} main' } }
- { name: percona ,description: 'Percona TDE' ,module: percona ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://repo.pigsty.io/apt/percona ${distro_codename} main' ,china : 'https://repo.pigsty.cc/apt/percona ${distro_codename} main' ,origin : 'http://repo.percona.com/ppg-18.1/apt ${distro_codename} main' }}
- { name: wiltondb ,description: 'WiltonDB' ,module: mssql ,releases: [ 20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://repo.pigsty.io/apt/mssql/ ${distro_codename} main' ,china : 'https://repo.pigsty.cc/apt/mssql/ ${distro_codename} main' ,origin : 'https://ppa.launchpadcontent.net/wiltondb/wiltondb/ubuntu/ ${distro_codename} main' }}
- { name: groonga ,description: 'Groonga Debian' ,module: groonga ,releases: [11,12,13 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packages.groonga.org/debian/ ${distro_codename} main' }}
- { name: groonga ,description: 'Groonga Ubuntu' ,module: groonga ,releases: [ 20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://ppa.launchpadcontent.net/groonga/ppa/ubuntu/ ${distro_codename} main' }}
- { name: mysql ,description: 'MySQL' ,module: mysql ,releases: [11,12, 20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://repo.mysql.com/apt/${distro_name} ${distro_codename} mysql-8.0 mysql-tools' , china : 'https://mirrors.tuna.tsinghua.edu.cn/mysql/apt/${distro_name} ${distro_codename} mysql-8.0 mysql-tools' }}
- { name: mongo ,description: 'MongoDB' ,module: mongo ,releases: [11,12, 20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://repo.mongodb.org/apt/${distro_name} ${distro_codename}/mongodb-org/8.0 multiverse' , china : 'https://mirrors.aliyun.com/mongodb/apt/${distro_name} ${distro_codename}/mongodb-org/8.0 multiverse' }}
- { name: redis ,description: 'Redis' ,module: redis ,releases: [11,12, 20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packages.redis.io/deb ${distro_codename} main' }}
- { name: llvm ,description: 'LLVM' ,module: llvm ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://apt.llvm.org/${distro_codename}/ llvm-toolchain-${distro_codename} main' ,china : 'https://mirrors.tuna.tsinghua.edu.cn/llvm-apt/${distro_codename}/ llvm-toolchain-${distro_codename} main' }}
- { name: haproxyd ,description: 'Haproxy Debian' ,module: haproxy ,releases: [11,12 ] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://haproxy.debian.net/ ${distro_codename}-backports-3.1 main' }}
- { name: haproxyu ,description: 'Haproxy Ubuntu' ,module: haproxy ,releases: [ 20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://ppa.launchpadcontent.net/vbernat/haproxy-3.1/ubuntu/ ${distro_codename} main' }}
- { name: grafana ,description: 'Grafana' ,module: grafana ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://apt.grafana.com stable main' ,china : 'https://mirrors.aliyun.com/grafana/apt/ stable main' }}
- { name: kubernetes ,description: 'Kubernetes' ,module: kube ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://pkgs.k8s.io/core:/stable:/v1.33/deb/ /', china : 'https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.33/deb/ /' }}
- { name: gitlab-ee ,description: 'Gitlab EE' ,module: gitlab ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packages.gitlab.com/gitlab/gitlab-ee/${distro_name}/ ${distro_codename} main' }}
- { name: gitlab-ce ,description: 'Gitlab CE' ,module: gitlab ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://packages.gitlab.com/gitlab/gitlab-ce/${distro_name}/ ${distro_codename} main' }}
- { name: clickhouse ,description: 'ClickHouse' ,module: click ,releases: [11,12,13,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://packages.clickhouse.com/deb/ stable main', china : 'https://mirrors.aliyun.com/clickhouse/deb/ stable main' }}
repo_packages : [ node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules ]
repo_extra_packages : [ pgsql-main ]
repo_url_packages : []
#-----------------------------------------------------------------
# INFRA_PACKAGE
#-----------------------------------------------------------------
infra_packages : # packages to be installed on infra nodes
- grafana,grafana-plugins,grafana-victorialogs-ds,grafana-victoriametrics-ds,victoria-metrics,victoria-logs,victoria-traces,vmutils,vlogscli,alertmanager
- node-exporter,blackbox-exporter,nginx-exporter,pg-exporter,pev2,nginx,dnsmasq,ansible,etcd,python3-requests,redis,mcli,restic,certbot,python3-certbot-nginx
infra_packages_pip : '' # pip installed packages for infra nodes
#-----------------------------------------------------------------
# NGINX
#-----------------------------------------------------------------
nginx_enabled : true # enable nginx on this infra node?
nginx_clean : false # clean existing nginx config during init?
nginx_exporter_enabled : true # enable nginx_exporter on this infra node?
nginx_exporter_port : 9113 # nginx_exporter listen port, 9113 by default
nginx_sslmode : enable # nginx ssl mode? disable,enable,enforce
nginx_cert_validity : 397d # nginx self-signed cert validity, 397d by default
nginx_home : /www # nginx content dir, `/www` by default (soft link to nginx_data)
nginx_data : /data/nginx # nginx actual data dir, /data/nginx by default
nginx_users : { admin : pigsty } # nginx basic auth users : name and pass dict
nginx_port : 80 # nginx listen port, 80 by default
nginx_ssl_port : 443 # nginx ssl listen port, 443 by default
certbot_sign : false # sign nginx cert with certbot during setup?
certbot_email : your@email.com # certbot email address, used for free ssl
certbot_options : '' # certbot extra options
#-----------------------------------------------------------------
# DNS
#-----------------------------------------------------------------
dns_enabled : true # setup dnsmasq on this infra node?
dns_port : 53 # dns server listen port, 53 by default
dns_records : # dynamic dns records resolved by dnsmasq
- "${admin_ip} i.pigsty"
- "${admin_ip} m.pigsty supa.pigsty api.pigsty adm.pigsty cli.pigsty ddl.pigsty"
#-----------------------------------------------------------------
# VICTORIA
#-----------------------------------------------------------------
vmetrics_enabled : true # enable victoria-metrics on this infra node?
vmetrics_clean : false # whether clean existing victoria metrics data during init?
vmetrics_port : 8428 # victoria-metrics listen port, 8428 by default
vmetrics_scrape_interval : 10s # victoria global scrape interval, 10s by default
vmetrics_scrape_timeout : 8s # victoria global scrape timeout, 8s by default
vmetrics_options : >-
-retentionPeriod=15d
-promscrape.fileSDCheckInterval=5s
vlogs_enabled : true # enable victoria-logs on this infra node?
vlogs_clean : false # clean victoria-logs data during init?
vlogs_port : 9428 # victoria-logs listen port, 9428 by default
vlogs_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
-insert.maxLineSizeBytes=1MB
-search.maxQueryDuration=120s
vtraces_enabled : true # enable victoria-traces on this infra node?
vtraces_clean : false # clean victoria-trace data during inti?
vtraces_port : 10428 # victoria-traces listen port, 10428 by default
vtraces_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
vmalert_enabled : true # enable vmalert on this infra node?
vmalert_port : 8880 # vmalert listen port, 8880 by default
vmalert_options : '' # vmalert extra server options
#-----------------------------------------------------------------
# PROMETHEUS
#-----------------------------------------------------------------
blackbox_enabled : true # setup blackbox_exporter on this infra node?
blackbox_port : 9115 # blackbox_exporter listen port, 9115 by default
blackbox_options : '' # blackbox_exporter extra server options
alertmanager_enabled : true # setup alertmanager on this infra node?
alertmanager_port : 9059 # alertmanager listen port, 9059 by default
alertmanager_options : '' # alertmanager extra server options
exporter_metrics_path : /metrics # exporter metric path, `/metrics` by default
#-----------------------------------------------------------------
# GRAFANA
#-----------------------------------------------------------------
grafana_enabled : true # enable grafana on this infra node?
grafana_port : 3000 # default listen port for grafana
grafana_clean : true # clean grafana data during init?
grafana_admin_username : admin # grafana admin username, `admin` by default
grafana_admin_password : pigsty # grafana admin password, `pigsty` by default
grafana_auth_proxy : false # enable grafana auth proxy?
grafana_pgurl : '' # external postgres database url for grafana if given
grafana_view_password : DBUser.Viewer # password for grafana meta pg datasource
#================================================================#
# VARS: NODE #
#================================================================#
#-----------------------------------------------------------------
# NODE_IDENTITY
#-----------------------------------------------------------------
#nodename: # [INSTANCE] # node instance identity, use hostname if missing, optional
node_cluster : nodes # [CLUSTER] # node cluster identity, use 'nodes' if missing, optional
nodename_overwrite : true # overwrite node's hostname with nodename?
nodename_exchange : false # exchange nodename among play hosts?
node_id_from_pg : true # use postgres identity as node identity if applicable?
#-----------------------------------------------------------------
# NODE_DNS
#-----------------------------------------------------------------
node_write_etc_hosts : true # modify `/etc/hosts` on target node?
node_default_etc_hosts : # static dns records in `/etc/hosts`
- "${admin_ip} i.pigsty"
node_etc_hosts : [] # extra static dns records in `/etc/hosts`
node_dns_method: add # how to handle dns servers : add,none,overwrite
node_dns_servers : [ '${admin_ip}' ] # dynamic nameserver in `/etc/resolv.conf`
node_dns_options : # dns resolv options in `/etc/resolv.conf`
- options single-request-reopen timeout:1
#-----------------------------------------------------------------
# NODE_PACKAGE
#-----------------------------------------------------------------
node_repo_modules : local # upstream repo to be added on node, local by default
node_repo_remove : true # remove existing repo on node?
node_packages : [ openssh-server] # packages to be installed current nodes with latest version
node_default_packages : # default packages to be installed on all nodes
- lz4,unzip,bzip2,pv,jq,git,ncdu,make,patch,bash,lsof,wget,uuid,tuned,nvme-cli,numactl,sysstat,iotop,htop,rsync,tcpdump
- python3,python3-pip,socat,lrzsz,net-tools,ipvsadm,telnet,ca-certificates,openssl,keepalived,etcd,haproxy,chrony,pig
- zlib1g,acl,dnsutils,libreadline-dev,vim-tiny,node-exporter,openssh-server,openssh-client,vector
#-----------------------------------------------------------------
# NODE_SEC
#-----------------------------------------------------------------
node_selinux_mode: permissive # set selinux mode : enforcing,permissive,disabled
node_firewall_mode: zone # firewall mode : off , none, zone, zone by default
node_firewall_intranet : # which intranet cidr considered as internal network
- 10.0.0.0 /8
- 192.168.0.0 /16
- 172.16.0.0 /12
node_firewall_public_port : # expose these ports to public network in (zone, strict) mode
- 22 # enable ssh access
- 80 # enable http access
- 443 # enable https access
- 5432 # enable postgresql access (think twice before exposing it!)
#-----------------------------------------------------------------
# NODE_TUNE
#-----------------------------------------------------------------
node_disable_numa : false # disable node numa, reboot required
node_disable_swap : false # disable node swap, use with caution
node_static_network : true # preserve dns resolver settings after reboot
node_disk_prefetch : false # setup disk prefetch on HDD to increase performance
node_kernel_modules : [ softdog, ip_vs, ip_vs_rr, ip_vs_wrr, ip_vs_sh ]
node_hugepage_count : 0 # number of 2MB hugepage, take precedence over ratio
node_hugepage_ratio : 0 # node mem hugepage ratio, 0 disable it by default
node_overcommit_ratio : 0 # node mem overcommit ratio, 0 disable it by default
node_tune: oltp # node tuned profile : none,oltp,olap,crit,tiny
node_sysctl_params : { } # sysctl parameters in k:v format in addition to tuned
#-----------------------------------------------------------------
# NODE_ADMIN
#-----------------------------------------------------------------
node_data : /data # node main data directory, `/data` by default
node_admin_enabled : true # create a admin user on target node?
node_admin_uid : 88 # uid and gid for node admin user
node_admin_username : dba # name of node admin user, `dba` by default
node_admin_sudo : nopass # admin sudo privilege, all,nopass. nopass by default
node_admin_ssh_exchange : true # exchange admin ssh key among node cluster
node_admin_pk_current : true # add current user's ssh pk to admin authorized_keys
node_admin_pk_list : [] # ssh public keys to be added to admin user
node_aliases : {} # extra shell aliases to be added, k:v dict
#-----------------------------------------------------------------
# NODE_TIME
#-----------------------------------------------------------------
node_timezone : '' # setup node timezone, empty string to skip
node_ntp_enabled : true # enable chronyd time sync service?
node_ntp_servers : # ntp servers in `/etc/chrony.conf`
- pool pool.ntp.org iburst
node_crontab_overwrite : true # overwrite or append to `/etc/crontab`?
node_crontab : [ ] # crontab entries in `/etc/crontab`
#-----------------------------------------------------------------
# NODE_VIP
#-----------------------------------------------------------------
vip_enabled : false # enable vip on this node cluster?
# vip_address: [IDENTITY] # node vip address in ipv4 format, required if vip is enabled
# vip_vrid: [IDENTITY] # required, integer, 1-254, should be unique among same VLAN
vip_role : backup # optional, `master|backup`, backup by default, use as init role
vip_preempt : false # optional, `true/false`, false by default, enable vip preemption
vip_interface : eth0 # node vip network interface to listen, `eth0` by default
vip_dns_suffix : '' # node vip dns name suffix, empty string by default
vip_exporter_port : 9650 # keepalived exporter listen port, 9650 by default
#-----------------------------------------------------------------
# HAPROXY
#-----------------------------------------------------------------
haproxy_enabled : true # enable haproxy on this node?
haproxy_clean : false # cleanup all existing haproxy config?
haproxy_reload : true # reload haproxy after config?
haproxy_auth_enabled : true # enable authentication for haproxy admin page
haproxy_admin_username : admin # haproxy admin username, `admin` by default
haproxy_admin_password : pigsty # haproxy admin password, `pigsty` by default
haproxy_exporter_port : 9101 # haproxy admin/exporter port, 9101 by default
haproxy_client_timeout : 24h # client side connection timeout, 24h by default
haproxy_server_timeout : 24h # server side connection timeout, 24h by default
haproxy_services : [] # list of haproxy service to be exposed on node
#-----------------------------------------------------------------
# NODE_EXPORTER
#-----------------------------------------------------------------
node_exporter_enabled : true # setup node_exporter on this node?
node_exporter_port : 9100 # node exporter listen port, 9100 by default
node_exporter_options : '--no-collector.softnet --no-collector.nvme --collector.tcpstat --collector.processes'
#-----------------------------------------------------------------
# VECTOR
#-----------------------------------------------------------------
vector_enabled : true # enable vector log collector?
vector_clean : false # purge vector data dir during init?
vector_data : /data/vector # vector data dir, /data/vector by default
vector_port : 9598 # vector metrics port, 9598 by default
vector_read_from : beginning # vector read from beginning or end
vector_log_endpoint : [ infra ] # if defined, sending vector log to this endpoint.
#================================================================#
# VARS: DOCKER #
#================================================================#
docker_enabled : false # enable docker on this node?
docker_data : /var/lib/docker # docker data directory, /var/lib/docker by default
docker_storage_driver : overlay2 # docker storage driver, can be zfs, btrfs
docker_cgroups_driver: systemd # docker cgroup fs driver : cgroupfs,systemd
docker_registry_mirrors : [] # docker registry mirror list
docker_exporter_port : 9323 # docker metrics exporter port, 9323 by default
docker_image : [] # docker image to be pulled after bootstrap
docker_image_cache : /tmp/docker/*.tgz # docker image cache glob pattern
#================================================================#
# VARS: ETCD #
#================================================================#
#etcd_seq: 1 # etcd instance identifier, explicitly required
etcd_cluster : etcd # etcd cluster & group name, etcd by default
etcd_safeguard : false # prevent purging running etcd instance?
etcd_clean : true # purging existing etcd during initialization?
etcd_data : /data/etcd # etcd data directory, /data/etcd by default
etcd_port : 2379 # etcd client port, 2379 by default
etcd_peer_port : 2380 # etcd peer port, 2380 by default
etcd_init : new # etcd initial cluster state, new or existing
etcd_election_timeout : 1000 # etcd election timeout, 1000ms by default
etcd_heartbeat_interval : 100 # etcd heartbeat interval, 100ms by default
etcd_root_password : Etcd.Root # etcd root password for RBAC, change it!
#================================================================#
# VARS: MINIO #
#================================================================#
#minio_seq: 1 # minio instance identifier, REQUIRED
minio_cluster : minio # minio cluster identifier, REQUIRED
minio_clean : false # cleanup minio during init?, false by default
minio_user : minio # minio os user, `minio` by default
minio_https : true # use https for minio, true by default
minio_node : '${minio_cluster}-${minio_seq}.pigsty' # minio node name pattern
minio_data : '/data/minio' # minio data dir(s), use {x...y} to specify multi drivers
#minio_volumes: # minio data volumes, override defaults if specified
minio_domain : sss.pigsty # minio external domain name, `sss.pigsty` by default
minio_port : 9000 # minio service port, 9000 by default
minio_admin_port : 9001 # minio console port, 9001 by default
minio_access_key : minioadmin # root access key, `minioadmin` by default
minio_secret_key : S3User.MinIO # root secret key, `S3User.MinIO` by default
minio_extra_vars : '' # extra environment variables
minio_provision : true # run minio provisioning tasks?
minio_alias : sss # alias name for local minio deployment
#minio_endpoint: https://sss.pigsty:9000 # if not specified, overwritten by defaults
minio_buckets : # list of minio bucket to be created
- { name : pgsql }
- { name: meta ,versioning : true }
- { name : data }
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
#================================================================#
# VARS: REDIS #
#================================================================#
#redis_cluster: <CLUSTER> # redis cluster name, required identity parameter
#redis_node: 1 <NODE> # redis node sequence number, node int id required
#redis_instances: {} <NODE> # redis instances definition on this redis node
redis_fs_main : /data # redis main data mountpoint, `/data` by default
redis_exporter_enabled : true # install redis exporter on redis nodes?
redis_exporter_port : 9121 # redis exporter listen port, 9121 by default
redis_exporter_options : '' # cli args and extra options for redis exporter
redis_safeguard : false # prevent purging running redis instance?
redis_clean : true # purging existing redis during init?
redis_rmdata : true # remove redis data when purging redis server?
redis_mode: standalone # redis mode : standalone,cluster,sentinel
redis_conf : redis.conf # redis config template path, except sentinel
redis_bind_address : '0.0.0.0' # redis bind address, empty string will use host ip
redis_max_memory : 1GB # max memory used by each redis instance
redis_mem_policy : allkeys-lru # redis memory eviction policy
redis_password : '' # redis password, empty string will disable password
redis_rdb_save : [ '1200 1' ] # redis rdb save directives, disable with empty list
redis_aof_enabled : false # enable redis append only file?
redis_rename_commands : {} # rename redis dangerous commands
redis_cluster_replicas : 1 # replica number for one master in redis cluster
redis_sentinel_monitor : [] # sentinel master list, works on sentinel cluster only
#================================================================#
# VARS: PGSQL #
#================================================================#
#-----------------------------------------------------------------
# PG_IDENTITY
#-----------------------------------------------------------------
pg_mode: pgsql #CLUSTER # pgsql cluster mode : pgsql,citus,gpsql,mssql,mysql,ivory,polar
# pg_cluster: #CLUSTER # pgsql cluster name, required identity parameter
# pg_seq: 0 #INSTANCE # pgsql instance seq number, required identity parameter
# pg_role: replica #INSTANCE # pgsql role, required, could be primary,replica,offline
# pg_instances: {} #INSTANCE # define multiple pg instances on node in `{port:ins_vars}` format
# pg_upstream: #INSTANCE # repl upstream ip addr for standby cluster or cascade replica
# pg_shard: #CLUSTER # pgsql shard name, optional identity for sharding clusters
# pg_group: 0 #CLUSTER # pgsql shard index number, optional identity for sharding clusters
# gp_role: master #CLUSTER # greenplum role of this cluster, could be master or segment
pg_offline_query : false #INSTANCE # set to true to enable offline queries on this instance
#-----------------------------------------------------------------
# PG_BUSINESS
#-----------------------------------------------------------------
# postgres business object definition, overwrite in group vars
pg_users : [] # postgres business users
pg_databases : [] # postgres business databases
pg_services : [] # postgres business services
pg_hba_rules : [] # business hba rules for postgres
pgb_hba_rules : [] # business hba rules for pgbouncer
# global credentials, overwrite in global vars
pg_dbsu_password : '' # dbsu password, empty string means no dbsu password by default
pg_replication_username : replicator
pg_replication_password : DBUser.Replicator
pg_admin_username : dbuser_dba
pg_admin_password : DBUser.DBA
pg_monitor_username : dbuser_monitor
pg_monitor_password : DBUser.Monitor
#-----------------------------------------------------------------
# PG_INSTALL
#-----------------------------------------------------------------
pg_dbsu : postgres # os dbsu name, postgres by default, better not change it
pg_dbsu_uid : 543 # os dbsu uid and gid, 26 for default postgres users and groups
pg_dbsu_sudo : limit # dbsu sudo privilege, none,limit,all,nopass. limit by default
pg_dbsu_home : /var/lib/pgsql # postgresql home directory, `/var/lib/pgsql` by default
pg_dbsu_ssh_exchange : true # exchange postgres dbsu ssh key among same pgsql cluster
pg_version : 18 # postgres major version to be installed, 18 by default
pg_bin_dir : /usr/pgsql/bin # postgres binary dir, `/usr/pgsql/bin` by default
pg_log_dir : /pg/log/postgres # postgres log dir, `/pg/log/postgres` by default
pg_packages : # pg packages to be installed, alias can be used
- pgsql-main pgsql-common
pg_extensions : [] # pg extensions to be installed, alias can be used
#-----------------------------------------------------------------
# PG_BOOTSTRAP
#-----------------------------------------------------------------
pg_data : /pg/data # postgres data directory, `/pg/data` by default
pg_fs_main : /data/postgres # postgres main data directory, `/data/postgres` by default
pg_fs_backup : /data/backups # postgres backup data directory, `/data/backups` by default
pg_storage_type : SSD # storage type for pg main data, SSD,HDD, SSD by default
pg_dummy_filesize : 64MiB # size of `/pg/dummy`, hold 64MB disk space for emergency use
pg_listen : '0.0.0.0' # postgres/pgbouncer listen addresses, comma separated list
pg_port : 5432 # postgres listen port, 5432 by default
pg_localhost : /var/run/postgresql # postgres unix socket dir for localhost connection
patroni_enabled : true # if disabled, no postgres cluster will be created during init
patroni_mode: default # patroni working mode : default,pause,remove
pg_namespace : /pg # top level key namespace in etcd, used by patroni & vip
patroni_port : 8008 # patroni listen port, 8008 by default
patroni_log_dir : /pg/log/patroni # patroni log dir, `/pg/log/patroni` by default
patroni_ssl_enabled : false # secure patroni RestAPI communications with SSL?
patroni_watchdog_mode: off # patroni watchdog mode : automatic,required,off. off by default
patroni_username : postgres # patroni restapi username, `postgres` by default
patroni_password : Patroni.API # patroni restapi password, `Patroni.API` by default
pg_etcd_password : '' # etcd password for this pg cluster, '' to use pg_cluster
pg_primary_db : postgres # primary database name, used by citus,etc... ,postgres by default
pg_parameters : {} # extra parameters in postgresql.auto.conf
pg_files : [] # extra files to be copied to postgres data directory (e.g. license)
pg_conf: oltp.yml # config template : oltp,olap,crit,tiny. `oltp.yml` by default
pg_max_conn : auto # postgres max connections, `auto` will use recommended value
pg_shared_buffer_ratio : 0.25 # postgres shared buffers ratio, 0.25 by default, 0.1~0.4
pg_io_method : worker # io method for postgres, auto,fsync,worker,io_uring, auto by default
pg_rto : 30 # recovery time objective in seconds, `30s` by default
pg_rpo : 1048576 # recovery point objective in bytes, `1MiB` at most by default
pg_libs : 'pg_stat_statements, auto_explain' # preloaded libraries, `pg_stat_statements,auto_explain` by default
pg_delay : 0 # replication apply delay for standby cluster leader
pg_checksum : true # enable data checksum for postgres cluster?
pg_encoding : UTF8 # database cluster encoding, `UTF8` by default
pg_locale : C # database cluster local, `C` by default
pg_lc_collate : C # database cluster collate, `C` by default
pg_lc_ctype : C # database character type, `C` by default
#pgsodium_key: "" # pgsodium key, 64 hex digit, default to sha256(pg_cluster)
#pgsodium_getkey_script: "" # pgsodium getkey script path, pgsodium_getkey by default
#-----------------------------------------------------------------
# PG_PROVISION
#-----------------------------------------------------------------
pg_provision : true # provision postgres cluster after bootstrap
pg_init : pg-init # provision init script for cluster template, `pg-init` by default
pg_default_roles : # default roles and users in postgres cluster
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
pg_default_privileges : # default privileges when created by admin user
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
pg_default_schemas : [ monitor ] # default schemas to be created
pg_default_extensions : # default extensions to be created
- { name: pg_stat_statements ,schema : monitor }
- { name: pgstattuple ,schema : monitor }
- { name: pg_buffercache ,schema : monitor }
- { name: pageinspect ,schema : monitor }
- { name: pg_prewarm ,schema : monitor }
- { name: pg_visibility ,schema : monitor }
- { name: pg_freespacemap ,schema : monitor }
- { name: postgres_fdw ,schema : public }
- { name: file_fdw ,schema : public }
- { name: btree_gist ,schema : public }
- { name: btree_gin ,schema : public }
- { name: pg_trgm ,schema : public }
- { name: intagg ,schema : public }
- { name: intarray ,schema : public }
- { name : pg_repack }
pg_reload : true # reload postgres after hba changes
pg_default_hba_rules : # postgres default host-based authentication rules
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title : 'replicator replication from localhost' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title : 'replicator replication from intranet' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title : 'replicator postgres db from intranet' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title : 'monitor from infra host with password' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title : 'admin @ everywhere with ssl & pwd' }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title : 'pgbouncer read/write via local socket' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title : 'read/write biz user via password' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title : 'allow etl offline tasks from intranet' }
pgb_default_hba_rules : # pgbouncer default host-based authentication rules
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title : 'dbsu local admin access with os ident' }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title : 'allow all user local access with pwd' }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: pwd ,title : 'monitor access via intranet with pwd' }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other monitor access addr' }
- {user : '${admin}' ,db: all ,addr: intra ,auth: pwd ,title : 'admin access via intranet with pwd' }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other admin access addr' }
- {user: 'all' ,db: all ,addr: intra ,auth: pwd ,title : 'allow all user intra access with pwd' }
#-----------------------------------------------------------------
# PG_BACKUP
#-----------------------------------------------------------------
pgbackrest_enabled : true # enable pgbackrest on pgsql host?
pgbackrest_log_dir : /pg/log/pgbackrest # pgbackrest log dir, `/pg/log/pgbackrest` by default
pgbackrest_method: local # pgbackrest repo method : local,minio,[user-defined...]
pgbackrest_init_backup : true # take a full backup after pgbackrest is initialized?
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backups when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /etc/pki/ca.crt # minio ca file path, `/etc/pki/ca.crt` by default
block : y # Enable block incremental backup
bundle : y # bundle small files into a single file
bundle_limit : 20MiB # Limit for file bundles, 20MiB for object storage
bundle_size : 128MiB # Target size for file bundles, 128MiB for object storage
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for the the last 14 days
#-----------------------------------------------------------------
# PG_ACCESS
#-----------------------------------------------------------------
pgbouncer_enabled : true # if disabled, pgbouncer will not be launched on pgsql host
pgbouncer_port : 6432 # pgbouncer listen port, 6432 by default
pgbouncer_log_dir : /pg/log/pgbouncer # pgbouncer log dir, `/pg/log/pgbouncer` by default
pgbouncer_auth_query : false # query postgres to retrieve unlisted business users?
pgbouncer_poolmode: transaction # pooling mode : transaction,session,statement, transaction by default
pgbouncer_sslmode : disable # pgbouncer client ssl mode, disable by default
pgbouncer_ignore_param : [ extra_float_digits, application_name, TimeZone, DateStyle, IntervalStyle, search_path ]
pg_weight : 100 #INSTANCE # relative load balance weight in service, 100 by default, 0-255
pg_service_provider : '' # dedicate haproxy node group name, or empty string for local nodes by default
pg_default_service_dest : pgbouncer # default service destination if svc.dest='default'
pg_default_services : # postgres default service definitions
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
pg_vip_enabled : false # enable a l2 vip for pgsql primary? false by default
pg_vip_address : 127.0.0.1 /24 # vip address in `<ipv4>/<mask>` format, require if vip is enabled
pg_vip_interface : eth0 # vip network interface to listen, eth0 by default
pg_dns_suffix : '' # pgsql dns suffix, '' by default
pg_dns_target : auto # auto, primary, vip, none, or ad hoc ip
#-----------------------------------------------------------------
# PG_MONITOR
#-----------------------------------------------------------------
pg_exporter_enabled : true # enable pg_exporter on pgsql hosts?
pg_exporter_config : pg_exporter.yml # pg_exporter configuration file name
pg_exporter_cache_ttls : '1,10,60,300' # pg_exporter collector ttl stage in seconds, '1,10,60,300' by default
pg_exporter_port : 9630 # pg_exporter listen port, 9630 by default
pg_exporter_params : 'sslmode=disable' # extra url parameters for pg_exporter dsn
pg_exporter_url : '' # overwrite auto-generate pg dsn if specified
pg_exporter_auto_discovery : true # enable auto database discovery? enabled by default
pg_exporter_exclude_database : 'template0,template1,postgres' # csv of database that WILL NOT be monitored during auto-discovery
pg_exporter_include_database : '' # csv of database that WILL BE monitored during auto-discovery
pg_exporter_connect_timeout : 200 # pg_exporter connect timeout in ms, 200 by default
pg_exporter_options : '' # overwrite extra options for pg_exporter
pgbouncer_exporter_enabled : true # enable pgbouncer_exporter on pgsql hosts?
pgbouncer_exporter_port : 9631 # pgbouncer_exporter listen port, 9631 by default
pgbouncer_exporter_url : '' # overwrite auto-generate pgbouncer dsn if specified
pgbouncer_exporter_options : '' # overwrite extra options for pgbouncer_exporter
pgbackrest_exporter_enabled : true # enable pgbackrest_exporter on pgsql hosts?
pgbackrest_exporter_port : 9854 # pgbackrest_exporter listen port, 9854 by default
pgbackrest_exporter_options : >
--collect.interval=120
--log.level=info
#-----------------------------------------------------------------
# PG_REMOVE
#-----------------------------------------------------------------
pg_safeguard : false # stop pg_remove running if pg_safeguard is enabled, false by default
pg_rm_data : true # remove postgres data during remove? true by default
pg_rm_backup : true # remove pgbackrest backup during primary remove? true by default
pg_rm_pkg : true # uninstall postgres packages during remove? true by default
... 配置解读 demo/debian 模板是针对 Debian 和 Ubuntu 发行版优化的配置。
支持的发行版 :
Debian 12 (Bookworm) Debian 13 (Trixie) Ubuntu 22.04 LTS (Jammy) Ubuntu 24.04 LTS (Noble) 关键特性 :
使用 PGDG APT 软件源 针对 APT 包管理器优化 支持 Debian/Ubuntu 特定的软件包名称 适用场景 :
云服务器(Ubuntu 广泛使用) 容器环境(Debian 常用作基础镜像) 开发测试环境 9.33 - demo/demo Pigsty 公开演示站点配置,展示如何配置 SSL 证书、暴露域名、安装全部扩展
demo/demo 配置模板是 Pigsty 公开演示站点使用的配置文件,展示了如何对外暴露网站、配置 SSL 证书、安装全部扩展插件。
如果您希望在云服务器上搭建自己的公开服务,可以参考此配置模板。
配置概览 配置名称: demo/demo 节点数量: 单节点 配置说明:Pigsty 公开演示站点配置 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64 相关配置:meta ,rich 启用方式:
./configure -c demo/demo [ -i <primary_ip>]
主要特性 此模板在 meta 基础上进行了以下增强:
配置 SSL 证书和自定义域名(如 pigsty.cc) 下载并安装 PostgreSQL 18 所有可用扩展 启用 Docker 并配置镜像加速 部署 MinIO 对象存储 预置多个业务数据库和用户 添加 Redis 主从实例示例 添加 FerretDB MongoDB 兼容集群 添加 Kafka 样例集群 配置内容 源文件地址:pigsty/conf/demo/demo.yml
---
#==============================================================#
# File : demo.yml
# Desc : Pigsty Public Demo Configuration
# Ctime : 2020-05-22
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
all :
children :
# infra cluster for proxy, monitor, alert, etc..
infra :
hosts : { 10.10.10.10 : { infra_seq : 1 } }
vars :
nodename : pigsty.cc # overwrite the default hostname
node_id_from_pg : false # do not use the pg identity as hostname
docker_enabled : true # enable docker on this node
docker_registry_mirrors : [ "https://mirror.ccs.tencentyun.com" , "https://docker.1ms.run" ]
# ./pgsql-monitor.yml -l infra # monitor 'external' PostgreSQL instance
pg_exporters : # treat local postgres as RDS for demonstration purpose
20001 : { pg_cluster: pg-foo, pg_seq: 1, pg_host : 10.10.10.10 }
#20002: { pg_cluster: pg-bar, pg_seq: 1, pg_host: 10.10.10.11 , pg_port: 5432 }
#20003: { pg_cluster: pg-bar, pg_seq: 2, pg_host: 10.10.10.12 , pg_exporter_url: 'postgres://dbuser_monitor:DBUser.Monitor@10.10.10.12:5432/postgres?sslmode=disable' }
#20004: { pg_cluster: pg-bar, pg_seq: 3, pg_host: 10.10.10.13 , pg_monitor_username: dbuser_monitor, pg_monitor_password: DBUser.Monitor }
# etcd cluster for ha postgres
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
# minio cluster, s3 compatible object storage
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
# postgres example cluster: pg-meta
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
- {name: dbuser_grafana ,password: DBUser.Grafana ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for grafana database }
- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for bytebase database }
- {name: dbuser_kong ,password: DBUser.Kong ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for kong api gateway }
- {name: dbuser_gitea ,password: DBUser.Gitea ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for gitea service }
- {name: dbuser_wiki ,password: DBUser.Wiki ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for wiki.js service }
- {name: dbuser_noco ,password: DBUser.Noco ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for nocodb service }
- {name: dbuser_odoo ,password: DBUser.Odoo ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for odoo service ,createdb: true } #,superuser : true }
- {name: dbuser_mattermost ,password: DBUser.MatterMost ,pgbouncer: true ,roles: [dbrole_admin] ,comment: admin user for mattermost ,createdb : true }
pg_databases :
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name : vector},{name: postgis},{name: timescaledb}]}
- {name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment : grafana primary database }
- {name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment : bytebase primary database }
- {name: kong ,owner: dbuser_kong ,revokeconn: true ,comment : kong api gateway database }
- {name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment : gitea meta database }
- {name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment : wiki meta database }
- {name: noco ,owner: dbuser_noco ,revokeconn: true ,comment : nocodb database }
#- {name: odoo ,owner: dbuser_odoo ,revokeconn: true ,comment: odoo main database }
- {name: mattermost ,owner: dbuser_mattermost ,revokeconn: true ,comment : mattermost main database }
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
pg_libs : 'timescaledb,pg_stat_statements, auto_explain' # add timescaledb to shared_preload_libraries
pg_extensions : # extensions to be installed on this cluster
- timescaledb timescaledb_toolkit pg_timeseries periods temporal_tables emaj table_version pg_cron pg_task pg_later pg_background
- postgis pgrouting pointcloud pg_h3 q3c ogr_fdw geoip pg_polyline pg_geohash #mobilitydb
- pgvector vchord pgvectorscale pg_vectorize pg_similarity smlar pg_summarize pg_tiktoken pg4ml #pgml
- pg_search pgroonga pg_bigm zhparser pg_bestmatch vchord_bm25 hunspell
- citus hydra pg_analytics pg_duckdb pg_mooncake duckdb_fdw pg_parquet pg_fkpart pg_partman plproxy #pg_strom
- age hll rum pg_graphql pg_jsonschema jsquery pg_hint_plan hypopg index_advisor pg_plan_filter imgsmlr pg_ivm pg_incremental pgmq pgq pg_cardano omnigres #rdkit
- pg_tle plv8 pllua plprql pldebugger plpgsql_check plprofiler plsh pljava #plr #pgtap #faker #dbt2
- pg_prefix pg_semver pgunit pgpdf pglite_fusion md5hash asn1oid roaringbitmap pgfaceting pgsphere pg_country pg_xenophile pg_currency pg_collection pgmp numeral pg_rational pguint pg_uint128 hashtypes ip4r pg_uri pgemailaddr pg_acl timestamp9 chkpass #pg_duration #debversion #pg_rrule
- pg_gzip pg_bzip pg_zstd pg_http pg_net pg_curl pgjq pgjwt pg_smtp_client pg_html5_email_address url_encode pgsql_tweaks pg_extra_time pgpcre icu_ext pgqr pg_protobuf envvar floatfile pg_readme ddl_historization data_historization pg_schedoc pg_hashlib pg_xxhash shacrypt cryptint pg_ecdsa pgsparql
- pg_idkit pg_uuidv7 permuteseq pg_hashids sequential_uuids topn quantile lower_quantile count_distinct omnisketch ddsketch vasco pgxicor tdigest first_last_agg extra_window_functions floatvec aggs_for_vecs aggs_for_arrays pg_arraymath pg_math pg_random pg_base36 pg_base62 pg_base58 pg_financial
- pg_repack pg_squeeze pg_dirtyread pgfincore pg_cooldown pg_ddlx pg_prioritize pg_checksums pg_readonly pg_upless pg_permissions pgautofailover pg_catcheck preprepare pgcozy pg_orphaned pg_crash pg_cheat_funcs pg_fio pg_savior safeupdate pg_drop_events table_log #pgagent #pgpool
- pg_profile pg_tracing pg_show_plans pg_stat_kcache pg_stat_monitor pg_qualstats pg_store_plans pg_track_settings pg_wait_sampling system_stats pg_meta pgnodemx pg_sqlog bgw_replstatus pgmeminfo toastinfo pg_explain_ui pg_relusage pagevis powa
- passwordcheck supautils pgsodium pg_vault pg_session_jwt pg_anon pg_tde pgsmcrypto pgaudit pgauditlogtofile pg_auth_mon credcheck pgcryptokey pg_jobmon logerrors login_hook set_user pg_snakeoil pgextwlist pg_auditor sslutils pg_noset
- wrappers multicorn odbc_fdw jdbc_fdw mysql_fdw tds_fdw sqlite_fdw pgbouncer_fdw mongo_fdw redis_fdw pg_redis_pubsub kafka_fdw hdfs_fdw firebird_fdw aws_s3 log_fdw #oracle_fdw #db2_fdw
- documentdb orafce pgtt session_variable pg_statement_rollback pg_dbms_metadata pg_dbms_lock pgmemcache #pg_dbms_job #wiltondb
- pglogical pglogical_ticker pgl_ddl_deploy pg_failover_slots db_migrator wal2json wal2mongo decoderbufs decoder_raw mimeo pg_fact_loader pg_bulkload #repmgr
redis-ms : # redis classic primary & replica
hosts : { 10.10.10.10 : { redis_node: 1 , redis_instances : { 6379 : { }, 6380 : { replica_of: '10.10.10.10 6379' }, 6381 : { replica_of : '10.10.10.10 6379' } } } }
vars : { redis_cluster: redis-ms ,redis_password: 'redis.ms' ,redis_max_memory : 64MB }
# ./mongo.yml -l pg-mongo
pg-mongo :
hosts : { 10.10.10.10 : { mongo_seq : 1 } }
vars :
mongo_cluster : pg-mongo
mongo_pgurl : 'postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5432/grafana'
# ./kafka.yml -l kf-main
kf-main :
hosts : { 10.10.10.10 : { kafka_seq: 1, kafka_role : controller } }
vars :
kafka_cluster : kf-main
kafka_peer_port : 9093
vars : # global variables
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: china # upstream mirror region : default|china|europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
cc : { domain: pigsty.cc ,path : "/www/pigsty.cc" ,cert: /etc/cert/pigsty.cc.crt ,key : /etc/cert/pigsty.cc.key }
minio : { domain: m.pigsty.cc ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
postgrest : { domain: api.pigsty.cc ,endpoint : "127.0.0.1:8884" }
pgadmin : { domain: adm.pigsty.cc ,endpoint : "127.0.0.1:8885" }
pgweb : { domain: cli.pigsty.cc ,endpoint : "127.0.0.1:8886" }
bytebase : { domain: ddl.pigsty.cc ,endpoint : "127.0.0.1:8887" }
jupyter : { domain: lab.pigsty.cc ,endpoint : "127.0.0.1:8888" , websocket : true }
gitea : { domain: git.pigsty.cc ,endpoint : "127.0.0.1:8889" }
wiki : { domain: wiki.pigsty.cc ,endpoint : "127.0.0.1:9002" }
noco : { domain: noco.pigsty.cc ,endpoint : "127.0.0.1:9003" }
supa : { domain: supa.pigsty.cc ,endpoint : "10.10.10.10:8000" ,websocket : true }
dify : { domain: dify.pigsty.cc ,endpoint : "10.10.10.10:8001" ,websocket : true }
odoo : { domain: odoo.pigsty.cc ,endpoint : "127.0.0.1:8069" ,websocket : true }
mm : { domain: mm.pigsty.cc ,endpoint : "10.10.10.10:8065" ,websocket : true }
# scp -r ~/pgsty/cc/cert/* pj:/etc/cert/ # copy https certs
# scp -r ~/dev/pigsty.cc/public pj:/www/pigsty.cc # copy pigsty.cc website
node_etc_hosts : [ "${admin_ip} sss.pigsty" ]
node_timezone : Asia/Hong_Kong
node_ntp_servers :
- pool cn.pool.ntp.org iburst
- pool ${admin_ip} iburst # assume non-admin nodes does not have internet access
pgbackrest_enabled : false # do not take backups since this is disposable demo env
#prometheus_options: '--storage.tsdb.retention.time=15d' # prometheus extra server options
prometheus_options : '--storage.tsdb.retention.size=3GB' # keep 3GB data at most on demo env
# install all postgresql18 extensions
pg_version : 18 # default postgres version
repo_extra_packages : [ pg18-core ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_extensions : [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl ] #,pg18-olap]
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
grafana_view_password : DBUser.Viewer
pg_admin_password : DBUser.DBA
pg_monitor_password : DBUser.Monitor
pg_replication_password : DBUser.Replicator
patroni_password : Patroni.API
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
etcd_root_password : Etcd.Root
... 配置解读 demo/demo 模板是 Pigsty 的 公开演示配置 ,展示了完整的生产级部署示例。
关键特性 :
配置 HTTPS 证书和自定义域名 安装所有可用的 PostgreSQL 扩展 集成 Redis、FerretDB、Kafka 等组件 配置 Docker 镜像加速 适用场景 :
搭建公开演示站点 需要完整功能展示的场景 学习 Pigsty 高级配置 注意事项 :
需要准备 SSL 证书文件 需要配置 DNS 解析 部分扩展在 ARM64 架构不可用 9.34 - demo/minio 四节点 x 四盘位的高可用多节点多盘 MinIO 集群演示
demo/minio 配置模板演示了如何部署一套四节点 x 四盘位、总计十六盘的高可用 MinIO 集群,提供 S3 兼容的对象存储服务。
更多教程,请参考 MINIO 模块文档。
配置概览 配置名称: demo/minio 节点数量: 四节点 配置说明:高可用多节点多盘 MinIO 集群演示 适用系统:el8, el9, el10, d12, d13, u22, u24 适用架构:x86_64, aarch64 相关配置:meta 启用方式:
./configure -c demo/minio
备注:这是一个四节点模版,您需要在生成配置后修改其他三个节点的 IP 地址
配置内容 源文件地址:pigsty/conf/demo/minio.yml
---
#==============================================================#
# File : minio.yml
# Desc : pigsty: 4 node x 4 disk MNMD minio clusters
# Ctime : 2023-01-07
# Mtime : 2025-12-12
# Docs : https://doc.pgsty.com/config
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
# One pass installation with:
# ./deploy.yml
#==============================================================#
# 1. minio-1 @ 10.10.10.10:9000 - - (9002) svc <-x 10.10.10.9:9002
# 2. minio-2 @ 10.10.10.11:9000 -xx- (9002) svc <-x <----------------
# 3. minio-3 @ 10.10.10.12:9000 -xx- (9002) svc <-x sss.pigsty:9002
# 4. minio-4 @ 10.10.10.12:9000 - - (9002) svc <-x (intranet dns)
#==============================================================#
# use minio load balancer service (9002) instead of direct access (9000)
# mcli alias set sss https://sss.pigsty:9002 minioadmin S3User.MinIO
#==============================================================#
# https://min.io/docs/minio/linux/operations/install-deploy-manage/deploy-minio-multi-node-multi-drive.html
# MINIO_VOLUMES="https://minio-{1...4}.pigsty:9000/data{1...4}/minio"
all :
children :
# infra cluster for proxy, monitor, alert, etc..
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } } }
# minio cluster with 4 nodes and 4 drivers per node
minio :
hosts :
10.10.10.10 : { minio_seq: 1 , nodename : minio-1 }
10.10.10.11 : { minio_seq: 2 , nodename : minio-2 }
10.10.10.12 : { minio_seq: 3 , nodename : minio-3 }
10.10.10.13 : { minio_seq: 4 , nodename : minio-4 }
vars :
minio_cluster : minio
minio_data : '/data{1...4}'
minio_buckets : # list of minio bucket to be created
- { name : pgsql }
- { name: meta ,versioning : true }
- { name : data }
minio_users : # list of minio user to be created
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
# bind a node l2 vip (10.10.10.9) to minio cluster (optional)
node_cluster : minio
vip_enabled : true
vip_vrid : 128
vip_address : 10.10.10.9
vip_interface : eth1
# expose minio service with haproxy on all nodes
haproxy_services :
- name : minio # [REQUIRED] service name, unique
port : 9002 # [REQUIRED] service port, unique
balance : leastconn # [OPTIONAL] load balancer algorithm
options : # [OPTIONAL] minio health check
- option httpchk
- option http-keep-alive
- http-check send meth OPTIONS uri /minio/health/live
- http-check expect status 200
servers :
- { name: minio-1 ,ip: 10.10.10.10 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-2 ,ip: 10.10.10.11 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-3 ,ip: 10.10.10.12 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-4 ,ip: 10.10.10.13 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
vars :
version : v4.0.0 # pigsty version string
admin_ip : 10.10.10.10 # admin node ip address
region: default # upstream mirror region : default|china|europe
infra_portal : # infra services exposed via portal
home : { domain : i.pigsty } # default domain name
# domain names to access minio web console via nginx web portal (optional)
minio : { domain: m.pigsty ,endpoint : "10.10.10.10:9001" ,scheme: https ,websocket : true }
minio10 : { domain: m10.pigsty ,endpoint : "10.10.10.10:9001" ,scheme: https ,websocket : true }
minio11 : { domain: m11.pigsty ,endpoint : "10.10.10.11:9001" ,scheme: https ,websocket : true }
minio12 : { domain: m12.pigsty ,endpoint : "10.10.10.12:9001" ,scheme: https ,websocket : true }
minio13 : { domain: m13.pigsty ,endpoint : "10.10.10.13:9001" ,scheme: https ,websocket : true }
minio_endpoint : https://sss.pigsty:9002 # explicit overwrite minio endpoint with haproxy port
node_etc_hosts : [ "10.10.10.9 sss.pigsty" ] # domain name to access minio from all nodes (required)
#----------------------------------------------#
# PASSWORD : https://doc.pgsty.com/config/security
#----------------------------------------------#
grafana_admin_password : pigsty
haproxy_admin_password : pigsty
minio_secret_key : S3User.MinIO
... 配置解读 demo/minio 模板是 MinIO 生产级部署的参考配置,展示了多节点多盘 (MNMD) 架构。
关键特性 :
多节点多盘架构 :4 节点 × 4 盘 = 16 盘纠删码组L2 VIP 高可用 :通过 Keepalived 绑定虚拟 IPHAProxy 负载均衡 :9002 端口统一访问入口细粒度权限 :为不同应用创建独立用户和存储桶访问方式 :
# 使用 mcli 配置 MinIO 别名(通过 HAProxy 负载均衡)
mcli alias set sss https://sss.pigsty:9002 minioadmin S3User.MinIO
# 列出存储桶
mcli ls sss/
# 使用控制台
# 访问 https://m.pigsty 或 https://m10-m13.pigsty
适用场景 :
需要 S3 兼容对象存储的环境 PostgreSQL 备份存储(pgBackRest 远程仓库) 大数据和 AI 工作负载的数据湖 需要高可用对象存储的生产环境 注意事项 :
每个节点需要准备 4 块独立磁盘挂载到 /data1 - /data4 生产环境建议至少 4 节点以实现纠删码冗余 VIP 需要正确配置网络接口(vip_interface) 9.35 - build/oss Pigsty 开源版离线软件包构建环境配置
build/oss 配置模板是 Pigsty 开源版离线软件包的构建环境配置,用于在多个操作系统上批量构建离线安装包。
此配置仅供开发者和贡献者使用。
配置概览 配置名称: build/oss 节点数量: 六节点(el9, el10, d12, d13, u22, u24) 配置说明:Pigsty 开源版离线软件包构建环境 适用系统:el9, el10, d12, d13, u22, u24 适用架构:x86_64 启用方式:
cp conf/build/oss.yml pigsty.yml
备注:这是一个固定 IP 地址的构建模板,仅供内部使用
配置内容 源文件地址:pigsty/conf/build/oss.yml
---
#==============================================================#
# File : oss.yml
# Desc : Pigsty 3-node building env (PG18)
# Ctime : 2024-10-22
# Mtime : 2025-12-12
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
all :
vars :
version : v4.0.0
admin_ip : 10.10.10.24
region : china
etcd_clean : true
proxy_env :
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn,*.pigsty.cc"
# building spec
pg_version : 18
cache_pkg_dir : 'dist/${version}'
repo_modules : infra,node,pgsql
repo_packages : [ node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules ]
repo_extra_packages : [ pg18-core ,pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
pg_extensions : [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap, pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
children :
#el8: { hosts: { 10.10.10.8: { pg_cluster: el8 ,pg_seq: 1 ,pg_role: primary }}}
el9 : { hosts : { 10.10.10.9 : { pg_cluster: el9 ,pg_seq: 1 ,pg_role : primary }}}
el10 : { hosts : { 10.10.10.10 : { pg_cluster: el10 ,pg_seq: 1 ,pg_role : primary }}}
d12 : { hosts : { 10.10.10.12 : { pg_cluster: d12 ,pg_seq: 1 ,pg_role : primary }}}
d13 : { hosts : { 10.10.10.13 : { pg_cluster: d13 ,pg_seq: 1 ,pg_role : primary }}}
u22 : { hosts : { 10.10.10.22 : { pg_cluster: u22 ,pg_seq: 1 ,pg_role : primary }}}
u24 : { hosts : { 10.10.10.24 : { pg_cluster: u24 ,pg_seq: 1 ,pg_role : primary }}}
etcd : { hosts : { 10.10.10.24 : { etcd_seq: 1 }}, vars : { etcd_cluster : etcd }}
infra :
hosts :
#10.10.10.8: { infra_seq: 1, admin_ip: 10.10.10.8 ,ansible_host: el8 } #, ansible_python_interpreter: /usr/bin/python3.12 }
10.10.10.9 : { infra_seq: 2, admin_ip: 10.10.10.9 ,ansible_host : el9 }
10.10.10.10 : { infra_seq: 3, admin_ip: 10.10.10.10 ,ansible_host : el10 }
10.10.10.12 : { infra_seq: 4, admin_ip: 10.10.10.12 ,ansible_host : d12 }
10.10.10.13 : { infra_seq: 5, admin_ip: 10.10.10.13 ,ansible_host : d13 }
10.10.10.22 : { infra_seq: 6, admin_ip: 10.10.10.22 ,ansible_host : u22 }
10.10.10.24 : { infra_seq: 7, admin_ip: 10.10.10.24 ,ansible_host : u24 }
vars : { node_conf : oltp }
... 配置解读 build/oss 模板是 Pigsty 开源版离线软件包的构建配置。
构建内容 :
PostgreSQL 18 及所有分类扩展包 基础设施软件包(Prometheus、Grafana、Nginx 等) 节点软件包(监控代理、工具等) 额外模块(extra-modules) 支持的操作系统 :
EL9 (Rocky/Alma/RHEL 9) EL10 (Rocky 10 / RHEL 10) Debian 12 (Bookworm) Debian 13 (Trixie) Ubuntu 22.04 (Jammy) Ubuntu 24.04 (Noble) 构建流程 :
# 1. 准备构建环境
cp conf/build/oss.yml pigsty.yml
# 2. 在各节点上下载软件包
./infra.yml -t repo_build
# 3. 打包离线安装包
make cache
适用场景 :
Pigsty 开发者构建新版本 贡献者测试新扩展 企业用户自定义离线包 9.36 - build/pro Pigsty 专业版离线软件包构建环境配置(多版本)
build/pro 配置模板是 Pigsty 专业版离线软件包的构建环境配置,包含 PostgreSQL 13-18 全版本及额外商业组件。
此配置仅供开发者和贡献者使用。
配置概览 配置名称: build/pro 节点数量: 六节点(el9, el10, d12, d13, u22, u24) 配置说明:Pigsty 专业版离线软件包构建环境(多版本) 适用系统:el9, el10, d12, d13, u22, u24 适用架构:x86_64 启用方式:
cp conf/build/pro.yml pigsty.yml
备注:这是一个固定 IP 地址的构建模板,仅供内部使用
配置内容 源文件地址:pigsty/conf/build/pro.yml
---
#==============================================================#
# File : pro.yml
# Desc : Pigsty 6-node pro building env (PG 13-18)
# Ctime : 2024-10-22
# Mtime : 2025-12-15
# License : Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright : 2018-2026 Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
all :
vars :
version : v4.0.0
admin_ip : 10.10.10.24
region : china
etcd_clean : true
proxy_env :
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn,*.pigsty.cc"
# building spec
pg_version : 18
cache_pkg_dir : 'dist/${version}/pro'
repo_modules : infra,node,pgsql
pg_extensions : []
repo_packages : [
node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules,
pg18-full,pg18-time,pg18-gis,pg18-rag,pg18-fts,pg18-olap,pg18-feat,pg18-lang,pg18-type,pg18-util,pg18-func,pg18-admin,pg18-stat,pg18-sec,pg18-fdw,pg18-sim,pg18-etl,
pg17-full,pg17-time,pg17-gis,pg17-rag,pg17-fts,pg17-olap,pg17-feat,pg17-lang,pg17-type,pg17-util,pg17-func,pg17-admin,pg17-stat,pg17-sec,pg17-fdw,pg17-sim,pg17-etl,
pg16-full,pg16-time,pg16-gis,pg16-rag,pg16-fts,pg16-olap,pg16-feat,pg16-lang,pg16-type,pg16-util,pg16-func,pg16-admin,pg16-stat,pg16-sec,pg16-fdw,pg16-sim,pg16-etl,
pg15-full,pg15-time,pg15-gis,pg15-rag,pg15-fts,pg15-olap,pg15-feat,pg15-lang,pg15-type,pg15-util,pg15-func,pg15-admin,pg15-stat,pg15-sec,pg15-fdw,pg15-sim,pg15-etl,
pg14-full,pg14-time,pg14-gis,pg14-rag,pg14-fts,pg14-olap,pg14-feat,pg14-lang,pg14-type,pg14-util,pg14-func,pg14-admin,pg14-stat,pg14-sec,pg14-fdw,pg14-sim,pg14-etl,
pg13-full,pg13-time,pg13-gis,pg13-rag,pg13-fts,pg13-olap,pg13-feat,pg13-lang,pg13-type,pg13-util,pg13-func,pg13-admin,pg13-stat,pg13-sec,pg13-fdw,pg13-sim,pg13-etl,
infra-extra, kafka, java-runtime, sealos, tigerbeetle, polardb, ivorysql
]
children :
#el8: { hosts: { 10.10.10.8: { pg_cluster: el8 ,pg_seq: 1 ,pg_role: primary }}}
el9 : { hosts : { 10.10.10.9 : { pg_cluster: el9 ,pg_seq: 1 ,pg_role : primary }}}
el10 : { hosts : { 10.10.10.10 : { pg_cluster: el10 ,pg_seq: 1 ,pg_role : primary }}}
d12 : { hosts : { 10.10.10.12 : { pg_cluster: d12 ,pg_seq: 1 ,pg_role : primary }}}
d13 : { hosts : { 10.10.10.13 : { pg_cluster: d13 ,pg_seq: 1 ,pg_role : primary }}}
u22 : { hosts : { 10.10.10.22 : { pg_cluster: u22 ,pg_seq: 1 ,pg_role : primary }}}
u24 : { hosts : { 10.10.10.24 : { pg_cluster: u24 ,pg_seq: 1 ,pg_role : primary }}}
etcd : { hosts : { 10.10.10.24 : { etcd_seq: 1 }}, vars : { etcd_cluster : etcd }}
infra :
hosts :
#10.10.10.8: { infra_seq: 9, admin_ip: 10.10.10.8 ,ansible_host: el8 } #, ansible_python_interpreter: /usr/bin/python3.12 }
10.10.10.9 : { infra_seq: 1, admin_ip: 10.10.10.9 ,ansible_host : el9 }
10.10.10.10 : { infra_seq: 2, admin_ip: 10.10.10.10 ,ansible_host : el10 }
10.10.10.12 : { infra_seq: 3, admin_ip: 10.10.10.12 ,ansible_host : d12 }
10.10.10.13 : { infra_seq: 4, admin_ip: 10.10.10.13 ,ansible_host : d13 }
10.10.10.22 : { infra_seq: 5, admin_ip: 10.10.10.22 ,ansible_host : u22 }
10.10.10.24 : { infra_seq: 6, admin_ip: 10.10.10.24 ,ansible_host : u24 }
vars : { node_conf : oltp }
... 配置解读 build/pro 模板是 Pigsty 专业版离线软件包的构建配置,比开源版包含更多内容。
与 OSS 版的区别 :
包含 PostgreSQL 13-18 全部六个大版本 包含额外商业/企业组件:Kafka、PolarDB、IvorySQL 等 包含 Java 运行时和 Sealos 等工具 输出目录为 dist/${version}/pro/ 构建内容 :
PostgreSQL 13、14、15、16、17、18 全版本 每个版本的全部分类扩展包 Kafka 消息队列 PolarDB 和 IvorySQL 内核 TigerBeetle 分布式数据库 Sealos 容器平台 适用场景 :
企业客户需要多版本支持 需要 Oracle/MySQL 兼容内核 需要 Kafka 消息队列集成 需要长期支持版本(LTS) 构建流程 :
# 1. 准备构建环境
cp conf/build/pro.yml pigsty.yml
# 2. 在各节点上下载软件包
./infra.yml -t repo_build
# 3. 打包离线安装包
make cache-pro
10 - 模块参考 11 - 模块:PGSQL 如何使用 Pigsty 部署并管理世界上最先进的开源关系型数据库 —— PostgreSQL,按需定制,开箱即用!
世界上最先进的开源关系型数据库!
而 Pigsty 帮它进入全盛状态:开箱即用、可靠、可观测、可维护、可伸缩! 配置 | 管理 | 剧本 | 监控 | 参数
概览 了解关于 PostgreSQL 的重要主题与概念。
配置 描述 你想要的 PostgreSQL 集群
身份参数 :定义PostgreSQL集群的身份参数读写主库 :创建由单一主库构成的单实例“集群“只读从库 :创建一主一从的两节点基础高可用集群离线从库 :创建专用于OLAP/ETL/交互式查询的特殊只读实例同步备库 :启用同步提交,以确保没有数据丢失法定人数 :使用法定人数同步提交以获得更高的一致性级别备份集群 :克隆现有集群,并保持同步(异地灾备集群)延迟集群 :克隆现有集群,并延迟重放,用于紧急数据恢复Citus集群 :定义并创建 Citus 水平分布式数据库集群大版本切换 :使用不同的PostgreSQL大版本部署集群管理 管理 您所创建的 PostgreSQL 集群。
剧本 使用幂等的剧本 ,将您的描述变为现实。
样例:安装 PGSQL 模块
样例:移除 PGSQL 模块
监控 在 Grafana 仪表盘 中查阅 PostgreSQL 的详情状态。
在 Pigsty 中共有 26 个与 PostgreSQL 相关的监控面板:
参数 PGSQL 模块的配置参数列表
完整参数列表 参数 参数组 类型 级别 说明 中文说明 pg_modePG_IDenum C pgsql cluster mode: pgsql,citus,gpsql pgsql 集群模式: pgsql,citus,gpsql pg_clusterPG_IDstring C pgsql cluster name, REQUIRED identity parameter pgsql 集群名称, 必选身份参数 pg_seqPG_IDint I pgsql instance seq number, REQUIRED identity parameter pgsql 实例号, 必选身份参数 pg_rolePG_IDenum I pgsql role, REQUIRED, could be primary,replica,offline pgsql 实例角色, 必选身份参数, 可为 primary,replica,offline pg_instancesPG_IDdict I define multiple pg instances on node in {port:ins_vars} format 在一个节点上定义多个 pg 实例,使用 {port:ins_vars} 格式 pg_upstreamPG_IDip I repl upstream ip addr for standby cluster or cascade replica 级联从库或备份集群或的复制上游节点IP地址 pg_shardPG_IDstring C pgsql shard name, optional identity for sharding clusters pgsql 分片名,对 citus 与 gpsql 等水平分片集群为必选身份参数 pg_groupPG_IDint C pgsql shard index number, optional identity for sharding clusters pgsql 分片号,正整数,对 citus 与 gpsql 等水平分片集群为必选身份参数 gp_rolePG_IDenum C greenplum role of this cluster, could be master or segment 这个集群的 greenplum 角色,可以是 master 或 segment pg_exportersPG_IDdict C additional pg_exporters to monitor remote postgres instances 在该节点上设置额外的 pg_exporters 用于监控远程 postgres 实例 pg_offline_queryPG_IDbool I set to true to enable offline query on this instance 设置为 true 将此只读实例标记为特殊的离线从库,承载 Offline 服务,允许离线查询 pg_usersPG_BUSINESSuser[] C postgres business users postgres 业务用户 pg_databasesPG_BUSINESSdatabase[] C postgres business databases postgres 业务数据库 pg_servicesPG_BUSINESSservice[] C postgres business services postgres 业务服务 pg_hba_rulesPG_BUSINESShba[] C business hba rules for postgres postgres 的业务 hba 规则 pgb_hba_rulesPG_BUSINESShba[] C business hba rules for pgbouncer pgbouncer 的业务 hba 规则 pg_replication_usernamePG_BUSINESSusername G postgres replication username, replicator by default postgres 复制用户名,默认为 replicator pg_replication_passwordPG_BUSINESSpassword G postgres replication password, DBUser.Replicator by default postgres 复制密码,默认为 DBUser.Replicator pg_admin_usernamePG_BUSINESSusername G postgres admin username, dbuser_dba by default postgres 管理员用户名,默认为 dbuser_dba pg_admin_passwordPG_BUSINESSpassword G postgres admin password in plain text, DBUser.DBA by default postgres 管理员明文密码,默认为 DBUser.DBA pg_monitor_usernamePG_BUSINESSusername G postgres monitor username, dbuser_monitor by default postgres 监控用户名,默认为 dbuser_monitor pg_monitor_passwordPG_BUSINESSpassword G postgres monitor password, DBUser.Monitor by default postgres 监控密码,默认为 DBUser.Monitor pg_dbsu_passwordPG_BUSINESSpassword G/C dbsu password, empty string means no dbsu password by default dbsu 密码,默认为空字符串意味着不设置 dbsu 密码,最好不要设置。 pg_dbsuPG_INSTALLusername C os dbsu name, postgres by default, better not change it 操作系统 dbsu 名称,默认为 postgres,最好不要更改 pg_dbsu_uidPG_INSTALLint C os dbsu uid and gid, 26 for default postgres users and groups 操作系统 dbsu uid 和 gid,对于默认的 postgres 用户和组为 26 pg_dbsu_sudoPG_INSTALLenum C dbsu sudo privilege, none,limit,all,nopass. limit by default dbsu sudo 权限, none,limit,all,nopass,默认为 limit,有限sudo权限 pg_dbsu_homePG_INSTALLpath C postgresql home directory, /var/lib/pgsql by default postgresql 主目录,默认为 /var/lib/pgsql pg_dbsu_ssh_exchangePG_INSTALLbool C exchange postgres dbsu ssh key among same pgsql cluster 在 pgsql 集群之间交换 postgres dbsu ssh 密钥 pg_versionPG_INSTALLenum C postgres major version to be installed, 18 by default 要安装的 postgres 主版本,默认为 18 pg_bin_dirPG_INSTALLpath C postgres binary dir, /usr/pgsql/bin by default postgres 二进制目录,默认为 /usr/pgsql/bin pg_log_dirPG_INSTALLpath C postgres log dir, /pg/log/postgres by default postgres 日志目录,默认为 /pg/log/postgres pg_packagesPG_INSTALLstring[] C pg packages to be installed, ${pg_version} will be replaced 要安装的 pg 包,${pg_version} 将被替换为实际主版本号 pg_extensionsPG_INSTALLstring[] C pg extensions to be installed, ${pg_version} will be replaced 要安装的 pg 扩展,${pg_version} 将被替换为实际主版本号 pg_cleanPG_BOOTSTRAPbool G/C/A purging existing postgres during pgsql init? true by default 在 pgsql 初始化期间清除现有的 postgres?默认为 true pg_dataPG_BOOTSTRAPpath C postgres data directory, /pg/data by default postgres 数据目录,默认为 /pg/data pg_fs_mainPG_BOOTSTRAPpath C mountpoint/path for postgres main data, /data by default postgres 主数据的挂载点/路径,默认为 /data pg_fs_bkupPG_BOOTSTRAPpath C mountpoint/path for pg backup data, /data/backup by default pg 备份数据的挂载点/路径,默认为 /data/backup pg_storage_typePG_BOOTSTRAPenum C storage type for pg main data, SSD,HDD, SSD by default pg 主数据的存储类型,SSD、HDD,默认为 SSD,影响自动优化的参数。 pg_dummy_filesizePG_BOOTSTRAPsize C size of /pg/dummy, hold 64MB disk space for emergency use /pg/dummy 的大小,默认保留 64MB 磁盘空间用于紧急抢修pg_listenPG_BOOTSTRAPip(s) C/I postgres/pgbouncer listen addresses, comma separated list postgres/pgbouncer 的监听地址,用逗号分隔的IP列表,默认为 0.0.0.0 pg_portPG_BOOTSTRAPport C postgres listen port, 5432 by default postgres 监听端口,默认为 5432 pg_localhostPG_BOOTSTRAPpath C postgres unix socket dir for localhost connection postgres 的 Unix 套接字目录,用于本地连接 pg_namespacePG_BOOTSTRAPpath C top level key namespace in etcd, used by patroni & vip 在 etcd 中的顶级键命名空间,被 patroni & vip 用于高可用管理 patroni_enabledPG_BOOTSTRAPbool C if disabled, no postgres cluster will be created during init 如果禁用,初始化期间不会创建 postgres 集群 patroni_modePG_BOOTSTRAPenum C patroni working mode: default,pause,remove patroni 工作模式:default,pause,remove patroni_portPG_BOOTSTRAPport C patroni listen port, 8008 by default patroni 监听端口,默认为 8008 patroni_log_dirPG_BOOTSTRAPpath C patroni log dir, /pg/log/patroni by default patroni 日志目录,默认为 /pg/log/patroni patroni_ssl_enabledPG_BOOTSTRAPbool G secure patroni RestAPI communications with SSL? 使用 SSL 保护 patroni RestAPI 通信? patroni_watchdog_modePG_BOOTSTRAPenum C patroni watchdog mode: automatic,required,off. off by default patroni 看门狗模式:automatic,required,off,默认为 off patroni_usernamePG_BOOTSTRAPusername C patroni restapi username, postgres by default patroni restapi 用户名,默认为 postgres patroni_passwordPG_BOOTSTRAPpassword C patroni restapi password, Patroni.API by default patroni restapi 密码,默认为 Patroni.API pg_etcd_passwordPG_BOOTSTRAPpassword C etcd password for this pg cluster, empty to use pg_cluster 此 PostgreSQL 集群在 etcd 中使用的密码,默认使用集群名 pg_primary_dbPG_BOOTSTRAPstring C primary database in this cluster, optional, postgres by default 指定集群中首要使用的数据库名,Citus等模式会用到,默认为 postgres pg_parametersPG_BOOTSTRAPdict C extra parameters in postgresql.auto.conf 覆盖 postgresql.auto.conf 中的 PostgreSQL 参数 pg_filesPG_BOOTSTRAPpath[] C extra files to be copied to postgres data directory 拷贝至PGDATA目录中的额外文件列表 (例如许可证文件) pg_confPG_BOOTSTRAPenum C config template: oltp,olap,crit,tiny. oltp.yml by default 配置模板:oltp,olap,crit,tiny,默认为 oltp.yml pg_max_connPG_BOOTSTRAPint C postgres max connections, auto will use recommended value postgres 最大连接数,auto 将使用推荐值 pg_shared_buffer_ratioPG_BOOTSTRAPfloat C postgres shared buffer memory ratio, 0.25 by default, 0.1~0.4 postgres 共享缓冲区内存比率,默认为 0.25,范围 0.1~0.4 pg_io_methodPG_BOOTSTRAPenum C io method for postgres: auto,sync,worker,io_uring, auto by default PostgreSQL IO方法:auto,sync,worker,io_uring,默认为 auto pg_rtoPG_BOOTSTRAPint C recovery time objective in seconds, 30s by default 恢复时间目标(秒),默认为 30s pg_rpoPG_BOOTSTRAPint C recovery point objective in bytes, 1MiB at most by default 恢复点目标(字节),默认为 1MiB pg_libsPG_BOOTSTRAPstring C preloaded libraries, timescaledb,pg_stat_statements,auto_explain by default 预加载的库,默认为 timescaledb,pg_stat_statements,auto_explain pg_delayPG_BOOTSTRAPinterval I replication apply delay for standby cluster leader 备份集群主库的WAL重放应用延迟,用于制备延迟从库 pg_checksumPG_BOOTSTRAPbool C enable data checksum for postgres cluster? 为 postgres 集群启用数据校验和? pg_pwd_encPG_BOOTSTRAPenum C passwords encryption algorithm: md5,scram-sha-256 密码加密算法:md5,scram-sha-256 pg_encodingPG_BOOTSTRAPenum C database cluster encoding, UTF8 by default 数据库集群编码,默认为 UTF8 pg_localePG_BOOTSTRAPenum C database cluster local, C by default 数据库集群本地化设置,默认为 C pg_lc_collatePG_BOOTSTRAPenum C database cluster collate, C by default 数据库集群排序,默认为 C pg_lc_ctypePG_BOOTSTRAPenum C database character type, C by default 数据库字符类型,默认为 C pgsodium_keyPG_BOOTSTRAPstring C pgsodium key, 64 hex digit, default to sha256(pg_cluster) pgsodium 加密主密钥,64位十六进制,默认使用 sha256(pg_cluster) pgsodium_getkey_scriptPG_BOOTSTRAPpath C pgsodium getkey script path pgsodium getkey 脚本路径 pgbouncer_enabledPG_ACCESSbool C if disabled, pgbouncer will not be launched on pgsql host 如果禁用,则不会配置 pgbouncer 连接池 pgbouncer_portPG_ACCESSport C pgbouncer listen port, 6432 by default pgbouncer 监听端口,默认为 6432 pgbouncer_log_dirPG_ACCESSpath C pgbouncer log dir, /pg/log/pgbouncer by default pgbouncer 日志目录,默认为 /pg/log/pgbouncer pgbouncer_auth_queryPG_ACCESSbool C query postgres to retrieve unlisted business users? 使用 AuthQuery 来从 postgres 获取未列出的业务用户? pgbouncer_poolmodePG_ACCESSenum C pooling mode: transaction,session,statement, transaction by default 池化模式:transaction,session,statement,默认为 transaction pgbouncer_sslmodePG_ACCESSenum C pgbouncer client ssl mode, disable by default pgbouncer 客户端 SSL 模式,默认为禁用 pgbouncer_ignore_paramPG_ACCESSstring[] C pgbouncer ignore_startup_parameters, param list pgbouncer 忽略的启动参数列表 pg_provisionPG_PROVISIONbool C provision postgres cluster after bootstrap 在引导后置备 postgres 集群内部的业务对象? pg_initPG_PROVISIONstring G/C provision init script for cluster template, pg-init by default 为集群模板提供初始化脚本,默认为 pg-init pg_default_rolesPG_PROVISIONrole[] G/C default roles and users in postgres cluster postgres 集群中的默认预定义角色和系统用户 pg_default_privilegesPG_PROVISIONstring[] G/C default privileges when created by admin user 由管理员用户创建数据库内对象时的默认权限 pg_default_schemasPG_PROVISIONstring[] G/C default schemas to be created 要创建的默认模式列表 pg_default_extensionsPG_PROVISIONextension[] G/C default extensions to be created 要创建的默认扩展列表 pg_reloadPG_PROVISIONbool A reload postgres after hba changes 更改HBA后,是否立即重载 postgres 配置 pg_default_hba_rulesPG_PROVISIONhba[] G/C postgres default host-based authentication rules postgres 基于主机的认证规则,全局PG默认HBA pgb_default_hba_rulesPG_PROVISIONhba[] G/C pgbouncer default host-based authentication rules pgbouncer 默认的基于主机的认证规则,全局PGB默认HBA pgbackrest_enabledPG_BACKUPbool C enable pgbackrest on pgsql host? 在 pgsql 主机上启用 pgbackrest? pgbackrest_cleanPG_BACKUPbool C remove pg backup data during init? 在初始化时删除以前的 pg 备份数据? pgbackrest_log_dirPG_BACKUPpath C pgbackrest log dir, /pg/log/pgbackrest by default pgbackrest 日志目录,默认为 /pg/log/pgbackrest pgbackrest_methodPG_BACKUPenum C pgbackrest repo method: local,minio,etc… pgbackrest 使用的仓库:local,minio,等… pgbackrest_init_backupPG_BACKUPbool C take a full backup after pgbackrest is initialized? pgbackrest 初始化完成后是否立即执行全量备份? pgbackrest_repoPG_BACKUPdict G/C pgbackrest repo: https://pgbackrest.org/configuration.html#section-repository pgbackrest 仓库定义:https://pgbackrest.org/configuration.html#section-repository pg_weightPG_ACCESSint I relative load balance weight in service, 100 by default, 0-255 在服务中的相对负载均衡权重,默认为 100,范围 0-255 pg_service_providerPG_ACCESSenum G/C dedicate haproxy node group name, or empty string for local nodes by default 专用的 haproxy 节点组名称,或默认空字符,使用本地节点上的 haproxy pg_default_service_destPG_ACCESSenum G/C default service destination if svc.dest=‘default’ 如果 svc.dest=‘default’,默认服务指向哪里?postgres 或 pgbouncer,默认指向 pgbouncer pg_default_servicesPG_ACCESSservice[] G/C postgres default service definitions postgres 默认服务定义列表,全局共用。 pg_vip_enabledPG_ACCESSbool C enable a l2 vip for pgsql primary? false by default 是否为 pgsql 主节点启用 L2 VIP?默认不启用 pg_vip_addressPG_ACCESScidr4 C vip address in <ipv4>/<mask> format, require if vip is enabled vip 地址的格式为 /,启用 vip 时为必选参数 pg_vip_interfacePG_ACCESSstring C/I vip network interface to listen, eth0 by default 监听的 vip 网络接口,默认为 eth0 pg_dns_suffixPG_ACCESSstring C pgsql dns suffix, ’’ by default pgsql dns 后缀,默认为空 pg_dns_targetPG_ACCESSenum C auto, primary, vip, none, or ad hoc ip PG DNS 解析到哪里?auto、primary、vip、none 或者特定的 IP 地址 pg_exporter_enabledPG_MONITORbool C enable pg_exporter on pgsql hosts? 在 pgsql 主机上启用 pg_exporter 吗? pg_exporter_configPG_MONITORstring C pg_exporter configuration file name pg_exporter 配置文件/模板名称 pg_exporter_cache_ttlsPG_MONITORstring C pg_exporter collector ttl stage in seconds, ‘1,10,60,300’ by default pg_exporter 收集器阶梯TTL配置,默认为4个由逗号分隔的秒数:‘1,10,60,300’ pg_exporter_portPG_MONITORport C pg_exporter listen port, 9630 by default pg_exporter 监听端口,默认为 9630 pg_exporter_paramsPG_MONITORstring C extra url parameters for pg_exporter dsn pg_exporter dsn 中传入的额外 URL 参数 pg_exporter_urlPG_MONITORpgurl C overwrite auto-generate pg dsn if specified 如果指定,则覆盖自动生成的 postgres DSN 连接串 pg_exporter_auto_discoveryPG_MONITORbool C enable auto database discovery? enabled by default 监控是否启用自动数据库发现?默认启用 pg_exporter_exclude_databasePG_MONITORstring C csv of database that WILL NOT be monitored during auto-discovery 启用自动发现时,排除在外的数据库名称列表,用逗号分隔 pg_exporter_include_databasePG_MONITORstring C csv of database that WILL BE monitored during auto-discovery 启用自动发现时,只监控这个列表中的数据库,名称用逗号分隔 pg_exporter_connect_timeoutPG_MONITORint C pg_exporter connect timeout in ms, 200 by default pg_exporter 连接超时,单位毫秒,默认为 200 pg_exporter_optionsPG_MONITORarg C overwrite extra options for pg_exporter pg_exporter 的额外命令行参数选项 pgbouncer_exporter_enabledPG_MONITORbool C enable pgbouncer_exporter on pgsql hosts? 在 pgsql 主机上启用 pgbouncer_exporter 吗? pgbouncer_exporter_portPG_MONITORport C pgbouncer_exporter listen port, 9631 by default pgbouncer_exporter 监听端口,默认为 9631 pgbouncer_exporter_urlPG_MONITORpgurl C overwrite auto-generate pgbouncer dsn if specified 如果指定,则覆盖自动生成的 pgbouncer dsn 连接串 pgbouncer_exporter_optionsPG_MONITORarg C overwrite extra options for pgbouncer_exporter pgbouncer_exporter 的额外命令行参数选项 pgbackrest_exporter_enabledPG_MONITORbool C enable pgbackrest_exporter on pgsql hosts? 在 pgsql 主机上启用 pgbackrest_exporter 吗? pgbackrest_exporter_portPG_MONITORport C pgbackrest_exporter listen port, 9854 by default pgbackrest_exporter 监听端口,默认为 9854 pgbackrest_exporter_optionsPG_MONITORarg C overwrite extra options for pgbackrest_exporter pgbackrest_exporter 的额外命令行参数选项 pg_safeguardPG_REMOVEbool G/C/A prevent purging running postgres instance? false by default 防误删保险,禁止清除正在运行的 postgres 实例?默认为 false pg_rm_dataPG_REMOVEbool G/C/A remove postgres data during remove? true by default 删除 pgsql 实例时是否清理 postgres 数据目录?默认为 true pg_rm_backupPG_REMOVEbool G/C/A remove pgbackrest backup during primary remove? true by default 删除主库时是否一并清理 pgbackrest 备份?默认为 true pg_rm_pkgPG_REMOVEbool G/C/A uninstall postgres packages during remove? true by default 删除 pgsql 实例时是否卸载相关软件包?默认为 true
教程 一些使用/管理 Pigsty中 PostgreSQL 数据库的教程。
克隆一套现有的 PostgreSQL 集群 创建一套现有 PostgreSQL 集群的在线备份集群。 创建一套现有 PostgreSQL 集群的延迟备份集群 监控一个已有的 postgres 实例? 使用逻辑复制从外部 PostgreSQL 迁移至 Pigsty 托管的 PostgreSQL 实例? 使用 MinIO 作为集中的 pgBackRest 备份仓库。 使用专门的 etcd 集群作为 PostgreSQL / Patroni 的 DCS ? 使用专用的 haproxy 负载均衡器集群对外暴露暴露 PostgreSQL 服务。 使用 pg-meta CMDB 替代 pigsty.yml 作为配置清单源。 使用 PostgreSQL 作为 Grafana 的后端存储数据库? 使用 PostgreSQL 作为 Prometheus 后端存储数据库? 11.2 - 系统架构 介绍 PostgreSQL 集群的整体架构与实现细节。
11.2.1 - 实体关系图 介绍 Pigsty 中 PostgreSQL 集群的实体-关系模型,E-R 关系图,实体释义与命名规范。
先弄清楚“有哪些对象、它们如何互相引用”,再去讨论部署和运维。Pigsty 的 PGSQL 模块围绕几个核心实体构成一张稳定的 E-R 图,理解这张图能帮助你设计清晰的配置和自动化流程。
PGSQL模块在生产环境中以集群 的形式组织,这些集群 是由一组由主-备 关联的数据库实例 组成的逻辑实体 。
每个集群都是一个自治 的业务单元,由至少一个 主库实例 组成,并通过服务向外暴露能力。
在 Pigsty 的PGSQL模块中有四种核心实体:
集群 (Cluster):自治的 PostgreSQL 业务单元,用作其他实体的顶级命名空间。服务 (Service):对外暴露能力的命名抽象,路由流量,并使用节点端口暴露服务。实例 (Instance):由在单个节点上的运行进程和数据库文件组成的单一 PostgreSQL 服务器。节点 (Node):运行 Linux + Systemd 环境的硬件资源抽象,可以是裸机、VM、容器或 Pod。辅以“数据库”“角色”两个业务实体,共同组成完整的逻辑视图。如下图所示:
命名约定(沿用 Pigsty 早期约束)
集群名应为有效的 DNS 域名,不包含任何点号,正则表达式为:[a-zA-Z0-9-]+ 服务名应以集群名为前缀,并以特定单词作为后缀:primary、replica、offline、delayed,中间用-连接。 实例名以集群名为前缀,以正整数实例号为后缀,用-连接,例如${cluster}-${seq}。 节点由其首要内网IP地址标识,因为PGSQL模块中数据库与主机1:1部署,所以主机名通常与实例名相同。 11.2.2 - 组件与交互 介绍 Pigsty 中 PostgreSQL 集群中的组件,以及它们之间的交互行为与依赖关系。
总览 以下是 PostgreSQL 模块组件及其相互作用的详细描述,从上至下分别为:
集群 DNS 由 infra 节点上的 DNSMASQ 负责解析 集群 VIP 由 vip-manager 组件管理,它负责将 pg_vip_address 绑定到集群主库节点上。vip-manager 从 etcd 集群获取由 patroni 写入的集群领导者信息 集群服务由节点上的 Haproxy 对外暴露,不同服务通过节点的不同端口(543x)区分。Haproxy 端口 9101:监控指标 & 统计 & 管理页面 Haproxy 端口 5433:默认路由至主 pgbouncer:读写服务 Haproxy 端口 5434:默认路由至从库 pgbouncer:只读服务 Haproxy 端口 5436:默认路由至主 postgres:默认服务 Haproxy 端口 5438:默认路由至离线 postgres:离线服务 HAProxy 将根据 patroni 提供的健康检查信息路由流量。 Pgbouncer 是一个连接池中间件,默认监听6432端口,可以缓冲连接、暴露额外的指标,并提供额外的灵活性。Pgbouncer 是无状态的,并通过本地 Unix 套接字以 1:1 的方式与 Postgres 服务器部署。 生产流量(主/从)将默认通过 pgbouncer(可以通过pg_default_service_dest 指定跳过) 默认/离线服务将始终绕过 pgbouncer ,并直接连接到目标 Postgres。 PostgreSQL 监听5432端口,提供关系型数据库服务在多个节点上安装 PGSQL 模块,并使用同一集群名,将自动基于流式复制组成高可用集群 PostgreSQL 进程默认由 patroni 管理。 Patroni 默认监听端口 8008,监管着 PostgreSQL 服务器进程Patroni 将 Postgres 服务器作为子进程启动 Patroni 使用 etcd 作为 DCS:存储配置、故障检测和领导者选举。 Patroni 通过健康检查提供 Postgres 信息(比如主/从),HAProxy 通过健康检查使用该信息分发服务流量 Patroni 指标将被 infra 节点上的 Prometheus 抓取 PG Exporter 在 9630 端口对外暴露 postgres 架空指标PostgreSQL 指标将被 infra 节点上的 Prometheus 抓取 Pgbouncer Exporter 在端口 9631 暴露 pgbouncer 指标Pgbouncer 指标将被 infra 节点上的 Prometheus 抓取 pgBackRest 默认在使用本地备份仓库 (pgbackrest_method = local) Postgres 相关日志(postgres, pgbouncer, patroni, pgbackrest)由 promtail 负责收集Promtail 监听 9080 端口,也对 infra 节点上的 Prometheus 暴露自身的监控指标 Promtail 将日志发送至 infra 节点上的 Loki 集群 DNS 集群 DNS 服务由 infra 节点的 DNSMASQ 维护,为每个 pg_cluster 提供稳定的 FQDN(<cluster>.<pg_dns_suffix>)。DNS 记录会指向主库或 VIP,供业务侧、自动化流程与跨集群的数据服务访问,不需要直接关心节点的实时 IP。DNS 依赖部署期写入的库存信息,运行期只在 VIP 或主节点漂移时更新,其上游是 vip-manager 与 etcd 中的主节点状态。
DNS 的下游是客户端与第三方服务入口,它也为 HAProxy 等中间层提供统一的目标地址。组件可选;当集群运行在独立网络或业务端直接使用 IP 时可以跳过,但绝大多数生产环境建议启用,以避免硬编码节点地址。
关键参数
主库虚拟 IP(vip-manager) vip-manager 在每个 PG 节点上运行,通过监视 etcd 中由 Patroni 写入的领导者键,把 pg_vip_address 绑定到当前主节点上,实现透明的 L2 漂移。它依赖 DCS 的健康状态,并要求目标网络接口可被当前节点控制,从而在故障转移时立即释放并重绑 VIP,保障旧主机不会继续响应。
VIP 的下游包含 DNS、自建客户端、遗留系统等需要固定端点的访问者。该组件可选:只在 pg_vip_enabled 为 true 且业务需要静态地址时启用。启用后必须保证所有参与节点都具备相同的 VLAN 接入,否则 VIP 无法正确漂移。
关键参数
服务入口与流量调度(HAProxy) HAProxy 安装在 PG 节点(或专用服务节点),统一对外暴露数据库服务端口组:5433/5434(读写/只读,通过 Pgbouncer),5436/5438(直连主库/离线库),以及 9101 管理接口。每个后端池依靠 patroni REST API 提供的角色与健康信息做路由判断,并把流量转发到对应实例或连接池。
该组件是整个集群的入口,下游直接面向应用、ETL 与管理工具。可将 pg_service_provider 指向专用 HA 节点以承载更高流量,也可在实例本地进行发布。HAProxy 对 VIP 无依赖,但通常与 DNS 和 VIP 联动,打造统一访问口。服务定义由 pg_default_services 与 pg_services 组合而成,可精细化配置端口、负载均衡策略与目标。
关键参数
连接池(Pgbouncer) Pgbouncer 在每个实例上以无状态方式运行,优先通过本地 Unix Socket 连接 PostgreSQL,用于吸收瞬时连接、稳定会话与提供额外指标。Pigsty 默认让生产流量(5433/5434)经由 Pgbouncer,只有默认/离线服务绕过它直连 PostgreSQL。Pgbouncer 不依赖 VIP,可与 HAProxy、Patroni 独立伸缩,在 Pgbouncer 停止时 PostgreSQL 仍可提供直连服务。
Pgbouncer 的下游是大量短连接客户端,以及统一入口 HAProxy。它允许基于 auth_query 的动态用户加载,并可按需配置 SSL。组件可选,通过 pgbouncer_enabled 关闭时,默认服务将直接指向 PostgreSQL,需要相应调整连接数与会话管理策略。
关键参数
数据库实例(PostgreSQL) PostgreSQL 进程是整个模块的核心,默认监听 5432 并由 Patroni 托管。以同一 pg_cluster 在多节点安装 PGSQL 模块,将自动构建基于物理流复制的主从拓扑;primary/replica/offline 角色由 pg_role 控制,必要时可通过 pg_instances 在同一节点运行多实例。实例依赖本地数据盘、操作系统内核调优与 NODE 模块提供的系统服务。
该组件的下游是业务读写流量、pgBackRest、pg_exporter 等服务;上游是 Patroni、Ansible 引导脚本,以及 etcd 中的元数据。可根据 pg_conf 模板切换 OLTP/OLAP 配置,并通过 pg_upstream 定义级联复制。若使用 citus/gpsql,需进一步设置 pg_shard 与 pg_group。pg_hba_rules 与 pg_default_hba_rules 决定访问控制策略。
关键参数
高可用控制器(Patroni + etcd) Patroni 监听 8008,接管 PostgreSQL 的启动、配置与健康状态,将领导者、成员信息写入 etcd(命名空间由 pg_namespace 定义)。它负责自动故障转移、保持复制因子、协调参数,以及提供 REST API 供 HAProxy、监控与管理员查询。Patroni 可启用看门狗强制隔离旧主机,以避免脑裂。
Patroni 的上游是 etcd 集群与系统服务(systemd、Keepalive),下游包括 vip-manager、HAProxy、Pgbackrest 与监控组件。可以通过 patroni_mode 切换为 pause/remove 模式,以便维护或删除集群。禁用 Patroni 仅在管理外部 PG 实例时使用。
关键参数
备份子系统(pgBackRest) pgBackRest 在主库上创建本地或远程仓库,用于全量/增量备份与 WAL 归档。它与 PostgreSQL 配合执行控制命令,支持本地磁盘(默认)、MinIO 等多种目标,能够覆盖 PITR、备份链条验证与远程拉起。上游是主库的数据与归档流,下游是对象存储或本地备份盘,以及 pgbackrest_exporter 提供的可观测性。
组件可择时运行,通常在初始化完成后立即发起一次全量备份;也支持关闭(实验环境或外部备份系统)。启用 minio 仓库时需要可达的对象存储服务与凭据。恢复过程与 Patroni 集成,可通过 pgbackrest 命令将副本引导为新的主库或备库。
关键参数
PostgreSQL 指标(pg_exporter) pg_exporter 运行在 PG 节点上,使用本地 socket 登录,导出覆盖会话、缓冲命中、复制延迟、事务率等指标供 infra 节点上的 Prometheus 抓取。它与 PostgreSQL 紧耦合,重启 PostgreSQL 时会自动重连,对外监听 9630(默认)。Exporter 不依赖 VIP,与 HA 拓扑解耦。
关键参数
连接池指标(pgbouncer_exporter) pgbouncer_exporter 启动在节点上,读取 Pgbouncer 的统计视图,提供连接池利用率、等待队列与命中率指标。它依赖 Pgbouncer 的 admin 用户,并通过独立端口暴露给 Prometheus。若禁用 Pgbouncer,本组件应同时关闭。
关键参数
备份指标(pgbackrest_exporter) pgbackrest_exporter 解析该节点的 pgBackRest 状态,生成最近备份时间、大小、类型等指标。Prometheus 通过 9854(默认)采集这些指标,结合告警策略即可快速发现备份过期或失败。组件依赖 pgBackRest 元数据目录,关闭备份系统时也应禁用它。
关键参数
日志采集(Vector) Vector 常驻在节点上,跟踪 PostgreSQL、Pgbouncer、Patroni 与 pgBackRest 的日志目录,
关键参数(位于 NODE 模块的 VECTOR 组件)
11.2.3 - 身份标识符 介绍 Pigsty 中 PostgreSQL 集群的实体身份标识符:命名规范、设计理念,以及使用方法。
Pigsty 使用 PG_ID 参数组为 PGSQL 模块的每个实体赋予确定的身份。
核心身份参数 三项必填参数构成 PGSQL 的最小 ID 集:
参数 层级 作用 约束 pg_cluster集群 业务命名空间 [a-z][a-z0-9-]*pg_seq实例 集群内实例序号 递增分配的自然数,唯一且不可复用 pg_role实例 复制角色 primary / replica / offline / delayed
pg_cluster 决定所有衍生名称:实例、服务、监控标签。pg_seq 与节点 1:1 绑定,表达拓扑顺序和预期优先级。pg_role 驱动 Patroni/HAProxy 的行为:primary 唯一,replica 承载在线只读,offline 只接离线服务,delayed 用于延迟集群。Pigsty 不会为上述参数提供默认值,必须在 inventory 中显式写明。
实体身份标识 Pigsty 的 PostgreSQL 实体标识符将根据上面的核心身份参数自动生成
实体 生成规则 示例 实例 {{ pg_cluster }}-{{ pg_seq }}pg-test-1服务 {{ pg_cluster }}-{{ pg_role }}pg-test-primary节点名 默认等同实例名,但可以显式覆盖 pg-test-1
服务后缀采用内置约定:primary、replica、default、offline、delayed 等。HAProxy/pgbouncer 会读取这些标识自动构建路由。命名保持前缀一致,可直接通过 pg-test-* 查询或筛选。
监控标签体系 在 PGSQL 模块中,所有监控指标使用以下标签体系:
cls:集群名:{{ pg_cluster }}。ins:实例名:{{ pg_cluster }}-{{ pg_seq }} 。ip:实例所在节点 IP。对于 VictoriaMetrics 而言,采集 PostgreSQL 指标的 job 名固定为 pgsql;
用于监控远程 PG 实例的 job 名固定为 pgrds。
对于 VictoriaLogs 而言,采集 PostgreSQL CSV 日志的 job 名固定为 postgres;
采集 pgbackrest 日志的 job 名固定为 pgbackrest,其余组件通过 syslog 采集日志。
示例:pg-test 身份视图 pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role: replica, pg_offline_query : true }
vars :
pg_cluster : pg-test
集群 序号 角色 节点/IP 实例 服务入口 pg-test 1 primary 10.10.10.11 pg-test-1 pg-test-primary pg-test 2 replica 10.10.10.12 pg-test-2 pg-test-replica pg-test 3 replica+offline 10.10.10.13 pg-test-3 pg-test-replica / pg-test-offline
Prometheus 标签示例:
pg_up{cls="pg-test", ins="pg-test-1", ip="10.10.10.11", job="pgsql"}
pg_up{cls="pg-test", ins="pg-test-2", ip="10.10.10.12", job="pgsql"}
pg_up{cls="pg-test", ins="pg-test-3", ip="10.10.10.13", job="pgsql"}
11.2.4 - 高可用集群 深入介绍 Pigsty 中 PostgreSQL 高可用集群的架构设计、组件交互、故障场景与恢复机制。
Pigsty 的 PostgreSQL 集群带有开箱即用的高可用方案,由 Patroni 、Etcd 和 HAProxy 强力驱动。
当您的 PostgreSQL 集群含有两个或更多实例时,您无需任何配置即拥有了硬件故障自愈的数据库高可用能力 —— 只要集群中有任意实例存活,集群就可以对外提供完整的服务,而客户端只要连接至集群中的任意节点,即可获得完整的服务,而无需关心主从拓扑变化。
在默认配置下,主库故障恢复时间目标 RTO ≈ 30s,数据恢复点目标 RPO < 1MB;从库故障 RPO = 0,RTO ≈ 0 (闪断);在一致性优先模式下,可确保故障切换数据零损失:RPO = 0。以上指标均可通过参数,根据您的实际硬件条件与可靠性要求 按需配置 。
Pigsty 内置了 HAProxy 负载均衡器用于自动流量切换,提供 DNS/VIP/LVS 等多种接入方式供客户端选用。故障切换与主动切换对业务侧除零星闪断外几乎无感知,应用不需要修改连接串重启。
极小的维护窗口需求带来了极大的灵活便利:您完全可以在无需应用配合的情况下滚动维护升级整个集群。硬件故障可以等到第二天再抽空善后处置的特性,让研发,运维与 DBA 都能在故障时安心睡个好觉。
许多大型组织与核心机构已经在生产环境中长时间使用 Pigsty ,最大的部署有 25K CPU 核心与 220+ PostgreSQL 超大规格实例(64c / 512g / 3TB NVMe SSD);在这一部署案例中,五年内经历了数十次硬件故障与各类事故,但依然可以保持高于 99.999% 的总体可用性战绩。
架构概览 Pigsty 高可用架构由四个核心组件构成,它们协同工作,实现故障自动检测、领导者选举与流量切换:
flowchart TB
subgraph Client["🖥️ 客户端接入层"]
C[("Client")]
ACCESS["DNS / VIP / HAProxy / L4 LVS"]
end
subgraph Node1["📦 Node 1"]
HAP1["HAProxy :9101<br/>Primary :5433 | Replica :5434"]
subgraph Stack1["Patroni :8008"]
PG1[("PostgreSQL<br/>[Primary] :5432")]
PGB1["PgBouncer :6432"]
end
end
subgraph Node2["📦 Node 2"]
HAP2["HAProxy :9101<br/>Primary :5433 | Replica :5434"]
subgraph Stack2["Patroni :8008"]
PG2[("PostgreSQL<br/>[Replica] :5432")]
PGB2["PgBouncer :6432"]
end
end
subgraph Node3["📦 Node 3"]
HAP3["HAProxy :9101<br/>Primary :5433 | Replica :5434"]
subgraph Stack3["Patroni :8008"]
PG3[("PostgreSQL<br/>[Replica] :5432")]
PGB3["PgBouncer :6432"]
end
end
subgraph ETCD["🔐 Etcd Cluster (Raft Consensus)"]
E1[("Etcd-1<br/>:2379")]
E2[("Etcd-2<br/>:2379")]
E3[("Etcd-3<br/>:2379")]
end
C --> ACCESS
ACCESS --> HAP1 & HAP2 & HAP3
HAP1 -.->|"HTTP Health Check"| Stack1
HAP2 -.->|"HTTP Health Check"| Stack2
HAP3 -.->|"HTTP Health Check"| Stack3
HAP1 --> PGB1
HAP2 --> PGB2
HAP3 --> PGB3
PG1 ==>|"Streaming Replication"| PG2
PG1 ==>|"Streaming Replication"| PG3
Stack1 <-->|"Leader Lease"| ETCD
Stack2 <-->|"Leader Lease"| ETCD
Stack3 <-->|"Leader Lease"| ETCD
E1 <--> E2 <--> E3
E1 <--> E3
style PG1 fill:#4CAF50,color:#fff
style PG2 fill:#2196F3,color:#fff
style PG3 fill:#2196F3,color:#fff
style ETCD fill:#FF9800,color:#fff 组件详解 PostgreSQL PostgreSQL 是核心数据库服务,使用标准流复制 (Streaming Replication)搭建物理从库:
主库(Primary) :接受读写请求,生成 WAL 日志从库(Replica) :通过流复制实时接收 WAL,提供只读查询复制槽(Replication Slot) :确保 WAL 不被过早清理同步提交 :可选的同步复制模式,确保 RPO = 0关键配置(由 Patroni 动态管理):
wal_level : logical # 启用逻辑复制级别
max_wal_senders : 50 # 最大 WAL 发送进程数
max_replication_slots : 50 # 最大复制槽数量
hot_standby : on # 从库可读
wal_log_hints : on # 支持 pg_rewind
track_commit_timestamp : on # 追踪事务时间戳
synchronous_standby_names : '' # 同步从库列表(动态管理)
Patroni Patroni 是高可用的核心引擎,负责管理 PostgreSQL 生命周期与集群状态:
核心职责 :
管理 PostgreSQL 进程的启停与配置 维护领导者租约(Leader Lease) 执行自动故障切换(Failover)与主动切换(Switchover) 提供 REST API 用于健康检查与集群管理 处理从库的自动重建与 pg_rewind 关键时序参数 (控制 RTO):
参数 默认值 说明 ttl30s 领导者租约有效期,即故障检测时间窗口 loop_wait10s Patroni 主循环间隔 retry_timeout10s DCS 与 PostgreSQL 操作重试超时 primary_start_timeout10s 主库启动超时时间 primary_stop_timeout30s 主库优雅停止超时(同步模式下生效)
这些参数由 pg_rto 统一计算派生,默认 30s 的 RTO 对应:
ttl : 30 # 领导者租约 TTL
loop_wait : 10 # 主循环间隔 = RTO/3
retry_timeout : 10 # 重试超时 = RTO/3
primary_start_timeout : 10 # 主库启动超时 = RTO/3
约束条件 :ttl >= loop_wait + retry_timeout * 2
健康检查端点 (供 HAProxy 使用):
端点 用途 返回 200 条件 /primary主库服务 当前节点是 Leader /replica从库服务 当前节点是 Replica /read-only只读服务 节点可读(主库或从库) /health健康检查 PostgreSQL 运行正常 /leader领导者检查 持有领导者锁 /async异步从库 异步复制从库 /sync同步从库 同步复制从库
Etcd Etcd 作为分布式配置存储(DCS),提供集群共识能力:
核心职责 :
存储集群配置与状态信息 提供领导者选举的原子操作 通过租约机制实现故障检测 存储 PostgreSQL 动态配置 存储结构 (以 /pg 命名空间为例):
/pg/
├── <cluster_name>/
│ ├── leader # 当前领导者标识
│ ├── config # 集群配置(DCS 配置)
│ ├── history # 故障切换历史
│ ├── initialize # 集群初始化标记
│ ├── members/ # 成员信息目录
│ │ ├── pg-test-1 # 实例 1 元数据
│ │ ├── pg-test-2 # 实例 2 元数据
│ │ └── pg-test-3 # 实例 3 元数据
│ └── sync # 同步从库状态
关键配置 :
election_timeout : 1000ms # 选举超时(影响 Etcd 自身 HA)
heartbeat_interval : 100ms # 心跳间隔
quota_backend_bytes : 16GB # 存储配额
auto_compaction_mode : periodic # 自动压缩
auto_compaction_retention : 24h # 保留 24 小时历史
Etcd 集群要求 :
必须奇数节点 :3、5、7 个节点,确保多数派仲裁推荐独立部署于管理节点,与 PostgreSQL 节点分离 网络延迟应保持在 10ms 以内 HAProxy HAProxy 负责服务发现与流量分发:
核心职责 :
通过 HTTP 健康检查发现主从角色 将流量路由到正确的后端节点 提供负载均衡与连接池功能 实现服务的自动故障转移 默认服务定义 :
服务名 端口 目标 健康检查 用途 primary 5433 pgbouncer /primary读写服务,路由到主库 replica 5434 pgbouncer /read-only只读服务,优先路由到从库 default 5436 postgres /primary直连主库(绕过连接池) offline 5438 postgres /replica离线从库(ETL/备份)
健康检查配置 :
listen pg-test-primary
bind *:5433
mode tcp
option httpchk
http-check send meth OPTIONS uri /primary
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3
on-marked-down shutdown-sessions slowstart 30s
maxconn 3000 maxqueue 128 weight 100
server pg-test-1 10.10.10.11:6432 check port 8008
server pg-test-2 10.10.10.12:6432 check port 8008 backup
server pg-test-3 10.10.10.13:6432 check port 8008 backup
健康检查时序参数 (影响 RTO 敏感度):
参数 默认值 说明 inter3s 正常检查间隔 fastinter1s 状态变化后的快速检查间隔 downinter5s 节点宕机后的检查间隔 rise3 节点恢复需要连续成功次数 fall3 节点宕机需要连续失败次数
流量切换时序 (主库故障):
故障检测:fall × inter = 3 × 3s = 9s 快速探测:一旦发现异常,切换到 fastinter(1s) 服务恢复:新主库提升后,rise × fastinter = 3 × 1s = 3s VIP Manager(可选) vip-manager 提供可选的二层 VIP 支持:
工作原理 :
监听 Etcd 中的领导者键(/pg/<cluster>/leader) 当本节点成为领导者时,绑定 VIP 到指定网卡 发送免费 ARP 通告网络中的设备更新 MAC 映射 当失去领导者地位时,解绑 VIP 配置示例 :
interval : 1000 # 检查间隔(毫秒)
trigger-key : "/pg/pg-test/leader" # 监听的 Etcd 键
trigger-value : "pg-test-1" # 匹配的领导者值
ip : 10.10.10.100 # VIP 地址
netmask : 24 # 子网掩码
interface : eth0 # 绑定网卡
dcs-type : etcd # DCS 类型
retry-num : 2 # 重试次数
retry-after : 250 # 重试间隔(毫秒)
使用限制 :
要求所有节点在同一二层网络 云环境通常不支持,需使用云厂商 VIP 或 DNS 方案 切换时间约 1-2 秒 控制流与数据流 正常运行状态 控制流 :Patroni 与 Etcd 之间的心跳与租约管理
flowchart LR
subgraph Control["⚙️ 控制流 (Control Flow)"]
direction LR
P1["Patroni<br/>(Primary)"]
P2["Patroni<br/>(Replica)"]
ETCD[("Etcd<br/>Cluster")]
P1 -->|"续租/心跳"| ETCD
P2 -->|"续租/心跳"| ETCD
ETCD -->|"租约/配置"| P1
ETCD -->|"租约/配置"| P2
end
style ETCD fill:#FF9800,color:#fff 数据流 :客户端请求与 WAL 复制
flowchart LR
subgraph Data["📊 数据流 (Data Flow)"]
direction LR
CLIENT["Client"]
HAP["HAProxy"]
PGB["PgBouncer"]
PG_P[("PostgreSQL<br/>[Primary]")]
PG_R[("PostgreSQL<br/>[Replica]")]
PATRONI["Patroni :8008"]
CLIENT -->|"SQL Request"| HAP
HAP -->|"路由"| PGB
PGB --> PG_P
HAP -.->|"健康检查<br/>/primary /replica"| PATRONI
PG_P ==>|"WAL Stream"| PG_R
end
style PG_P fill:#4CAF50,color:#fff
style PG_R fill:#2196F3,color:#fff 故障切换流程 当主库发生故障时,系统经历以下阶段:
sequenceDiagram
autonumber
participant Primary as 🟢 Primary
participant Patroni_P as Patroni (Primary)
participant Etcd as 🟠 Etcd Cluster
participant Patroni_R as Patroni (Replica)
participant Replica as 🔵 Replica
participant HAProxy as HAProxy
Note over Primary: T=0s 主库故障发生
rect rgb(255, 235, 235)
Note right of Primary: 故障检测阶段 (0-10s)
Primary-x Patroni_P: 进程崩溃
Patroni_P--x Etcd: 停止续租
HAProxy--x Patroni_P: 健康检查失败
Etcd->>Etcd: 租约倒计时开始
end
rect rgb(255, 248, 225)
Note right of Etcd: 选举阶段 (10-20s)
Etcd->>Etcd: 租约过期,释放领导者锁
Patroni_R->>Etcd: 检查资格 (LSN, 复制延迟)
Etcd->>Patroni_R: 授予领导者锁
end
rect rgb(232, 245, 233)
Note right of Replica: 提升阶段 (20-30s)
Patroni_R->>Replica: 执行 PROMOTE
Replica-->>Replica: 提升为新主库
Patroni_R->>Etcd: 更新状态
HAProxy->>Patroni_R: 健康检查 /primary
Patroni_R-->>HAProxy: 200 OK
end
Note over HAProxy: T≈30s 服务恢复
HAProxy->>Replica: 路由写入流量到新主库 关键时序公式 :
RTO ≈ TTL + Election_Time + Promote_Time + HAProxy_Detection
其中:
- TTL = pg_rto (默认 30s)
- Election_Time ≈ 1-2s
- Promote_Time ≈ 1-5s
- HAProxy_Detection = fall × inter + rise × fastinter ≈ 12s
实际 RTO 通常在 15-40s 之间,取决于:
- 网络延迟
- 从库 WAL 回放进度
- PostgreSQL 恢复速度
高可用部署模式 三节点标准模式 最推荐的生产部署模式 ,提供完整的自动故障转移能力:
flowchart TB
subgraph Cluster["🏢 三节点高可用架构"]
direction TB
subgraph Node1["Node 1"]
E1[("Etcd")]
H1["HAProxy"]
P1["Patroni + PostgreSQL<br/>🟢 Primary"]
end
subgraph Node2["Node 2"]
E2[("Etcd")]
H2["HAProxy"]
P2["Patroni + PostgreSQL<br/>🔵 Replica"]
end
subgraph Node3["Node 3"]
E3[("Etcd")]
H3["HAProxy"]
P3["Patroni + PostgreSQL<br/>🔵 Replica"]
end
end
E1 <-->|"Raft"| E2
E2 <-->|"Raft"| E3
E1 <-->|"Raft"| E3
P1 ==>|"Replication"| P2
P1 ==>|"Replication"| P3
style P1 fill:#4CAF50,color:#fff
style P2 fill:#2196F3,color:#fff
style P3 fill:#2196F3,color:#fff
style E1 fill:#FF9800,color:#fff
style E2 fill:#FF9800,color:#fff
style E3 fill:#FF9800,color:#fff 故障容忍 :
✅ 任意 1 个节点故障:自动切换,服务继续 ⚠️ 2 个节点故障:需要人工介入 配置示例 :
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : replica }
vars :
pg_cluster : pg-test
五节点增强模式 更高可用性要求的部署 ,可容忍 2 个节点故障:
flowchart LR
subgraph Cluster["🏛️ 五节点高可用架构"]
direction TB
subgraph Row1[""]
direction LR
N1["Node 1<br/>Etcd + 🟢 Primary"]
N2["Node 2<br/>Etcd + 🔵 Replica"]
N3["Node 3<br/>Etcd + 🔵 Replica"]
N4["Node 4<br/>Etcd + 🔵 Replica"]
N5["Node 5<br/>Etcd + 🔵 Replica"]
end
end
N1 ==> N2 & N3 & N4 & N5
N1 <-.->|"Etcd Raft"| N2
N2 <-.->|"Etcd Raft"| N3
N3 <-.->|"Etcd Raft"| N4
N4 <-.->|"Etcd Raft"| N5
style N1 fill:#4CAF50,color:#fff
style N2 fill:#2196F3,color:#fff
style N3 fill:#2196F3,color:#fff
style N4 fill:#2196F3,color:#fff
style N5 fill:#2196F3,color:#fff Etcd 仲裁 :3/5 多数派 | PostgreSQL :1 主 4 从
故障容忍 :
✅ 任意 2 个节点故障:自动切换 ⚠️ 3 个节点故障:需要人工介入 适用场景 :
金融核心系统 跨机房部署(2+2+1 分布) 需要专用离线从库的场景 两节点半高可用模式 资源受限时的折中方案 ,提供有限的自动切换能力:
flowchart TB
subgraph Cluster["⚠️ 两节点半高可用架构"]
direction LR
subgraph Node1["Node 1 (Infra)"]
E1[("Etcd")]
H1["HAProxy"]
P1["Patroni + PostgreSQL<br/>🟢 Primary"]
end
subgraph Node2["Node 2"]
E2[("Etcd")]
H2["HAProxy"]
P2["Patroni + PostgreSQL<br/>🔵 Replica"]
end
subgraph Arbiter["❓ 需要仲裁者"]
E3[("Etcd<br/>(外部)")]
end
end
E1 <-->|"无法形成多数派"| E2
E1 <-.-> E3
E2 <-.-> E3
P1 ==>|"Replication"| P2
style P1 fill:#4CAF50,color:#fff
style P2 fill:#2196F3,color:#fff
style E1 fill:#FF9800,color:#fff
style E2 fill:#FF9800,color:#fff
style E3 fill:#9E9E9E,color:#fff,stroke-dasharray: 5 5 问题 :Etcd 只有 2 节点,无法形成多数派
解决方案 :
在外部添加第 3 个 Etcd 节点(纯仲裁) 使用 failsafe_mode 防止脑裂 接受非对称故障切换 非对称故障切换 :
从库故障 :✅ 自动处理,主库继续服务主库故障 :⚠️ 需要人工介入(无法自动选举)配置建议 :
# 启用 failsafe 模式防止误切换
patroni_watchdog_mode : off # 禁用 watchdog
pg_rto : 60 # 增大 RTO 减少误报
同城双中心模式 同城容灾部署 ,机房级故障容忍:
flowchart TB
subgraph DualDC["🌐 同城双中心架构"]
direction TB
subgraph DCA["📍 数据中心 A"]
direction LR
N1["Node 1<br/>Etcd + 🟢 Primary"]
N2["Node 2<br/>Etcd + 🔵 Replica"]
end
subgraph DCB["📍 数据中心 B"]
direction LR
N3["Node 3<br/>Etcd + 🔵 Replica"]
N4["Node 4<br/>Etcd + 🔵 Replica"]
end
subgraph Arbiter["🏠 第三方机房"]
N5["Node 5<br/>Etcd (仲裁)"]
end
end
N1 ==>|"Replication"| N2 & N3 & N4
N1 & N2 <-->|"< 5ms"| N3 & N4
N1 & N2 & N3 & N4 <-.->|"Etcd Raft"| N5
style N1 fill:#4CAF50,color:#fff
style N2 fill:#2196F3,color:#fff
style N3 fill:#2196F3,color:#fff
style N4 fill:#2196F3,color:#fff
style N5 fill:#FF9800,color:#fff 网络要求 :
机房间延迟 < 5ms(同步复制)或 < 20ms(异步复制) 带宽充足,确保 WAL 传输 仲裁节点可以是轻量级 VM 故障场景 :
故障 影响 恢复方式 DC-A 单节点故障 无影响 自动 DC-B 单节点故障 无影响 自动 DC-A 整体故障 切换到 DC-B 自动(需仲裁节点) DC-B 整体故障 无影响 自动 仲裁节点故障 降级为 4 节点 可容忍 1 节点故障
异地多活模式 跨地域部署 ,需要考虑延迟与带宽:
flowchart LR
subgraph GeoDR["🌍 异地容灾架构"]
direction LR
subgraph Beijing["🏙️ 主数据中心 (北京)"]
direction TB
BJ_E[("Etcd<br/>3节点")]
BJ1["🟢 Primary"]
BJ2["🔵 Replica"]
end
subgraph Shanghai["🏙️ 灾备数据中心 (上海)"]
direction TB
SH_E[("Etcd<br/>独立集群")]
SH1["🔵 Replica"]
SH2["🔵 Replica"]
end
end
BJ1 ==>|"Async Replication<br/>延迟: 20-50ms"| SH1
BJ1 --> BJ2
SH1 --> SH2
style BJ1 fill:#4CAF50,color:#fff
style BJ2 fill:#2196F3,color:#fff
style SH1 fill:#9C27B0,color:#fff
style SH2 fill:#9C27B0,color:#fff
style BJ_E fill:#FF9800,color:#fff
style SH_E fill:#607D8B,color:#fff 部署策略 :
主中心:完整 HA 集群(3+ 节点) 灾备中心:级联从库(Standby Cluster) 异步复制:容忍网络延迟 独立 Etcd:避免跨地域仲裁 级联从库配置 :
# 灾备集群配置
pg-standby :
hosts :
10.20.10.11 : { pg_seq: 1, pg_role : primary } # 级联领导者
10.20.10.12 : { pg_seq: 2, pg_role : replica }
vars :
pg_cluster : pg-standby
pg_upstream : 10.10.10.11 # 指向主集群
pg_delay : 1h # 可选:延迟复制
故障场景分析 单节点故障 主库进程崩溃 场景 :PostgreSQL 主库进程被 kill -9 或发生崩溃
flowchart LR
subgraph Detection["🔍 故障检测"]
D1["Patroni 检测进程消失"]
D2["尝试重启 PostgreSQL"]
D3["重启失败,停止续租"]
D1 --> D2 --> D3
end
subgraph Failover["🔄 故障切换"]
F1["Etcd 租约过期 (~10s)"]
F2["触发选举,最新从库胜出"]
F3["新主库提升"]
F4["HAProxy 检测到新主库"]
F1 --> F2 --> F3 --> F4
end
subgraph Impact["📊 影响"]
I1["写服务中断: 15-30s"]
I2["读服务: 短暂闪断"]
I3["数据丢失: < 1MB 或 0"]
end
Detection --> Failover --> Impact
style D1 fill:#ffcdd2
style F3 fill:#c8e6c9
style I1 fill:#fff9c4 Patroni 进程故障 场景 :Patroni 进程被杀或崩溃
flowchart TB
FAULT["Patroni 进程故障"]
subgraph Detection["故障检测"]
D1["Patroni 停止续租"]
D2["PostgreSQL 继续运行<br/>(orphan 状态)"]
D3["Etcd 租约倒计时"]
end
subgraph FailsafeOn["failsafe_mode: true"]
FS1["检查是否能访问其他 Patroni"]
FS2["✅ 可以 → 继续作为主库"]
FS3["❌ 不能 → 自我降级"]
end
subgraph FailsafeOff["failsafe_mode: false"]
FF1["租约过期后触发切换"]
FF2["原主库降级"]
end
FAULT --> Detection
Detection --> FailsafeOn
Detection --> FailsafeOff
style FAULT fill:#f44336,color:#fff
style FS2 fill:#4CAF50,color:#fff
style FS3 fill:#ff9800,color:#fff 从库故障 场景 :任意从库节点故障
影响 :
只读流量重新分配到其他从库 如果无其他从库,主库承担只读流量 ✅ 写服务完全不受影响 恢复 :
节点恢复后 Patroni 自动启动 自动从主库重新同步 恢复为从库角色 多节点故障 三节点坏两个(2/3 故障) 场景 :3 节点集群,2 个节点同时故障
flowchart TB
subgraph Analysis["情况分析"]
A1["Etcd 失去多数派 (1/3 < 2/3)"]
A2["无法进行领导者选举"]
A3["自动切换机制失效"]
end
subgraph Survivor["存活节点情况"]
S1{"存活节点是?"}
S2["🟢 主库<br/>failsafe_mode 下继续运行"]
S3["🔵 从库<br/>无法自动提升"]
end
A1 --> A2 --> A3 --> S1
S1 -->|"Primary"| S2
S1 -->|"Replica"| S3
style A1 fill:#ffcdd2
style S2 fill:#c8e6c9
style S3 fill:#fff9c4 紧急恢复流程 :
# 1. 确认存活节点状态
patronictl -c /etc/patroni/patroni.yml list
# 2. 如果存活节点是从库,手动提升
pg_ctl promote -D /pg/data
# 3. 或者使用 pg-promote 脚本
/pg/bin/pg-promote
# 4. 修改 HAProxy 配置,直接指向存活节点
# 注释掉健康检查,硬编码路由
# 5. 恢复 Etcd 集群后,重新初始化
两节点坏一个(1/2 故障) 场景 :2 节点集群,主库故障
问题 :
Etcd 只有 2 节点,无多数派 无法完成选举 从库无法自动提升 解决方案 :
方案 1:添加外部 Etcd 仲裁节点 方案 2:人工介入提升从库 方案 3:使用 Witness 节点 手动提升步骤 :
确认主库确实不可恢复 停止从库 Patroni:systemctl stop patroni 手动提升:pg_ctl promote -D /pg/data 直接启动 PostgreSQL:systemctl start postgres 更新应用连接串或 HAProxy 配置 Etcd 集群故障 Etcd 单节点故障 场景 :3 节点 Etcd 集群,1 节点故障
影响 :
✅ Etcd 仍有多数派(2/3) ✅ 服务正常运行 ✅ PostgreSQL HA 不受影响 恢复 :
修复故障节点 使用 etcd-add 重新加入 或替换为新节点 Etcd 多数派丢失 场景 :3 节点 Etcd 集群,2 节点故障
flowchart TB
subgraph Impact["❌ 影响"]
I1["Etcd 无法写入"]
I2["Patroni 无法续租"]
I3["failsafe_mode 激活"]
I4["无法进行故障切换"]
end
subgraph PG["PostgreSQL 表现"]
P1["🟢 主库: 继续运行"]
P2["🔵 从库: 继续复制"]
P3["✅ 新写入可以继续"]
end
subgraph Limit["⚠️ 限制"]
L1["无法 switchover"]
L2["无法 failover"]
L3["配置变更无法生效"]
end
Impact --> PG --> Limit
style I1 fill:#ffcdd2
style P1 fill:#c8e6c9
style L1 fill:#fff9c4 恢复优先级 :
恢复 Etcd 多数派 验证 PostgreSQL 状态 检查 Patroni 是否正常续租 网络分区 主库网络隔离 场景 :主库与 Etcd/其他节点网络不通
flowchart LR
subgraph Isolated["🔒 隔离侧 (主库)"]
P1["Primary"]
CHECK{"failsafe_mode<br/>检查"}
CONT["继续运行"]
DEMOTE["自我降级"]
P1 --> CHECK
CHECK -->|"能访问其他 Patroni"| CONT
CHECK -->|"不能访问"| DEMOTE
end
subgraph Majority["✅ 多数派侧"]
E[("Etcd")]
P2["Replica"]
ELECT["触发选举"]
NEWPRI["新主库产生"]
E --> ELECT --> P2 --> NEWPRI
end
Isolated -.->|"网络分区"| Majority
style P1 fill:#ff9800,color:#fff
style DEMOTE fill:#f44336,color:#fff
style NEWPRI fill:#4CAF50,color:#fff 脑裂防护 :
Patroni failsafe_mode 旧主库自我检测 fencing(可选) Watchdog(可选) Watchdog 机制 用于极端情况下的防护 :
watchdog :
mode : automatic # off|automatic|required
device : /dev/watchdog
safety_margin : 5 # 安全边际(秒)
工作原理 :
Patroni 定期向 watchdog 设备写入 如果 Patroni 无响应,内核触发重启 确保旧主库不会继续服务 防止严重的脑裂场景 RTO / RPO 深度分析 RTO 时序分解 恢复时间目标(RTO) 由多个阶段组成:
gantt
title RTO 时间分解 (默认配置 pg_rto=30s)
dateFormat ss
axisFormat %S秒
section 故障检测
Patroni 检测/停止续租 :a1, 00, 10s
section 选举阶段
Etcd 租约过期 :a2, after a1, 2s
候选者竞选 (比较 LSN) :a3, after a2, 3s
section 提升阶段
执行 promote :a4, after a3, 3s
更新 Etcd 状态 :a5, after a4, 2s
section 流量切换
HAProxy 检测新主库 :a6, after a5, 5s
HAProxy 确认 (rise) :a7, after a6, 3s
服务恢复 :milestone, after a7, 0s 影响 RTO 的关键参数 参数 影响 调优建议 pg_rtoTTL/loop_wait/retry_timeout 的基准 网络稳定可减小到 15-20s ttl故障检测时间窗口 = pg_rto loop_waitPatroni 检查间隔 = pg_rto / 3 interHAProxy 健康检查间隔 可减小到 1-2s fall故障判定次数 可减小到 2 rise恢复判定次数 可减小到 2
激进配置(RTO ≈ 15s) :
pg_rto : 15 # 更短的 TTL
# HAProxy 配置
default-server inter 1s fastinter 500ms fall 2 rise 2
警告 :过短的 RTO 会增加误报切换的风险!
RPO 时序分解 恢复点目标(RPO) 取决于复制模式:
异步复制模式(默认) sequenceDiagram
participant P as 🟢 Primary
participant W as WAL
participant R as 🔵 Replica
Note over P: T=0 Commit
P->>W: WAL 写入本地
P-->>P: 返回成功给客户端
Note over P,R: T+Δ (复制延迟)
P->>R: WAL 发送
R->>R: WAL 接收 & 回放
Note over P: T+X 故障发生
Note over P: ❌ 未发送的 WAL 丢失
Note over R: RPO = Δ ≈ 几十KB ~ 1MB 复制延迟监控 :
-- 查看复制延迟
SELECT client_addr ,
state ,
sent_lsn ,
write_lsn ,
flush_lsn ,
replay_lsn ,
pg_wal_lsn_diff ( sent_lsn , replay_lsn ) AS lag_bytes
FROM pg_stat_replication ;
同步复制模式(RPO = 0) sequenceDiagram
participant P as 🟢 Primary
participant W as WAL
participant R as 🔵 Sync Replica
Note over P: T=0 Commit
P->>W: WAL 写入本地
P->>R: WAL 发送
R->>R: WAL 接收
R-->>P: 确认接收 ✓
P-->>P: 返回成功给客户端
Note over P: 故障发生
Note over R: ✅ 所有已提交数据已在从库
Note over P,R: RPO = 0 (零数据丢失) 启用同步复制 :
# 使用 crit.yml 模板
pg_conf : crit.yml
# 或设置 RPO = 0
pg_rpo : 0
# Patroni 将自动配置:
# synchronous_mode: true
# synchronous_standby_names: '*'
RTO / RPO 权衡矩阵 配置模式 pg_rto pg_rpo 实际 RTO 实际 RPO 适用场景 默认 (OLTP) 30s 1MB 20-40s < 1MB 常规业务系统 快速切换 15s 1MB 10-20s < 1MB 低延迟要求 零丢失 (CRIT) 30s 0 20-40s 0 金融核心系统 保守模式 60s 1MB 40-80s < 1MB 不稳定网络
配置示例 :
# 快速切换模式
pg_rto : 15
pg_rpo : 1048576
pg_conf : oltp.yml
# 零丢失模式
pg_rto : 30
pg_rpo : 0
pg_conf : crit.yml
# 保守模式(不稳定网络)
pg_rto : 60
pg_rpo : 1048576
pg_conf : oltp.yml
利弊权衡 可用性优先 vs 一致性优先 维度 可用性优先 (默认) 一致性优先 (crit) 同步复制 关闭 开启 故障切换 快速,可能丢数据 谨慎,零数据丢失 写延迟 低 高(多一次网络往返) 吞吐量 高 较低 从库故障影响 无 可能阻塞写入 RPO < 1MB = 0
RTO 权衡 较小 RTO 较大 RTO ✅ 故障恢复快 ✅ 误报风险低 ✅ 业务中断短 ✅ 网络抖动容忍度高 ❌ 误报切换风险高 ❌ 故障恢复慢 ❌ 网络要求严格 ❌ 业务中断长
RPO 权衡 较大 RPO RPO = 0 ✅ 高性能 ✅ 零数据丢失 ✅ 高可用(单从库故障无影响) ✅ 金融合规 ❌ 故障可能丢数据 ❌ 写延迟增加 ❌ 同步从库故障影响写入
最佳实践 生产环境检查清单 基础设施 :
参数配置 :
监控告警 :
灾备演练 :
常见问题排查 故障切换失败 :
# 检查 Patroni 状态
patronictl -c /etc/patroni/patroni.yml list
# 检查 Etcd 集群健康
etcdctl endpoint health
# 检查复制延迟
psql -c "SELECT * FROM pg_stat_replication"
# 查看 Patroni 日志
journalctl -u patroni -f
脑裂场景处理 :
# 1. 确认哪个是"真正"的主库
psql -c "SELECT pg_is_in_recovery()"
# 2. 停止"错误"的主库
systemctl stop patroni
# 3. 使用 pg_rewind 同步
pg_rewind --target-pgdata= /pg/data --source-server= "host=<true_primary>"
# 4. 重启 Patroni
systemctl start patroni
相关参数 参数名称: pg_rto, 类型: int, 层次:C
以秒为单位的恢复时间目标(RTO)。默认为 30 秒。
此参数用于派生 Patroni 的关键时序参数:
ttl = pg_rtoloop_wait = pg_rto / 3retry_timeout = pg_rto / 3primary_start_timeout = pg_rto / 3减小此值可以加快故障恢复,但会增加误报切换的风险。
参数名称: pg_rpo, 类型: int, 层次:C
以字节为单位的恢复点目标(RPO),默认为 1048576(1MB)。
设为 0 启用同步复制,确保零数据丢失 设为较大值允许更多复制延迟,提高可用性 此值也用于 maximum_lag_on_failover 参数 参数名称: pg_conf, 类型: string, 层次:C
Patroni 配置模板,默认为 oltp.yml。可选值:
模板 用途 同步复制 适用场景 oltp.ymlOLTP 负载 否 常规业务系统 olap.ymlOLAP 负载 否 分析型应用 crit.yml关键系统 是 金融核心系统 tiny.yml微型实例 否 开发测试环境
参数名称: patroni_watchdog_mode, 类型: string, 层次:C
Watchdog 模式,默认为 off。可选值:
off:禁用 watchdogautomatic:如果可用则使用required:必须使用,否则拒绝启动Watchdog 用于在极端情况下(如 Patroni 挂起)确保节点自我重启,防止脑裂。
参数名称: pg_vip_enabled, 类型: bool, 层次:C
是否启用 L2 VIP,默认为 false。
启用后需要配置:
pg_vip_address:VIP 地址(CIDR 格式)pg_vip_interface:绑定网卡注意:云环境通常不支持 L2 VIP。
参考资料 11.2.5 - 时间点恢复 介绍 Pigsty 中 PostgreSQL 时间点恢复的实现架构,原理,利弊权衡与实现细节。
您可以将集群恢复回滚至过去任意时刻,避免软件缺陷与人为失误导致的数据损失。
Pigsty 的 PostgreSQL 集群带有自动配置的时间点恢复(PITR)方案,基于备份组件 pgBackRest 与可选的对象存储仓库 MinIO 提供。
高可用方案 可以解决硬件故障,但却对软件缺陷与人为失误导致的数据删除/覆盖写入/删库等问题却无能为力。
对于这种情况,Pigsty 提供了开箱即用的 时间点恢复 (Point in Time Recovery, PITR)能力,无需额外配置即默认启用。
Pigsty 为您提供了基础备份与 WAL 归档的默认配置,您可以使用本地目录与磁盘,亦或专用的 MinIO 集群或 S3 对象存储服务来存储备份并实现异地容灾。
当您使用本地磁盘时,默认保留恢复至过去一天内的任意时间点的能力。当您使用 MinIO 或 S3 时,默认保留恢复至过去一周内的任意时间点的能力。
只要存储空间管够,您尽可保留任意长地可恢复时间段,丰俭由人。
时间点恢复(PITR)解决什么问题?
容灾能⼒增强:RPO 从 ∞ 降⾄ ⼗⼏MB, RTO 从 ∞ 降⾄ ⼏⼩时/⼏刻钟。 确保数据安全:C/I/A 中的 数据完整性 :避免误删导致的数据⼀致性问题。 确保数据安全:C/I/A 中的 数据可⽤性 :提供对“永久不可⽤”这种灾难情况的兜底 单实例配置策略 事件 RTO RPO 什么也不做宕机 永久丢失 全部丢失 基础备份宕机 取决于备份大小与带宽(几小时) 丢失上一次备份后的数据(几个小时到几天) 基础备份 + WAL归档宕机 取决于备份大小与带宽(几小时) 丢失最后尚未归档的数据(几十MB)
时间点恢复有什么代价?
降低数据安全中的 C:机密性 ,产生额外泄漏点,需要额外对备份进⾏保护。 额外的资源消耗:本地存储或⽹络流量 / 带宽开销,通常并不是⼀个问题。 复杂度代价升⾼:⽤户需要付出备份管理成本。 时间点恢复的局限性
如果只有 PITR 用于故障恢复,则 RTO 与 RPO 指标相比 高可用方案 更为逊色,通常应两者组合使用。
RTO :如果只有单机 + PITR,恢复时长取决于备份大小与网络/磁盘带宽,从十几分钟到几小时,几天不等。RPO :如果只有单机 + PITR,宕机时可能丢失少量数据,一个或几个 WAL 日志段文件可能尚未归档,损失 16 MB 到⼏⼗ MB 不等的数据。除了 PITR 之外,您还可以在 Pigsty 中使用 延迟集群 来解决人为失误或软件缺陷导致的数据误删误改问题。
原理 时间点恢复允许您将集群恢复回滚至过去的“任意时刻”,避免软件缺陷与人为失误导致的数据损失。要做到这一点,首先需要做好两样准备工作:基础备份 与 WAL归档 。
拥有 基础备份 ,允许用户将数据库恢复至备份时的状态,而同时拥有从某个基础备份开始的 WAL归档 ,允许用户将数据库恢复至基础备份时刻之后的任意时间点。
详细原理,请参阅:基础备份与时间点恢复 ;具体操作,请参考 PGSQL管理:备份恢复 。
基础备份 Pigsty 使用 pgbackrest 管理 PostgreSQL 备份。pgBackRest 将在所有集群实例上初始化空仓库,但只会在集群主库上实际使用仓库。
pgBackRest 支持三种备份模式:全量备份 ,增量备份 ,差异备份,其中前两者最为常用。
全量备份将对数据库集群取一个当前时刻的全量物理快照,增量备份会记录当前数据库集群与上一次全量备份之间的差异。
Pigsty 为备份提供了封装命令:/pg/bin/pg-backup [full|incr]。您可以通过 Crontab 或任何其他任务调度系统,按需定期制作基础备份。
WAL归档 Pigsty 默认在集群主库上启⽤了 WAL 归档,并使⽤ pgbackrest 命令行工具持续推送 WAL 段⽂件至备份仓库。
pgBackRest 会⾃动管理所需的 WAL ⽂件,并根据备份的保留策略及时清理过期的备份,与其对应的 WAL 归档⽂件。
如果您不需要 PITR 功能,可以通过 配置集群 : archive_mode: off 来关闭 WAL 归档,移除 node_crontab 来停止定期备份任务。
实现 默认情况下,Pigsty提供了两种预置备份策略 :默认使用本地文件系统备份仓库,在这种情况下每天进行一次全量备份,确保用户任何时候都能回滚至一天内的任意时间点。备选策略使用专用的 MinIO 集群或S3存储备份,每周一全备,每天一增备,默认保留两周的备份与WAL归档。
Pigsty 使用 pgBackRest 管理备份,接收 WAL 归档,执行 PITR。备份仓库可以进行灵活配置(pgbackrest_repo ):默认使用主库本地文件系统(local),但也可以使用其他磁盘路径,或使用自带的可选 MinIO 服务(minio)与云上 S3 服务。
pgbackrest_enabled : true # 在 pgsql 主机上启用 pgBackRest 吗?
pgbackrest_clean : true # 初始化时删除 pg 备份数据?
pgbackrest_log_dir : /pg/log/pgbackrest # pgbackrest 日志目录,默认为 `/pg/log/pgbackrest`
pgbackrest_method : local # pgbackrest 仓库方法:local, minio, [用户定义...]
pgbackrest_repo : # pgbackrest 仓库:https://pgbackrest.org/configuration.html#section-repository
local : # 默认使用本地 posix 文件系统的 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按计数保留完整备份
retention_full : 2 # 使用本地文件系统仓库时,最多保留 3 个完整备份,至少保留 2 个
minio : # pgbackrest 的可选 minio 仓库
type : s3 # minio 是与 s3 兼容的,所以使用 s3
s3_endpoint : sss.pigsty # minio 端点域名,默认为 `sss.pigsty`
s3_region : us-east-1 # minio 区域,默认为 us-east-1,对 minio 无效
s3_bucket : pgsql # minio 桶名称,默认为 `pgsql`
s3_key : pgbackrest # pgbackrest 的 minio 用户访问密钥
s3_key_secret : S3User.Backup # pgbackrest 的 minio 用户秘密密钥
s3_uri_style : path # 对 minio 使用路径风格的 uri,而不是主机风格
path : /pgbackrest # minio 备份路径,默认为 `/pgbackrest`
storage_port : 9000 # minio 端口,默认为 9000
storage_ca_file : /etc/pki/ca.crt # minio ca 文件路径,默认为 `/etc/pki/ca.crt`
bundle : y # 将小文件打包成一个文件
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 在 minio 仓库上按时间保留完整备份
retention_full : 14 # 保留过去 14 天的完整备份
# 您还可以添加其他的可选备份仓库,例如 S3,用于异地容灾
Pigsty 参数 pgbackrest_repo 中的目标仓库会被转换为 /etc/pgbackrest/pgbackrest.conf 配置文件中的仓库定义。
例如,如果您定义了一个美西区的 S3 仓库用于存储冷备份,可以使用下面的参考配置。
s3 : # ------> /etc/pgbackrest/pgbackrest.conf
repo1-type : s3 # ----> repo1-type=s3
repo1-s3-region : us-west-1 # ----> repo1-s3-region=us-west-1
repo1-s3-endpoint : s3-us-west-1.amazonaws.com # ----> repo1-s3-endpoint=s3-us-west-1.amazonaws.com
repo1-s3-key : '<your_access_key>' # ----> repo1-s3-key=<your_access_key>
repo1-s3-key-secret : '<your_secret_key>' # ----> repo1-s3-key-secret=<your_secret_key>
repo1-s3-bucket : pgsql # ----> repo1-s3-bucket=pgsql
repo1-s3-uri-style : host # ----> repo1-s3-uri-style=host
repo1-path : /pgbackrest # ----> repo1-path=/pgbackrest
repo1-bundle : y # ----> repo1-bundle=y
repo1-cipher-type : aes-256-cbc # ----> repo1-cipher-type=aes-256-cbc
repo1-cipher-pass : pgBackRest # ----> repo1-cipher-pass=pgBackRest
repo1-retention-full-type : time # ----> repo1-retention-full-type=time
repo1-retention-full : 90 # ----> repo1-retention-full=90
恢复 您可以直接使用以下封装命令可以用于 PostgreSQL 数据库集群的 时间点恢复 。
Pigsty 默认使用增量差分并行恢复,允许您以最快速度恢复到指定时间点。
pg-pitr # 恢复到WAL存档流的结束位置(例如在整个数据中心故障的情况下使用)
pg-pitr -i # 恢复到最近备份完成的时间(不常用)
pg-pitr --time= "2022-12-30 14:44:44+08" # 恢复到指定的时间点(在删除数据库或表的情况下使用)
pg-pitr --name= "my-restore-point" # 恢复到使用 pg_create_restore_point 创建的命名恢复点
pg-pitr --lsn= "0/7C82CB8" -X # 在LSN之前立即恢复
pg-pitr --xid= "1234567" -X -P # 在指定的事务ID之前立即恢复,然后将集群直接提升为主库
pg-pitr --backup= latest # 恢复到最新的备份集
pg-pitr --backup= 20221108-105325 # 恢复到特定备份集,备份集可以使用 pgbackrest info 列出
pg-pitr # pgbackrest --stanza=pg-meta restore
pg-pitr -i # pgbackrest --stanza=pg-meta --type=immediate restore
pg-pitr -t "2022-12-30 14:44:44+08" # pgbackrest --stanza=pg-meta --type=time --target="2022-12-30 14:44:44+08" restore
pg-pitr -n "my-restore-point" # pgbackrest --stanza=pg-meta --type=name --target=my-restore-point restore
pg-pitr -b 20221108-105325F # pgbackrest --stanza=pg-meta --type=name --set=20221230-120101F restore
pg-pitr -l "0/7C82CB8" -X # pgbackrest --stanza=pg-meta --type=lsn --target="0/7C82CB8" --target-exclusive restore
pg-pitr -x 1234567 -X -P # pgbackrest --stanza=pg-meta --type=xid --target="0/7C82CB8" --target-exclusive --target-action=promote restore
在执行 PITR 时,您可以使用 Pigsty 监控系统观察集群 LSN 位点状态,判断是否成功恢复到指定的时间点,事务点,LSN位点,或其他点位。
11.2.6 - 安全与合规 Pigsty 中 PostgreSQL 集群的安全特性与合规能力详解
Pigsty v4.0 提供了 企业级 的 PostgreSQL 安全配置,涵盖身份鉴别、访问控制、通信加密、审计日志、数据完整性、备份恢复等多个维度。
本文档以 中国等保三级 (GB/T 22239-2019)和 SOC 2 Type II 安全合规要求为参照,逐项对比验证 Pigsty 的安全能力。
每个安全维度包含两部分说明:
默认配置 :使用 conf/meta.yml 及默认参数时的安全合规状态 (个人使用)可用配置 :通过调整 Pigsty 参数可达到的增强安全状态 (企业级配置可达)合规对照总结 等保三级核心要求对照 要求项 默认满足 配置可达 说明 身份唯一性 ✅ ✅ 角色系统保证用户唯一标识 口令复杂度 ⚠️ ✅ 可启用 passwordcheck / credcheck 强制执行密码复杂度 口令定期更换 ⚠️ ✅ 通过 expire_in/expire_at 设置用户有效期并定时刷新 登录失败处理 ⚠️ ✅ 日志中记录失败的登陆请求,可配合 fail2ban 自动封禁 双因素认证 ⚠️ ✅ 密码 + 客户端 SSL 证书认证 访问控制 ✅ ✅ HBA规则 + RBAC + SELinux 最小权限 ✅ ✅ 分层角色体系 权限分离 ✅ ✅ DBA / Monitor / 应用读/写/ETL/个人用户分离 通信加密 ✅ ✅ 默认启用并使用 SSL,可强制 SSL 数据完整性 ✅ ✅ 数据校验和默认启用 存储加密 ⚠️ ✅ 备份加密 + Percona TDE 内核支持 审计日志 ✅ ✅ 日志记录 DDL 与敏感操作,可记录所有操作。 日志保护 ✅ ✅ 文件权限隔离,VictoriaLogs 集中收集防篡改 备份恢复 ✅ ✅ pgBackRest 自动备份 网络隔离 ✅ ✅ 防火墙 + HBA
SOC 2 Type II 控制点对照 控制点 默认满足 配置可达 说明 CC6.1 逻辑访问控制 ✅ ✅ HBA + RBAC + SELinux CC6.2 用户注册授权 ✅ ✅ Ansible声明式管理 CC6.3 最小权限 ✅ ✅ 分层角色 CC6.6 传输加密 ✅ ✅ SSL/TLS 全局启用 CC6.7 静态加密 ⚠️ ✅ 可使用 Percona PGTDE 内核,以及 pgsodium/valut 等扩展 CC6.8 恶意软件防护 ⚠️ ✅ 最小安装 + 审计 CC7.1 入侵检测 ⚠️ ✅ 设置日志 Auth Fail 监控告警规则 CC7.2 系统监控 ✅ ✅ VictoriaMetrics + Grafana CC7.3 事件响应 ✅ ✅ Alertmanager CC9.1 业务连续性 ✅ ✅ HA + 自动故障转移 A1.2 数据恢复 ✅ ✅ PITR备份恢复
图例 :✅ 默认满足 ⚠️ 需要额外配置
身份鉴别 等保要求 :应对登录的用户进行身份标识和鉴别,身份标识具有唯一性;应采用口令、密码技术、生物技术等两种或两种以上组合的鉴别技术。
SOC 2 :CC6.1 - 逻辑和物理访问控制;用户身份验证机制。
用户身份标识 PostgreSQL 通过角色(Role)系统实现用户身份标识,每个用户具有唯一的角色名。
默认配置 :Pigsty 预置了分层的角色体系:
pg_default_roles :
- { name: dbrole_readonly ,login: false ,comment : '全局只读角色' }
- { name: dbrole_offline ,login: false ,comment : '受限只读角色(离线查询)' }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : '全局读写角色' }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor,dbrole_readwrite] ,comment : '对象管理角色' }
- { name: postgres ,superuser: true ,comment : '系统超级用户' }
- { name: replicator ,replication: true,roles: [pg_monitor,dbrole_readonly] ,comment : '复制用户' }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,comment : '管理员用户' }
- { name: dbuser_monitor ,roles: [pg_monitor,dbrole_readonly] ,pgbouncer: true ,comment : '监控用户' }
可用配置 :用户可通过 pg_users 定义业务用户,支持设置账户有效期、连接限制等:
pg_users :
- name : dbuser_app
password : 'SecurePass123!'
roles : [ dbrole_readwrite]
expire_in : 365 # 365天后过期
connlimit : 100 # 最大100个连接
comment : '应用程序用户'
密码策略 默认配置 :
密码加密采用 SCRAM-SHA-256 算法,这是目前 PostgreSQL 支持的最安全的密码哈希算法 密码在设置时自动使用 SET log_statement TO 'none' 防止明文泄露到日志 数据库超级用户 postgres 默认无密码,仅允许通过本地 Unix Socket 使用 ident 认证 可用配置 :
认证机制 默认配置 :Pigsty 实现了基于来源地址的分层认证策略:
pg_default_hba_rules :
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu本地ident认证' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu本地复制' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title : '复制用户本地密码认证' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title : '复制用户内网密码认证' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title : '复制用户内网访问postgres' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : '监控用户本地密码认证' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title : '监控用户从基础设施节点访问' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : '管理员SSL+密码认证' }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title : '管理员全局SSL+密码认证' }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title : '只读角色本地密码认证' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title : '只读角色内网密码认证' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title : '离线角色内网密码认证' }
支持的认证方法别名:
别名 实际方法 说明 denyreject拒绝连接 pwdscram-sha-256密码认证(默认加密) sslscram-sha-256 + hostsslSSL + 密码认证 certcert客户端证书认证 os/ident/peerident/peer操作系统用户映射 trusttrust无条件信任(不推荐)
可用配置 :
启用客户端证书认证实现双因素认证:
pg_hba_rules :
- {user: 'secure_user', db: all, addr: world, auth: cert, title : '证书认证用户' }
限制特定用户只能从指定 IP 访问:
pg_hba_rules :
- {user: 'app_user', db: 'appdb', addr: '192.168.1.100/32', auth : ssl}
访问控制 等保要求 :应授予管理用户所需的最小权限,实现管理用户的权限分离;应由授权主体配置访问控制策略。
SOC 2 :CC6.3 - 基于角色的访问控制和最小权限原则。
权限分离 默认配置 :Pigsty 实现了清晰的职责分离模型:
角色 权限 用途 postgresSUPERUSER 系统超级用户,仅限本地OS认证 dbuser_dbaSUPERUSER + dbrole_admin 数据库管理员 replicatorREPLICATION + pg_monitor 复制和监控 dbuser_monitorpg_monitor + dbrole_readonly 只读监控 dbrole_adminCREATE + dbrole_readwrite 对象管理(DDL) dbrole_readwriteINSERT/UPDATE/DELETE + dbrole_readonly 数据读写 dbrole_readonlySELECT 只读访问 dbrole_offlineSELECT(受限) 离线/ETL查询
可用配置 :
操作系统层面权限 默认配置 :
数据库超级用户 postgres 的 sudo 权限为 limit,仅允许执行特定的服务管理命令:启动/停止/重启 PostgreSQL 相关服务 加载 softdog 内核模块(用于 watchdog) %postgres ALL = NOPASSWD: /bin/systemctl stop postgres
%postgres ALL = NOPASSWD: /bin/systemctl start postgres
%postgres ALL = NOPASSWD: /bin/systemctl reload patroni
# ... 等受限命令
可用配置 :
pg_dbsu_sudo: none - 完全禁用 sudo 权限(最严格)pg_dbsu_sudo: all - 需要密码的完整 sudo(平衡方案)pg_dbsu_sudo: nopass - 无密码完整 sudo(不推荐)行级安全策略(RLS) PostgreSQL 原生支持行级安全策略(Row Level Security),可通过 pg_users 设置用户属性:
pg_users :
- name : secure_user
bypassrls : false # 不允许绕过RLS
roles : [ dbrole_readwrite]
配合数据库内的 RLS 策略,可实现细粒度的数据访问控制。
通信安全 等保要求 :应采用密码技术保证通信过程中数据的完整性和保密性。
SOC 2 :CC6.6 - 数据传输安全;CC6.7 - 加密控制。
SSL/TLS 加密 默认配置 :
PostgreSQL 服务端 默认启用 SSL ,支持加密连接 管理员用户(${admin})强制使用 hostssl 连接 自动生成并分发 SSL 证书到所有数据库节点 # patroni.yml 中的 SSL 配置
ssl : 'on'
ssl_cert_file : '/pg/cert/server.crt'
ssl_key_file : '/pg/cert/server.key'
ssl_ca_file : '/pg/cert/ca.crt'
可用配置 :
PKI 证书管理 默认配置 :
Pigsty 使用自建 PKI 体系,自动管理证书生命周期:
files/pki/
├── ca/ # CA 根证书
│ ├── ca.crt # CA 公钥证书
│ └── ca.key # CA 私钥
├── csr/ # 证书签名请求
├── pgsql/ # PostgreSQL 集群证书
├── etcd/ # ETCD 集群证书
├── infra/ # 基础设施节点证书
└── minio/ # MinIO 证书
每个 PostgreSQL 集群共享一个私钥,每个实例有独立的证书 证书包含正确的 SAN(Subject Alternative Name)配置 CA 证书自动分发到 /etc/pki/ca.crt 和 /pg/cert/ca.crt 可用配置 :
使用外部 CA 签发的证书:将证书放入 files/pki/ 目录,设置 ca_create: false 调整证书有效期:cert_validity: 365d(1年) ETCD 通信安全 ETCD 作为 Patroni 的 DCS(分布式配置存储),默认使用 mTLS(双向 TLS)认证:
etcd3 :
hosts : '10.10.10.10:2379'
protocol : https
cacert : /pg/cert/ca.crt
cert : /pg/cert/server.crt
key : /pg/cert/server.key
username : 'pg-meta' # 集群专用账号
password : 'pg-meta' # 默认与集群名相同
数据加密 等保要求 :应采用密码技术保证重要数据在存储过程中的保密性。
SOC 2 :CC6.1 - 数据加密存储。
备份加密 配置项 默认值 说明 cipher_typeaes-256-cbc备份加密算法(MinIO仓库) cipher_passpgBackRest加密密码(需修改)
默认配置 :
本地备份(pgbackrest_method: local)默认不加密 远程对象存储备份支持 AES-256-CBC 加密 可用配置 :
启用备份加密(推荐用于远程存储):
pgbackrest_method : minio
pgbackrest_repo :
minio :
type : s3
s3_endpoint : sss.pigsty
s3_bucket : pgsql
s3_key : pgbackrest
s3_key_secret : S3User.Backup
cipher_type : aes-256-cbc
cipher_pass : 'YourSecureBackupPassword!' # 务必修改!
retention_full_type : time
retention_full : 14
透明数据加密(TDE) PostgreSQL 社区版本不支持原生 TDE,但可通过以下方式实现存储加密:
文件系统级加密 :使用 LUKS/dm-crypt 加密存储卷pgsodium 扩展 :支持列级加密# 启用 pgsodium 列级加密
pg_libs : 'pgsodium, pg_stat_statements, auto_explain'
# 自定义加密密钥(64位十六进制)
pgsodium_key : 'a1b2c3d4e5f6...' # 或使用外部密钥管理脚本
数据完整性校验 默认配置 :
数据校验和默认启用 ,可检测存储层数据损坏crit.yml 模板强制启用数据校验和支持 pg_rewind 进行故障恢复 pg_checksum : true # 强烈建议保持启用
安全审计 等保要求 :应启用安全审计功能,审计覆盖到每个用户,对重要的用户行为和重要安全事件进行审计。
SOC 2 :CC7.2 - 系统监控和日志记录;CC7.3 - 安全事件检测。
数据库审计日志 配置项 默认值 说明 logging_collectoron启用日志收集器 log_destinationcsvlogCSV格式日志 log_statementddl记录DDL语句 log_min_duration_statement100ms慢查询阈值 log_connectionsauthorization (PG18) / on连接审计 log_disconnectionson (crit模板)断开连接审计 log_checkpointson检查点日志 log_lock_waitson锁等待日志 log_replication_commandson复制命令日志
默认配置 :
# oltp.yml 模板的审计配置
log_destination : csvlog
logging_collector : 'on'
log_directory : /pg/log/postgres
log_filename : 'postgresql-%a.log' # 按星期轮转
log_file_mode : '0640' # 限制日志文件权限
log_rotation_age : '1d'
log_truncate_on_rotation : 'on'
log_checkpoints : 'on'
log_lock_waits : 'on'
log_replication_commands : 'on'
log_statement : ddl # 记录所有DDL
log_min_duration_statement : 100 # 记录慢查询 >100ms
可用配置(crit.yml 关键业务模板) :
# crit.yml 提供更全面的审计
log_connections : 'receipt,authentication,authorization' # PG18完整连接审计
log_disconnections : 'on' # 记录断开连接
log_lock_failures : 'on' # 记录锁失败(PG18)
track_activity_query_size : 32768 # 完整查询记录
启用 pgaudit 扩展实现细粒度审计:
pg_libs : 'pgaudit, pg_stat_statements, auto_explain'
pg_parameters :
pgaudit.log : 'all'
pgaudit.log_catalog : 'on'
pgaudit.log_relation : 'on'
性能与执行审计 扩展 默认启用 说明 pg_stat_statements是 SQL统计信息 auto_explain是 慢查询执行计划 pg_wait_sampling配置可用 等待事件采样
默认配置 :
pg_libs : 'pg_stat_statements, auto_explain'
# auto_explain 配置
auto_explain.log_min_duration : 1s # 记录>1s的查询计划
auto_explain.log_analyze : 'on'
auto_explain.log_verbose : 'on'
auto_explain.log_timing : 'on'
# pg_stat_statements 配置
pg_stat_statements.max : 10000
pg_stat_statements.track : all
日志集中管理 默认配置 :
PostgreSQL 日志:/pg/log/postgres/ Patroni 日志:/pg/log/patroni/ PgBouncer 日志:/pg/log/pgbouncer/ pgBackRest 日志:/pg/log/pgbackrest/ 可用配置 :
通过 Vector 将日志发送到 VictoriaLogs 集中存储:
# 日志自动收集到 VictoriaLogs
vlogs_enabled : true
vlogs_port : 9428
vlogs_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
网络安全 等保要求 :应在网络边界部署访问控制设备,对进出网络的数据流实现访问控制。
SOC 2 :CC6.1 - 边界保护和网络安全。
防火墙配置 默认配置 :
node_firewall_mode : zone # 启用区域防火墙
node_firewall_intranet : # 定义内网地址
- 10.0.0.0 /8
- 192.168.0.0 /16
- 172.16.0.0 /12
node_firewall_public_port : # 公网开放端口
- 22 # SSH
- 80 # HTTP
- 443 # HTTPS
- 5432 # PostgreSQL(谨慎开放)
防火墙规则:
内网地址自动加入 trusted 区域 仅指定端口对外开放 支持 firewalld(RHEL系)和 ufw(Debian系) 可用配置 :
node_firewall_mode: off - 禁用防火墙(不推荐)node_firewall_mode: none - 不修改现有配置移除5432端口,仅允许内网访问数据库 服务访问控制 配置项 默认值 说明 pg_listen0.0.0.0PostgreSQL监听地址 patroni_allowlistinfra + cluster Patroni API白名单
默认配置 :
Patroni REST API 仅允许来自以下地址的访问:
# 自动计算的白名单
pg_allow_list = [admin_ip] + pg_cluster_members + groups["infra"]
可用配置 :
限制 PostgreSQL 只监听特定网卡:
pg_listen : '${ip}' # 仅监听主机IP,不监听0.0.0.0
SELinux 默认配置 :SELinux 设为 permissive 模式(记录但不阻止)
可用配置 :
node_selinux_mode : enforcing # 强制模式(需要额外配置策略)
可用性与恢复 等保要求 :应提供数据备份与恢复功能;应提供自动故障恢复功能。
SOC 2 :CC9.1 - 业务连续性;A1.2 - 数据备份和恢复。
高可用架构 默认配置 :
Patroni 自动故障检测与切换(RTO < 30秒) 异步复制,最大数据丢失 1MB(RPO) failsafe_mode: true 防止脑裂可用配置 :
启用同步复制实现 RPO = 0:
pg_rpo : 0 # 零数据丢失
pg_conf : crit.yml # 使用关键业务模板
# crit.yml 自动启用 synchronous_mode: true
启用硬件看门狗:
patroni_watchdog_mode : automatic # 或 required
备份恢复 默认配置 :
pgbackrest_enabled : true
pgbackrest_method : local
pgbackrest_repo :
local :
path : /pg/backup
retention_full_type : count
retention_full : 2 # 保留2个完整备份
可用配置 :
异地备份到对象存储:
pgbackrest_method : minio
pgbackrest_repo :
minio :
type : s3
s3_endpoint : sss.pigsty
s3_bucket : pgsql
cipher_type : aes-256-cbc # 加密备份
retention_full_type : time
retention_full : 14 # 保留14天
block : y # 块级增量备份
bundle : y # 小文件合并
定时备份策略:
node_crontab :
- '00 01 * * * postgres /pg/bin/pg-backup full' # 每日1点全量备份
- '00 */4 * * * postgres /pg/bin/pg-backup diff' # 每4小时差异备份
入侵防范 等保要求 :应遵循最小安装的原则,仅安装需要的组件和应用程序;应能够检测到对重要节点进行入侵的行为,并在发生严重入侵事件时提供报警。
SOC 2 :CC6.8 - 恶意软件防护;CC7.1 - 入侵检测。
最小化安装 默认配置 :
仅安装必要的 PostgreSQL 组件和扩展 通过 pg_packages 和 pg_extensions 精确控制安装内容 生产系统不安装开发工具和调试符号 pg_packages : [ pgsql-main, pgsql-common ] # 最小化安装
pg_extensions : [] # 按需添加扩展
安全扩展 Pigsty 提供以下 安全相关扩展 ,可按需安装启用:
安装所有安全扩展包:
pg_extensions : [ pg18-sec ] # 安装安全类扩展组
告警与监控 默认配置 :
VictoriaMetrics + Alertmanager 提供监控告警 预置 PostgreSQL 告警规则 Grafana 可视化仪表板 关键安全相关告警:
认证失败次数过多 复制延迟过大 备份失败 磁盘空间不足 连接数耗尽 11.3 - 集群配置 根据需求场景选择合适的实例与集群类型,配置出满足需求的 PostgreSQL 数据库集群。
Pigsty 是一个“配置驱动”的 PostgreSQL 平台:所有行为都来自 ~/pigsty/conf/*.yml 清单与 PGSQL 参数 的组合。
只要写好配置,你就能在几分钟内复刻出一套包含实例、用户、数据库、访问控制、扩展与调优策略的定制集群。
配置入口 准备清单 :复制 pigsty/conf/*.yml 模板或从零开始编写 Ansible Inventory,将集群分组(all.children.<cls>.hosts)与全局变量(all.vars)写入同一个文件。定义参数 :在 vars 区块中覆盖需要的 PGSQL 参数 。全局 → 集群 → 主机的覆盖顺序决定了最终值。应用配置 :运行 ./configure -c <conf> 或 bin/pgsql-add <cls> 等剧本让配置落地。Pigsty 会根据参数生成 Patroni/pgbouncer/pgbackrest 等服务所需的配置文件。Pigsty 默认的 Demo 清单 conf/pgsql.yml 就是一份最小化示例:一个 pg-meta 集群、全局 pg_version: 18、少量业务用户与数据库定义。你可以在此基础上扩展更多集群。
关注点与文档索引 Pigsty 的 PostgreSQL 配置可以从以下几个维度组合,后续文档会逐一展开“如何配置”:
集群实例 :通过 pg_cluster / pg_role / pg_seq / pg_upstream 定义实例拓扑(单机、主从、备份集群、延迟集群、Citus 等)。内核版本 :使用 pg_version、pg_mode、pg_packages、pg_extensions、pg_conf 等参数挑选核心版本、风味和调优模板。用户/角色 :在 pg_default_roles 与 pg_users 中声明系统角色、业务账号、密码策略以及连接池属性。数据库对象 :借助 pg_databases、baseline、schemas、extensions、pool_* 字段按需创建数据库并自动接入 pgbouncer/Grafana。访问控制 (HBA) :利用 pg_default_hba_rules 与 pg_hba_rules 维护主机级认证策略,保证不同角色/网络的访问边界。权限模型 (ACL) :通过 pg_default_privileges、pg_default_roles、pg_revoke_public 等参数收敛对象权限,开箱即用地提供分层角色体系。理解这些参数之后,你就可以针对任意业务需求写出“配置即基础设施”的声明式清单,Pigsty 会负责执行并确保幂等。
一个典型示例 下面的片段展示了如何在同一个配置文件中同时控制实例拓扑、内核版本、扩展、用户以及数据库:
all :
children :
pg-analytics :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role: replica, pg_offline_query : true }
vars :
pg_cluster : pg-analytics
pg_conf : olap.yml
pg_extensions : [ postgis, timescaledb, pgvector ]
pg_databases :
- { name: bi, owner: dbuser_bi, schemas: [mart], extensions: [timescaledb], pool_mode : session }
pg_users :
- { name: dbuser_bi, password: DBUser.BI, roles: [dbrole_admin], pgbouncer : true }
vars :
pg_version : 17
pg_packages : [ pgsql-main pgsql-common ]
pg_hba_rules :
- { user: dbuser_bi, db: bi, addr: intra, auth: ssl, title : 'BI 只允许内网 SSL 访问' }
pg-analytics 集群包含一个主库和一个离线副本。全局指定 pg_version: 17 与一套扩展示例,并加载 olap.yml 调优。 在 pg_databases 与 pg_users 中声明业务对象,自动生成 schema/extension 与连接池条目。 附加的 pg_hba_rules 限制了访问来源与认证方式。 修改并应用这份清单即可得到一套定制化的 PostgreSQL 集群,而无需手工逐项配置。
11.3.1 - 集群实例 根据需求场景选择合适的实例与集群类型,配置出满足需求的 PostgreSQL 数据库集群。
根据需求场景选择合适的实例与集群类型,配置出满足需求的 PostgreSQL 数据库集群。
您可以定义不同类型的实例和集群,下面是 Pigsty 中常见的几种 PostgreSQL 实例/集群类型:
读写主库 我们从最简单的情况开始:由一个主库(Primary)组成的单实例集群:
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-test
这段配置言简意赅,自我描述,仅由 身份参数 构成,请注意 Ansible Group 分组名应当与 pg_cluster 保持一致。
使用以下命令创建该集群:
Demo展示,开发测试,承载临时需求,进行无关紧要的计算分析任务时,使用单一数据库实例可能并没有太大问题。但这样的单机集群没有高可用 ,当出现硬件故障时,您需要使用 PITR 或其他恢复手段来确保集群的 RTO / RPO。为此,您可以考虑为集群添加若干个只读从库
只读从库 要添加一台只读从库(Replica)实例,您可以在 pg-test 中添加一个新节点,并将其 pg_role 设置为replica。
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica } # <--- 新添加的从库
vars :
pg_cluster : pg-test
如果整个集群不存在,您可以直接创建 这个完整的集群。 如果集群主库已经初始化好了,那么您可以向现有集群添加 一个从库:
bin/pgsql-add pg-test # 一次性初始化整个集群
bin/pgsql-add pg-test 10.10.10.12 # 添加从库到现有的集群
当集群主库出现故障时,只读实例(Replica)可以在高可用系统的帮助下接管主库的工作。除此之外,只读实例还可以用于执行只读查询:许多业务的读请求要比写请求多很多,而大部分只读查询负载都可以由从库实例承担。
离线从库 离线实例(Offline)是专门用于服务慢查询、ETL、OLAP流量和交互式查询等的专用只读从库。慢查询/长事务对在线业务的性能与稳定性有不利影响,因此最好将它们与在线业务隔离开来。
要添加离线实例,请为其分配一个新实例,并将pg_role 设置为offline。
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : offline } # <--- 新添加的离线从库
vars :
pg_cluster : pg-test
专用离线实例的工作方式与常见的从库实例类似,但它在 pg-test-replica 服务中用作备份服务器。 也就是说,只有当所有replica实例都宕机时,离线和主实例才会提供此项只读服务。
许多情况下,数据库资源有限,单独使用一台服务器作为离线实例是不经济的做法。作为折中,您可以选择一台现有的从库实例,打上 pg_offline_query 标记,将其标记为一台可以承载“离线查询”的实例。在这种情况下,这台只读从库会同时承担在线只读请求与离线类查询。您可以使用 pg_default_hba_rules 和pg_hba_rules 对离线实例进行额外的访问控制。
同步备库 当启用同步备库(Sync Standby)时,PostgreSQL 将选择一个从库作为同步备库 ,其他所有从库作为候选者 。 主数据库会等待备库实例刷新到磁盘,然后才确认提交,备库实例始终拥有最新的数据,没有复制延迟,主从切换至同步备库不会有数据丢失。
PostgreSQL 默认使用异步流复制,这可能会有小的复制延迟(10KB / 10ms 数量级)。当主库失败时,可能会有一个小的数据丢失窗口(可以使用pg_rpo 来控制),但对于大多数场景来说,这是可以接受的。
但在某些关键场景中(例如,金融交易),数据丢失是完全不可接受的,或者,读取复制延迟是不可接受的。在这种情况下,您可以使用同步提交来解决这个问题。 要启用同步备库模式,您可以简单地使用pg_conf 中的crit.yml模板。
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : replica }
vars :
pg_cluster : pg-test
pg_conf : crit.yml # <--- 使用 crit 模板
要在现有集群上启用同步备库,请配置集群 并启用 synchronous_mode:
$ pg edit-config pg-test # 在管理员节点以管理员用户身份运行
+++
-synchronous_mode: false # <--- 旧值
+synchronous_mode: true # <--- 新值
synchronous_mode_strict: false
应用这些更改?[ y/N] : y
在这种情况下,PostgreSQL 配置项 synchronous_standby_names 由 Patroni 自动管理。
一台从库将被选拔为同步从库,它的 application_name 将被写入 PostgreSQL 主库配置文件中并应用生效。
法定人数提交 法定人数提交(Quorum Commit)提供了比同步备库更强大的控制能力:特别是当您有多个从库时,您可以设定提交成功的标准,实现更高/更低的一致性级别(以及可用性之间的权衡)。
如果想要最少两个从 库来确认提交,可以通过 Patroni 配置集群 ,调整参数 synchronous_node_count 并应用生效
synchronous_mode : true # 确保同步提交已经启用
synchronous_node_count : 2 # 指定“至少”有多少个从库提交成功,才算提交成功
如果你想要使用更多的同步从库,修改 synchronous_node_count 的取值即可。当集群的规模发生变化时,您应当确保这里的配置仍然是有效的,以避免服务不可用。
在这种情况下,PostgreSQL 配置项 synchronous_standby_names 由 Patroni 自动管理。
synchronous_standby_names = '2 ("pg-test-3","pg-test-2")'
示例:使用多个同步从库 $ pg edit-config pg-test
---
+synchronous_node_count: 2
Apply these changes? [ y/N] : y
应用配置后,出现两个同步备库。
+ Cluster: pg-test ( 7080814403632534854) +---------+----+-----------+-----------------+
| Member | Host | Role | State | TL | Lag in MB | Tags |
+-----------+-------------+--------------+---------+----+-----------+-----------------+
| pg-test-1 | 10.10.10.10 | Leader | running | 1 | | clonefrom: true |
| pg-test-2 | 10.10.10.11 | Sync Standby | running | 1 | 0 | clonefrom: true |
| pg-test-3 | 10.10.10.12 | Sync Standby | running | 1 | 0 | clonefrom: true |
+-----------+-------------+--------------+---------+----+-----------+-----------------+
另一种情景是,使用 任意n个 从库来确认提交。在这种情况下,配置的方式略有不同,例如,假设我们只需要任意一个从库确认提交:
synchronous_mode : quorum # 使用法定人数提交
postgresql :
parameters : # 修改 PostgreSQL 的配置参数 synchronous_standby_names ,使用 `ANY n ()` 语法
synchronous_standby_names : 'ANY 1 (*)' # 你可以指定具体的从库列表,或直接使用 * 通配所有从库。
示例:启用ANY法定人数提交 $ pg edit-config pg-test
+ synchronous_standby_names: 'ANY 1 (*)' # 在 ANY 模式下,需要使用此参数
- synchronous_node_count: 2 # 在 ANY 模式下, 不需要使用此参数
Apply these changes? [ y/N] : y
应用后,配置生效,所有备库在 Patroni 中变为普通的 replica。但是在 pg_stat_replication 中可以看到 sync_state 会变为 quorum。
备份集群 您可以克隆现有的集群,并创建一个备份集群(Standby Cluster),用于数据迁移、水平拆分、多区域部署,或灾难恢复。
在正常情况下,备份集群将追随上游集群并保持内容同步,您可以将备份集群提升,作为真正地独立集群。
备份集群的定义方式与正常集群的定义基本相同,除了在主库上额外定义了 pg_upstream 参数,备份集群的主库被称为 备份集群领导者 (Standby Leader)。
例如,下面定义了一个pg-test集群,以及其备份集群pg-test2,其配置清单可能如下所示:
# pg-test 是原始集群
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
vars : { pg_cluster : pg-test }
# pg-test2 是 pg-test 的备份集群
pg-test2 :
hosts :
10.10.10.12 : { pg_seq: 1, pg_role: primary , pg_upstream : 10.10.10.11 } # <--- pg_upstream 在这里定义
10.10.10.13 : { pg_seq: 2, pg_role : replica }
vars : { pg_cluster : pg-test2 }
而 pg-test2 集群的主节点 pg-test2-1 将是 pg-test 的下游从库,并在pg-test2集群中充当备份集群领导者(Standby Leader )。
只需确保备份集群的主节点上配置了pg_upstream 参数,以便自动从原始上游拉取备份。
bin/pgsql-add pg-test # 创建原始集群
bin/pgsql-add pg-test2 # 创建备份集群
示例:更改复制上游 如有必要(例如,上游发生主从切换/故障转移),您可以通过配置集群 更改备份集群的复制上游。
要这样做,只需将standby_cluster.host更改为新的上游IP地址并应用。
$ pg edit-config pg-test2
standby_cluster:
create_replica_methods:
- basebackup
- host: 10.10.10.13 # <--- 旧的上游
+ host: 10.10.10.12 # <--- 新的上游
port: 5432
Apply these changes? [ y/N] : y
示例:提升备份集群 你可以随时将备份集群提升为独立集群,这样该集群就可以独立承载写入请求,并与原集群分叉。
为此,你必须配置 该集群并完全擦除standby_cluster部分,然后应用。
$ pg edit-config pg-test2
-standby_cluster:
- create_replica_methods:
- - basebackup
- host: 10.10.10.11
- port: 5432
Apply these changes? [ y/N] : y
示例:级联复制 如果您在一台从库上指定了 pg_upstream ,而不是主库。那么可以配置集群的 级联复制 (Cascade Replication)
在配置级联复制时,您必须使用集群中某一个实例的IP地址作为参数的值,否则初始化会报错。该从库从特定的实例进行流复制,而不是主库。
这台充当 WAL 中继器的实例被称为 桥接实例 (Bridge Instance)。使用桥接实例可以分担主库发送 WAL 的负担,当您有几十台从库时,使用桥接实例级联复制是一个不错的注意。
pg-test :
hosts : # pg-test-1 ---> pg-test-2 ---> pg-test-3
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica } # <--- 桥接实例
10.10.10.13 : { pg_seq: 3, pg_role: replica, pg_upstream : 10.10.10.12 }
# ^--- 从 pg-test-2 (桥接)复制,而不是从 pg-test-1 (主节点)
vars : { pg_cluster : pg-test }
延迟集群 延迟集群(Delayed Cluster)是一种特殊类型的备份集群 ,用于尽快恢复“意外删除”的数据。
例如,如果你希望有一个名为 pg-testdelay 的集群,其数据内容与一小时前的 pg-test 集群相同:
# pg-test 是原始集群
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
vars : { pg_cluster : pg-test }
# pg-testdelay 是 pg-test 的延迟集群
pg-testdelay :
hosts :
10.10.10.12 : { pg_seq: 1, pg_role: primary , pg_upstream: 10.10.10.11, pg_delay : 1d }
10.10.10.13 : { pg_seq: 2, pg_role : replica }
vars : { pg_cluster : pg-test2 }
你还可以在现有的备份集群 上配置 一个“复制延迟”。
$ pg edit-config pg-testdelay
standby_cluster:
create_replica_methods:
- basebackup
host: 10.10.10.11
port: 5432
+ recovery_min_apply_delay: 1h # <--- 在此处添加延迟时长,例如1小时
Apply these changes? [ y/N] : y
当某些元组和表格被意外删除时,你可以通过修改此参数的方式,将此延迟集群推进到适当的时间点,并从中读取数据,快速修复原始集群。
延迟集群需要额外的资源,但比起 PITR 要快得多,并且对系统的影响也小得多,对于非常关键的集群,可以考虑搭建延迟集群。
Citus集群 Pigsty 原生支持 Citus。可以参考 files/pigsty/citus.yml 与 prod.yml 作为样例。
要定义一个 citus 集群,您需要指定以下参数:
此外,还需要额外的 hba 规则,允许从本地和其他数据节点进行 SSL 访问。如下所示:
all :
children :
pg-citus0 : # citus 0号分片
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus0 , pg_group : 0 }
pg-citus1 : # citus 1号分片
hosts : { 10.10.10.11 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus1 , pg_group : 1 }
pg-citus2 : # citus 2号分片
hosts : { 10.10.10.12 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus2 , pg_group : 2 }
pg-citus3 : # citus 3号分片
hosts :
10.10.10.13 : { pg_seq: 1, pg_role : primary }
10.10.10.14 : { pg_seq: 2, pg_role : replica }
vars : { pg_cluster: pg-citus3 , pg_group : 3 }
vars : # 所有 Citus 集群的全局参数
pg_mode : citus # pgsql 集群模式需要设置为: citus
pg_shard : pg-citus # citus 水平分片名称: pg-citus
patroni_citus_db : meta # citus 数据库名称:meta
pg_dbsu_password : DBUser.Postgres # 如果使用 dbsu ,那么需要为其配置一个密码
pg_users : [ { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles : [ dbrole_admin ] } ]
pg_databases : [ { name: meta ,extensions : [ { name : citus }, { name: postgis }, { name: timescaledb } ] } ]
pg_hba_rules :
- { user: 'all' ,db: all ,addr: 127.0.0.1/32 ,auth: ssl ,title : 'all user ssl access from localhost' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'all user ssl access from intranet' }
在协调者节点上,您可以创建分布式表和引用表,并从任何数据节点查询它们。从 11.2 开始,任何 Citus 数据库节点都可以扮演协调者的角色了。
SELECT create_distributed_table( 'pgbench_accounts' , 'aid' ) ; SELECT truncate_local_data_after_distributing_table( $$ public.pgbench_accounts$$ ) ;
SELECT create_reference_table( 'pgbench_branches' ) ; SELECT truncate_local_data_after_distributing_table( $$ public.pgbench_branches$$ ) ;
SELECT create_reference_table( 'pgbench_history' ) ; SELECT truncate_local_data_after_distributing_table( $$ public.pgbench_history$$ ) ;
SELECT create_reference_table( 'pgbench_tellers' ) ; SELECT truncate_local_data_after_distributing_table( $$ public.pgbench_tellers$$ ) ;
11.3.2 - 内核版本 如何选择合适的 PostgreSQL 内核与大版本。
在 Pigsty 中选择"内核"意味着确定 PostgreSQL 大版本、模式/发行版、需要安装的包以及要加载的调优模板。
Pigsty 从 PostgreSQL 10 起提供支持,当前版本默认打包了 13 - 18 的核心软件,并在 17/18 上提供完整扩展集合。下方内容展示如何通过配置文件完成这些选择。
大版本与软件包 pg_version:指定 PostgreSQL 主版本(默认 18)。Pigsty 会根据版本自动映射到正确的包名前缀。pg_packages:定义需要安装的核心包集合,支持使用包别名 (默认 pgsql-main pgsql-common,包含内核 + patroni/pgbouncer/pgbackrest 等常用工具)。pg_extensions:额外需要安装的扩展包列表,同样支持别名;缺省为空表示只装核心依赖。all :
vars :
pg_version : 17
pg_packages : [ pgsql-main pgsql-common ]
pg_extensions : [ postgis, timescaledb, pgvector, pgml ]
效果:Ansible 在安装阶段会拉取与 pg_version=17 对应的包,将扩展预装到系统中,随后数据库初始化脚本即可直接 CREATE EXTENSION。
Pigsty 的离线仓库中不同版本的扩展支持范围不同:12/13 只提供核心与一级扩展,15/17/18 则涵盖全部扩展。若某扩展未预打包,可通过 repo_packages_extra 追加。
内核模式(pg_mode) pg_mode 控制要部署的内核“风味”,默认 pgsql 表示标准 PostgreSQL。Pigsty 目前支持以下模式:
模式 场景 pgsql标准 PostgreSQL,高可用 + 复制 citusCitus 分布式集群,需要额外的 pg_shard / pg_group gpsqlGreenplum / MatrixDB mssqlBabelfish for PostgreSQL mysqlOpenGauss/HaloDB 兼容 MySQL 协议 polar阿里 PolarDB(基于 pg polar 发行) ivoryIvorySQL(Oracle 兼容语法) orioleOrioleDB 存储引擎 oraclePostgreSQL + ora 兼容(pg_mode: oracle)
选择模式后,Pigsty 会自动加载对应的模板、依赖包与 Patroni 配置。以部署 Citus 为例:
all :
children :
pg-citus0 :
hosts : { 10.10.10.11 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus0, pg_group : 0 }
pg-citus1 :
hosts : { 10.10.10.12 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus1, pg_group : 1 }
vars :
pg_mode : citus
pg_shard : pg-citus
patroni_citus_db : meta
效果:所有成员会安装 Citus 相关包,Patroni 以分片模式写入 etcd,并自动在 meta 数据库内 CREATE EXTENSION citus。
扩展与预置对象 除了系统包,你还可以通过以下参数控制数据库启动后自动加载的组件:
pg_libs:写入 shared_preload_libraries 的列表。例如 pg_libs: 'timescaledb, pg_stat_statements, auto_explain'。pg_default_extensions / pg_default_schemas:控制初始化脚本对 template1 与 postgres 预创建的 schema、扩展。pg_parameters:为所有实例附加 ALTER SYSTEM SET(写入 postgresql.auto.conf)。示例:启用 TimescaleDB、pgvector 并自定义一些系统参数。
pg-analytics :
vars :
pg_cluster : pg-analytics
pg_libs : 'timescaledb, pg_stat_statements, pgml'
pg_default_extensions :
- { name : timescaledb }
- { name : pgvector }
pg_parameters :
timescaledb.max_background_workers : 8
shared_preload_libraries : "'timescaledb,pg_stat_statements,pgml'"
效果:初始化时 template1 会创建扩展、Patroni 的 postgresql.conf 注入对应参数,所有业务库继承这些设置。
调优模板 (pg_conf) pg_conf 指向 roles/pgsql/templates/*.yml 中的 Patroni 模板。Pigsty内置四套通用模板:
模板 适用场景 oltp.yml默认模板,面向 4–128 核的 TP 负载 olap.yml针对分析场景优化 crit.yml强调同步提交/最小延迟,适合金融等零丢失场景 tiny.yml轻量机 / 边缘场景 / 资源受限环境
你可以直接替换模板或自定义一个 YAML 文件放在 templates/ 下,然后在集群 vars 里指定。
pg-ledger :
hosts : { 10.10.10.21 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-ledger
pg_conf : crit.yml
pg_parameters :
synchronous_commit : 'remote_apply'
max_wal_senders : 16
wal_keep_size : '2GB'
效果:拷贝 crit.yml 作为 Patroni 配置,叠加 pg_parameters 写入 postgresql.auto.conf,使实例立即以同步提交模式运行。
组合实例:一个完整示例 pg-rag :
hosts :
10.10.10.31 : { pg_seq: 1, pg_role : primary }
10.10.10.32 : { pg_seq: 2, pg_role : replica }
vars :
pg_cluster : pg-rag
pg_version : 18
pg_mode : pgsql
pg_conf : olap.yml
pg_packages : [ pgsql-main pgsql-common ]
pg_extensions : [ pgvector, pgml, postgis ]
pg_libs : 'pg_stat_statements, pgvector, pgml'
pg_parameters :
max_parallel_workers : 8
shared_buffers : '32GB'
第一台主库 + 一台 replica,使用 olap.yml 调优。 安装 PG18 + RAG 常用扩展,自动在系统级加载 pgvector/pgml。 Patroni/pgbouncer/pgbackrest 由 Pigsty 生成,无需手工干预。 根据业务需要替换上述参数即可完成内核层的全部定制。
11.3.3 - 别名翻译 Pigsty 提供软件包别名翻译机制,可以屏蔽底层操作系统的二进制包细节差异,让安装更简易。
PostgreSQL 在不同操作系统上的软件包命名规则存在显著差异:
EL 系统 (RHEL/Rocky/Alma/…)使用 pgvector_17,postgis36_17* 这样的格式Debian/Ubuntu 系统 使用 postgresql-17-pgvector,postgresql-17-postgis-3 这样的格式这种差异给用户带来了额外的认知负担:您需要记住不同系统的包名规则,还要处理 PostgreSQL 版本号嵌入的问题。
软件包别名 Pigsty 通过 软件包别名(Package Alias) 机制解决了这个问题:您只需使用统一的别名,Pigsty 会处理好所有细节:
# 使用别名 —— 简单、统一、跨平台
pg_extensions : [ postgis, pgvector, timescaledb ]
# 等效于 EL9 + PG17 上的实际包名
pg_extensions : [ postgis36_17*, pgvector_17*, timescaledb-tsl_17* ]
# 等效于 Ubuntu 24 + PG17 上的实际包名
pg_extensions : [ postgresql-17-postgis-3, postgresql-17-pgvector, postgresql-17-timescaledb-tsl ]
别名翻译 别名还可以将一组软件包归类为一个整体,例如 Pigsty 默认安装的软件包 —— pg_packages 的默认值是:
pg_packages : # pg packages to be installed, alias can be used
- pgsql-main pgsql-common
Pigsty 将查询当前的操作系统别名清单(假设为 el10.x86_64 ),将其翻译为 PGSQL 内核,扩展,以及工具包:
pgsql-main : "postgresql$v postgresql$v-server postgresql$v-libs postgresql$v-contrib postgresql$v-plperl postgresql$v-plpython3 postgresql$v-pltcl postgresql$v-llvmjit pg_repack_$v* wal2json_$v* pgvector_$v*"
pgsql-common : "patroni patroni-etcd pgbouncer pgbackrest pg_exporter pgbackrest_exporter vip-manager"
接下来,Pigsty 又进一步通过当前指定的 PG 大版本(假设 pg_version = 18 ),将 pgsql-main 翻译为:
pg18-main : "postgresql18 postgresql18-server postgresql18-libs postgresql18-contrib postgresql18-plperl postgresql18-plpython3 postgresql18-pltcl postgresql18-llvmjit pg_repack_18* wal2json_18* pgvector_18*"
通过这种方式,Pigsty 屏蔽了软件包的复杂性,让用户可以简单的指定自己想要的功能组件。
哪些变量可以使用别名? 您可以在以下四个参数中使用包别名,别名会根据翻译流程自动转换为实际的软件包名称:
别名列表 你可以在 Pigsty 项目源代码的 roles/node_id/vars/ 目录下,找到各操作系统与架构对应的别名映射文件:
工作原理 别名翻译流程 用户配置别名 --> 检测操作系统 --> 查找别名映射表 ---> 替换$v占位符 ---> 安装实际软件包
↓ ↓ ↓ ↓
postgis el9.x86_64 postgis36_$v * postgis36_17*
postgis u24.x86_64 postgresql-$v -postgis-3 postgresql-17-postgis-3
版本占位符 Pigsty 的别名系统使用 $v 作为 PostgreSQL 版本号的占位符。当您使用 pg_version 指定了 PostgreSQL 版本后,所有别名中的 $v 都会被替换为实际版本号。
例如,当 pg_version: 17 时:
别名定义 (EL) 展开结果 postgresql$v*postgresql17*pgvector_$v*pgvector_17*timescaledb-tsl_$v*timescaledb-tsl_17*
别名定义 (Debian/Ubuntu) 展开结果 postgresql-$vpostgresql-17postgresql-$v-pgvectorpostgresql-17-pgvectorpostgresql-$v-timescaledb-tslpostgresql-17-timescaledb-tsl
通配符匹配 在 EL 系统上,许多别名使用 * 通配符来匹配相关的子包。例如:
postgis36_17* 会匹配 postgis36_17、postgis36_17-client、postgis36_17-utils 等postgresql17* 会匹配 postgresql17、postgresql17-server、postgresql17-libs、postgresql17-contrib 等这种设计确保您无需逐一列出每个子包,一个别名即可安装完整的扩展。
11.3.4 - 用户/角色 用户/角色指的是使用 SQL 命令 CREATE USER/ROLE 创建的,数据库集簇内的逻辑对象。
在这里的上下文中,用户指的是使用 SQL 命令 CREATE USER/ROLE 创建的,数据库集簇内的逻辑对象。
在PostgreSQL中,用户直接隶属于数据库集簇而非某个具体的数据库。因此在创建业务数据库和业务用户时,应当遵循"先用户,后数据库"的原则。
定义用户 Pigsty通过两个配置参数定义数据库集群中的角色与用户:
前者用于定义了整套环境中共用的角色与用户,后者定义单个集群中特有的业务角色与用户。二者形式相同,均为用户定义对象的数组。
你可以定义多个用户/角色,它们会按照先全局,后集群,最后按数组内排序的顺序依次创建,所以后面的用户可以属于前面定义的角色。
下面是 Pigsty 演示环境中默认集群 pg-meta 中的业务用户定义:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
- {name: dbuser_grafana ,password: DBUser.Grafana ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for grafana database }
- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for bytebase database }
- {name: dbuser_kong ,password: DBUser.Kong ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for kong api gateway }
- {name: dbuser_gitea ,password: DBUser.Gitea ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for gitea service }
- {name: dbuser_wiki ,password: DBUser.Wiki ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for wiki.js service }
- {name: dbuser_noco ,password: DBUser.Noco ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for nocodb service }
- {name: dbuser_remove ,state: absent } # 使用 state : absent 删除用户
每个用户/角色定义都是一个 object,可能包括以下字段,以 dbuser_meta 用户为例:
- name : dbuser_meta # 必需,`name` 是用户定义的唯一必选字段
state : create # 可选,用户状态:create(创建,默认)、absent(删除)
password : DBUser.Meta # 可选,密码,可以是 scram-sha-256 哈希字符串或明文
login : true # 可选,默认情况下可以登录
superuser : false # 可选,默认为 false,是超级用户吗?
createdb : false # 可选,默认为 false,可以创建数据库吗?
createrole : false # 可选,默认为 false,可以创建角色吗?
inherit : true # 可选,默认情况下,此角色可以使用继承的权限吗?
replication : false # 可选,默认为 false,此角色可以进行复制吗?
bypassrls : false # 可选,默认为 false,此角色可以绕过行级安全吗?
pgbouncer : true # 可选,默认为 false,将此用户添加到 pgbouncer 用户列表吗?(使用连接池的生产用户应该显式定义为 true)
connlimit : -1 # 可选,用户连接限制,默认 -1 禁用限制
expire_in : 3650 # 可选,此角色过期时间:从创建时 + n天计算(优先级比 expire_at 更高)
expire_at : '2030-12-31' # 可选,此角色过期的时间点,使用 YYYY-MM-DD 格式的字符串指定一个特定日期(优先级没 expire_in 高)
comment : pigsty admin user # 可选,此用户/角色的说明与备注字符串
roles : [ dbrole_admin] # 可选,所属角色,默认角色为:dbrole_{admin,readonly,readwrite,offline}
parameters : {} # 可选,使用 `ALTER ROLE SET` 针对这个角色,配置角色级的数据库参数
pool_mode : transaction # 可选,默认为 transaction 的 pgbouncer 池模式,用户级别
pool_connlimit : -1 # 可选,用户级别的最大数据库连接数,默认 -1 禁用限制
search_path : public # 可选,根据 postgresql 文档的键值配置参数(例如:使用 pigsty 作为默认 search_path)
唯一必需的字段是 name,它应该是 PostgreSQL 集群中的一个有效且唯一的用户名。 用户名必须匹配正则表达式 ^[a-z_][a-z0-9_]{0,62}$(小写字母、数字、下划线,以字母或下划线开头,最长63字符)。 角色不需要 password,但对于可登录的业务用户,通常是需要指定一个密码的。 password 可以是明文或 scram-sha-256 / md5 哈希字符串,请最好不要使用明文密码。用户/角色按数组顺序逐一创建,因此,请确保角色/分组的定义在成员之前。 login、superuser、createdb、createrole、inherit、replication、bypassrls 是布尔标志。pgbouncer 默认是禁用的:要将业务用户添加到 pgbouncer 用户列表,您应当显式将其设置为 true。参数总览 字段 分类 类型 可变性 说明 name基本 string必选 用户名,必须是有效且唯一的标识符 state基本 enum可选 用户状态:create(默认)、absent password基本 string可变 用户密码,明文或哈希 comment基本 string可变 用户备注信息 login权限 bool可变 是否允许登录,默认 true superuser权限 bool可变 是否为超级用户,默认 false createdb权限 bool可变 是否可创建数据库,默认 false createrole权限 bool可变 是否可创建角色,默认 false inherit权限 bool可变 是否继承所属角色权限,默认 true replication权限 bool可变 是否可进行复制,默认 false bypassrls权限 bool可变 是否可绕过行级安全,默认 false connlimit权限 int可变 连接数限制,-1 表示不限制 expire_in有效期 int可变 从当前日期起 N 天后过期(优先级高于 expire_at) expire_at有效期 string可变 过期日期,YYYY-MM-DD 格式 roles角色 array增量 所属角色数组,支持字符串或对象格式 parameters参数 object可变 角色级参数 pgbouncer连接池 bool可变 是否加入连接池,默认 false pool_mode连接池 enum可变 池化模式:transaction(默认) pool_connlimit连接池 int可变 连接池用户最大连接数
可变性说明 可变性 含义 必选 必须指定的字段 可选 可选字段,有默认值 可变 可通过重新执行剧本修改 增量 只会添加新内容,不会删除已有内容
基本参数 name类型 :string可变性 :必选说明 :用户名,集群内唯一标识符用户名必须是有效的 PostgreSQL 标识符,必须匹配正则表达式 ^[a-z_][a-z0-9_]{0,62}$:
以小写字母或下划线开头 只能包含小写字母、数字、下划线 最长 63 个字符 - name : dbuser_app # 标准命名
- name : app_readonly # 下划线分隔
- name : _internal # 下划线开头(用于内部角色)
state类型 :enum可变性 :可选默认值 :create可选值 :create、absent说明 :用户目标状态状态 说明 create创建用户(默认),已存在则更新属性 absent删除用户,使用 DROP ROLE
- name : dbuser_app # state 默认为 create
- name : dbuser_old
state : absent # 删除用户
注意 :以下系统用户无法通过 state: absent 删除:
postgres(超级用户)replicator(或 pg_replication_username 配置的用户)dbuser_dba(或 pg_admin_username 配置的用户)dbuser_monitor(或 pg_monitor_username 配置的用户)password类型 :string可变性 :可变默认值 :无说明 :用户密码密码可以是以下格式之一:
明文密码 :DBUser.Meta(不推荐用于生产环境)SCRAM-SHA-256 哈希 :SCRAM-SHA-256$4096:...(推荐)MD5 哈希 :md5...(兼容旧版本)# 明文密码(会被记录到配置文件,不推荐)
- name : dbuser_app
password : MySecretPassword
# SCRAM-SHA-256 哈希(推荐)
- name : dbuser_app
password : 'SCRAM-SHA-256$4096:xxx$yyy:zzz'
生成 SCRAM-SHA-256 哈希 :
# 使用 PostgreSQL 生成
psql -c "SELECT 'SCRAM-SHA-256 $' || pg_catalog.scram_sha_256('your_password')"
# 或使用 Python
python3 -c "import hashlib, secrets; print('SCRAM-SHA-256 $4096 :' + ...)"
类型 :string可变性 :可变默认值 :business user {name}说明 :用户备注信息会执行 COMMENT ON ROLE 语句。支持中文和特殊字符(会自动转义单引号)。
- name : dbuser_app
comment : '业务应用主账号'
权限参数 login类型 :bool可变性 :可变默认值 :true说明 :是否允许登录设置为 false 创建的是角色 (Role)而非用户(User),通常用于权限分组。
# 创建可登录用户
- name : dbuser_app
login : true
# 创建角色(不可登录)
- name : dbrole_custom
login : false
superuser类型 :bool可变性 :可变默认值 :false说明 :是否为超级用户安全警告
超级用户拥有数据库的全部权限,可以绕过所有权限检查。
除非绝对必要,否则不应创建额外的超级用户。
createdb类型 :bool可变性 :可变默认值 :false说明 :是否可创建数据库createrole类型 :bool可变性 :可变默认值 :false说明 :是否可创建角色inherit类型 :bool可变性 :可变默认值 :true说明 :是否自动继承所属角色的权限设置为 false 时,用户需要通过 SET ROLE 显式切换角色才能使用继承的权限。
replication类型 :bool可变性 :可变默认值 :false说明 :是否可以发起流复制连接通常只有复制用户(如 replicator)需要此权限。
bypassrls类型 :bool可变性 :可变默认值 :false说明 :是否可以绕过行级安全(RLS)策略connlimit类型 :int可变性 :可变默认值 :-1(不限制)说明 :用户最大并发连接数- name : dbuser_app
connlimit : 100 # 最多 100 个并发连接
- name : dbuser_batch
connlimit : 10 # 批处理用户限制连接数
有效期参数 expire_in类型 :int可变性 :可变说明 :从当前日期起 N 天后过期此参数优先级高于 expire_at。每次执行剧本时会重新计算过期时间。
- name : temp_user
expire_in : 30 # 30 天后过期
- name : long_term_user
expire_in : 3650 # 约 10 年后过期
expire_at格式为 YYYY-MM-DD 或特殊值 infinity(永不过期)。
- name : contractor_user
expire_at : '2024-12-31' # 指定日期过期
- name : permanent_user
expire_at : 'infinity' # 永不过期
注意 :expire_in 优先级高于 expire_at,如果同时指定,只有 expire_in 生效。
角色成员参数 roles类型 :array可变性 :增量说明 :用户所属角色数组roles 数组支持两种格式:
简单格式(字符串) - name : dbuser_app
roles :
- dbrole_readwrite
- pg_read_all_data
生成的 SQL:
GRANT "dbrole_readwrite" TO "dbuser_app" ;
GRANT "pg_read_all_data" TO "dbuser_app" ;
扩展格式(对象) 对象格式支持更精细的角色成员关系控制:
- name : dbuser_app
roles :
- dbrole_readwrite # 简单字符串:GRANT 角色
- { name: dbrole_admin, admin : true } # GRANT WITH ADMIN OPTION
- { name: pg_monitor, set: false } # PG16+ : REVOKE SET OPTION
- { name: pg_signal_backend, inherit: false } # PG16+ : REVOKE INHERIT OPTION
- { name: old_role, state : absent } # REVOKE 角色成员关系
对象格式参数 参数 类型 说明 namestring 角色名称(必选) stateenum grant(默认)或 absent/revoke:控制成员关系adminbool true: WITH ADMIN OPTION / false: REVOKE ADMINsetbool PG16+: true: WITH SET TRUE / false: REVOKE SET inheritbool PG16+: true: WITH INHERIT TRUE / false: REVOKE INHERIT
PostgreSQL 16+ 新特性 PostgreSQL 16 引入了更细粒度的角色成员关系控制:
ADMIN OPTION :允许将角色授予其他用户SET OPTION :允许使用 SET ROLE 切换到该角色INHERIT OPTION :是否自动继承该角色的权限# PostgreSQL 16+ 完整示例
- name : dbuser_app
roles :
# 普通成员关系
- dbrole_readwrite
# 可以将 dbrole_admin 授予其他用户
- { name: dbrole_admin, admin : true }
# 不能 SET ROLE 到 pg_monitor(只能继承权限)
- { name: pg_monitor, set : false }
# 不自动继承 pg_execute_server_program 的权限(需要显式 SET ROLE)
- { name: pg_execute_server_program, inherit : false }
# 撤销 old_role 的成员关系
- { name: old_role, state : absent }
注意 :set 和 inherit 选项仅在 PostgreSQL 16+ 中有效,在早期版本会被忽略并生成警告注释。
角色级参数 parameters类型 :object可变性 :可变说明 :角色级配置参数通过 ALTER ROLE ... SET 设置参数,参数会对该用户的所有会话生效。
- name : dbuser_analyst
parameters :
work_mem : '256MB'
statement_timeout : '5min'
search_path : 'analytics,public'
log_statement : 'all'
生成的 SQL:
ALTER USER "dbuser_analyst" SET "work_mem" = '256MB' ;
ALTER USER "dbuser_analyst" SET "statement_timeout" = '5min' ;
ALTER USER "dbuser_analyst" SET "search_path" = 'analytics,public' ;
ALTER USER "dbuser_analyst" SET "log_statement" = 'all' ;
重置参数为默认值 使用特殊值 DEFAULT(大小写不敏感)可以将参数重置为 PostgreSQL 默认值:
- name : dbuser_app
parameters :
work_mem : DEFAULT # 重置为 PostgreSQL 默认值
statement_timeout : '30s' # 设置新值
生成的 SQL:
ALTER USER "dbuser_app" SET "work_mem" = DEFAULT ;
ALTER USER "dbuser_app" SET "statement_timeout" = '30s' ;
常用角色级参数 参数 说明 示例值 work_mem查询工作内存 '64MB'statement_timeout语句超时时间 '30s'lock_timeout锁等待超时 '10s'idle_in_transaction_session_timeout空闲事务超时 '10min'search_pathSchema 搜索路径 'app,public'log_statement日志记录级别 'ddl'temp_file_limit临时文件大小限制 '10GB'
连接池参数 这些参数控制用户在 Pgbouncer 连接池中的行为。
pgbouncer类型 :bool可变性 :可变默认值 :false说明 :是否将用户添加到 Pgbouncer 用户列表重要
对于需要通过连接池访问数据库的生产用户,必须显式设置 pgbouncer: true。
默认为 false 是为了避免意外将内部用户暴露给连接池。
# 生产用户:需要连接池
- name : dbuser_app
password : DBUser.App
pgbouncer : true
# 内部用户:不需要连接池
- name : dbuser_internal
password : DBUser.Internal
pgbouncer : false # 默认值,可省略
pool_mode类型 :enum可变性 :可变可选值 :transaction、session、statement默认值 :transaction说明 :用户级别的池化模式模式 说明 适用场景 transaction事务结束后归还连接(默认) 大多数 OLTP 应用 session会话结束后归还连接 需要会话状态的应用 statement语句结束后归还连接 简单无状态查询
# DBA 用户使用 session 模式(可能需要 SET 命令等会话状态)
- name : dbuser_dba
pgbouncer : true
pool_mode : session
# 普通业务用户使用 transaction 模式
- name : dbuser_app
pgbouncer : true
pool_mode : transaction
pool_connlimit类型 :int可变性 :可变默认值 :-1(不限制)说明 :用户级别的连接池最大连接数- name : dbuser_app
pgbouncer : true
pool_connlimit : 50 # 此用户最多使用 50 个连接池连接
ACL系统 Pigsty 具有一套内置的,开箱即用的访问控制 / ACL 系统,您只需将以下四个默认角色分配给业务用户即可轻松使用:
dbrole_readwrite:全局读写访问的角色(主属业务使用的生产账号应当具有数据库读写权限)dbrole_readonly:全局只读访问的角色(如果别的业务想要只读访问,可以使用此角色)dbrole_admin:拥有DDL权限的角色 (业务管理员,需要在应用中建表的场景)dbrole_offline:受限的只读访问角色(只能访问 offline 实例,通常是个人用户)如果您希望重新设计您自己的 ACL 系统,可以考虑定制以下参数和模板:
Pgbouncer用户 默认情况下启用 Pgbouncer,并作为连接池中间件,其用户默认被管理。
Pigsty 默认将 pg_users 中显式带有 pgbouncer: true 标志的所有用户添加到 pgbouncer 用户列表中。
Pgbouncer 连接池中的用户在 /etc/pgbouncer/userlist.txt 中列出:
"postgres" ""
"dbuser_wiki" "SCRAM-SHA-256$4096:+77dyhrPeFDT/TptHs7/7Q = =$KeatuohpKIYzHPCt/tqBu85vI11o9mar/by0hHYM2W8=:X9gig4JtjoS8Y/o1vQsIX/gY1Fns8ynTXkbWOjUfbRQ="
"dbuser_view" "SCRAM-SHA-256$4096:DFoZHU/DXsHL8MJ8regdEw = =$gx9sUGgpVpdSM4o6A2R9PKAUkAsRPLhLoBDLBUYtKS0=:MujSgKe6rxcIUMv4GnyXJmV0YNbf39uFRZv724+X1FE="
"dbuser_monitor" "SCRAM-SHA-256$4096:fwU97ZMO/KR0ScHO5+UuBg = =$CrNsmGrx1DkIGrtrD1Wjexb/aygzqQdirTO1oBZROPY=:L8+dJ+fqlMQh7y4PmVR/gbAOvYWOr+KINjeMZ8LlFww="
"dbuser_meta" "SCRAM-SHA-256$4096:leB2RQPcw1OIiRnPnOMUEg = =$eyC+NIMKeoTxshJu314+BmbMFpCcspzI3UFZ1RYfNyU=:fJgXcykVPvOfro2MWNkl5q38oz21nSl1dTtM65uYR1Q="
而用户级别的连接池参数则是使用另一个单独的文件: /etc/pgbouncer/useropts.txt 进行维护,比如:
dbuser_dba = pool_mode=session max_user_connections=16
dbuser_monitor = pool_mode=session max_user_connections=8
当您创建用户 时,Pgbouncer 的用户列表定义文件将会被刷新,并通过在线重载配置的方式生效,不会影响现有的连接。
Pgbouncer 使用和 PostgreSQL 同样的 dbsu 运行,默认为 postgres 操作系统用户,您可以使用 pgb 别名,使用 dbsu 访问 pgbouncer 管理功能。
请注意,pgbouncer_auth_query 参数允许你使用动态查询来完成连接池用户认证,当您懒得管理连接池中的用户时,这是一种折中的方案。
关于用户管理操作,请参考 用户管理 一节。
关于用户的访问权限,请参考 ACL:角色权限 一节。
11.3.5 - 数据库 数据库指的是使用 SQL 命令 CREATE DATABASE 创建的,数据库集簇内的逻辑对象。
在这里的上下文中,数据库指的是使用 SQL 命令 CREATE DATABASE 创建的,数据库集簇内的逻辑对象。
一组 PostgreSQL 服务器可以同时服务于多个 数据库 (Database)。在 Pigsty 中,你可以在集群配置中定义 好所需的数据库。
Pigsty会对默认模板数据库template1进行修改与定制,创建默认模式,安装默认扩展,配置默认权限,新创建的数据库默认会从template1继承这些设置。
默认情况下,所有业务数据库都会被1:1添加到 Pgbouncer 连接池中;pg_exporter 默认会通过 自动发现 机制查找所有业务数据库并进行库内对象监控。
定义数据库 业务数据库定义在数据库集群参数 pg_databases 中,这是一个数据库定义构成的对象数组。
数组内的数据库按照定义顺序 依次创建,因此后面定义的数据库可以使用先前定义的数据库作为模板 。
下面是 Pigsty 演示环境中默认集群 pg-meta 中的数据库定义:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name: postgis, schema : public}, {name: timescaledb}]}
- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment : grafana primary database }
- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment : bytebase primary database }
- { name: kong ,owner: dbuser_kong ,revokeconn: true ,comment : kong the api gateway database }
- { name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment : gitea meta database }
- { name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment : wiki meta database }
- { name: noco ,owner: dbuser_noco ,revokeconn: true ,comment : nocodb database }
每个数据库定义都是一个 object,可能包括以下字段,以 meta 数据库为例:
- name : meta # 必选,`name` 是数据库定义的唯一必选字段
state : create # 可选,数据库状态:create(创建,默认)、absent(删除)、recreate(重建)
baseline : cmdb.sql # 可选,数据库 sql 的基线定义文件路径(ansible 搜索路径中的相对路径,如 files/)
pgbouncer : true # 可选,是否将此数据库添加到 pgbouncer 数据库列表?默认为 true
schemas : [ pigsty] # 可选,要创建的附加模式,由模式名称字符串组成的数组
extensions : # 可选,要安装的附加扩展: 扩展对象的数组
- { name: postgis , schema : public } # 可以指定将扩展安装到某个模式中,也可以不指定(不指定则安装到 search_path 首位模式中)
- { name : timescaledb } # 例如有的扩展会创建并使用固定的模式,就不需要指定模式。
comment : pigsty meta database # 可选,数据库的说明与备注信息
owner : postgres # 可选,数据库所有者,不指定则为当前用户
template : template1 # 可选,要使用的模板,默认为 template1,目标必须是一个模板数据库
strategy : FILE_COPY # 可选,克隆策略:FILE_COPY 或 WAL_LOG(PG15+),不指定使用 PG 默认
encoding : UTF8 # 可选,不指定则继承模板/集群配置(UTF8)
locale : C # 可选,不指定则继承模板/集群配置(C)
lc_collate : C # 可选,不指定则继承模板/集群配置(C)
lc_ctype : C # 可选,不指定则继承模板/集群配置(C)
locale_provider : libc # 可选,本地化提供者:libc、icu、builtin(PG15+)
icu_locale : en-US # 可选,ICU 本地化规则(PG15+)
icu_rules : '' # 可选,ICU 排序规则(PG16+)
builtin_locale : C.UTF-8 # 可选,内置本地化提供者规则(PG17+)
tablespace : pg_default # 可选,默认表空间,默认为 'pg_default'
is_template : false # 可选,是否标记为模板数据库,允许任何有 CREATEDB 权限的用户克隆
allowconn : true # 可选,是否允许连接,默认为 true。显式设置 false 将完全禁止连接到此数据库
revokeconn : false # 可选,撤销公共连接权限。默认为 false,设置为 true 时,属主和管理员之外用户的 CONNECT 权限会被回收
register_datasource : true # 可选,是否将此数据库注册到 grafana 数据源?默认为 true,显式设置为 false 会跳过注册
connlimit : -1 # 可选,数据库连接限制,默认为 -1 ,不限制,设置为正整数则会限制连接数。
parameters : # 可选,数据库级参数,通过 ALTER DATABASE SET 设置
work_mem : '64MB'
statement_timeout : '30s'
pool_auth_user : dbuser_meta # 可选,连接到此 pgbouncer 数据库的所有连接都将使用此用户进行验证(启用 pgbouncer_auth_query 才有用)
pool_mode : transaction # 可选,数据库级别的 pgbouncer 池化模式,默认为 transaction
pool_size : 64 # 可选,数据库级别的 pgbouncer 默认池子大小,默认为 64
pool_size_reserve : 32 # 可选,数据库级别的 pgbouncer 池子保留空间,默认为 32,当默认池子不够用时,最多再申请这么多条突发连接。
pool_size_min : 0 # 可选,数据库级别的 pgbouncer 池的最小大小,默认为 0
pool_max_db_conn : 100 # 可选,数据库级别的最大数据库连接数,默认为 100
唯一必选的字段是 name,它应该是当前 PostgreSQL 集群中有效且唯一的数据库名称,其他参数都有合理的默认值。
参数总览 字段 分类 类型 可变性 说明 name基本 string必选 数据库名称,必须是有效且唯一的标识符 state基本 enum可选 数据库状态:create(默认)、absent、recreate owner基本 string可变 数据库属主,不指定则为 postgres comment基本 string可变 数据库备注信息 template模板 string不可变 创建时使用的模板数据库,默认 template1 strategy模板 enum不可变 克隆策略:FILE_COPY 或 WAL_LOG(PG15+) encoding编码 string不可变 字符编码,默认继承模板(UTF8) locale编码 string不可变 本地化规则,默认继承模板(C) lc_collate编码 string不可变 排序规则,默认继承模板(C) lc_ctype编码 string不可变 字符分类,默认继承模板(C) locale_provider编码 enum不可变 本地化提供者:libc、icu、builtin(PG15+) icu_locale编码 string不可变 ICU 本地化规则(PG15+) icu_rules编码 string不可变 ICU 排序定制规则(PG16+) builtin_locale编码 string不可变 内置本地化规则(PG17+) tablespace存储 string可变 默认表空间,修改会触发数据迁移 is_template权限 bool可变 是否标记为模板数据库 allowconn权限 bool可变 是否允许连接,默认 true revokeconn权限 bool可变 是否回收 PUBLIC 的 CONNECT 权限 connlimit权限 int可变 连接数限制,-1 表示不限制 baseline初始化 string一次性 SQL 基线文件路径,仅首次创建时执行 schemas初始化 (string|object)[]增量 要创建的模式定义数组 extensions初始化 object[]增量 要安装的扩展定义数组 parameters初始化 object可变 数据库级参数 pgbouncer连接池 bool可变 是否加入连接池,默认 true pool_mode连接池 enum可变 池化模式:transaction(默认) pool_size连接池 int可变 默认池大小,默认 64 pool_size_min连接池 int可变 最小池大小,默认 0 pool_reserve连接池 int可变 保留池大小,默认 32 pool_connlimit连接池 int可变 最大数据库连接数,默认 100 pool_auth_user连接池 string可变 认证查询用户 register_datasource监控 bool可变 是否注册到 Grafana 数据源,默认 true
可变性说明 可变性 含义 必选 必须指定的字段 可选 可选字段,有默认值 不可变 仅在创建时生效,创建后无法修改,需重建数据库 可变 可通过重新执行剧本修改 一次性 仅在首次创建时执行,已存在的数据库不会重复执行 增量 只会添加新内容,不会删除已有内容
基本参数 name类型 :string可变性 :必选说明 :数据库名称,集群内唯一标识符数据库名称必须是有效的 PostgreSQL 标识符,建议使用小写字母、数字和下划线,避免使用特殊字符。
- name : myapp # 简单命名
- name : my_application # 下划线分隔
- name : app_v2 # 包含版本号
state类型 :enum可变性 :可选默认值 :create可选值 :create、absent、recreate说明 :数据库目标状态状态 说明 create创建数据库(默认),已存在则跳过 absent删除数据库,使用 DROP DATABASE WITH (FORCE) recreate先删除再创建,用于重置数据库
- name : myapp # state 默认为 create
- name : olddb
state : absent # 删除数据库
- name : testdb
state : recreate # 重建数据库
owner类型 :string可变性 :可变默认值 :postgres(当前用户)说明 :数据库所有者指定的用户必须已存在。修改 owner 会执行:
ALTER DATABASE "myapp" OWNER TO "new_owner" ;
GRANT ALL PRIVILEGES ON DATABASE "myapp" TO "new_owner" ;
类型 :string可变性 :可变默认值 :business database {name}说明 :数据库备注信息会执行 COMMENT ON DATABASE 语句。支持中文和特殊字符(会自动转义单引号)。
模板与克隆参数 template类型 :string可变性 :不可变默认值 :template1说明 :创建数据库时使用的模板常用模板:
模板 说明 template1默认模板,包含 Pigsty 预配置的扩展和权限 template0干净模板,用于指定不同编码或本地化设置时必须使用 自定义数据库 可以使用已有数据库作为模板克隆
重要 :使用 icu 或 builtin 本地化提供者时,必须指定 template: template0。
- name : myapp_icu
template : template0 # 使用 ICU 时必须
locale_provider : icu
icu_locale : en-US
strategy类型 :enum可变性 :不可变版本要求 :PostgreSQL 15+可选值 :FILE_COPY、WAL_LOG说明 :从模板克隆数据库的策略策略 说明 适用场景 FILE_COPY直接复制数据文件(PG15+ 默认) 大模板,通用场景 WAL_LOG通过 WAL 日志复制 小模板,不阻塞连接
在 PostgreSQL 14 及更早版本中,此参数会被忽略。
编码与本地化参数 encoding类型 :string可变性 :不可变默认值 :继承模板(通常为 UTF8)说明 :数据库字符编码常用编码:UTF8、LATIN1、SQL_ASCII
locale类型 :string可变性 :不可变默认值 :继承模板(通常为 C)说明 :数据库本地化规则,同时设置 lc_collate 和 lc_ctypelc_collate类型 :string可变性 :不可变默认值 :继承模板(通常为 C)说明 :字符串排序规则常用值:C、C.UTF-8、en_US.UTF-8、zh_CN.UTF-8
lc_ctype类型 :string可变性 :不可变默认值 :继承模板(通常为 C)说明 :字符分类规则(大小写、数字等)locale_provider类型 :enum可变性 :不可变版本要求 :PostgreSQL 15+可选值 :libc、icu、builtin默认值 :libc说明 :本地化实现提供者提供者 版本 说明 libc- 使用操作系统 C 库,传统默认方式 icuPG15+ 使用 ICU 库,跨平台一致 builtinPG17+ PostgreSQL 内置实现,最高效的 C/C.UTF-8
注意 :使用 icu 或 builtin 时,必须指定 template: template0。
icu_locale类型 :string可变性 :不可变版本要求 :PostgreSQL 15+说明 :ICU 本地化规则标识符常用值:
值 说明 en-US美式英语 en-GB英式英语 zh-Hans简体中文 zh-Hant繁体中文 ja-JP日语 ko-KR韩语
- name : chinese_db
template : template0
locale_provider : icu
icu_locale : zh-Hans
encoding : UTF8
icu_rules类型 :string可变性 :不可变版本要求 :PostgreSQL 16+说明 :ICU 排序定制规则用于自定义排序行为,使用 ICU 规则语法。
- name : custom_sort_db
template : template0
locale_provider : icu
icu_locale : en-US
icu_rules : '&V << w <<< W' # 自定义 V/W 排序
builtin_locale类型 :string可变性 :不可变版本要求 :PostgreSQL 17+可选值 :C、C.UTF-8说明 :内置本地化提供者的规则builtin 提供者比 libc 更快,特别适合只需要 C 或 C.UTF-8 排序的场景。
- name : fast_db
template : template0
locale_provider : builtin
builtin_locale : C.UTF-8
encoding : UTF8
存储与权限参数 tablespace类型 :string可变性 :可变默认值 :pg_default说明 :数据库默认表空间修改表空间会触发数据物理迁移,对于大数据库可能需要较长时间。
- name : archive_db
tablespace : slow_hdd # 归档数据使用慢速存储
is_template类型 :bool可变性 :可变默认值 :false说明 :是否标记为模板数据库设置为 true 后,任何有 CREATEDB 权限的用户都可以使用此数据库作为模板克隆新数据库。
- name : app_template
is_template : true # 允许普通用户克隆
schemas : [ core, api]
extensions : [ postgis]
注意 :标记为 is_template: true 的数据库删除时,会先执行 ALTER DATABASE ... IS_TEMPLATE false。
allowconn类型 :bool可变性 :可变默认值 :true说明 :是否允许连接到此数据库设置为 false 会完全禁止任何用户连接到此数据库(包括超级用户)。
- name : archive_db
allowconn : false # 禁止连接
revokeconn类型 :bool可变性 :可变默认值 :false说明 :是否回收 PUBLIC 的 CONNECT 权限设置为 true 时:
回收 PUBLIC 的 CONNECT 权限 授予 replicator、monitor 连接权限 授予 admin、owner 连接权限(WITH GRANT OPTION) 设置为 false 时:
- name : secure_db
owner : dbuser_secure
revokeconn : true # 只有指定用户可连接
connlimit类型 :int可变性 :可变默认值 :-1(不限制)说明 :数据库最大连接数限制- name : limited_db
connlimit : 50 # 最多 50 个并发连接
初始化参数 baseline类型 :string可变性 :一次性说明 :SQL 基线文件路径指定在数据库创建后执行的 SQL 文件,用于初始化表结构、数据等。
路径是相对于 Ansible 搜索路径(通常是 files/ 目录) 仅在首次创建数据库时执行 使用 state: recreate 重建时会重新执行 - name : myapp
baseline : myapp_init.sql # 会查找 files/myapp_init.sql
schemas类型 :(string | object)[]可变性 :增量说明 :要创建的模式定义数组支持两种格式:
schemas :
# 简单格式:只指定模式名
- app
- api
# 完整格式:对象定义
- name : core # 模式名(必选)
owner : dbuser_app # 模式属主(可选)
- name : old_schema
state : absent # 删除模式
模式属主 :使用 owner 指定模式属主,会生成 AUTHORIZATION 子句:
- name : myapp
owner : dbuser_myapp
schemas :
- name : app
owner : dbuser_myapp # 模式属主与数据库属主一致
- name : audit
owner : dbuser_audit # 模式属主为其他用户
执行的 SQL:
CREATE SCHEMA IF NOT EXISTS "app" AUTHORIZATION "dbuser_myapp" ;
CREATE SCHEMA IF NOT EXISTS "audit" AUTHORIZATION "dbuser_audit" ;
删除模式 :使用 state: absent 删除模式:
schemas :
- { name: deprecated_schema, state : absent }
执行的 SQL:
DROP SCHEMA IF EXISTS "deprecated_schema" CASCADE ;
注意 :
创建操作是增量的,使用 IF NOT EXISTS 删除操作使用 CASCADE,会同时删除模式内的所有对象 extensions类型 :object[]可变性 :增量说明 :要安装的扩展定义数组支持两种格式:
extensions :
# 简单格式:只指定扩展名
- postgis
- pg_trgm
# 完整格式:对象定义
- name : vector # 扩展名(必选)
schema : public # 安装到指定 schema(可选)
version : '0.5.1' # 指定版本(可选)
state : absent # 设为 absent 可卸载扩展(可选)
扩展卸载 :使用 state: absent 可以卸载扩展:
extensions :
- { name: pg_trgm, state : absent } # 卸载 pg_trgm
卸载会执行 DROP EXTENSION IF EXISTS "name" CASCADE,注意 CASCADE 会删除依赖对象。
parameters类型 :object可变性 :可变说明 :数据库级配置参数通过 ALTER DATABASE ... SET 设置参数,参数会对连接到此数据库的所有会话生效。
- name : analytics
parameters :
work_mem : '256MB'
maintenance_work_mem : '512MB'
statement_timeout : '5min'
search_path : 'analytics,public'
重置参数 :使用特殊值 DEFAULT(大小写不敏感)重置为 PostgreSQL 默认值:
- name : myapp
parameters :
work_mem : DEFAULT # 重置为默认值
statement_timeout : '30s' # 设置新值
执行的 SQL:
ALTER DATABASE "myapp" SET "work_mem" = DEFAULT ;
ALTER DATABASE "myapp" SET "statement_timeout" = '30s' ;
连接池参数 这些参数控制数据库在 Pgbouncer 连接池中的行为。
pgbouncer类型 :bool可变性 :可变默认值 :true说明 :是否将数据库添加到 Pgbouncer 连接池- name : internal_db
pgbouncer : false # 不通过连接池访问
pool_mode类型 :enum可变性 :可变可选值 :transaction、session、statement默认值 :transaction说明 :数据库级别的池化模式模式 说明 适用场景 transaction事务结束后归还连接 大多数 OLTP 应用 session会话结束后归还连接 需要会话状态的应用 statement语句结束后归还连接 简单无状态查询
pool_size类型 :int可变性 :可变默认值 :64说明 :数据库默认连接池大小pool_size_min类型 :int可变性 :可变默认值 :0说明 :最小连接池大小,预热连接数pool_reserve类型 :int可变性 :可变默认值 :32说明 :保留连接数,突发时可额外申请的连接pool_connlimit类型 :int可变性 :可变默认值 :100说明 :通过连接池访问此数据库的最大连接数pool_auth_user需要启用 pgbouncer_auth_query 后生效。
指定后,所有到此数据库的连接都会使用该用户查询密码。
监控参数 register_datasource类型 :bool可变性 :可变默认值 :true说明 :是否注册到 Grafana 数据源设置为 false 可以跳过 Grafana 数据源注册,适用于不需要监控的临时数据库。
模板继承 许多参数如果不显式指定,会从模板数据库继承。默认模板是 template1,其编码设置由集群初始化参数决定:
新创建的数据库默认会从 template1 数据库 Fork 出来,这个模版数据库会在 PG_PROVISION 阶段进行定制修改:
配置好扩展、模式以及默认权限,因此新创建的数据库也会继承这些配置,除非您显式使用一个其他的数据库作为模板。
关于数据库管理操作,请参考 数据库管理 一节。
关于数据库的访问权限,请参考 ACL:数据库权限 一节。
11.3.6 - HBA 规则 Pigsty 中 PostgreSQL 与 Pgbouncer 的 HBA(Host-Based Authentication)规则配置详解。
HBA(Host-Based Authentication)控制"谁可以从哪里、以什么方式连接到数据库"。
Pigsty 通过 pg_default_hba_rules 与 pg_hba_rules 让 HBA 规则也能以声明式配置形式管理。
概述 Pigsty 在集群初始化或 HBA 刷新时渲染以下配置文件:
配置文件 路径 说明 PostgreSQL HBA /pg/data/pg_hba.confPostgreSQL 服务器的 HBA 规则 Pgbouncer HBA /etc/pgbouncer/pgb_hba.conf连接池 Pgbouncer 的 HBA 规则
HBA 规则由以下参数控制:
规则特性:
按角色过滤 :规则支持 role 字段,根据实例的 pg_role 自动筛选生效按顺序排序 :规则支持 order 字段,控制规则在最终配置文件中的位置两种写法 :支持别名形式(简化语法)和原始形式(直接 HBA 文本)参数详解 pg_default_hba_rulesPostgreSQL 全局默认 HBA 规则列表,通常定义在 all.vars 中,为所有 PostgreSQL 集群提供基础访问控制。
类型:rule[] 层级:全局 (G) 默认值:见下文 pg_default_hba_rules :
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title: 'dbsu access via local os user ident' ,order : 100 }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title: 'dbsu replication from local os ident' ,order : 150 }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title: 'replicator replication from localhost',order : 200 }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title: 'replicator replication from intranet' ,order : 250 }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title: 'replicator postgres db from intranet' ,order : 300 }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title: 'monitor from localhost with password' ,order : 350 }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title: 'monitor from infra host with password',order : 400 }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title: 'admin @ infra nodes with pwd & ssl' ,order : 450 }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title: 'admin @ everywhere with ssl & pwd' ,order : 500 }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title: 'pgbouncer read/write via local socket',order : 550 }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title: 'read/write biz user via password' ,order : 600 }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title: 'allow etl offline tasks from intranet',order : 650 }
pg_hba_rulesPostgreSQL 集群/实例级 HBA 追加规则,可在集群或实例级别覆盖,与默认规则合并后按 order 排序。
类型:rule[] 层级:全局/集群/实例 (G/C/I) 默认值:[] pg_hba_rules :
- {user: app_user, db: app_db, addr: intra, auth: pwd, title : 'app user access' }
pgb_default_hba_rulesPgbouncer 全局默认 HBA 规则列表,通常定义在 all.vars 中。
类型:rule[] 层级:全局 (G) 默认值:见下文 pgb_default_hba_rules :
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title: 'dbsu local admin access with os ident',order : 100 }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title: 'allow all user local access with pwd' ,order : 150 }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: pwd ,title: 'monitor access via intranet with pwd' ,order : 200 }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title: 'reject all other monitor access addr' ,order : 250 }
- {user : '${admin}' ,db: all ,addr: intra ,auth: pwd ,title: 'admin access via intranet with pwd' ,order : 300 }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title: 'reject all other admin access addr' ,order : 350 }
- {user: 'all' ,db: all ,addr: intra ,auth: pwd ,title: 'allow all user intra access with pwd' ,order : 400 }
pgb_hba_rulesPgbouncer 集群/实例级 HBA 追加规则。
类型:rule[] 层级:全局/集群/实例 (G/C/I) 默认值:[] 注意 :Pgbouncer HBA 不支持 db: replication。
规则字段 每条 HBA 规则是一个 YAML 字典,支持以下字段:
字段 类型 必需 默认值 说明 userstring 否 all用户名,支持 all、变量占位符、+rolename 等 dbstring 否 all数据库名,支持 all、replication、具体库名 addrstring 是* - 地址别名或 CIDR,见地址别名 authstring 否 pwd认证方式别名,见认证方式 titlestring 否 - 规则说明/注释,会渲染为配置文件中的注释 rolestring 否 common实例角色过滤,见角色过滤 orderint 否 1000排序权重,数字小的排前面,见排序机制 ruleslist 是* - 原始 HBA 文本行列表,与 addr 二选一
addr 和 rules 必须指定其一。使用 rules 时可以直接写原始 HBA 格式。
地址别名 Pigsty 提供地址别名,简化 HBA 规则编写:
别名 展开为 说明 localUnix socket 本地 Unix 套接字连接 localhostUnix socket + 127.0.0.1/32 + ::1/128 本地回环地址 admin${admin_ip}/32管理员 IP 地址 infra所有 infra 组节点 IP 基础设施节点列表 cluster当前集群所有成员 IP 同一集群内的所有实例 intra / intranet10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16内网 CIDR 网段 world / all0.0.0.0/0 + ::/0任意地址(IPv4 + IPv6) <CIDR>直接使用 如 192.168.1.0/24、10.1.1.100/32
内网 CIDR 可通过 node_firewall_intranet 参数自定义:
node_firewall_intranet :
- 10.0.0.0 /8
- 172.16.0.0 /12
- 192.168.0.0 /16
认证方式 Pigsty 提供认证方式别名,简化配置:
别名 实际方式 连接类型 说明 pwdscram-sha-256 或 md5host根据 pg_pwd_enc 自动选择 sslscram-sha-256 或 md5hostssl强制 SSL + 密码 ssl-shascram-sha-256hostssl强制 SSL + SCRAM-SHA-256 ssl-md5md5hostssl强制 SSL + MD5 certcerthostssl客户端证书认证 trusttrusthost无条件信任(危险) deny / rejectrejecthost拒绝连接 identidenthostOS 用户映射(PostgreSQL) peerpeerlocalOS 用户映射(Pgbouncer/本地)
pg_pwd_enc 默认为 scram-sha-256,可设为 md5 以兼容老客户端。
用户变量 HBA 规则支持以下用户占位符,渲染时自动替换为实际用户名:
占位符 默认值 说明 ${dbsu}postgres数据库超级用户 ${repl}replicator复制用户 ${monitor}dbuser_monitor监控用户 ${admin}dbuser_dba管理员用户
这些变量的实际值由对应参数控制:
pg_dbsu : postgres
pg_replication_username : replicator
pg_monitor_username : dbuser_monitor
pg_admin_username : dbuser_dba
角色过滤 HBA 规则的 role 字段控制规则在哪些实例上生效:
角色 说明 common默认值,所有实例都生效 primary仅主库实例生效 replica仅从库实例生效 offline仅离线实例生效(pg_role: offline 或 pg_offline_query: true) standby备库实例 delayed延迟从库实例
角色过滤基于实例的 pg_role 变量进行匹配。不匹配的规则会被注释掉(以 # 开头)。
pg_hba_rules :
# 仅在主库生效
- {user: writer, db: all, addr: intra, auth: pwd, role: primary, title : 'writer only on primary' }
# 仅在离线实例生效
- {user: '+dbrole_offline', db: all, addr: '172.20.0.0/16', auth: ssl, role: offline, title : 'offline dedicated' }
排序机制 PostgreSQL HBA 是首条匹配生效 ,规则顺序至关重要。Pigsty 通过 order 字段控制规则渲染顺序。
Order 区间约定 区间 用途 0 - 99用户高优先规则(在所有默认规则之前) 100 - 650默认规则区(间隔 50,便于插入) 1000+用户规则默认值(不填 order 时追加到最后)
默认规则 Order 分配 PostgreSQL 默认规则 :
Order 规则说明 100 dbsu local ident 150 dbsu replication local 200 replicator localhost 250 replicator intra replication 300 replicator intra postgres 350 monitor localhost 400 monitor infra 450 admin infra ssl 500 admin world ssl 550 dbrole_readonly localhost 600 dbrole_readonly intra 650 dbrole_offline intra
Pgbouncer 默认规则 :
Order 规则说明 100 dbsu local peer 150 all localhost pwd 200 monitor pgbouncer intra 250 monitor world deny 300 admin intra pwd 350 admin world deny 400 all intra pwd
排序示例 pg_hba_rules :
# order: 0,在所有默认规则之前(黑名单)
- {user: all, db: all, addr: '10.1.1.100/32', auth: deny, order: 0, title : 'blacklist bad ip' }
# order: 120,在 dbsu(100) 和 replicator(200) 之间
- {user: auditor, db: all, addr: local, auth: ident, order: 120, title : 'auditor access' }
# order: 420,在 monitor(400) 和 admin(450) 之间
- {user: exporter, db: all, addr: infra, auth: pwd, order: 420, title : 'prometheus exporter' }
# 不填 order,默认 1000,追加到所有默认规则之后
- {user: app_user, db: app_db, addr: intra, auth: pwd, title : 'app user access' }
写法示例 别名形式 使用 Pigsty 提供的简化语法:
pg_hba_rules :
- title : allow grafana view access
role : primary
user : dbuser_view
db : meta
addr : infra
auth : ssl
渲染结果:
# allow grafana view access [primary]
hostssl meta dbuser_view 10.10.10.10/32 scram-sha-256
原始形式 直接使用 PostgreSQL HBA 语法:
pg_hba_rules :
- title : allow intranet password access
role : common
rules :
- host all all 10.0.0.0/8 scram-sha-256
- host all all 172.16.0.0/12 scram-sha-256
- host all all 192.168.0.0/16 scram-sha-256
渲染结果:
# allow intranet password access [common]
host all all 10.0.0.0/8 scram-sha-256
host all all 172.16.0.0/12 scram-sha-256
host all all 192.168.0.0/16 scram-sha-256
常见配置示例 1. 内网密码访问业务库 pg_hba_rules :
- title : 'intra readwrite access'
role : common
user : '+dbrole_readwrite'
db : all
addr : intra
auth : pwd
效果:所有业务读写角色可以从内网网段使用密码访问任意数据库。
2. 离线实例专用网络 pg_hba_rules :
- title : 'offline replica dedicated network'
role : offline
user : '+dbrole_offline'
db : all
addr : 172.20.0.0 /16
auth : ssl-sha
效果:仅 pg_role: offline 或 pg_offline_query: true 的实例启用该规则。
3. 黑名单 IP pg_hba_rules :
- user : all
db : all
addr : '10.1.1.100/32'
auth : deny
order : 0
title : 'block compromised host'
效果:order: 0 排在所有默认规则(100+)之前,优先匹配并拒绝。
4. 白名单特定应用 pg_hba_rules :
- title : 'allow app server access'
user : app_user
db : app_db
addr : '192.168.1.10/32'
auth : ssl
order : 50
效果:特定应用服务器使用 SSL 连接,高优先级(50)确保在默认规则之前匹配。
5. 管理员强制证书认证 pg_hba_rules :
- title : 'admin cert access'
role : common
user : '${admin}'
db : all
addr : world
auth : cert
order : 10
效果:管理员必须携带客户端证书才能连接,order: 10 优先于默认的 ssl 规则(450/500)。
6. 允许外网只读访问 pg_hba_rules :
- title : 'readonly from internet'
role : replica
user : '+dbrole_readonly'
db : all
addr : world
auth : ssl
效果:只读用户可从外网通过 SSL 连接从库。
7. Pgbouncer 专用规则 pgb_hba_rules :
- title : 'app via pgbouncer'
role : common
user : '+dbrole_readwrite'
db : all
addr : world
auth : ssl
注意:Pgbouncer HBA 不支持 db: replication。
8. 多条件组合 pg_hba_rules :
# 开发环境:信任本地连接
- {user: all, db: all, addr: local, auth: trust, title : 'dev trust local' }
# 生产环境:严格 SSL
- {user: '+dbrole_readwrite', db: all, addr: intra, auth: ssl-sha, title : 'prod ssl only' }
# 监控专用:从 Prometheus 节点
- {user : '${monitor}' , db: all, addr: infra, auth: pwd, order: 380, title : 'prometheus access' }
9. 按数据库限制访问 pg_hba_rules :
# 财务系统:仅允许特定网段
- {user: fin_user, db: finance_db, addr: '10.20.0.0/16', auth: ssl, title : 'finance restricted' }
# HR 系统:仅允许 HR 网段
- {user: hr_user, db: hr_db, addr: '10.30.0.0/16', auth: ssl, title : 'hr restricted' }
10. 完整集群配置示例 pg-prod :
hosts :
10.10.10.11 : {pg_seq: 1, pg_role : primary}
10.10.10.12 : {pg_seq: 2, pg_role : replica}
10.10.10.13 : {pg_seq: 3, pg_role : offline}
vars :
pg_cluster : pg-prod
pg_hba_rules :
# 黑名单:已知恶意 IP
- {user: all, db: all, addr: '10.1.1.100/32', auth: deny, order: 0, title : 'blacklist' }
# 应用服务器白名单
- {user: app_user, db: app_db, addr: '192.168.1.0/24', auth: ssl, order: 50, title : 'app servers' }
# ETL 任务:仅离线实例
- {user: etl_user, db: all, addr: '172.20.0.0/16', auth: pwd, role: offline, title : 'etl tasks' }
# 监控增强
- {user : '${monitor}' , db: all, addr: cluster, auth: pwd, order: 380, title : 'cluster monitor' }
pgb_hba_rules :
# 应用通过连接池
- {user: '+dbrole_readwrite', db: all, addr: '192.168.1.0/24', auth: ssl, title : 'app via pgbouncer' }
渲染原理 Pigsty 使用 Jinja2 模板渲染 HBA 配置文件:
合并规则 :pg_default_hba_rules + pg_hba_rules排序规则 :按 order 字段升序排列(无 order 的规则追加到最后)角色过滤 :根据实例 pg_role 筛选,不匹配的规则被注释变量替换 :${dbsu} 等占位符替换为实际用户名地址展开 :intra、infra 等别名展开为实际 IP/CIDR认证映射 :pwd、ssl 等别名映射为实际认证方式模板位置:
PostgreSQL:roles/pgsql/templates/pg_hba.conf Pgbouncer:roles/pgsql/templates/pgbouncer.hba 注意事项 顺序敏感 :PostgreSQL HBA 首条匹配生效,规则顺序很重要角色匹配 :确保 role 字段与目标实例的 pg_role 一致地址验证 :CIDR 格式必须正确,如 10.0.0.0/8 而非 10.0.0.0/255.0.0.0Pgbouncer 限制 :不支持 db: replication变量作用域 :用户变量仅限预定义的四个(${dbsu}, ${repl}, ${monitor}, ${admin})SSL 配置 :使用 ssl、cert 认证方式前确保 SSL 已正确配置测试优先 :修改 HBA 前建议先在测试环境验证测试与验证 Pigsty 提供了 HBA order 排序功能的测试工具,可在部署前验证配置正确性:
运行排序逻辑测试 # 在 pigsty 目录下运行排序逻辑测试
./files/test-hba-order.yml
该测试验证:
规则按 order 字段正确排序 无 order 字段的规则追加到末尾 相同 order 值的规则保持原始顺序(稳定排序) 向后兼容性(旧配置无需修改) 运行模板渲染测试 # 在目标服务器上测试 HBA 模板渲染
./files/test-hba-render.yml -l 10.10.10.10
该测试在目标服务器上渲染 HBA 模板,验证:
模板语法正确 规则顺序符合预期 高优先级规则出现在前面 验证渲染结果 # 查看渲染后的 PostgreSQL HBA
cat /pg/data/pg_hba.conf
# 查看规则标题顺序(验证 order 生效)
grep '^#' /pg/data/pg_hba.conf | grep -v '^#=' | head -20
# 验证首条规则是否为预期的高优先级规则
head -30 /pg/data/pg_hba.conf
相关参数 参数 说明 pg_pwd_enc密码加密方式:scram-sha-256(默认)或 md5 pg_dbsu数据库超级用户名 pg_replication_username复制用户名 pg_monitor_username监控用户名 pg_admin_username管理员用户名 node_firewall_intranet内网 CIDR 定义
相关文档 11.3.7 - 访问控制 Pigsty 提供的默认角色系统与权限模型
访问控制由“角色体系 + 权限模板 + HBA”共同决定。本节聚焦于如何通过配置参数声明角色与对象权限。
Pigsty 预置了一套精简的 ACL 模型,全部通过以下参数描述:
pg_default_roles:系统角色与系统用户。pg_users:业务用户与角色。pg_default_privileges:管理员/属主新建对象时的默认权限。pg_revoke_public、pg_default_schemas、pg_default_extensions:控制 template1 的默认行为。理解这些参数后,你就可以写出完全可复现的权限配置。
默认角色体系(pg_default_roles) 默认包含 4 个业务角色 + 4 个系统用户:
名称 类型 说明 dbrole_readonlyNOLOGIN所有业务共用,拥有 SELECT/USAGE dbrole_readwriteNOLOGIN继承只读角色,并拥有 INSERT/UPDATE/DELETE dbrole_adminNOLOGIN继承 pg_monitor + 读写角色,可建对象和触发器 dbrole_offlineNOLOGIN受限只读角色,仅允许访问离线实例 postgres用户 系统超级用户,与 pg_dbsu 同名 replicator用户 用于流复制与备份,继承监控与只读权限 dbuser_dba用户 主要管理员账号,同时同步到 pgbouncer dbuser_monitor用户 监控账号,具备 pg_monitor 权限,默认记录慢 SQL
这些定义位于 pg_default_roles,理论上可以自定义,但若要替换名称,必须同步更新 HBA/ACL/脚本中的引用。
示例:为离线任务额外加一个 dbrole_etl:
pg_default_roles :
- { name: dbrole_etl, login: false, roles: [dbrole_offline], comment : 'etl read-only role' }
- { name: dbrole_admin, login: false, roles : [ pg_monitor, dbrole_readwrite, dbrole_etl] }
效果:所有继承 dbrole_admin 的用户自动拥有 dbrole_etl 权限,可访问 offline 实例并执行 ETL。
默认用户与凭据参数 系统用户的用户名/密码由以下参数控制:
参数 默认值 作用 pg_dbsupostgres数据库/系统超级用户 pg_dbsu_password空字符串 dbsu 密码(默认不启用) pg_replication_usernamereplicator复制用户名称 pg_replication_passwordDBUser.Replicator复制用户密码 pg_admin_usernamedbuser_dba管理员用户名 pg_admin_passwordDBUser.DBA管理员密码 pg_monitor_usernamedbuser_monitor监控用户 pg_monitor_passwordDBUser.Monitor监控用户密码
如果修改这些参数,请同步在 pg_default_roles 中更新对应用户的定义,以避免角色属性不一致。
业务角色与授权(pg_users) 业务用户通过 pg_users 声明(详细字段见用户配置 ),其中 roles 字段控制授予的业务角色。
示例:创建只读/读写用户各一名:
pg_users :
- { name: app_reader, password: DBUser.Reader, roles: [dbrole_readonly], pgbouncer : true }
- { name: app_writer, password: DBUser.Writer, roles: [dbrole_readwrite], pgbouncer : true }
通过继承 dbrole_* 来控制访问权限,无需为每个库单独 GRANT。配合 pg_hba_rules 即可区分访问来源。
若需要更细粒度的 ACL,可在 baseline SQL 中或后续剧本里使用标准 GRANT/REVOKE。Pigsty 不会阻止你额外授予权限。
默认权限模板(pg_default_privileges) pg_default_privileges 会在 postgres、dbuser_dba、dbrole_admin(业务管理员 SET ROLE 后)上设置 DEFAULT PRIVILEGE。默认模板如下:
pg_default_privileges :
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
只要对象由上述管理员创建,就会自动携带对应权限,无需人为执行 GRANT。若业务需要自定义模板,直接替换该数组即可。
额外提示:
pg_revoke_public 默认为 true,意味着自动撤销 PUBLIC 在数据库和 public schema 上的 CREATE 权限。pg_default_schemas 和 pg_default_extensions 控制在 template1/postgres 中预创建的 schema/扩展,通常用于监控对象(monitor schema、pg_stat_statements 等)。常见配置场景 为合作方提供只读账号 pg_users :
- name : partner_ro
password : Partner.Read
roles : [ dbrole_readonly]
pg_hba_rules :
- { user: partner_ro, db: analytics, addr: 203.0.113.0/24, auth : ssl }
效果:合作方账号登录后只具备默认只读权限,并且只能通过 TLS 从指定网段访问 analytics 库。
为业务管理员赋予 DDL 能力 pg_users :
- name : app_admin
password : DBUser.AppAdmin
roles : [ dbrole_admin]
业务管理员通过 SET ROLE dbrole_admin 或直接以 app_admin 登录,即可继承默认的 DDL 权限模板。
自定义默认权限 pg_default_privileges :
- GRANT INSERT,UPDATE,DELETE ON TABLES TO dbrole_admin
- GRANT SELECT,UPDATE ON SEQUENCES TO dbrole_admin
- GRANT SELECT ON TABLES TO reporting_group
替换默认模板后,所有由管理员创建的对象都会携带新的权限定义,避免逐对象授权。
与其他组件的协同 HBA 规则 :使用 pg_hba_rules 将角色与来源进行绑定(例如只让 dbrole_offline 访问离线实例)。Pgbouncer :pgbouncer: true 的用户会被写入 userlist.txt,pool_mode/pool_connlimit 可以控制连接池层面的配额。Grafana/监控 :dbuser_monitor 的权限来自 pg_default_roles,如果你新增监控用户,记得赋予 pg_monitor + monitor schema 的访问权。通过这些参数,可以让权限体系与代码一起版本化,真正做到“配置即策略”。
11.4 - 服务/接入 分离读写操作,正确路由流量,稳定可靠地交付 PostgreSQL 集群提供的能力。
分离读写操作,正确路由流量,稳定可靠地交付 PostgreSQL 集群提供的能力。
服务 是一种抽象:它是数据库集群对外提供能力的形式,并封装了底层集群的细节。
服务对于生产环境中的稳定接入 至关重要,在高可用 集群自动故障时方显其价值,单机用户 通常不需要操心这个概念。
单机用户 “服务” 的概念是给生产环境用的,个人用户/单机集群可以不折腾,直接拿实例名/IP地址访问数据库。
例如,Pigsty 默认的单节点 pg-meta.meta 数据库,就可以直接用下面三个不同的用户连接上去。
psql postgres://dbuser_dba:DBUser.DBA@10.10.10.10/meta # 直接用 DBA 超级用户连上去
psql postgres://dbuser_meta:DBUser.Meta@10.10.10.10/meta # 用默认的业务管理员用户连上去
psql postgres://dbuser_view:DBUser.View@pg-meta/meta # 用默认的只读用户走实例域名连上去
服务概述 在真实世界生产环境中,我们会使用基于复制的主从数据库集群。集群中有且仅有一个实例作为领导者(主库 )可以接受写入。
而其他实例(从库 )则会从持续从集群领导者获取变更日志,与领导者保持一致。同时,从库还可以承载只读请求,在读多写少的场景下可以显著分担主库的负担,
因此对集群的写入请求与只读请求进行区分,是一种十分常见的实践。
此外对于高频短连接的生产环境,我们还会通过连接池中间件(Pgbouncer)对请求进行池化,减少连接与后端进程的创建开销。但对于ETL与变更执行等场景,我们又需要绕过连接池,直接访问数据库。
同时,高可用集群在故障时会出现故障切换(Failover),故障切换会导致集群的领导者出现变更。因此高可用的数据库方案要求写入流量可以自动适配集群的领导者变化。
这些不同的访问需求(读写分离,池化与直连,故障切换自动适配)最终抽象出 服务 (Service)的概念。
通常来说,数据库集群都必须提供这种最基础的服务:
对于生产数据库集群,至少应当提供这两种服务:
读写服务(primary) :写入数据:只能由主库所承载。只读服务(replica) :读取数据:可以由从库承载,没有从库时也可由主库承载此外,根据具体的业务场景,可能还会有其他的服务,例如:
默认直连服务(default) :允许(管理)用户,绕过连接池直接访问数据库的服务离线从库服务(offline) :不承接线上只读流量的专用从库,用于ETL与分析查询同步从库服务(standby) :没有复制延迟的只读服务,由同步备库 /主库处理只读查询延迟从库服务(delayed) :访问同一个集群在一段时间之前的旧数据,由延迟从库 来处理默认服务 Pigsty默认为每个 PostgreSQL 数据库集群提供四种不同的服务,以下是默认服务及其定义:
以默认的 pg-meta 集群为例,它提供四种默认服务:
psql postgres://dbuser_meta:DBUser.Meta@pg-meta:5433/meta # pg-meta-primary : 通过主要的 pgbouncer(6432) 进行生产读写
psql postgres://dbuser_meta:DBUser.Meta@pg-meta:5434/meta # pg-meta-replica : 通过备份的 pgbouncer(6432) 进行生产只读
psql postgres://dbuser_dba:DBUser.DBA@pg-meta:5436/meta # pg-meta-default : 通过主要的 postgres(5432) 直接连接
psql postgres://dbuser_stats:DBUser.Stats@pg-meta:5438/meta # pg-meta-offline : 通过离线的 postgres(5432) 直接连接
从示例集群架构图 上可以看出这四种服务的工作方式:
注意在这里pg-meta 域名指向了集群的 L2 VIP,进而指向集群主库上的 haproxy 负载均衡器,它负责将流量路由到不同的实例上,详见服务接入
服务实现 在 Pigsty 中,服务使用节点 上的 haproxy 来实现,通过主机节点上的不同端口进行区分。
Pigsty 所纳管的每个节点上都默认启用了 Haproxy 以对外暴露服务,而数据库节点也不例外。
集群中的节点尽管从数据库的视角来看有主从之分,但从服务的视角来看,每个节点都是相同的:
这意味着即使您访问的是从库节点,只要使用正确的服务端口,就依然可以使用到主库读写的服务。
这样的设计可以屏蔽复杂度:所以您只要可以访问 PostgreSQL 集群上的任意一个实例,就可以完整的访问到所有服务。
这样的设计类似于 Kubernetes 中的 NodePort 服务,同样在 Pigsty 中,每一个服务都包括以下两个核心要素:
通过 NodePort 暴露的访问端点(端口号,从哪访问?) 通过 Selectors 选择的目标实例(实例列表,谁来承载?) Pigsty的服务交付边界止步于集群的HAProxy,用户可以用各种手段访问这些负载均衡器,请参考接入服务 。
所有的服务都通过配置文件进行声明,例如,PostgreSQL 默认服务就是由 pg_default_services 参数所定义的:
pg_default_services :
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
您也可以在 pg_services 中定义额外的服务,参数 pg_default_services 与 pg_services 都是由 服务定义 对象组成的数组。
定义服务 Pigsty 允许您定义自己的服务:
对于 PostgreSQL 集群来说,通常只需要关注前两者即可。
每一条服务定义都会在所有相关 HAProxy 实例的配置目录下生成一个新的配置文件:/etc/haproxy/<svcname>.cfg
下面是一个自定义的服务样例 standby:当您想要对外提供没有复制延迟的只读服务时,就可以在 pg_services 新增这条记录:
- name : standby # 必选,服务名称,最终的 svc 名称会使用 `pg_cluster` 作为前缀,例如:pg-meta-standby
port : 5435 # 必选,暴露的服务端口(作为 kubernetes 服务节点端口模式)
ip : "*" # 可选,服务绑定的 IP 地址,默认情况下为所有 IP 地址
selector : "[]" # 必选,服务成员选择器,使用 JMESPath 来筛选配置清单
backup : "[? pg_role == `primary`]" # 可选,服务成员选择器(备份),也就是当默认选择器选中的实例都宕机后,服务才会由这里选中的实例成员来承载
dest : default # 可选,目标端口,default|postgres|pgbouncer|<port_number>,默认为 'default',Default的意思就是使用 pg_default_service_dest 的取值来最终决定
check : /sync # 可选,健康检查 URL 路径,默认为 /,这里使用 Patroni API:/sync ,只有同步备库和主库才会返回 200 健康状态码
maxconn : 5000 # 可选,允许的前端连接最大数,默认为5000
balance : roundrobin # 可选,haproxy 负载均衡算法(默认为 roundrobin,其他选项:leastconn)
options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
而上面的服务定义,在样例的三节点 pg-test 上将会被转换为 haproxy 配置文件 /etc/haproxy/pg-test-standby.conf:
#---------------------------------------------------------------------
# service: pg-test-standby @ 10.10.10.11:5435
#---------------------------------------------------------------------
# service instances 10.10.10.11, 10.10.10.13, 10.10.10.12
# service backups 10.10.10.11
listen pg-test-standby
bind *:5435 # <--- 绑定了所有IP地址上的 5435 端口
mode tcp # <--- 负载均衡器工作在 TCP 协议上
maxconn 5000 # <--- 最大连接数为 5000,可按需调大
balance roundrobin # <--- 负载均衡算法为 rr 轮询,还可以使用 leastconn
option httpchk # <--- 启用 HTTP 健康检查
option http-keep-alive # <--- 保持HTTP连接
http-check send meth OPTIONS uri /sync # <---- 这里使用 /sync ,Patroni 健康检查 API ,只有同步备库和主库才会返回 200 健康状态码。
http-check expect status 200 # <---- 健康检查返回代码 200 代表正常
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers: # pg-test 集群全部三个实例都被 selector: "[]" 给圈中了,因为没有任何的筛选条件,所以都会作为 pg-test-replica 服务的后端服务器。但是因为还有 /sync 健康检查,所以只有主库和同步备库才能真正承载请求。
server pg-test-1 10.10.10.11:6432 check port 8008 weight 100 backup # <----- 唯独主库满足条件 pg_role == `primary`, 被 backup selector 选中。
server pg-test-3 10.10.10.13:6432 check port 8008 weight 100 # 因此作为服务的兜底实例:平时不承载请求,其他从库全部宕机后,才会承载只读请求,从而最大避免了读写服务受到只读服务的影响
server pg-test-2 10.10.10.12:6432 check port 8008 weight 100 #
在这里,pg-test 集群全部三个实例都被 selector: "[]" 给圈中了,渲染进入 pg-test-replica 服务的后端服务器列表中。但是因为还有 /sync 健康检查,Patroni Rest API只有在主库和同步备库 上才会返回代表健康的 HTTP 200 状态码,因此只有主库和同步备库才能真正承载请求。
此外,主库因为满足条件 pg_role == primary, 被 backup selector 选中,被标记为了备份服务器,只有当没有其他实例(也就是同步备库)可以满足需求时,才会顶上。
Primary服务 Primary服务可能是生产环境中最关键的服务,它在 5433 端口提供对数据库集群的读写能力,服务定义如下:
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
选择器参数 selector: "[]" 意味着所有集群成员都将被包括在Primary服务中 但只有主库能够通过健康检查(check: /primary),实际承载Primary服务的流量。 目的地参数 dest: default 意味着Primary服务的目的地受到 pg_default_service_dest 参数的影响 dest 默认值 default 会被替换为 pg_default_service_dest 的值,默认为 pgbouncer。默认情况下 Primary 服务的目的地默认是主库上的连接池,也就是由 pgbouncer_port 指定的端口,默认为 6432 如果 pg_default_service_dest 的值为 postgres,那么 primary 服务的目的地就会绕过连接池,直接使用 PostgreSQL 数据库的端口(pg_port ,默认值 5432),对于一些不希望使用连接池的场景,这个参数非常实用。
示例:pg-test-primary 的 haproxy 配置 listen pg-test-primary
bind *:5433 # <--- primary 服务默认使用 5433 端口
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /primary # <--- primary 服务默认使用 Patroni RestAPI /primary 健康检查
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-1 10.10.10.11:6432 check port 8008 weight 100
server pg-test-3 10.10.10.13:6432 check port 8008 weight 100
server pg-test-2 10.10.10.12:6432 check port 8008 weight 100
Patroni 的高可用 机制确保任何时候最多只会有一个实例的 /primary 健康检查为真,因此Primary服务将始终将流量路由到主实例。
使用 Primary 服务而不是直连数据库的一个好处是,如果集群因为某种情况出现了双主(比如在没有watchdog的情况下kill -9杀死主库 Patroni),Haproxy在这种情况下仍然可以避免脑裂,因为它只会在 Patroni 存活且返回主库状态时才会分发流量。
Replica服务 Replica服务在生产环境中的重要性仅次于Primary服务,它在 5434 端口提供对数据库集群的只读能力,服务定义如下:
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
选择器参数 selector: "[]" 意味着所有集群成员都将被包括在Replica服务中 所有实例都能够通过健康检查(check: /read-only),承载Replica服务的流量。 备份选择器:[? pg_role == 'primary' || pg_role == 'offline' ] 将主库和离线从库 标注为备份服务器。 只有当所有普通从库 都宕机后,Replica服务才会由主库或离线从库来承载。 目的地参数 dest: default 意味着Replica服务的目的地也受到 pg_default_service_dest 参数的影响 dest 默认值 default 会被替换为 pg_default_service_dest 的值,默认为 pgbouncer,这一点和 Primary服务 相同默认情况下 Replica 服务的目的地默认是从库上的连接池,也就是由 pgbouncer_port 指定的端口,默认为 6432 示例:pg-test-replica 的 haproxy 配置 listen pg-test-replica
bind *:5434
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /read-only
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-1 10.10.10.11:6432 check port 8008 weight 100 backup
server pg-test-3 10.10.10.13:6432 check port 8008 weight 100
server pg-test-2 10.10.10.12:6432 check port 8008 weight 100
Replica服务非常灵活:如果有存活的专用 Replica 实例,那么它会优先使用这些实例来承载只读请求,只有当从库实例全部宕机后,才会由主库来兜底只读请求。对于常见的一主一从双节点集群就是:只要从库活着就用从库,从库挂了再用主库。
此外,除非专用只读实例全部宕机,Replica 服务也不会使用专用 Offline 实例,这样就避免了在线快查询与离线慢查询混在一起,相互影响。
Default服务 Default服务在 5436 端口上提供服务,它是Primary服务的变体。
Default服务总是绕过连接池直接连到主库上的 PostgreSQL,这对于管理连接、ETL写入、CDC数据变更捕获等都很有用。
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
如果 pg_default_service_dest 被修改为 postgres,那么可以说 Default 服务除了端口和名称内容之外,与 Primary 服务是完全等价的。在这种情况下,您可以考虑将 Default 从默认服务中剔除。
示例:pg-test-default 的 haproxy 配置 listen pg-test-default
bind *:5436 # <--- 除了监听端口/目标端口和服务名,其他配置和 primary 服务一模一样
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /primary
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-1 10.10.10.11:5432 check port 8008 weight 100
server pg-test-3 10.10.10.13:5432 check port 8008 weight 100
server pg-test-2 10.10.10.12:5432 check port 8008 weight 100
Offline服务 Default服务在 5438 端口上提供服务,它也绕开连接池直接访问 PostgreSQL 数据库,通常用于慢查询/分析查询/ETL读取/个人用户交互式查询,其服务定义如下:
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
Offline服务将流量直接路由到专用的离线从库 上,或者带有 pg_offline_query 标记的普通只读实例 。
选择器参数从集群中筛选出了两种实例:pg_role = offline 的离线从库,或是带有 pg_offline_query = true 标记的普通只读实例 专用离线从库和打标记的普通从库主要的区别在于:前者默认不承载 Replica服务 的请求,避免快慢请求混在一起,而后者默认会承载。 备份选择器参数从集群中筛选出了一种实例:不带 offline 标记的普通从库,这意味着如果离线实例或者带Offline标记的普通从库挂了之后,其他普通的从库可以用来承载Offline服务。 健康检查 /replica 只会针对从库返回 200, 主库会返回错误,因此 Offline服务 永远不会将流量分发到主库实例上去,哪怕集群中只剩这一台主库。 同时,主库实例既不会被选择器圈中,也不会被备份选择器圈中,因此它永远不会承载Offline服务。因此 Offline 服务总是可以避免用户访问主库,从而避免对主库的影响。 示例:pg-test-offline 的 haproxy 配置 listen pg-test-offline
bind *:5438
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /replica
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-3 10.10.10.13:5432 check port 8008 weight 100
server pg-test-2 10.10.10.12:5432 check port 8008 weight 100 backup
Offline服务提供受限的只读服务,通常用于两类查询:交互式查询(个人用户),慢查询长事务(分析/ETL)。
Offline 服务需要额外的维护照顾:当集群发生主从切换或故障自动切换时,集群的实例角色会发生变化,而 Haproxy 的配置却不会自动发生变化。对于有多个从库的集群来说,这通常并不是一个问题。
然而对于一主一从,从库跑Offline查询的精简小集群而言,主从切换意味着从库变成了主库(健康检查失效),原来的主库变成了从库(不在 Offline 后端列表中),于是没有实例可以承载 Offline 服务了,因此需要手动重载服务 以使变更生效。
如果您的业务模型较为简单,您可以考虑剔除 Default 服务与 Offline 服务,使用 Primary 服务与 Replica 服务直连数据库。
重载服务 当集群成员发生变化,如添加/删除副本、主备切换或调整相对权重时, 你需要 重载服务 以使更改生效。
bin/pgsql-svc <cls> [ ip...] # 为 lb 集群或 lb 实例重载服务
# ./pgsql.yml -t pg_service # 重载服务的实际 ansible 任务
接入服务 Pigsty的服务交付边界止步于集群的HAProxy,用户可以用各种手段访问这些负载均衡器。
典型的做法是使用 DNS 或 VIP 接入,将其绑定在集群所有或任意数量的负载均衡器上。
你可以使用不同的 主机 & 端口 组合,它们以不同的方式提供 PostgreSQL 服务。
主机
类型 样例 描述 集群域名 pg-test通过集群域名访问(由 dnsmasq @ infra 节点解析) 集群 VIP 地址 10.10.10.3通过由 vip-manager 管理的 L2 VIP 地址访问,绑定到主节点 实例主机名 pg-test-1通过任何实例主机名访问(由 dnsmasq @ infra 节点解析) 实例 IP 地址 10.10.10.11访问任何实例的 IP 地址
端口
Pigsty 使用不同的 端口 来区分 pg services
端口 服务 类型 描述 5432 postgres 数据库 直接访问 postgres 服务器 6432 pgbouncer 中间件 访问 postgres 前先通过连接池中间件 5433 primary 服务 访问主 pgbouncer (或 postgres) 5434 replica 服务 访问备份 pgbouncer (或 postgres) 5436 default 服务 访问主 postgres 5438 offline 服务 访问离线 postgres
组合
# 通过集群域名访问
postgres://test@pg-test:5432/test # DNS -> L2 VIP -> 主直接连接
postgres://test@pg-test:6432/test # DNS -> L2 VIP -> 主连接池 -> 主
postgres://test@pg-test:5433/test # DNS -> L2 VIP -> HAProxy -> 主连接池 -> 主
postgres://test@pg-test:5434/test # DNS -> L2 VIP -> HAProxy -> 备份连接池 -> 备份
postgres://dbuser_dba@pg-test:5436/test # DNS -> L2 VIP -> HAProxy -> 主直接连接 (用于管理员)
postgres://dbuser_stats@pg-test:5438/test # DNS -> L2 VIP -> HAProxy -> 离线直接连接 (用于 ETL/个人查询)
# 通过集群 VIP 直接访问
postgres://test@10.10.10.3:5432/test # L2 VIP -> 主直接访问
postgres://test@10.10.10.3:6432/test # L2 VIP -> 主连接池 -> 主
postgres://test@10.10.10.3:5433/test # L2 VIP -> HAProxy -> 主连接池 -> 主
postgres://test@10.10.10.3:5434/test # L2 VIP -> HAProxy -> 备份连接池 -> 备份
postgres://dbuser_dba@10.10.10.3:5436/test # L2 VIP -> HAProxy -> 主直接连接 (用于管理员)
postgres://dbuser_stats@10.10.10.3::5438/test # L2 VIP -> HAProxy -> 离线直接连接 (用于 ETL/个人查询)
# 直接指定任何集群实例名
postgres://test@pg-test-1:5432/test # DNS -> 数据库实例直接连接 (单例访问)
postgres://test@pg-test-1:6432/test # DNS -> 连接池 -> 数据库
postgres://test@pg-test-1:5433/test # DNS -> HAProxy -> 连接池 -> 数据库读/写
postgres://test@pg-test-1:5434/test # DNS -> HAProxy -> 连接池 -> 数据库只读
postgres://dbuser_dba@pg-test-1:5436/test # DNS -> HAProxy -> 数据库直接连接
postgres://dbuser_stats@pg-test-1:5438/test # DNS -> HAProxy -> 数据库离线读/写
# 直接指定任何集群实例 IP 访问
postgres://test@10.10.10.11:5432/test # 数据库实例直接连接 (直接指定实例, 没有自动流量分配)
postgres://test@10.10.10.11:6432/test # 连接池 -> 数据库
postgres://test@10.10.10.11:5433/test # HAProxy -> 连接池 -> 数据库读/写
postgres://test@10.10.10.11:5434/test # HAProxy -> 连接池 -> 数据库只读
postgres://dbuser_dba@10.10.10.11:5436/test # HAProxy -> 数据库直接连接
postgres://dbuser_stats@10.10.10.11:5438/test # HAProxy -> 数据库离线读-写
# 智能客户端:自动进行读写分离
postgres://test@10.10.10.11:6432,10.10.10.12:6432,10.10.10.13:6432/test?target_session_attrs= primary
postgres://test@10.10.10.11:6432,10.10.10.12:6432,10.10.10.13:6432/test?target_session_attrs= prefer-standby
覆盖服务 你可以通过多种方式覆盖默认的服务配置,一种常见的需求是让 Primary服务 与 Replica服务 绕过Pgbouncer连接池,直接访问 PostgreSQL 数据库。
为了实现这一点,你可以将 pg_default_service_dest 更改为 postgres,这样所有服务定义中 svc.dest='default' 的服务都会使用 postgres 而不是默认的 pgbouncer 作为目标。
如果您已经将 Primary服务 指向了 PostgreSQL,那么 default服务 就会比较多余,可以考虑移除。
如果您不需要区分个人交互式查询,分析/ETL慢查询,可以考虑从默认服务列表 pg_default_services 中移除Offline服务 。
如果您不需要只读从库来分担在线只读流量,也可以从默认服务列表中移除 Replica服务 。
委托服务 Pigsty 通过节点上的 haproxy 暴露 PostgreSQL 服务。整个集群中的所有 haproxy 实例都使用相同的服务定义 进行配置。
但是,你可以将 pg 服务委托给特定的节点分组(例如,专门的 haproxy 负载均衡器集群),而不是 PostgreSQL 集群成员上的 haproxy。
为此,你需要使用 pg_default_services 覆盖默认的服务定义,并将 pg_service_provider 设置为代理组名称。
例如,此配置将在端口 10013 的 proxy haproxy 节点组上公开 pg 集群的主服务。
pg_service_provider : proxy # 使用端口 10013 上的 `proxy` 组的负载均衡器
pg_default_services : [ { name: primary ,port: 10013 ,dest: postgres ,check: /primary ,selector : "[]" }]
用户需要确保每个委托服务的端口,在代理集群中都是唯一 的。
在 43 节点生产环境仿真沙箱 中提供了一个使用专用负载均衡器集群的例子:prod.yml
11.5 - 访问控制 Pigsty 提供的默认角色系统与权限模型
Pigsty 提供了一套开箱即用的,基于角色系统 和权限系统 的访问控制模型。
权限控制很重要,但很多用户做不好。因此 Pigsty 提供了一套开箱即用的精简访问控制模型,为您的集群安全性提供一个兜底。
角色系统 Pigsty 默认的角色系统包含四个默认角色 和四个默认用户 :
角色名称 属性 所属 描述 dbrole_readonlyNOLOGIN角色:全局只读访问 dbrole_readwriteNOLOGINdbrole_readonly 角色:全局读写访问 dbrole_adminNOLOGINpg_monitor,dbrole_readwrite 角色:管理员/对象创建 dbrole_offlineNOLOGIN角色:受限的只读访问 postgresSUPERUSER系统超级用户 replicatorREPLICATIONpg_monitor,dbrole_readonly 系统复制用户 dbuser_dbaSUPERUSERdbrole_admin pgsql 管理用户 dbuser_monitorpg_monitor pgsql 监控用户
这些角色与用户 的详细定义如下所示:
pg_default_roles : # 全局默认的角色与系统用户
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
默认角色 Pigsty 中有四个默认角色:
业务只读 (dbrole_readonly): 用于全局只读访问的角色。如果别的业务想要此库只读访问权限,可以使用此角色。 业务读写 (dbrole_readwrite): 用于全局读写访问的角色,主属业务使用的生产账号应当具有数据库读写权限 业务管理员 (dbrole_admin): 拥有DDL权限的角色,通常用于业务管理员,或者需要在应用中建表的场景(比如各种业务软件) 离线只读访问 (dbrole_offline): 受限的只读访问角色(只能访问 offline 实例,通常是个人用户,ETL工具账号) 默认角色在 pg_default_roles 中定义,除非您确实知道自己在干什么,建议不要更改默认角色的名称。
- { name: dbrole_readonly , login: false , comment : role for global read-only access } # 生产环境的只读角色
- { name: dbrole_offline , login: false , comment : role for restricted read-only access (offline instance) } # 受限的只读角色
- { name: dbrole_readwrite , login: false , roles: [dbrole_readonly], comment : role for global read-write access } # 生产环境的读写角色
- { name: dbrole_admin , login: false , roles: [pg_monitor, dbrole_readwrite] , comment : role for object creation } # 生产环境的 DDL 更改角色
默认用户 Pigsty 也有四个默认用户(系统用户):
超级用户 (postgres),集群的所有者和创建者,与操作系统 dbsu 名称相同。 复制用户 (replicator),用于主-从复制的系统用户。 监控用户 (dbuser_monitor),用于监控数据库和连接池指标的用户。 管理用户 (dbuser_dba),执行日常操作和数据库更改的管理员用户。 这4个默认用户的用户名/密码通过4对专用参数进行定义,并在很多地方引用:
在生产部署中记得更改这些密码,不要使用默认值!
pg_dbsu : postgres # 数据库超级用户名,这个用户名建议不要修改。
pg_dbsu_password : '' # 数据库超级用户密码,这个密码建议留空!禁止dbsu密码登陆。
pg_replication_username : replicator # 系统复制用户名
pg_replication_password : DBUser.Replicator # 系统复制密码,请务必修改此密码!
pg_monitor_username : dbuser_monitor # 系统监控用户名
pg_monitor_password : DBUser.Monitor # 系统监控密码,请务必修改此密码!
pg_admin_username : dbuser_dba # 系统管理用户名
pg_admin_password : DBUser.DBA # 系统管理密码,请务必修改此密码!
如果您修改默认用户的参数,在 pg_default_roles 中修改相应的角色定义 即可:
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 , comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor, dbrole_readonly] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
权限系统 Pigsty 拥有一套开箱即用的权限模型,该模型与默认角色 一起配合工作。
所有用户都可以访问所有模式。 只读用户(dbrole_readonly)可以从所有表中读取数据。(SELECT,EXECUTE) 读写用户(dbrole_readwrite)可以向所有表中写入数据并运行 DML。(INSERT,UPDATE,DELETE)。 管理员用户(dbrole_admin)可以创建对象并运行 DDL(CREATE,USAGE,TRUNCATE,REFERENCES,TRIGGER)。 离线用户(dbrole_offline)类似只读用户,但访问受到限制,只允许访问离线实例 (pg_role = 'offline' 或 pg_offline_query = true) 由管理员用户创建的对象将具有正确的权限。 所有数据库上都配置了默认权限,包括模板数据库。 数据库连接权限由数据库定义 管理。 默认撤销PUBLIC在数据库和public模式下的CREATE权限。 对象权限 数据库中新建对象的默认权限由参数 pg_default_privileges 所控制:
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
由管理员新创建 的对象,默认将会上述权限。使用 \ddp+ 可以查看这些默认权限:
类型 访问权限 函数 =X dbrole_readonly=X dbrole_offline=X dbrole_admin=X 模式 dbrole_readonly=U dbrole_offline=U dbrole_admin=UC 序列号 dbrole_readonly=r dbrole_offline=r dbrole_readwrite=wU dbrole_admin=rwU 表 dbrole_readonly=r dbrole_offline=r dbrole_readwrite=awd dbrole_admin=arwdDxt
默认权限 ALTER DEFAULT PRIVILEGES 允许您设置将来创建的对象的权限。 它不会影响已经存在对象的权限,也不会影响非管理员用户创建的对象。
在 Pigsty 中,默认权限针对三个角色进行定义:
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE {{ pg_dbsu }} {{ priv }} ;
{ % endfor % }
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE {{ pg_admin_username }} {{ priv }} ;
{ % endfor % }
-- 对于其他业务管理员而言,它们应当在执行 DDL 前执行 SET ROLE dbrole_admin,从而使用对应的默认权限配置。
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE "dbrole_admin" {{ priv }} ;
{ % endfor % }
这些内容将会被 PG集群初始化模板 pg-init-template.sql 所使用,在集群初始化的过程中渲染并输出至 /pg/tmp/pg-init-template.sql。
该命令会在 template1 与 postgres 数据库中执行,新创建的数据库会通过模板 template1 继承这些默认权限配置。
也就是说,为了维持正确的对象权限,您必须用管理员用户 来执行 DDL,它们可以是:
{{ pg_dbsu }} ,默认为 postgres{{ pg_admin_username }} ,默认为 dbuser_dba授予了 dbrole_admin 角色的业务管理员用户(通过 SET ROLE 切换为 dbrole_admin 身份)。 使用 postgres 作为全局对象所有者是明智的。如果您希望以业务管理员用户身份创建对象,创建之前必须使用 SET ROLE dbrole_admin 来维护正确的权限。
当然,您也可以在数据库中通过 ALTER DEFAULT PRIVILEGE FOR ROLE <some_biz_admin> XXX 来显式对业务管理员授予默认权限。
数据库权限 在 Pigsty 中,数据库(Database)层面的权限在数据库定义 中被涵盖。
数据库有三个级别的权限:CONNECT、CREATE、TEMP,以及一个特殊的’权限’:OWNERSHIP。
- name : meta # 必选,`name` 是数据库定义中唯一的必选字段
owner : postgres # 可选,数据库所有者,默认为 postgres
allowconn : true # 可选,是否允许连接,默认为 true。显式设置 false 将完全禁止连接到此数据库
revokeconn : false # 可选,撤销公共连接权限。默认为 false,设置为 true 时,属主和管理员之外用户的 CONNECT 权限会被回收
如果 owner 参数存在,它作为数据库属主,替代默认的 {{ pg_dbsu }} (通常也就是postgres) 如果 revokeconn 为 false,所有用户都有数据库的 CONNECT 权限,这是默认的行为。 如果显式设置了 revokeconn 为 true:数据库的 CONNECT 权限将从 PUBLIC 中撤销:普通用户无法连接上此数据库 CONNECT 权限将被显式授予 {{ pg_replication_username }}、{{ pg_monitor_username }} 和 {{ pg_admin_username }}CONNECT 权限将 GRANT OPTION 被授予数据库属主,数据库属主用户可以自行授权其他用户连接权限。 revokeconn 选项可用于在同一个集群间隔离跨数据库访问,您可以为每个数据库创建不同的业务用户作为属主,并为它们设置 revokeconn 选项。示例:数据库隔离 pg-infra :
hosts :
10.10.10.40 : { pg_seq: 1, pg_role : primary }
10.10.10.41 : { pg_seq: 2, pg_role: replica , pg_offline_query : true }
vars :
pg_cluster : pg-infra
pg_users :
- { name: dbuser_confluence, password: mc2iohos , pgbouncer: true, roles : [ dbrole_admin ] }
- { name: dbuser_gitlab, password: sdf23g22sfdd , pgbouncer: true, roles : [ dbrole_readwrite ] }
- { name: dbuser_jira, password: sdpijfsfdsfdfs , pgbouncer: true, roles : [ dbrole_admin ] }
pg_databases :
- { name: confluence , revokeconn: true, owner: dbuser_confluence , connlimit : 100 }
- { name: gitlab , revokeconn: true, owner: dbuser_gitlab, connlimit : 100 }
- { name: jira , revokeconn: true, owner: dbuser_jira , connlimit : 100 }
CREATE权限 出于安全考虑,Pigsty 默认从 PUBLIC 撤销数据库上的 CREATE 权限,从 PostgreSQL 15 开始这也是默认行为。
数据库属主总是可以根据实际需要,来自行调整 CREATE 权限。
11.6 - 其他说明 Pigsty 提供的默认角色系统与权限模型
11.6.1 - 用户/角色 用户/角色指的是使用 SQL 命令 CREATE USER/ROLE 创建的,数据库集簇内的逻辑对象。
在这里的上下文中,用户指的是使用 SQL 命令 CREATE USER/ROLE 创建的,数据库集簇内的逻辑对象。
在PostgreSQL中,用户直接隶属于数据库集簇而非某个具体的数据库。因此在创建业务数据库和业务用户时,应当遵循"先用户,后数据库"的原则。
定义用户 Pigsty通过两个配置参数定义数据库集群中的角色与用户:
前者用于定义了整套环境中共用的角色与用户,后者定义单个集群中特有的业务角色与用户。二者形式相同,均为用户定义对象的数组。
你可以定义多个用户/角色,它们会按照先全局,后集群,最后按数组内排序的顺序依次创建,所以后面的用户可以属于前面定义的角色。
下面是 Pigsty 演示环境中默认集群 pg-meta 中的业务用户定义:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
- {name: dbuser_grafana ,password: DBUser.Grafana ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for grafana database }
- {name: dbuser_bytebase ,password: DBUser.Bytebase ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for bytebase database }
- {name: dbuser_kong ,password: DBUser.Kong ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for kong api gateway }
- {name: dbuser_gitea ,password: DBUser.Gitea ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for gitea service }
- {name: dbuser_wiki ,password: DBUser.Wiki ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for wiki.js service }
- {name: dbuser_noco ,password: DBUser.Noco ,pgbouncer: true ,roles: [dbrole_admin] ,comment : admin user for nocodb service }
每个用户/角色定义都是一个 object,可能包括以下字段,以 dbuser_meta 用户为例:
- name : dbuser_meta # 必需,`name` 是用户定义的唯一必选字段
password : DBUser.Meta # 可选,密码,可以是 scram-sha-256 哈希字符串或明文
login : true # 可选,默认情况下可以登录
superuser : false # 可选,默认为 false,是超级用户吗?
createdb : false # 可选,默认为 false,可以创建数据库吗?
createrole : false # 可选,默认为 false,可以创建角色吗?
inherit : true # 可选,默认情况下,此角色可以使用继承的权限吗?
replication : false # 可选,默认为 false,此角色可以进行复制吗?
bypassrls : false # 可选,默认为 false,此角色可以绕过行级安全吗?
pgbouncer : true # 可选,默认为 false,将此用户添加到 pgbouncer 用户列表吗?(使用连接池的生产用户应该显式定义为 true)
connlimit : -1 # 可选,用户连接限制,默认 -1 禁用限制
expire_in : 3650 # 可选,此角色过期时间:从创建时 + n天计算(优先级比 expire_at 更高)
expire_at : '2030-12-31' # 可选,此角色过期的时间点,使用 YYYY-MM-DD 格式的字符串指定一个特定日期(优先级没 expire_in 高)
comment : pigsty admin user # 可选,此用户/角色的说明与备注字符串
roles : [ dbrole_admin] # 可选,默认角色为:dbrole_{admin,readonly,readwrite,offline}
parameters : {} # 可选,使用 `ALTER ROLE SET` 针对这个角色,配置角色级的数据库参数
pool_mode : transaction # 可选,默认为 transaction 的 pgbouncer 池模式,用户级别
pool_connlimit : -1 # 可选,用户级别的最大数据库连接数,默认 -1 禁用限制
search_path : public # 可选,根据 postgresql 文档的键值配置参数(例如:使用 pigsty 作为默认 search_path)
唯一必需的字段是 name,它应该是 PostgreSQL 集群中的一个有效且唯一的用户名。 角色不需要 password,但对于可登录的业务用户,通常是需要指定一个密码的。 password 可以是明文或 scram-sha-256 / md5 哈希字符串,请最好不要使用明文密码。用户/角色按数组顺序逐一创建,因此,请确保角色/分组的定义在成员之前。 login、superuser、createdb、createrole、inherit、replication、bypassrls 是布尔标志。pgbouncer 默认是禁用的:要将业务用户添加到 pgbouncer 用户列表,您应当显式将其设置为 true。ACL系统
Pigsty 具有一套内置的,开箱即用的访问控制 / ACL 系统,您只需将以下四个默认角色分配给业务用户即可轻松使用:
dbrole_readwrite:全局读写访问的角色(主属业务使用的生产账号应当具有数据库读写权限)dbrole_readonly:全局只读访问的角色(如果别的业务想要只读访问,可以使用此角色)dbrole_admin:拥有DDL权限的角色 (业务管理员,需要在应用中建表的场景)dbrole_offline:受限的只读访问角色(只能访问 offline 实例,通常是个人用户)如果您希望重新设计您自己的 ACL 系统,可以考虑定制以下参数和模板:
创建用户 在 pg_default_roles 和 pg_users 中定义 的用户和角色,将在集群初始化的 PROVISION 阶段中自动逐一创建。
如果您希望在现有的集群上创建用户 ,可以使用 bin/pgsql-user 工具。
将新用户/角色定义添加到 all.children.<cls>.pg_users,并使用以下方法创建该数据库:
bin/pgsql-user <cls> <username> # pgsql-user.yml -l <cls> -e username=<username>
不同于数据库,创建用户的剧本总是幂等的。当目标用户已经存在时,Pigsty会修改目标用户的属性使其符合配置。所以在现有集群上重复运行它通常不会有问题。
请使用剧本创建用户
我们不建议您手工创建新的业务用户,特别当您想要创建的用户使用默认的 pgbouncer 连接池时:除非您愿意手工负责维护 Pgbouncer 中的用户列表并与 PostgreSQL 保持一致。
使用 bin/pgsql-user 工具或 pgsql-user.yml 剧本创建新数据库时,会将此数据库一并添加到 Pgbouncer用户 列表中。
修改用户 修改 PostgreSQL 用户的属性的方式与 创建用户 相同。
首先,调整您的用户定义,修改需要调整的属性,然后执行以下命令应用:
bin/pgsql-user <cls> <username> # pgsql-user.yml -l <cls> -e username=<username>
请注意,修改用户不会删除用户,而是通过 ALTER USER 命令修改用户属性;也不会回收用户的权限与分组,并使用 GRANT 命令授予新的角色。
Pgbouncer用户 默认情况下启用 Pgbouncer,并作为连接池中间件,其用户默认被管理。
Pigsty 默认将 pg_users 中显式带有 pgbouncer: true 标志的所有用户添加到 pgbouncer 用户列表中。
Pgbouncer 连接池中的用户在 /etc/pgbouncer/userlist.txt 中列出:
"postgres" ""
"dbuser_wiki" "SCRAM-SHA-256$4096:+77dyhrPeFDT/TptHs7/7Q = =$KeatuohpKIYzHPCt/tqBu85vI11o9mar/by0hHYM2W8=:X9gig4JtjoS8Y/o1vQsIX/gY1Fns8ynTXkbWOjUfbRQ="
"dbuser_view" "SCRAM-SHA-256$4096:DFoZHU/DXsHL8MJ8regdEw = =$gx9sUGgpVpdSM4o6A2R9PKAUkAsRPLhLoBDLBUYtKS0=:MujSgKe6rxcIUMv4GnyXJmV0YNbf39uFRZv724+X1FE="
"dbuser_monitor" "SCRAM-SHA-256$4096:fwU97ZMO/KR0ScHO5+UuBg = =$CrNsmGrx1DkIGrtrD1Wjexb/aygzqQdirTO1oBZROPY=:L8+dJ+fqlMQh7y4PmVR/gbAOvYWOr+KINjeMZ8LlFww="
"dbuser_meta" "SCRAM-SHA-256$4096:leB2RQPcw1OIiRnPnOMUEg = =$eyC+NIMKeoTxshJu314+BmbMFpCcspzI3UFZ1RYfNyU=:fJgXcykVPvOfro2MWNkl5q38oz21nSl1dTtM65uYR1Q="
"dbuser_kong" "SCRAM-SHA-256$4096:bK8sLXIieMwFDz67/0dqXQ = =$P/tCRgyKx9MC9LH3ErnKsnlOqgNd/nn2RyvThyiK6e4=:CDM8QZNHBdPf97ztusgnE7olaKDNHBN0WeAbP/nzu5A="
"dbuser_grafana" "SCRAM-SHA-256$4096:HjLdGaGmeIAGdWyn2gDt/Q = =$jgoyOB8ugoce+Wqjr0EwFf8NaIEMtiTuQTg1iEJs9BM=:ed4HUFqLyB4YpRr+y25FBT7KnlFDnan6JPVT9imxzA4="
"dbuser_gitea" "SCRAM-SHA-256$4096:l1DBGCc4dtircZ8O8Fbzkw = =$tpmGwgLuWPDog8IEKdsaDGtiPAxD16z09slvu+rHE74=:pYuFOSDuWSofpD9OZhG7oWvyAR0PQjJBffgHZLpLHds="
"dbuser_dba" "SCRAM-SHA-256$4096:zH8niABU7xmtblVUo2QFew = =$Zj7/pq+ICZx7fDcXikiN7GLqkKFA+X5NsvAX6CMshF0=:pqevR2WpizjRecPIQjMZOm+Ap+x0kgPL2Iv5zHZs0+g="
"dbuser_bytebase" "SCRAM-SHA-256$4096:OMoTM9Zf8QcCCMD0svK5gg = =$kMchqbf4iLK1U67pVOfGrERa/fY818AwqfBPhsTShNQ=:6HqWteN+AadrUnrgC0byr5A72noqnPugItQjOLFw0Wk="
而用户级别的连接池参数则是使用另一个单独的文件: /etc/pgbouncer/useropts.txt 进行维护,比如:
dbuser_dba = pool_mode=session max_user_connections=16
dbuser_monitor = pool_mode=session max_user_connections=8
当您创建数据库 时,Pgbouncer 的数据库列表定义文件将会被刷新,并通过在线重载配置的方式生效,不会影响现有的连接。
Pgbouncer 使用和 PostgreSQL 同样的 dbsu 运行,默认为 postgres 操作系统用户,您可以使用 pgb 别名,使用 dbsu 访问 pgbouncer 管理功能。
Pigsty 还提供了一个实用函数 pgb-route ,可以将 pgbouncer 数据库流量快速切换至集群中的其他节点,用于零停机迁移:
连接池用户配置文件 userlist.txt 与 useropts.txt 会在您创建用户 时自动刷新,并通过在线重载配置的方式生效,正常不会影响现有的连接。
请注意,pgbouncer_auth_query 参数允许你使用动态查询来完成连接池用户认证,当您懒得管理连接池中的用户时,这是一种折中的方案。
11.6.2 - 数据库 数据库指的是使用 SQL 命令 CREATE DATABASE 创建的,数据库集簇内的逻辑对象。
在这里的上下文中,数据库指的是使用 SQL 命令 CREATE DATABASE 创建的,数据库集簇内的逻辑对象。
一组 PostgreSQL 服务器可以同时服务于多个 数据库 (Database)。在 Pigsty 中,你可以在集群配置中定义 好所需的数据库。
Pigsty会对默认模板数据库template1进行修改与定制,创建默认模式,安装默认扩展,配置默认权限,新创建的数据库默认会从template1继承这些设置。
默认情况下,所有业务数据库都会被1:1添加到 Pgbouncer 连接池中;pg_exporter 默认会通过 自动发现 机制查找所有业务数据库并进行库内对象监控。
定义数据库 业务数据库定义在数据库集群参数 pg_databases 中,这是一个数据库定义构成的对象数组。
数组内的数据库按照定义顺序 依次创建,因此后面定义的数据库可以使用先前定义的数据库作为模板 。
下面是 Pigsty 演示环境中默认集群 pg-meta 中的数据库定义:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name: postgis, schema : public}, {name: timescaledb}]}
- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment : grafana primary database }
- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment : bytebase primary database }
- { name: kong ,owner: dbuser_kong ,revokeconn: true ,comment : kong the api gateway database }
- { name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment : gitea meta database }
- { name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment : wiki meta database }
- { name: noco ,owner: dbuser_noco ,revokeconn: true ,comment : nocodb database }
每个数据库定义都是一个 object,可能包括以下字段,以 meta 数据库为例:
- name : meta # 必选,`name` 是数据库定义的唯一必选字段
baseline : cmdb.sql # 可选,数据库 sql 的基线定义文件路径(ansible 搜索路径中的相对路径,如 files/)
pgbouncer : true # 可选,是否将此数据库添加到 pgbouncer 数据库列表?默认为 true
schemas : [ pigsty] # 可选,要创建的附加模式,由模式名称字符串组成的数组
extensions : # 可选,要安装的附加扩展: 扩展对象的数组
- { name: postgis , schema : public } # 可以指定将扩展安装到某个模式中,也可以不指定(不指定则安装到 search_path 首位模式中)
- { name : timescaledb } # 例如有的扩展会创建并使用固定的模式,就不需要指定模式。
comment : pigsty meta database # 可选,数据库的说明与备注信息
owner : postgres # 可选,数据库所有者,默认为 postgres
template : template1 # 可选,要使用的模板,默认为 template1,目标必须是一个模板数据库
encoding : UTF8 # 可选,数据库编码,默认为 UTF8(必须与模板数据库相同)
locale : C # 可选,数据库地区设置,默认为 C(必须与模板数据库相同)
lc_collate : C # 可选,数据库 collate 排序规则,默认为 C(必须与模板数据库相同),没有理由不建议更改。
lc_ctype : C # 可选,数据库 ctype 字符集,默认为 C(必须与模板数据库相同)
tablespace : pg_default # 可选,默认表空间,默认为 'pg_default'
allowconn : true # 可选,是否允许连接,默认为 true。显式设置 false 将完全禁止连接到此数据库
revokeconn : false # 可选,撤销公共连接权限。默认为 false,设置为 true 时,属主和管理员之外用户的 CONNECT 权限会被回收
register_datasource : true # 可选,是否将此数据库注册到 grafana 数据源?默认为 true,显式设置为 false 会跳过注册
connlimit : -1 # 可选,数据库连接限制,默认为 -1 ,不限制,设置为正整数则会限制连接数。
pool_auth_user : dbuser_meta # 可选,连接到此 pgbouncer 数据库的所有连接都将使用此用户进行验证(启用 pgbouncer_auth_query 才有用)
pool_mode : transaction # 可选,数据库级别的 pgbouncer 池化模式,默认为 transaction
pool_size : 64 # 可选,数据库级别的 pgbouncer 默认池子大小,默认为 64
pool_size_reserve : 32 # 可选,数据库级别的 pgbouncer 池子保留空间,默认为 32,当默认池子不够用时,最多再申请这么多条突发连接。
pool_size_min : 0 # 可选,数据库级别的 pgbouncer 池的最小大小,默认为 0
pool_max_db_conn : 100 # 可选,数据库级别的最大数据库连接数,默认为 100
唯一必选的字段是 name,它应该是当前 PostgreSQL 集群中有效且唯一的数据库名称,其他参数都有合理的默认值。
name:数据库名称,必选项 。baseline:SQL文件路径(Ansible搜索路径,通常位于files),用于初始化数据库内容。owner:数据库属主,默认为postgrestemplate:数据库创建时使用的模板,默认为template1encoding:数据库默认字符编码,默认为UTF8,默认与实例保持一致。建议不要配置与修改。locale:数据库默认的本地化规则,默认为C,建议不要配置,与实例保持一致。lc_collate:数据库默认的本地化字符串排序规则,默认与实例设置相同,建议不要修改,必须与模板数据库一致。强烈建议不要配置,或配置为C。lc_ctype:数据库默认的LOCALE,默认与实例设置相同,建议不要修改或设置,必须与模板数据库一致。建议配置为C或en_US.UTF8。allowconn:是否允许连接至数据库,默认为true,不建议修改。revokeconn:是否回收连接至数据库的权限?默认为false。如果为true,则数据库上的PUBLIC CONNECT权限会被回收。只有默认用户(dbsu|monitor|admin|replicator|owner)可以连接。此外,admin|owner 会拥有GRANT OPTION,可以赋予其他用户连接权限。tablespace:数据库关联的表空间,默认为pg_default。connlimit:数据库连接数限制,默认为-1,即没有限制。extensions:对象数组 ,每一个对象定义了一个数据库中的扩展 ,以及其安装的模式 。parameters:KV对象,每一个KV定义了一个需要针对数据库通过ALTER DATABASE修改的参数。pgbouncer:布尔选项,是否将该数据库加入到Pgbouncer中。所有数据库都会加入至Pgbouncer列表,除非显式指定pgbouncer: false。comment:数据库备注信息。pool_auth_user:启用 pgbouncer_auth_query 时,连接到此 pgbouncer 数据库的所有连接都将使用这里指定的用户执行认证查询。你需要使用一个具有访问 pg_shadow 表权限的用户。pool_mode:数据库级别的 pgbouncer 池化模式,默认为 transaction,即事物池化。如果留空,会使用 pgbouncer_poolmode 参数作为默认值。pool_size:数据库级别的 pgbouncer 默认池子大小,默认为 64pool_size_reserve:数据库级别的 pgbouncer 池子保留空间,默认为 32,当默认池子不够用时,最多再申请这么多条突发连接。pool_size_min: 数据库级别的 pgbouncer 池的最小大小,默认为 0pool_max_db_conn: 数据库级别的 pgbouncer 连接池最大数据库连接数,默认为 100新创建的数据库默认会从 template1 数据库 Fork 出来,这个模版数据库会在 PG_PROVISION 阶段进行定制修改:
配置好扩展,模式以及默认权限,因此新创建的数据库也会继承这些配置,除非您显式使用一个其他的数据库作为模板。
关于数据库的访问权限,请参考 ACL:数据库权限 一节。
创建数据库 在 pg_databases 中定义 的数据库将在集群初始化时自动创建。
如果您希望在现有集群上创建数据库 ,可以使用 bin/pgsql-db 包装脚本。
将新的数据库定义添加到 all.children.<cls>.pg_databases 中,并使用以下命令创建该数据库:
bin/pgsql-db <cls> <dbname> # pgsql-db.yml -l <cls> -e dbname=<dbname>
下面是新建数据库时的一些注意事项:
创建数据库的剧本默认为幂等剧本,不过当您当使用 baseline 脚本时就不一定了:这种情况下,通常不建议在现有数据库上重复执行此操作,除非您确定所提供的 baseline SQL也是幂等的。
我们不建议您手工创建新的数据库,特别当您使用默认的 pgbouncer 连接池时:除非您愿意手工负责维护 Pgbouncer 中的数据库列表并与 PostgreSQL 保持一致。
使用 pgsql-db 工具或 pgsql-db.yml 剧本创建新数据库时,会将此数据库一并添加到 Pgbouncer 数据库 列表中。
如果您的数据库定义有一个非常规 owner(默认为 dbsu postgres),那么请确保在创建该数据库前,属主用户已经存在。
最佳实践永远是在创建数据库之前创建 用户 。
Pgbouncer数据库 Pigsty 会默认为 PostgreSQL 实例 1:1 配置启用一个 Pgbouncer 连接池,使用 /var/run/postgresql Unix Socket 通信。
连接池可以优化短连接性能,降低并发征用,以避免过高的连接数冲垮数据库,并在数据库迁移时提供额外的灵活处理空间。
Pigsty 默认将 pg_databases 中的所有数据库都添加到 pgbouncer 的数据库列表中。
您可以通过在数据库定义 中显式设置 pgbouncer: false 来禁用特定数据库的 pgbouncer 连接池支持。
Pgbouncer数据库列表在 /etc/pgbouncer/database.txt 中定义,数据库定义中关于连接池的参数会体现在这里:
meta = host=/var/run/postgresql mode=session
grafana = host=/var/run/postgresql mode=transaction
bytebase = host=/var/run/postgresql auth_user=dbuser_meta
kong = host=/var/run/postgresql pool_size=32 reserve_pool=64
gitea = host=/var/run/postgresql min_pool_size=10
wiki = host=/var/run/postgresql
noco = host=/var/run/postgresql
mongo = host=/var/run/postgresql
当您创建数据库 时,Pgbouncer 的数据库列表定义文件将会被刷新,并通过在线重载配置的方式生效,正常不会影响现有的连接。
Pgbouncer 使用和 PostgreSQL 同样的 dbsu 运行,默认为 postgres 操作系统用户,您可以使用 pgb 别名,使用 dbsu 访问 pgbouncer 管理功能。
Pigsty 还提供了一个实用函数 pgb-route ,可以将 pgbouncer 数据库流量快速切换至集群中的其他节点,用于零停机迁移:
# route pgbouncer traffic to another cluster member
function pgb-route(){
local ip = ${ 1 - '\/var\/run\/postgresql' }
sed -ie "s/host=[^[:space:]]\+/host= ${ ip } /g" /etc/pgbouncer/pgbouncer.ini
cat /etc/pgbouncer/pgbouncer.ini
}
11.6.3 - 服务/接入 分离读写操作,正确路由流量,稳定可靠地交付 PostgreSQL 集群提供的能力。
分离读写操作,正确路由流量,稳定可靠地交付 PostgreSQL 集群提供的能力。
服务 是一种抽象:它是数据库集群对外提供能力的形式,并封装了底层集群的细节。
服务对于生产环境中的稳定接入 至关重要,在高可用 集群自动故障时方显其价值,单机用户 通常不需要操心这个概念。
单机用户 “服务” 的概念是给生产环境用的,个人用户/单机集群可以不折腾,直接拿实例名/IP地址访问数据库。
例如,Pigsty 默认的单节点 pg-meta.meta 数据库,就可以直接用下面三个不同的用户连接上去。
psql postgres://dbuser_dba:DBUser.DBA@10.10.10.10/meta # 直接用 DBA 超级用户连上去
psql postgres://dbuser_meta:DBUser.Meta@10.10.10.10/meta # 用默认的业务管理员用户连上去
psql postgres://dbuser_view:DBUser.View@pg-meta/meta # 用默认的只读用户走实例域名连上去
服务概述 在真实世界生产环境中,我们会使用基于复制的主从数据库集群。集群中有且仅有一个实例作为领导者(主库 )可以接受写入。
而其他实例(从库 )则会从持续从集群领导者获取变更日志,与领导者保持一致。同时,从库还可以承载只读请求,在读多写少的场景下可以显著分担主库的负担,
因此对集群的写入请求与只读请求进行区分,是一种十分常见的实践。
此外对于高频短连接的生产环境,我们还会通过连接池中间件(Pgbouncer)对请求进行池化,减少连接与后端进程的创建开销。但对于ETL与变更执行等场景,我们又需要绕过连接池,直接访问数据库。
同时,高可用集群在故障时会出现故障切换(Failover),故障切换会导致集群的领导者出现变更。因此高可用的数据库方案要求写入流量可以自动适配集群的领导者变化。
这些不同的访问需求(读写分离,池化与直连,故障切换自动适配)最终抽象出 服务 (Service)的概念。
通常来说,数据库集群都必须提供这种最基础的服务:
对于生产数据库集群,至少应当提供这两种服务:
读写服务(primary) :写入数据:只能由主库所承载。只读服务(replica) :读取数据:可以由从库承载,没有从库时也可由主库承载此外,根据具体的业务场景,可能还会有其他的服务,例如:
默认直连服务(default) :允许(管理)用户,绕过连接池直接访问数据库的服务离线从库服务(offline) :不承接线上只读流量的专用从库,用于ETL与分析查询同步从库服务(standby) :没有复制延迟的只读服务,由同步备库 /主库处理只读查询延迟从库服务(delayed) :访问同一个集群在一段时间之前的旧数据,由延迟从库 来处理默认服务 Pigsty默认为每个 PostgreSQL 数据库集群提供四种不同的服务,以下是默认服务及其定义:
以默认的 pg-meta 集群为例,它提供四种默认服务:
psql postgres://dbuser_meta:DBUser.Meta@pg-meta:5433/meta # pg-meta-primary : 通过主要的 pgbouncer(6432) 进行生产读写
psql postgres://dbuser_meta:DBUser.Meta@pg-meta:5434/meta # pg-meta-replica : 通过备份的 pgbouncer(6432) 进行生产只读
psql postgres://dbuser_dba:DBUser.DBA@pg-meta:5436/meta # pg-meta-default : 通过主要的 postgres(5432) 直接连接
psql postgres://dbuser_stats:DBUser.Stats@pg-meta:5438/meta # pg-meta-offline : 通过离线的 postgres(5432) 直接连接
从示例集群架构图 上可以看出这四种服务的工作方式:
注意在这里pg-meta 域名指向了集群的 L2 VIP,进而指向集群主库上的 haproxy 负载均衡器,它负责将流量路由到不同的实例上,详见服务接入
服务实现 在 Pigsty 中,服务使用节点 上的 haproxy 来实现,通过主机节点上的不同端口进行区分。
Pigsty 所纳管的每个节点上都默认启用了 Haproxy 以对外暴露服务,而数据库节点也不例外。
集群中的节点尽管从数据库的视角来看有主从之分,但从服务的视角来看,每个节点都是相同的:
这意味着即使您访问的是从库节点,只要使用正确的服务端口,就依然可以使用到主库读写的服务。
这样的设计可以屏蔽复杂度:所以您只要可以访问 PostgreSQL 集群上的任意一个实例,就可以完整的访问到所有服务。
这样的设计类似于 Kubernetes 中的 NodePort 服务,同样在 Pigsty 中,每一个服务都包括以下两个核心要素:
通过 NodePort 暴露的访问端点(端口号,从哪访问?) 通过 Selectors 选择的目标实例(实例列表,谁来承载?) Pigsty的服务交付边界止步于集群的HAProxy,用户可以用各种手段访问这些负载均衡器,请参考接入服务 。
所有的服务都通过配置文件进行声明,例如,PostgreSQL 默认服务就是由 pg_default_services 参数所定义的:
pg_default_services :
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
您也可以在 pg_services 中定义额外的服务,参数 pg_default_services 与 pg_services 都是由 服务定义 对象组成的数组。
定义服务 Pigsty 允许您定义自己的服务:
对于 PostgreSQL 集群来说,通常只需要关注前两者即可。
每一条服务定义都会在所有相关 HAProxy 实例的配置目录下生成一个新的配置文件:/etc/haproxy/<svcname>.cfg
下面是一个自定义的服务样例 standby:当您想要对外提供没有复制延迟的只读服务时,就可以在 pg_services 新增这条记录:
- name : standby # 必选,服务名称,最终的 svc 名称会使用 `pg_cluster` 作为前缀,例如:pg-meta-standby
port : 5435 # 必选,暴露的服务端口(作为 kubernetes 服务节点端口模式)
ip : "*" # 可选,服务绑定的 IP 地址,默认情况下为所有 IP 地址
selector : "[]" # 必选,服务成员选择器,使用 JMESPath 来筛选配置清单
backup : "[? pg_role == `primary`]" # 可选,服务成员选择器(备份),也就是当默认选择器选中的实例都宕机后,服务才会由这里选中的实例成员来承载
dest : default # 可选,目标端口,default|postgres|pgbouncer|<port_number>,默认为 'default',Default的意思就是使用 pg_default_service_dest 的取值来最终决定
check : /sync # 可选,健康检查 URL 路径,默认为 /,这里使用 Patroni API:/sync ,只有同步备库和主库才会返回 200 健康状态码
maxconn : 5000 # 可选,允许的前端连接最大数,默认为5000
balance : roundrobin # 可选,haproxy 负载均衡算法(默认为 roundrobin,其他选项:leastconn)
options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
而上面的服务定义,在样例的三节点 pg-test 上将会被转换为 haproxy 配置文件 /etc/haproxy/pg-test-standby.conf:
#---------------------------------------------------------------------
# service: pg-test-standby @ 10.10.10.11:5435
#---------------------------------------------------------------------
# service instances 10.10.10.11, 10.10.10.13, 10.10.10.12
# service backups 10.10.10.11
listen pg-test-standby
bind *:5435 # <--- 绑定了所有IP地址上的 5435 端口
mode tcp # <--- 负载均衡器工作在 TCP 协议上
maxconn 5000 # <--- 最大连接数为 5000,可按需调大
balance roundrobin # <--- 负载均衡算法为 rr 轮询,还可以使用 leastconn
option httpchk # <--- 启用 HTTP 健康检查
option http-keep-alive # <--- 保持HTTP连接
http-check send meth OPTIONS uri /sync # <---- 这里使用 /sync ,Patroni 健康检查 API ,只有同步备库和主库才会返回 200 健康状态码。
http-check expect status 200 # <---- 健康检查返回代码 200 代表正常
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers: # pg-test 集群全部三个实例都被 selector: "[]" 给圈中了,因为没有任何的筛选条件,所以都会作为 pg-test-replica 服务的后端服务器。但是因为还有 /sync 健康检查,所以只有主库和同步备库才能真正承载请求。
server pg-test-1 10.10.10.11:6432 check port 8008 weight 100 backup # <----- 唯独主库满足条件 pg_role == `primary`, 被 backup selector 选中。
server pg-test-3 10.10.10.13:6432 check port 8008 weight 100 # 因此作为服务的兜底实例:平时不承载请求,其他从库全部宕机后,才会承载只读请求,从而最大避免了读写服务受到只读服务的影响
server pg-test-2 10.10.10.12:6432 check port 8008 weight 100 #
在这里,pg-test 集群全部三个实例都被 selector: "[]" 给圈中了,渲染进入 pg-test-replica 服务的后端服务器列表中。但是因为还有 /sync 健康检查,Patroni Rest API只有在主库和同步备库 上才会返回代表健康的 HTTP 200 状态码,因此只有主库和同步备库才能真正承载请求。
此外,主库因为满足条件 pg_role == primary, 被 backup selector 选中,被标记为了备份服务器,只有当没有其他实例(也就是同步备库)可以满足需求时,才会顶上。
Primary服务 Primary服务可能是生产环境中最关键的服务,它在 5433 端口提供对数据库集群的读写能力,服务定义如下:
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
选择器参数 selector: "[]" 意味着所有集群成员都将被包括在Primary服务中 但只有主库能够通过健康检查(check: /primary),实际承载Primary服务的流量。 目的地参数 dest: default 意味着Primary服务的目的地受到 pg_default_service_dest 参数的影响 dest 默认值 default 会被替换为 pg_default_service_dest 的值,默认为 pgbouncer。默认情况下 Primary 服务的目的地默认是主库上的连接池,也就是由 pgbouncer_port 指定的端口,默认为 6432 如果 pg_default_service_dest 的值为 postgres,那么 primary 服务的目的地就会绕过连接池,直接使用 PostgreSQL 数据库的端口(pg_port ,默认值 5432),对于一些不希望使用连接池的场景,这个参数非常实用。
示例:pg-test-primary 的 haproxy 配置 listen pg-test-primary
bind *:5433 # <--- primary 服务默认使用 5433 端口
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /primary # <--- primary 服务默认使用 Patroni RestAPI /primary 健康检查
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-1 10.10.10.11:6432 check port 8008 weight 100
server pg-test-3 10.10.10.13:6432 check port 8008 weight 100
server pg-test-2 10.10.10.12:6432 check port 8008 weight 100
Patroni 的高可用 机制确保任何时候最多只会有一个实例的 /primary 健康检查为真,因此Primary服务将始终将流量路由到主实例。
使用 Primary 服务而不是直连数据库的一个好处是,如果集群因为某种情况出现了双主(比如在没有watchdog的情况下kill -9杀死主库 Patroni),Haproxy在这种情况下仍然可以避免脑裂,因为它只会在 Patroni 存活且返回主库状态时才会分发流量。
Replica服务 Replica服务在生产环境中的重要性仅次于Primary服务,它在 5434 端口提供对数据库集群的只读能力,服务定义如下:
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
选择器参数 selector: "[]" 意味着所有集群成员都将被包括在Replica服务中 所有实例都能够通过健康检查(check: /read-only),承载Replica服务的流量。 备份选择器:[? pg_role == 'primary' || pg_role == 'offline' ] 将主库和离线从库 标注为备份服务器。 只有当所有普通从库 都宕机后,Replica服务才会由主库或离线从库来承载。 目的地参数 dest: default 意味着Replica服务的目的地也受到 pg_default_service_dest 参数的影响 dest 默认值 default 会被替换为 pg_default_service_dest 的值,默认为 pgbouncer,这一点和 Primary服务 相同默认情况下 Replica 服务的目的地默认是从库上的连接池,也就是由 pgbouncer_port 指定的端口,默认为 6432 示例:pg-test-replica 的 haproxy 配置 listen pg-test-replica
bind *:5434
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /read-only
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-1 10.10.10.11:6432 check port 8008 weight 100 backup
server pg-test-3 10.10.10.13:6432 check port 8008 weight 100
server pg-test-2 10.10.10.12:6432 check port 8008 weight 100
Replica服务非常灵活:如果有存活的专用 Replica 实例,那么它会优先使用这些实例来承载只读请求,只有当从库实例全部宕机后,才会由主库来兜底只读请求。对于常见的一主一从双节点集群就是:只要从库活着就用从库,从库挂了再用主库。
此外,除非专用只读实例全部宕机,Replica 服务也不会使用专用 Offline 实例,这样就避免了在线快查询与离线慢查询混在一起,相互影响。
Default服务 Default服务在 5436 端口上提供服务,它是Primary服务的变体。
Default服务总是绕过连接池直接连到主库上的 PostgreSQL,这对于管理连接、ETL写入、CDC数据变更捕获等都很有用。
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
如果 pg_default_service_dest 被修改为 postgres,那么可以说 Default 服务除了端口和名称内容之外,与 Primary 服务是完全等价的。在这种情况下,您可以考虑将 Default 从默认服务中剔除。
示例:pg-test-default 的 haproxy 配置 listen pg-test-default
bind *:5436 # <--- 除了监听端口/目标端口和服务名,其他配置和 primary 服务一模一样
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /primary
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-1 10.10.10.11:5432 check port 8008 weight 100
server pg-test-3 10.10.10.13:5432 check port 8008 weight 100
server pg-test-2 10.10.10.12:5432 check port 8008 weight 100
Offline服务 Default服务在 5438 端口上提供服务,它也绕开连接池直接访问 PostgreSQL 数据库,通常用于慢查询/分析查询/ETL读取/个人用户交互式查询,其服务定义如下:
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
Offline服务将流量直接路由到专用的离线从库 上,或者带有 pg_offline_query 标记的普通只读实例 。
选择器参数从集群中筛选出了两种实例:pg_role = offline 的离线从库,或是带有 pg_offline_query = true 标记的普通只读实例 专用离线从库和打标记的普通从库主要的区别在于:前者默认不承载 Replica服务 的请求,避免快慢请求混在一起,而后者默认会承载。 备份选择器参数从集群中筛选出了一种实例:不带 offline 标记的普通从库,这意味着如果离线实例或者带Offline标记的普通从库挂了之后,其他普通的从库可以用来承载Offline服务。 健康检查 /replica 只会针对从库返回 200, 主库会返回错误,因此 Offline服务 永远不会将流量分发到主库实例上去,哪怕集群中只剩这一台主库。 同时,主库实例既不会被选择器圈中,也不会被备份选择器圈中,因此它永远不会承载Offline服务。因此 Offline 服务总是可以避免用户访问主库,从而避免对主库的影响。 示例:pg-test-offline 的 haproxy 配置 listen pg-test-offline
bind *:5438
mode tcp
maxconn 5000
balance roundrobin
option httpchk
option http-keep-alive
http-check send meth OPTIONS uri /replica
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100
# servers
server pg-test-3 10.10.10.13:5432 check port 8008 weight 100
server pg-test-2 10.10.10.12:5432 check port 8008 weight 100 backup
Offline服务提供受限的只读服务,通常用于两类查询:交互式查询(个人用户),慢查询长事务(分析/ETL)。
Offline 服务需要额外的维护照顾:当集群发生主从切换或故障自动切换时,集群的实例角色会发生变化,而 Haproxy 的配置却不会自动发生变化。对于有多个从库的集群来说,这通常并不是一个问题。
然而对于一主一从,从库跑Offline查询的精简小集群而言,主从切换意味着从库变成了主库(健康检查失效),原来的主库变成了从库(不在 Offline 后端列表中),于是没有实例可以承载 Offline 服务了,因此需要手动重载服务 以使变更生效。
如果您的业务模型较为简单,您可以考虑剔除 Default 服务与 Offline 服务,使用 Primary 服务与 Replica 服务直连数据库。
重载服务 当集群成员发生变化,如添加/删除副本、主备切换或调整相对权重时, 你需要 重载服务 以使更改生效。
bin/pgsql-svc <cls> [ ip...] # 为 lb 集群或 lb 实例重载服务
# ./pgsql.yml -t pg_service # 重载服务的实际 ansible 任务
接入服务 Pigsty的服务交付边界止步于集群的HAProxy,用户可以用各种手段访问这些负载均衡器。
典型的做法是使用 DNS 或 VIP 接入,将其绑定在集群所有或任意数量的负载均衡器上。
你可以使用不同的 主机 & 端口 组合,它们以不同的方式提供 PostgreSQL 服务。
主机
类型 样例 描述 集群域名 pg-test通过集群域名访问(由 dnsmasq @ infra 节点解析) 集群 VIP 地址 10.10.10.3通过由 vip-manager 管理的 L2 VIP 地址访问,绑定到主节点 实例主机名 pg-test-1通过任何实例主机名访问(由 dnsmasq @ infra 节点解析) 实例 IP 地址 10.10.10.11访问任何实例的 IP 地址
端口
Pigsty 使用不同的 端口 来区分 pg services
端口 服务 类型 描述 5432 postgres 数据库 直接访问 postgres 服务器 6432 pgbouncer 中间件 访问 postgres 前先通过连接池中间件 5433 primary 服务 访问主 pgbouncer (或 postgres) 5434 replica 服务 访问备份 pgbouncer (或 postgres) 5436 default 服务 访问主 postgres 5438 offline 服务 访问离线 postgres
组合
# 通过集群域名访问
postgres://test@pg-test:5432/test # DNS -> L2 VIP -> 主直接连接
postgres://test@pg-test:6432/test # DNS -> L2 VIP -> 主连接池 -> 主
postgres://test@pg-test:5433/test # DNS -> L2 VIP -> HAProxy -> 主连接池 -> 主
postgres://test@pg-test:5434/test # DNS -> L2 VIP -> HAProxy -> 备份连接池 -> 备份
postgres://dbuser_dba@pg-test:5436/test # DNS -> L2 VIP -> HAProxy -> 主直接连接 (用于管理员)
postgres://dbuser_stats@pg-test:5438/test # DNS -> L2 VIP -> HAProxy -> 离线直接连接 (用于 ETL/个人查询)
# 通过集群 VIP 直接访问
postgres://test@10.10.10.3:5432/test # L2 VIP -> 主直接访问
postgres://test@10.10.10.3:6432/test # L2 VIP -> 主连接池 -> 主
postgres://test@10.10.10.3:5433/test # L2 VIP -> HAProxy -> 主连接池 -> 主
postgres://test@10.10.10.3:5434/test # L2 VIP -> HAProxy -> 备份连接池 -> 备份
postgres://dbuser_dba@10.10.10.3:5436/test # L2 VIP -> HAProxy -> 主直接连接 (用于管理员)
postgres://dbuser_stats@10.10.10.3::5438/test # L2 VIP -> HAProxy -> 离线直接连接 (用于 ETL/个人查询)
# 直接指定任何集群实例名
postgres://test@pg-test-1:5432/test # DNS -> 数据库实例直接连接 (单例访问)
postgres://test@pg-test-1:6432/test # DNS -> 连接池 -> 数据库
postgres://test@pg-test-1:5433/test # DNS -> HAProxy -> 连接池 -> 数据库读/写
postgres://test@pg-test-1:5434/test # DNS -> HAProxy -> 连接池 -> 数据库只读
postgres://dbuser_dba@pg-test-1:5436/test # DNS -> HAProxy -> 数据库直接连接
postgres://dbuser_stats@pg-test-1:5438/test # DNS -> HAProxy -> 数据库离线读/写
# 直接指定任何集群实例 IP 访问
postgres://test@10.10.10.11:5432/test # 数据库实例直接连接 (直接指定实例, 没有自动流量分配)
postgres://test@10.10.10.11:6432/test # 连接池 -> 数据库
postgres://test@10.10.10.11:5433/test # HAProxy -> 连接池 -> 数据库读/写
postgres://test@10.10.10.11:5434/test # HAProxy -> 连接池 -> 数据库只读
postgres://dbuser_dba@10.10.10.11:5436/test # HAProxy -> 数据库直接连接
postgres://dbuser_stats@10.10.10.11:5438/test # HAProxy -> 数据库离线读-写
# 智能客户端:自动进行读写分离
postgres://test@10.10.10.11:6432,10.10.10.12:6432,10.10.10.13:6432/test?target_session_attrs= primary
postgres://test@10.10.10.11:6432,10.10.10.12:6432,10.10.10.13:6432/test?target_session_attrs= prefer-standby
覆盖服务 你可以通过多种方式覆盖默认的服务配置,一种常见的需求是让 Primary服务 与 Replica服务 绕过Pgbouncer连接池,直接访问 PostgreSQL 数据库。
为了实现这一点,你可以将 pg_default_service_dest 更改为 postgres,这样所有服务定义中 svc.dest='default' 的服务都会使用 postgres 而不是默认的 pgbouncer 作为目标。
如果您已经将 Primary服务 指向了 PostgreSQL,那么 default服务 就会比较多余,可以考虑移除。
如果您不需要区分个人交互式查询,分析/ETL慢查询,可以考虑从默认服务列表 pg_default_services 中移除Offline服务 。
如果您不需要只读从库来分担在线只读流量,也可以从默认服务列表中移除 Replica服务 。
委托服务 Pigsty 通过节点上的 haproxy 暴露 PostgreSQL 服务。整个集群中的所有 haproxy 实例都使用相同的服务定义 进行配置。
但是,你可以将 pg 服务委托给特定的节点分组(例如,专门的 haproxy 负载均衡器集群),而不是 PostgreSQL 集群成员上的 haproxy。
为此,你需要使用 pg_default_services 覆盖默认的服务定义,并将 pg_service_provider 设置为代理组名称。
例如,此配置将在端口 10013 的 proxy haproxy 节点组上公开 pg 集群的主服务。
pg_service_provider : proxy # 使用端口 10013 上的 `proxy` 组的负载均衡器
pg_default_services : [ { name: primary ,port: 10013 ,dest: postgres ,check: /primary ,selector : "[]" }]
用户需要确保每个委托服务的端口,在代理集群中都是唯一 的。
在 43 节点生产环境仿真沙箱 中提供了一个使用专用负载均衡器集群的例子:prod.yml
11.6.4 - 认证 / HBA Pigsty 中基于主机的身份认证 HBA(Host-Based Authentication)详解。
Pigsty 中基于主机的身份认证 HBA(Host-Based Authentication)详解。
认证是 访问控制 与 权限系统 的基石,PostgreSQL拥有多种认证 方法。
这里主要介绍 HBA:Host Based Authentication,HBA规则定义了哪些用户能够通过哪些方式从哪些地方访问哪些数据库。
客户端认证 要连接到PostgreSQL数据库,用户必须先经过认证(默认使用密码)。
您可以在连接字符串中提供密码(不安全)或使用PGPASSWORD环境变量或.pgpass文件传递密码。参考psql 文档和PostgreSQL连接字符串 以获取更多详细信息。
psql 'host=<host> port=<port> dbname=<dbname> user=<username> password=<password>'
psql postgres://<username>:<password>@<host>:<port>/<dbname>
PGPASSWORD = <password>; psql -U <username> -h <host> -p <port> -d <dbname>
例如,连接 Pigsty 默认的 meta 数据库,可以使用以下连接串:
psql 'host=10.10.10.10 port=5432 dbname=meta user=dbuser_dba password=DBUser.DBA'
psql postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta
PGPASSWORD = DBUser.DBA; psql -U dbuser_dba -h 10.10.10.10 -p 5432 -d meta
默认配置下,Pigsty会启用服务端 SSL 加密,但不验证客户端 SSL 证书。要使用客户端SSL证书连接,你可以使用PGSSLCERT和PGSSLKEY环境变量或sslkey和sslcert参数提供客户端参数。
psql 'postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta?sslkey=/path/to/dbuser_dba.key&sslcert=/path/to/dbuser_dba.crt'
客户端证书(CN = 用户名)可以使用本地CA与cert.yml 剧本签发。
定义HBA 在Pigsty中,有四个与HBA规则有关的参数:
这些都是 HBA 规则对象的数组,每个HBA规则都是以下两种形式之一的对象:
1. 原始形式 原始形式的 HBA 与 PostgreSQL pg_hba.conf 的格式几乎完全相同:
- title : allow intranet password access
role : common
rules :
- host all all 10.0.0.0/8 md5
- host all all 172.16.0.0/12 md5
- host all all 192.168.0.0/16 md5
在这种形式中,rules 字段是字符串数组,每一行都是条原始形式的 HBA规则 。title 字段会被渲染为一条注释,解释下面规则的作用。
role 字段用于说明该规则适用于哪些实例角色,当实例的pg_role 与role相同时,HBA规则将被添加到这台实例的 HBA 中。
role: common的HBA规则将被添加到所有实例上。role: primary 的 HBA 规则只会添加到主库实例上。role: replica 的 HBA 规则只会添加到从库实例上。role: offline的HBA规则将被添加到离线实例上( pg_role = offline或pg_offline_query = true)2. 别名形式 别名形式允许您用更简单清晰便捷的方式维护 HBA 规则:它用addr、auth、user和db 字段替换了 rules。 title、role 和 order 字段则仍然生效。
- addr : 'intra' # world|intra|infra|admin|local|localhost|cluster|<cidr>
auth : 'pwd' # trust|pwd|ssl|cert|deny|<official auth method>
user : 'all' # all|${dbsu}|${repl}|${admin}|${monitor}|<user>|<group>
db : 'all' # all|replication|....
rules : [] # raw hba string precedence over above all
title : allow intranet password access
order : 100 # 排序权重,数字小的排前面(可选,默认追加到最后)
addr: where 哪些IP地址段受本条规则影响?world: 所有的IP地址intra: 所有的内网IP地址段: '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'infra: Infra节点的IP地址admin: admin_ip 管理节点的IP地址local: 本地 Unix Socketlocalhost: 本地 Unix Socket 以及TCP 127.0.0.1/32 环回地址cluster: 同一个 PostgresQL 集群所有成员的IP地址<cidr>: 一个特定的 CIDR 地址块或IP地址auth: how 本条规则指定的认证方式?deny: 拒绝访问trust: 直接信任,不需要认证pwd: 密码认证,根据 pg_pwd_enc 参数选用 md5 或 scram-sha-256 认证sha/scram-sha-256:强制使用 scram-sha-256 密码认证方式。md5: md5 密码认证方式,但也可以兼容 scram-sha-256 认证,不建议使用。ssl: 在密码认证 pwd 的基础上,强制要求启用SSLssl-md5: 在密码认证 md5 的基础上,强制要求启用SSLssl-sha: 在密码认证 sha 的基础上,强制要求启用SSLos/ident: 使用操作系统用户的身份进行 ident 认证peer: 使用 peer 认证方式,类似于 os identcert: 使用基于客户端SSL证书的认证方式,证书CN为用户名user: who :哪些用户受本条规则影响?db: which :哪些数据库受本条规则影响?all: 所有数据库replication: 允许建立复制连接(不指定特定数据库)某个特定的数据库 3. 定义位置 通常,全局的HBA定义在 all.vars 中,如果您想要修改全局默认的HBA规则,可以从 full.yml 模板中复制一份到 all.vars 中进行修改。
而集群特定的 HBA 规则定义在数据库的集群级配置中:
下面是一些集群HBA规则的定义例子:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_hba_rules :
- { user: dbuser_view ,db: all ,addr: infra ,auth: pwd ,title : '允许 dbuser_view 从基础设施节点密码访问所有库' }
- { user: all ,db: all ,addr: 100.0.0.0/8 ,auth: pwd ,title : '允许所有用户从K8S网段密码访问所有库' }
- { user : '${admin}' ,db: world ,addr: 0.0.0.0/0 ,auth: cert ,title : '允许管理员用户从任何地方用客户端证书登陆' }
重载HBA HBA 是一个静态的规则配置文件,修改后需要重载才能生效。默认的 HBA 规则集合因为不涉及 Role 与集群成员,所以通常不需要重载。
如果您设计的 HBA 使用了特定的实例角色限制,或者集群成员限制,那么当集群实例成员发生变化(新增/下线/主从切换),一部分HBA规则的生效条件/涉及范围发生变化,通常也需要重载HBA 以反映最新变化。
要重新加载 postgres/pgbouncer 的 hba 规则:
bin/pgsql-hba <cls> # 重新加载集群 `<cls>` 的 hba 规则
bin/pgsql-hba <cls> ip1 ip2... # 重新加载特定实例的 hba 规则
底层实际执行的 Ansible 剧本命令为:
./pgsql.yml -l <cls> -e pg_reload = true -t pg_hba,pg_reload
./pgsql.yml -l <cls> -e pg_reload = true -t pgbouncer_hba,pgbouncer_reload
默认HBA Pigsty 有一套默认的 HBA 规则,对于绝大多数场景来说,它已经足够安全了。这些规则使用别名形式,因此基本可以自我解释。
pg_default_hba_rules : # postgres 全局默认的HBA规则,按 order 排序
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title: 'dbsu access via local os user ident' ,order : 100 }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title: 'dbsu replication from local os ident' ,order : 150 }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title: 'replicator replication from localhost',order : 200 }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title: 'replicator replication from intranet' ,order : 250 }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title: 'replicator postgres db from intranet' ,order : 300 }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title: 'monitor from localhost with password' ,order : 350 }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title: 'monitor from infra host with password',order : 400 }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title: 'admin @ infra nodes with pwd & ssl' ,order : 450 }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title: 'admin @ everywhere with ssl & pwd' ,order : 500 }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title: 'pgbouncer read/write via local socket',order : 550 }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title: 'read/write biz user via password' ,order : 600 }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title: 'allow etl offline tasks from intranet',order : 650 }
pgb_default_hba_rules : # pgbouncer 全局默认的HBA规则,按 order 排序
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title: 'dbsu local admin access with os ident',order : 100 }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title: 'allow all user local access with pwd' ,order : 150 }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: pwd ,title: 'monitor access via intranet with pwd' ,order : 200 }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title: 'reject all other monitor access addr' ,order : 250 }
- {user : '${admin}' ,db: all ,addr: intra ,auth: pwd ,title: 'admin access via intranet with pwd' ,order : 300 }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title: 'reject all other admin access addr' ,order : 350 }
- {user: 'all' ,db: all ,addr: intra ,auth: pwd ,title: 'allow all user intra access with pwd' ,order : 400 }
注意 :order 字段控制规则渲染顺序。0-99 用于高优先规则(如黑名单),100-650 为默认规则区间,1000+ 用于追加规则。详见 HBA 配置 。
示例:渲染 pg_hba.conf #==============================================================#
# File : pg_hba.conf
# Desc : Postgres HBA Rules for pg-meta-1 [primary]
# Time : 2023-01-11 15:19
# Host : pg-meta-1 @ 10.10.10.10:5432
# Path : /pg/data/pg_hba.conf
# Note : ANSIBLE MANAGED, DO NOT CHANGE!
# Author : Ruohang Feng (rh@vonng.com)
# License : AGPLv3
#==============================================================#
# addr alias
# local : /var/run/postgresql
# admin : 10.10.10.10
# infra : 10.10.10.10
# intra : 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
# user alias
# dbsu : postgres
# repl : replicator
# monitor : dbuser_monitor
# admin : dbuser_dba
# dbsu access via local os user ident [default]
local all postgres ident
# dbsu replication from local os ident [default]
local replication postgres ident
# replicator replication from localhost [default]
local replication replicator scram-sha-256
host replication replicator 127.0.0.1/32 scram-sha-256
# replicator replication from intranet [default]
host replication replicator 10.0.0.0/8 scram-sha-256
host replication replicator 172.16.0.0/12 scram-sha-256
host replication replicator 192.168.0.0/16 scram-sha-256
# replicator postgres db from intranet [default]
host postgres replicator 10.0.0.0/8 scram-sha-256
host postgres replicator 172.16.0.0/12 scram-sha-256
host postgres replicator 192.168.0.0/16 scram-sha-256
# monitor from localhost with password [default]
local all dbuser_monitor scram-sha-256
host all dbuser_monitor 127.0.0.1/32 scram-sha-256
# monitor from infra host with password [default]
host all dbuser_monitor 10.10.10.10/32 scram-sha-256
# admin @ infra nodes with pwd & ssl [default]
hostssl all dbuser_dba 10.10.10.10/32 scram-sha-256
# admin @ everywhere with ssl & pwd [default]
hostssl all dbuser_dba 0.0.0.0/0 scram-sha-256
# pgbouncer read/write via local socket [default]
local all +dbrole_readonly scram-sha-256
host all +dbrole_readonly 127.0.0.1/32 scram-sha-256
# read/write biz user via password [default]
host all +dbrole_readonly 10.0.0.0/8 scram-sha-256
host all +dbrole_readonly 172.16.0.0/12 scram-sha-256
host all +dbrole_readonly 192.168.0.0/16 scram-sha-256
# allow etl offline tasks from intranet [default]
host all +dbrole_offline 10.0.0.0/8 scram-sha-256
host all +dbrole_offline 172.16.0.0/12 scram-sha-256
host all +dbrole_offline 192.168.0.0/16 scram-sha-256
# allow application database intranet access [common] [DISABLED]
#host kong dbuser_kong 10.0.0.0/8 md5
#host bytebase dbuser_bytebase 10.0.0.0/8 md5
#host grafana dbuser_grafana 10.0.0.0/8 md5
示例: 渲染 pgb_hba.conf #==============================================================#
# File : pgb_hba.conf
# Desc : Pgbouncer HBA Rules for pg-meta-1 [primary]
# Time : 2023-01-11 15:28
# Host : pg-meta-1 @ 10.10.10.10:5432
# Path : /etc/pgbouncer/pgb_hba.conf
# Note : ANSIBLE MANAGED, DO NOT CHANGE!
# Author : Ruohang Feng (rh@vonng.com)
# License : AGPLv3
#==============================================================#
# PGBOUNCER HBA RULES FOR pg-meta-1 @ 10.10.10.10:6432
# ansible managed: 2023-01-11 14:30:58
# addr alias
# local : /var/run/postgresql
# admin : 10.10.10.10
# infra : 10.10.10.10
# intra : 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
# user alias
# dbsu : postgres
# repl : replicator
# monitor : dbuser_monitor
# admin : dbuser_dba
# dbsu local admin access with os ident [default]
local pgbouncer postgres peer
# allow all user local access with pwd [default]
local all all scram-sha-256
host all all 127.0.0.1/32 scram-sha-256
# monitor access via intranet with pwd [default]
host pgbouncer dbuser_monitor 10.0.0.0/8 scram-sha-256
host pgbouncer dbuser_monitor 172.16.0.0/12 scram-sha-256
host pgbouncer dbuser_monitor 192.168.0.0/16 scram-sha-256
# reject all other monitor access addr [default]
host all dbuser_monitor 0.0.0.0/0 reject
# admin access via intranet with pwd [default]
host all dbuser_dba 10.0.0.0/8 scram-sha-256
host all dbuser_dba 172.16.0.0/12 scram-sha-256
host all dbuser_dba 192.168.0.0/16 scram-sha-256
# reject all other admin access addr [default]
host all dbuser_dba 0.0.0.0/0 reject
# allow all user intra access with pwd [default]
host all all 10.0.0.0/8 scram-sha-256
host all all 172.16.0.0/12 scram-sha-256
host all all 192.168.0.0/16 scram-sha-256
安全加固 对于那些需要更高安全性的场合,我们提供了一个安全加固的配置模板 security.yml ,使用了以下的默认 HBA 规则集:
pg_default_hba_rules : # postgres host-based auth rules by default
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: ssl ,title : 'replicator replication from localhost' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: ssl ,title : 'replicator replication from intranet' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: ssl ,title : 'replicator postgres db from intranet' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: ssl ,title : 'monitor from infra host with password' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- {user : '${admin}' ,db: all ,addr: world ,auth: cert ,title : 'admin @ everywhere with ssl & cert' }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: ssl ,title : 'pgbouncer read/write via local socket' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: ssl ,title : 'read/write biz user via password' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: ssl ,title : 'allow etl offline tasks from intranet' }
pgb_default_hba_rules : # pgbouncer host-based authentication rules
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title : 'dbsu local admin access with os ident' }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title : 'allow all user local access with pwd' }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: ssl ,title : 'monitor access via intranet with pwd' }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other monitor access addr' }
- {user : '${admin}' ,db: all ,addr: intra ,auth: ssl ,title : 'admin access via intranet with pwd' }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other admin access addr' }
- {user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'allow all user intra access with pwd' }
更多信息,请参考安全加固 一节。
11.6.5 - 访问控制 Pigsty 提供的默认角色系统与权限模型
Pigsty 提供了一套开箱即用的,基于角色系统 和权限系统 的访问控制模型。
权限控制很重要,但很多用户做不好。因此 Pigsty 提供了一套开箱即用的精简访问控制模型,为您的集群安全性提供一个兜底。
角色系统 Pigsty 默认的角色系统包含四个默认角色 和四个默认用户 :
角色名称 属性 所属 描述 dbrole_readonlyNOLOGIN角色:全局只读访问 dbrole_readwriteNOLOGINdbrole_readonly 角色:全局读写访问 dbrole_adminNOLOGINpg_monitor,dbrole_readwrite 角色:管理员/对象创建 dbrole_offlineNOLOGIN角色:受限的只读访问 postgresSUPERUSER系统超级用户 replicatorREPLICATIONpg_monitor,dbrole_readonly 系统复制用户 dbuser_dbaSUPERUSERdbrole_admin pgsql 管理用户 dbuser_monitorpg_monitor pgsql 监控用户
这些角色与用户 的详细定义如下所示:
pg_default_roles : # 全局默认的角色与系统用户
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
默认角色 Pigsty 中有四个默认角色:
业务只读 (dbrole_readonly): 用于全局只读访问的角色。如果别的业务想要此库只读访问权限,可以使用此角色。 业务读写 (dbrole_readwrite): 用于全局读写访问的角色,主属业务使用的生产账号应当具有数据库读写权限 业务管理员 (dbrole_admin): 拥有DDL权限的角色,通常用于业务管理员,或者需要在应用中建表的场景(比如各种业务软件) 离线只读访问 (dbrole_offline): 受限的只读访问角色(只能访问 offline 实例,通常是个人用户,ETL工具账号) 默认角色在 pg_default_roles 中定义,除非您确实知道自己在干什么,建议不要更改默认角色的名称。
- { name: dbrole_readonly , login: false , comment : role for global read-only access } # 生产环境的只读角色
- { name: dbrole_offline , login: false , comment : role for restricted read-only access (offline instance) } # 受限的只读角色
- { name: dbrole_readwrite , login: false , roles: [dbrole_readonly], comment : role for global read-write access } # 生产环境的读写角色
- { name: dbrole_admin , login: false , roles: [pg_monitor, dbrole_readwrite] , comment : role for object creation } # 生产环境的 DDL 更改角色
默认用户 Pigsty 也有四个默认用户(系统用户):
超级用户 (postgres),集群的所有者和创建者,与操作系统 dbsu 名称相同。 复制用户 (replicator),用于主-从复制的系统用户。 监控用户 (dbuser_monitor),用于监控数据库和连接池指标的用户。 管理用户 (dbuser_dba),执行日常操作和数据库更改的管理员用户。 这4个默认用户的用户名/密码通过4对专用参数进行定义,并在很多地方引用:
在生产部署中记得更改这些密码,不要使用默认值!
pg_dbsu : postgres # 数据库超级用户名,这个用户名建议不要修改。
pg_dbsu_password : '' # 数据库超级用户密码,这个密码建议留空!禁止dbsu密码登陆。
pg_replication_username : replicator # 系统复制用户名
pg_replication_password : DBUser.Replicator # 系统复制密码,请务必修改此密码!
pg_monitor_username : dbuser_monitor # 系统监控用户名
pg_monitor_password : DBUser.Monitor # 系统监控密码,请务必修改此密码!
pg_admin_username : dbuser_dba # 系统管理用户名
pg_admin_password : DBUser.DBA # 系统管理密码,请务必修改此密码!
如果您修改默认用户的参数,在 pg_default_roles 中修改相应的角色定义 即可:
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 , comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor, dbrole_readonly] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
权限系统 Pigsty 拥有一套开箱即用的权限模型,该模型与默认角色 一起配合工作。
所有用户都可以访问所有模式。 只读用户(dbrole_readonly)可以从所有表中读取数据。(SELECT,EXECUTE) 读写用户(dbrole_readwrite)可以向所有表中写入数据并运行 DML。(INSERT,UPDATE,DELETE)。 管理员用户(dbrole_admin)可以创建对象并运行 DDL(CREATE,USAGE,TRUNCATE,REFERENCES,TRIGGER)。 离线用户(dbrole_offline)类似只读用户,但访问受到限制,只允许访问离线实例 (pg_role = 'offline' 或 pg_offline_query = true) 由管理员用户创建的对象将具有正确的权限。 所有数据库上都配置了默认权限,包括模板数据库。 数据库连接权限由数据库定义 管理。 默认撤销PUBLIC在数据库和public模式下的CREATE权限。 对象权限 数据库中新建对象的默认权限由参数 pg_default_privileges 所控制:
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
由管理员新创建 的对象,默认将会上述权限。使用 \ddp+ 可以查看这些默认权限:
类型 访问权限 函数 =X dbrole_readonly=X dbrole_offline=X dbrole_admin=X 模式 dbrole_readonly=U dbrole_offline=U dbrole_admin=UC 序列号 dbrole_readonly=r dbrole_offline=r dbrole_readwrite=wU dbrole_admin=rwU 表 dbrole_readonly=r dbrole_offline=r dbrole_readwrite=awd dbrole_admin=arwdDxt
默认权限 ALTER DEFAULT PRIVILEGES 允许您设置将来创建的对象的权限。 它不会影响已经存在对象的权限,也不会影响非管理员用户创建的对象。
在 Pigsty 中,默认权限针对三个角色进行定义:
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE {{ pg_dbsu }} {{ priv }} ;
{ % endfor % }
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE {{ pg_admin_username }} {{ priv }} ;
{ % endfor % }
-- 对于其他业务管理员而言,它们应当在执行 DDL 前执行 SET ROLE dbrole_admin,从而使用对应的默认权限配置。
{ % for priv in pg_default_privileges % }
ALTER DEFAULT PRIVILEGES FOR ROLE "dbrole_admin" {{ priv }} ;
{ % endfor % }
这些内容将会被 PG集群初始化模板 pg-init-template.sql 所使用,在集群初始化的过程中渲染并输出至 /pg/tmp/pg-init-template.sql。
该命令会在 template1 与 postgres 数据库中执行,新创建的数据库会通过模板 template1 继承这些默认权限配置。
也就是说,为了维持正确的对象权限,您必须用管理员用户 来执行 DDL,它们可以是:
{{ pg_dbsu }} ,默认为 postgres{{ pg_admin_username }} ,默认为 dbuser_dba授予了 dbrole_admin 角色的业务管理员用户(通过 SET ROLE 切换为 dbrole_admin 身份)。 使用 postgres 作为全局对象所有者是明智的。如果您希望以业务管理员用户身份创建对象,创建之前必须使用 SET ROLE dbrole_admin 来维护正确的权限。
当然,您也可以在数据库中通过 ALTER DEFAULT PRIVILEGE FOR ROLE <some_biz_admin> XXX 来显式对业务管理员授予默认权限。
数据库权限 在 Pigsty 中,数据库(Database)层面的权限在数据库定义 中被涵盖。
数据库有三个级别的权限:CONNECT、CREATE、TEMP,以及一个特殊的’权限’:OWNERSHIP。
- name : meta # 必选,`name` 是数据库定义中唯一的必选字段
owner : postgres # 可选,数据库所有者,默认为 postgres
allowconn : true # 可选,是否允许连接,默认为 true。显式设置 false 将完全禁止连接到此数据库
revokeconn : false # 可选,撤销公共连接权限。默认为 false,设置为 true 时,属主和管理员之外用户的 CONNECT 权限会被回收
如果 owner 参数存在,它作为数据库属主,替代默认的 {{ pg_dbsu }} (通常也就是postgres) 如果 revokeconn 为 false,所有用户都有数据库的 CONNECT 权限,这是默认的行为。 如果显式设置了 revokeconn 为 true:数据库的 CONNECT 权限将从 PUBLIC 中撤销:普通用户无法连接上此数据库 CONNECT 权限将被显式授予 {{ pg_replication_username }}、{{ pg_monitor_username }} 和 {{ pg_admin_username }}CONNECT 权限将 GRANT OPTION 被授予数据库属主,数据库属主用户可以自行授权其他用户连接权限。 revokeconn 选项可用于在同一个集群间隔离跨数据库访问,您可以为每个数据库创建不同的业务用户作为属主,并为它们设置 revokeconn 选项。示例:数据库隔离 pg-infra :
hosts :
10.10.10.40 : { pg_seq: 1, pg_role : primary }
10.10.10.41 : { pg_seq: 2, pg_role: replica , pg_offline_query : true }
vars :
pg_cluster : pg-infra
pg_users :
- { name: dbuser_confluence, password: mc2iohos , pgbouncer: true, roles : [ dbrole_admin ] }
- { name: dbuser_gitlab, password: sdf23g22sfdd , pgbouncer: true, roles : [ dbrole_readwrite ] }
- { name: dbuser_jira, password: sdpijfsfdsfdfs , pgbouncer: true, roles : [ dbrole_admin ] }
pg_databases :
- { name: confluence , revokeconn: true, owner: dbuser_confluence , connlimit : 100 }
- { name: gitlab , revokeconn: true, owner: dbuser_gitlab, connlimit : 100 }
- { name: jira , revokeconn: true, owner: dbuser_jira , connlimit : 100 }
CREATE权限 出于安全考虑,Pigsty 默认从 PUBLIC 撤销数据库上的 CREATE 权限,从 PostgreSQL 15 开始这也是默认行为。
数据库属主总是可以根据实际需要,来自行调整 CREATE 权限。
11.8 - 管理预案 数据库管理任务标准操作指南(SOP)
如何使用 Pigsty 维护现有的 PostgreSQL 集群?
本章节提供 PostgreSQL 常见管理任务的标准操作流程(SOP):
常用预案 :创建/移除集群与实例,备份恢复,滚动升级等标准操作流程故障排查 :常见故障排查思路与处理方法,如磁盘写满、连接耗尽、XID回卷等误删处理 :处理误删数据、误删表、误删数据库的应急处理流程维护保养 :定期巡检、故障切换善后、表膨胀治理、VACUUM FREEZE 等维护任务参数优化 :内存、CPU、存储等参数的自动优化策略与调整方法11.8.1 - 数据库管理 数据库管理:创建、修改、删除、重建数据库,使用模板克隆数据库
在 Pigsty 中,数据库管理采用 IaC 的风格,先在配置清单中定义,然后执行剧本执行。
在没有定义 baseline SQL 的情况下,执行 pgsql-db.yml 剧本是幂等的。
它会将指定集群中的指定数据库调整至配置清单中的目标状态。
请注意,部分参数仅能在创建时指定。修改这些参数需要先删除再创建数据库(使用 state: recreate 重建数据库)。
定义数据库 业务数据库定义在数据库集群参数 pg_databases 中,这是一个数据库定义构成的对象数组。
数组内的数据库按照定义顺序 依次创建,因此后面定义的数据库可以使用先前定义的数据库作为模板 。
下面是 Pigsty 演示环境中默认集群 pg-meta 中的数据库定义:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name: postgis, schema : public}, {name: timescaledb}]}
- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment : grafana primary database }
- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment : bytebase primary database }
- { name: kong ,owner: dbuser_kong ,revokeconn: true ,comment : kong the api gateway database }
- { name: gitea ,owner: dbuser_gitea ,revokeconn: true ,comment : gitea meta database }
- { name: wiki ,owner: dbuser_wiki ,revokeconn: true ,comment : wiki meta database }
- { name: noco ,owner: dbuser_noco ,revokeconn: true ,comment : nocodb database }
唯一必选的字段是 name,它应该是当前 PostgreSQL 集群中有效且唯一的数据库名称,其他参数都有合理的默认值。
关于数据库定义参数的完整参考,请查阅 数据库配置参考 。
创建数据库 要在现有的 PostgreSQL 集群上创建新的业务数据库,请将数据库定义添加到 all.children.<cls>.pg_databases,然后执行:
bin/pgsql-db <cls> <dbname> # 等效于:pgsql-db.yml -l <cls> -e dbname=<dbname>
示例:创建名为 myapp 的业务数据库
在配置文件中添加数据库定义: pg-meta :
vars :
pg_databases :
- name : myapp
owner : dbuser_myapp
schemas : [ app]
extensions :
- { name : pg_trgm }
- { name : btree_gin }
comment : my application database
执行创建命令: bin/pgsql-db pg-meta myapp
执行效果:
在主库上创建数据库 myapp 设置数据库所有者为 dbuser_myapp 创建 schema app 安装扩展 pg_trgm 和 btree_gin 配置默认权限(dbrole_readonly/readwrite/admin) 将数据库添加到 Pgbouncer 连接池 将数据库注册到 Grafana 数据源 请使用剧本创建数据库
不建议手工使用 SQL 创建业务数据库,特别是需要使用 Pgbouncer 连接池时。
使用 bin/pgsql-db 工具创建数据库会自动处理连接池配置和监控注册。
修改数据库 修改数据库属性可以通过更新配置并重新执行剧本来完成:
bin/pgsql-db <cls> <dbname> # 幂等操作,可重复执行
可修改属性 属性 说明 示例 owner数据库属主 owner: dbuser_newtablespace默认表空间(会触发数据迁移) tablespace: fast_ssdis_template是否标记为模板数据库 is_template: trueallowconn是否允许连接 allowconn: falseconnlimit连接数限制 connlimit: 100revokeconn是否回收 PUBLIC 的 CONNECT 权限 revokeconn: truecomment备注信息 comment: 新的备注parameters数据库级参数 见下方示例 schemas添加/删除模式(增量操作) 见管理模式 extensions添加/删除扩展(增量操作) 见管理扩展 pgbouncer是否加入连接池 pgbouncer: falsepool_*连接池参数 见连接池配置
不可修改属性 以下属性在数据库创建后无法修改,需要使用 state: recreate 重建数据库:
template - 模板数据库encoding - 字符编码locale / lc_collate / lc_ctype - 本地化设置locale_provider / icu_locale / icu_rules / builtin_locale - 本地化提供者设置strategy - 克隆策略修改属主 - name : myapp
owner : dbuser_new_owner # 修改为新属主
bin/pgsql-db pg-meta myapp
执行的 SQL:
ALTER DATABASE "myapp" OWNER TO "dbuser_new_owner" ;
GRANT ALL PRIVILEGES ON DATABASE "myapp" TO "dbuser_new_owner" ;
修改连接限制 - name : myapp
connlimit : 100 # 限制最大 100 个连接
执行的 SQL:
ALTER DATABASE "myapp" CONNECTION LIMIT 100 ;
回收公共连接权限 - name : myapp
owner : dbuser_myapp
revokeconn : true # 回收 PUBLIC 的 CONNECT 权限
执行的 SQL:
REVOKE CONNECT ON DATABASE "myapp" FROM PUBLIC ;
GRANT CONNECT ON DATABASE "myapp" TO "replicator" ;
GRANT CONNECT ON DATABASE "myapp" TO "dbuser_monitor" ;
GRANT CONNECT ON DATABASE "myapp" TO "dbuser_dba" WITH GRANT OPTION ;
GRANT CONNECT ON DATABASE "myapp" TO "dbuser_myapp" WITH GRANT OPTION ;
要恢复公共连接权限,设置 revokeconn: false:
- name : myapp
revokeconn : false # 恢复 PUBLIC 的 CONNECT 权限
执行的 SQL:
GRANT CONNECT ON DATABASE "myapp" TO PUBLIC ;
标记为模板数据库 - name : app_template
is_template : true # 允许任何有 CREATEDB 权限的用户克隆
执行的 SQL:
ALTER DATABASE "app_template" IS_TEMPLATE true ;
管理参数 数据库级参数通过 parameters 字典配置,会生成 ALTER DATABASE ... SET 语句。
设置参数 - name : myapp
parameters :
work_mem : '256MB'
maintenance_work_mem : '512MB'
statement_timeout : '30s'
search_path : 'app,public'
执行的 SQL:
ALTER DATABASE "myapp" SET "work_mem" = '256MB' ;
ALTER DATABASE "myapp" SET "maintenance_work_mem" = '512MB' ;
ALTER DATABASE "myapp" SET "statement_timeout" = '30s' ;
ALTER DATABASE "myapp" SET "search_path" = 'app,public' ;
重置参数为默认值 使用特殊值 DEFAULT(大小写不敏感)可以将参数重置为 PostgreSQL 默认值:
- name : myapp
parameters :
work_mem : DEFAULT # 重置为 PostgreSQL 默认值
statement_timeout : DEFAULT
执行的 SQL:
ALTER DATABASE "myapp" SET "work_mem" = DEFAULT ;
ALTER DATABASE "myapp" SET "statement_timeout" = DEFAULT ;
常用数据库级参数 参数 说明 示例值 work_mem查询工作内存 '64MB'maintenance_work_mem维护操作内存 '256MB'statement_timeout语句超时时间 '30s'lock_timeout锁等待超时 '10s'idle_in_transaction_session_timeout空闲事务超时 '10min'search_pathSchema 搜索路径 'app,public'default_tablespace默认表空间 'fast_ssd'temp_tablespaces临时表空间 'temp_ssd'log_statement日志记录级别 'ddl'
管理模式 模式(Schema)通过 schemas 数组配置,支持创建、指定属主和删除操作。
创建模式 - name : myapp
schemas :
# 简单形式:只指定模式名
- app
- api
# 完整形式:指定属主
- { name: core, owner : dbuser_myapp }
执行的 SQL:
CREATE SCHEMA IF NOT EXISTS "app" ;
CREATE SCHEMA IF NOT EXISTS "api" ;
CREATE SCHEMA IF NOT EXISTS "core" AUTHORIZATION "dbuser_myapp" ;
指定模式属主 使用 owner 字段可以为模式指定属主,这在多租户或权限隔离场景中非常有用:
- name : multi_tenant_db
owner : dbuser_admin
schemas :
- { name: tenant_a, owner : dbuser_tenant_a }
- { name: tenant_b, owner : dbuser_tenant_b }
- { name: shared, owner : dbuser_admin }
删除模式 使用 state: absent 标记要删除的模式:
- name : myapp
schemas :
- { name: deprecated_schema, state : absent }
执行的 SQL:
DROP SCHEMA IF EXISTS "deprecated_schema" CASCADE ;
CASCADE 警告
删除模式使用 CASCADE 选项,会同时删除模式内的所有对象(表、视图、函数等)。
请确保理解影响范围后再执行删除操作。
管理扩展 扩展通过 extensions 数组配置,支持安装和卸载操作。
安装扩展 - name : myapp
extensions :
# 简单形式:只指定扩展名
- postgis
- pg_trgm
# 完整形式:指定 schema 和版本
- { name: vector, schema : public }
- { name: pg_stat_statements, schema: monitor, version : '1.10' }
执行的 SQL:
CREATE EXTENSION IF NOT EXISTS "postgis" CASCADE ;
CREATE EXTENSION IF NOT EXISTS "pg_trgm" CASCADE ;
CREATE EXTENSION IF NOT EXISTS "vector" WITH SCHEMA "public" CASCADE ;
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements" WITH SCHEMA "monitor" VERSION '1.10' CASCADE ;
卸载扩展 使用 state: absent 标记要卸载的扩展:
- name : myapp
extensions :
- { name: pg_trgm, state : absent } # 卸载扩展
- { name : postgis } # 保留扩展
执行的 SQL:
DROP EXTENSION IF EXISTS "pg_trgm" CASCADE ;
CREATE EXTENSION IF NOT EXISTS "postgis" CASCADE ;
CASCADE 警告
卸载扩展使用 CASCADE 选项,会同时删除依赖该扩展的所有对象(视图、函数等)。
请确保理解影响范围后再执行卸载操作。
删除数据库 要删除数据库,将其 state 设置为 absent 并执行剧本:
pg_databases :
- name : olddb
state : absent
删除操作会:
如果数据库标记为 is_template: true,先执行 ALTER DATABASE ... IS_TEMPLATE false 使用 DROP DATABASE ... WITH (FORCE) 强制删除数据库(PG13+) 终止所有到该数据库的活动连接 从 Pgbouncer 连接池中移除该数据库 从 Grafana 数据源中取消注册 保护机制:
系统数据库 postgres、template0、template1 无法删除 删除操作仅在主库上执行,流复制会自动同步到从库 危险操作警告
删除数据库是不可逆 操作,会永久删除该数据库中的所有数据。
执行前请确保:
已有最新的数据库备份 已确认没有业务在使用该数据库 已通知相关干系人 重建数据库 recreate 状态用于重建数据库,等效于先删除再创建:
pg_databases :
- name : testdb
state : recreate
owner : dbuser_test
baseline : test_init.sql # 重建后执行初始化
bin/pgsql-db <cls> testdb
适用场景:
测试环境重置 清空开发数据库 修改不可变属性(编码、本地化等) 恢复数据库到初始状态 与手动 DROP + CREATE 的区别:
单条命令完成,无需两次操作 自动保留 Pgbouncer 和 Grafana 配置 执行后自动加载 baseline 初始化脚本 克隆数据库 可以使用现有数据库作为模板创建新数据库,实现数据库结构的快速复制。
基本克隆 pg_databases :
# 1. 首先定义模板数据库
- name : app_template
owner : dbuser_app
schemas : [ core, api]
extensions : [ postgis, pg_trgm]
baseline : app_schema.sql
# 2. 使用模板创建业务数据库
- name : app_prod
template : app_template
owner : dbuser_app
指定克隆策略(PG15+) - name : app_staging
template : app_template
strategy : FILE_COPY # 或 WAL_LOG
owner : dbuser_app
策略 说明 适用场景 FILE_COPY直接复制数据文件 大模板,通用场景 WAL_LOG通过 WAL 日志复制 小模板,不阻塞模板连接
使用自定义模板数据库 当使用非系统模板(非 template0/template1)时,Pigsty 会自动终止模板数据库上的连接以允许克隆。
- name : new_db
template : existing_db # 使用现有业务数据库作为模板
owner : dbuser_app
标记为模板数据库 默认只有超级用户或数据库所有者可以使用普通数据库作为模板。
使用 is_template: true 可以允许任何有 CREATEDB 权限的用户克隆:
- name : shared_template
is_template : true # 允许任何有 CREATEDB 权限的用户克隆
owner : dbuser_app
使用 ICU 本地化提供者 使用 icu 本地化提供者时,必须指定 template: template0:
- name : myapp_icu
template : template0 # 必须使用 template0
locale_provider : icu
icu_locale : en-US
encoding : UTF8
连接池配置 默认情况下,所有业务数据库都会添加到 Pgbouncer 连接池中。
数据库级连接池参数 - name : myapp
pgbouncer : true # 是否加入连接池(默认 true)
pool_mode : transaction # 池化模式:transaction/session/statement
pool_size : 64 # 默认池大小
pool_size_min : 0 # 最小池大小
pool_reserve : 32 # 保留连接数
pool_connlimit : 100 # 最大数据库连接
pool_auth_user : dbuser_meta # 认证查询用户
生成的配置 配置文件位于 /etc/pgbouncer/database.txt:
myapp = host=/var/run/postgresql pool_mode=transaction pool_size=64
隐藏数据库 某些内部数据库可能不需要通过连接池访问:
- name : internal_db
pgbouncer : false # 不加入连接池
池化模式说明 模式 说明 适用场景 transaction事务结束后归还连接(默认) 大多数 OLTP 应用 session会话结束后归还连接 需要会话状态的应用 statement语句结束后归还连接 无状态查询
本地化提供者 PostgreSQL 15+ 引入了 locale_provider 参数,支持不同的本地化实现。
使用 ICU 提供者(PG15+) - name : myapp_icu
template : template0 # ICU 必须使用 template0
locale_provider : icu
icu_locale : en-US # ICU 本地化规则
encoding : UTF8
使用内置提供者(PG17+) - name : myapp_builtin
template : template0
locale_provider : builtin
builtin_locale : C.UTF-8 # 内置本地化规则
encoding : UTF8
ICU 排序规则(PG16+) - name : myapp_custom_icu
template : template0
locale_provider : icu
icu_locale : en-US
icu_rules : '&V << w <<< W' # 自定义 ICU 排序规则
提供者对比 提供者 版本要求 特点 libc- 传统方式,依赖操作系统 icuPG15+ 跨平台一致,功能丰富 builtinPG17+ 最高效的 C/C.UTF-8 排序
操作速查 常用命令 操作 命令 创建数据库 bin/pgsql-db <cls> <dbname>修改数据库 bin/pgsql-db <cls> <dbname>删除数据库 设置 state: absent 后执行 bin/pgsql-db <cls> <dbname> 重建数据库 设置 state: recreate 后执行 bin/pgsql-db <cls> <dbname> 查看数据库列表 psql -c '\l'查看连接池数据库 cat /etc/pgbouncer/database.txt
常见操作示例 # 创建基本数据库
- name : myapp
owner : dbuser_myapp
comment : my application database
# 创建带扩展的数据库
- name : geodata
owner : dbuser_geo
extensions : [ postgis, postgis_topology]
# 限制连接的私有数据库
- name : secure_db
owner : dbuser_secure
revokeconn : true
connlimit : 10
# 设置数据库级参数
- name : analytics
owner : dbuser_analyst
parameters :
work_mem : '512MB'
statement_timeout : '5min'
# 使用 ICU 本地化
- name : i18n_db
template : template0
locale_provider : icu
icu_locale : zh-Hans
encoding : UTF8
# 删除数据库
- name : old_db
state : absent
# 重建数据库
- name : test_db
state : recreate
baseline : test_init.sql
执行流程 bin/pgsql-db 执行时会依次:
验证 - 检查 dbname 参数和数据库定义删除 (如果 state=absent/recreate)- 执行 DROP DATABASE创建 (如果 state=create/recreate)- 执行 CREATE DATABASE配置 - 执行 ALTER DATABASE 设置属性初始化 - 创建 schema、安装扩展、执行 baseline注册 - 更新 Pgbouncer 和 Grafana 数据源关于数据库的访问权限,请参考 ACL:数据库权限 一节。
11.8.2 - HBA 管理 PostgreSQL 与 Pgbouncer HBA 规则的日常管理操作:刷新、重载、验证与故障排查。
HBA 规则的变更需要重新渲染配置文件并重载服务。本文介绍 HBA 规则的日常管理操作。
快速参考 操作 命令 刷新集群 HBA bin/pgsql-hba <cls>刷新特定实例 bin/pgsql-hba <cls> <ip>...仅刷新 PostgreSQL ./pgsql.yml -l <cls> -t pg_hba,pg_reload仅刷新 Pgbouncer ./pgsql.yml -l <cls> -t pgbouncer_hba,pgbouncer_reload查看当前 HBA psql -c "TABLE pg_hba_file_rules"验证 HBA 配置 psql -c "SELECT pg_reload_conf()"
刷新 HBA 规则 修改 pigsty.yml 中的 HBA 规则后,需要重新渲染配置文件并让服务重载。
使用管理脚本 推荐使用 bin/pgsql-hba 脚本,一键完成 PostgreSQL 和 Pgbouncer 的 HBA 刷新:
# 刷新整个集群的 HBA 规则
bin/pgsql-hba pg-meta
# 刷新特定实例(多个 IP 空格分隔)
bin/pgsql-hba pg-meta 10.10.10.10
bin/pgsql-hba pg-meta 10.10.10.11 10.10.10.12
# 查看脚本帮助
bin/pgsql-hba --help
脚本内部执行:
./pgsql.yml -l <cluster> -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload
使用 Ansible Playbook 直接使用 pgsql.yml playbook 的相关 tags:
# 刷新 PostgreSQL HBA 并重载
./pgsql.yml -l pg-meta -t pg_hba,pg_reload
# 刷新 Pgbouncer HBA 并重载
./pgsql.yml -l pg-meta -t pgbouncer_hba,pgbouncer_reload
# 同时刷新两者
./pgsql.yml -l pg-meta -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload
# 使用额外变量强制重载
./pgsql.yml -l pg-meta -e pg_reload = true -t pg_hba,pg_reload
Tag 说明 pg_hba渲染 PostgreSQL HBA 配置文件 pg_reload重载 PostgreSQL 配置(需配合 pg_reload=true) pgbouncer_hba渲染 Pgbouncer HBA 配置文件 pgbouncer_reload重载 Pgbouncer 配置
配置文件位置 HBA 配置文件由 Ansible 渲染生成:
服务 配置文件路径 模板文件 PostgreSQL /pg/data/pg_hba.confroles/pgsql/templates/pg_hba.confPgbouncer /etc/pgbouncer/pgb_hba.confroles/pgsql/templates/pgbouncer.hba
警告 :不要直接编辑这些文件,下次执行 playbook 时会被覆盖。所有变更应在 pigsty.yml 中进行。
验证 HBA 规则 查看当前生效的 HBA 规则 # 使用 psql 查看 PostgreSQL HBA 规则
psql -c "TABLE pg_hba_file_rules"
# 或者直接查看配置文件
cat /pg/data/pg_hba.conf
# 查看 Pgbouncer HBA 规则
cat /etc/pgbouncer/pgb_hba.conf
检查 HBA 配置语法 # PostgreSQL 重载配置(会验证语法)
psql -c "SELECT pg_reload_conf()"
# 如果有语法错误,查看日志
tail -f /pg/log/postgresql-*.log
测试连接认证 # 测试特定用户从特定地址的连接
psql -h <host> -p 5432 -U <user> -d <database> -c "SELECT 1"
# 查看连接被哪条 HBA 规则匹配
psql -c "SELECT * FROM pg_hba_file_rules WHERE database @> ARRAY['<dbname>']::text[]"
常见管理场景 添加新的 HBA 规则 编辑 pigsty.yml,在集群的 pg_hba_rules 中添加规则: pg-meta :
vars :
pg_hba_rules :
- {user: new_user, db: new_db, addr: '192.168.1.0/24', auth: pwd, title : 'new app access' }
执行刷新: 紧急封禁 IP 当发现恶意 IP 时,可以快速添加黑名单规则:
添加高优先级(order: 0)的拒绝规则: pg_hba_rules :
- {user: all, db: all, addr: '10.1.1.100/32', auth: deny, order: 0, title : 'emergency block' }
立即刷新: 按角色区分规则 为主库和从库配置不同的 HBA 规则:
pg_hba_rules :
# 仅主库允许写入用户
- {user: writer, db: all, addr: intra, auth: pwd, role: primary, title : 'writer on primary' }
# 从库允许只读用户
- {user: reader, db: all, addr: world, auth: ssl, role: replica, title : 'reader on replica' }
执行刷新后,规则会根据实例的 pg_role 自动启用或禁用。
集群扩容后刷新 HBA 当集群新增实例后,使用 addr: cluster 的规则需要刷新才能包含新成员:
# 扩容新实例
./pgsql.yml -l 10.10.10.14
# 刷新所有实例的 HBA(包含新成员 IP)
bin/pgsql-hba pg-meta
主从切换后刷新 HBA Patroni 故障转移后,实例的 pg_role 可能与配置不一致。如果 HBA 规则使用了 role 过滤,需要:
更新 pigsty.yml 中的角色定义 刷新 HBA 规则 # 更新配置文件中的角色后刷新
bin/pgsql-hba pg-meta
故障排查 连接被拒绝 症状 :FATAL: no pg_hba.conf entry for host "x.x.x.x", user "xxx", database "xxx"
排查步骤 :
检查当前 HBA 规则: psql -c "TABLE pg_hba_file_rules"
确认客户端 IP、用户名、数据库是否匹配任何规则
检查规则顺序(首条匹配生效)
添加对应规则并刷新
认证失败 症状 :FATAL: password authentication failed for user "xxx"
排查步骤 :
确认密码正确 检查密码加密方式(pg_pwd_enc)与客户端兼容性 检查用户是否存在:\du 或 SELECT * FROM pg_roles WHERE rolname = 'xxx' HBA 规则未生效 排查步骤 :
确认已执行刷新命令 检查 Ansible 执行是否成功 确认 PostgreSQL 已重载: psql -c "SELECT pg_reload_conf()"
检查配置文件是否更新: head -20 /pg/data/pg_hba.conf
规则顺序问题 HBA 是首条匹配生效,如果规则未按预期工作:
检查 order 值 使用 psql -c "TABLE pg_hba_file_rules" 查看实际顺序 调整 order 值或规则位置 在线修改 HBA(不推荐) 虽然可以直接编辑 /pg/data/pg_hba.conf 并重载,但不推荐 这样做:
# 直接编辑(不推荐)
vi /pg/data/pg_hba.conf
# 重载配置
psql -c "SELECT pg_reload_conf()"
# 或
pg_ctl reload -D /pg/data
# 或
systemctl reload postgresql
问题 :下次执行 Ansible playbook 时,手动修改会被覆盖。
正确做法 :始终在 pigsty.yml 中修改,然后执行 bin/pgsql-hba 刷新。
Pgbouncer HBA 管理 Pgbouncer 的 HBA 管理与 PostgreSQL 类似,但有一些差异:
配置差异 配置文件:/etc/pgbouncer/pgb_hba.conf 不支持 db: replication 认证方式:本地连接使用 peer 而非 ident 刷新命令 # 仅刷新 Pgbouncer HBA
./pgsql.yml -l pg-meta -t pgbouncer_hba,pgbouncer_reload
# 或使用统一脚本(同时刷新 PostgreSQL 和 Pgbouncer)
bin/pgsql-hba pg-meta
查看 Pgbouncer HBA cat /etc/pgbouncer/pgb_hba.conf
最佳实践 始终在配置文件中管理 :不要直接编辑 pg_hba.conf,所有变更通过 pigsty.yml测试环境先验证 :HBA 变更可能导致连接问题,先在测试环境验证使用 order 控制优先级 :黑名单规则使用 order: 0,确保优先匹配及时刷新 :添加/删除实例、主从切换后及时刷新 HBA最小权限原则 :只开放必要的访问,避免使用 addr: world + auth: trust监控认证失败 :关注 pg_stat_activity 中的认证失败记录备份配置 :重要变更前备份 pigsty.yml相关命令速查 # 刷新 HBA(推荐)
bin/pgsql-hba <cluster>
# 查看 PostgreSQL HBA
psql -c "TABLE pg_hba_file_rules"
cat /pg/data/pg_hba.conf
# 查看 Pgbouncer HBA
cat /etc/pgbouncer/pgb_hba.conf
# 重载 PostgreSQL 配置
psql -c "SELECT pg_reload_conf()"
# 测试连接
psql -h <host> -U <user> -d <db> -c "SELECT 1"
# 查看认证失败日志
tail -f /pg/log/postgresql-*.log | grep -i auth
相关文档 11.8.3 - 常用预案 Pigsty 中常用的 PostgreSQL 管理预案,用于维护生产环境中的数据库集群。
本文整理了 Pigsty 中常用的 PostgreSQL 管理预案,用于维护生产环境中的数据库集群。
以下是常见 PostgreSQL 管理任务的标准操作程序:
命令速查 PGSQL 剧本与快捷方式:
bin/pgsql-add <cls> # 创建 pgsql 集群 <cls>
bin/pgsql-user <cls> <username> # 在 <cls> 上创建 pg 用户 <username>
bin/pgsql-db <cls> <dbname> # 在 <cls> 上创建 pg 数据库 <dbname>
bin/pgsql-svc <cls> [ ...ip] # 重新加载集群 <cls> 的 pg 服务
bin/pgsql-hba <cls> [ ...ip] # 重新加载集群 <cls> 的 postgres/pgbouncer HBA 规则
bin/pgsql-add <cls> [ ...ip] # 为集群 <cls> 添加从库副本
bin/pgsql-rm <cls> [ ...ip] # 从集群 <cls> 移除实例
bin/pgsql-rm <cls> # 删除 pgsql 集群 <cls>
Patroni 管理命令与快捷方式:
pg list <cls> # 打印集群信息
pg edit-config <cls> # 编辑集群配置
pg reload <cls> [ ins] # 重新加载集群配置
pg restart <cls> [ ins] # 重启 PostgreSQL 集群
pg reinit <cls> [ ins] # 重新初始化集群成员
pg pause <cls> # 进入维护模式(自动故障转移暂停)
pg resume <cls> # 退出维护模式
pg switchover <cls> # 在集群 <cls> 上进行主动主从切换(主库健康)
pg failover <cls> # 在集群 <cls> 上进行故障转移(主库故障)
pgBackRest 备份/恢复命令与快捷方式:
pb info # 打印 pgbackrest 备份仓库信息
pg-backup # 进行备份,默认进行增量备份,如果没有完整备份过就做全量备份
pg-backup full # 进行全量备份
pg-backup diff # 进行差异备份
pg-backup incr # 进行增量备份
pg-pitr -i # 恢复到最近备份完成的时间(不常用)
pg-pitr --time= "2022-12-30 14:44:44+08" # 恢复到特定时间点(如在删除数据库或表的情况下)
pg-pitr --name= "my-restore-point" # 恢复到由 pg_create_restore_point 创建的命名还原点
pg-pitr --lsn= "0/7C82CB8" -X # 恢复到 LSN 之前
pg-pitr --xid= "1234567" -X -P # 恢复到特定的事务ID之前,然后将其提升为主库
pg-pitr --backup= latest # 恢复到最新的备份集
pg-pitr --backup= 20221108-105325 # 恢复到特定的备份集,使用名称指定,可以使用 pgbackrest info 进行检查
使用 Systemd 管理系统组件的命令:
systemctl stop patroni # 启动 停止 重启 重载
systemctl stop pgbouncer # 启动 停止 重启 重载
systemctl stop pg_exporter # 启动 停止 重启 重载
systemctl stop pgbouncer_exporter # 启动 停止 重启 重载
systemctl stop node_exporter # 启动 停止 重启
systemctl stop haproxy # 启动 停止 重启 重载
systemctl stop vip-manager # 启动 停止 重启 重载
systemctl stop postgres # 仅当 patroni_mode == 'remove' 时使用这个服务
创建集群 要创建一个新的Postgres集群,请首先在配置清单中定义,然后进行初始化:
bin/node-add <cls> # 为集群 <cls> 初始化节点 # ./node.yml -l <cls>
bin/pgsql-add <cls> # 初始化集群 <cls> 的pgsql实例 # ./pgsql.yml -l <cls>
请注意,PGSQL 模块需要在 Pigsty 纳管的节点上安装,请先使用 bin/node-add 纳管节点。
示例:创建集群
创建用户 要在现有的Postgres集群上创建一个新的业务用户,请将用户定义添加到 all.children.<cls>.pg_users,然后使用以下命令将其创建:
bin/pgsql-user <cls> <username> # ./pgsql-user.yml -l <cls> -e username=<username>
示例:创建业务用户
创建数据库 要在现有的Postgres集群上创建一个新的数据库用户,请将数据库定义添加到 all.children.<cls>.pg_databases,然后按照以下方式创建数据库:
bin/pgsql-db <cls> <dbname> # ./pgsql-db.yml -l <cls> -e dbname=<dbname>
注意:如果数据库指定了一个非默认的属主,该属主用户应当已存在,否则您必须先创建用户 。
示例:创建业务数据库
重载服务 服务 是 PostgreSQL 对外提供能力的访问点(PGURL可达),由主机节点上的 HAProxy 对外暴露。
当集群成员发生变化时使用此任务,例如:添加 /移除 副本,主从切换 /故障转移 / 暴露新服务,或更新现有服务的配置(例如,LB权重)
要在整个代理集群,或特定实例上创建新服务或重新加载现有服务:
bin/pgsql-svc <cls> # pgsql.yml -l <cls> -t pg_service -e pg_reload=true
bin/pgsql-svc <cls> [ ip...] # pgsql.yml -l ip... -t pg_service -e pg_reload=true
示例:重载PG服务以踢除一个实例
重载HBA 当您的 Postgres/Pgbouncer HBA 规则发生更改时,您 可能 需要重载 HBA 以应用更改。
如果您有任何特定于角色的 HBA 规则,或者在IP地址段中引用了集群成员的别名,那么当主从切换/集群扩缩容后也可能需要重载HBA。
要在整个集群或特定实例上重新加载 postgres 和 pgbouncer 的 HBA 规则:
bin/pgsql-hba <cls> # pgsql.yml -l <cls> -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload -e pg_reload=true
bin/pgsql-hba <cls> [ ip...] # pgsql.yml -l ip... -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload -e pg_reload=true
示例:重载集群 HBA 规则
配置集群 要更改现有的 Postgres 集群配置,您需要在管理节点 上使用管理员用户 (安装Pigsty的用户,nopass ssh/sudo)发起控制命令:
另一种方式是在数据库集群中的任何节点上,使用 dbsu (默认为 postgres) ,也可以执行管理命令,但只能管理本集群。
pg edit-config <cls> # interactive config a cluster with patronictl
更改 patroni 参数和 postgresql.parameters,根据提示保存并应用更改即可。
示例:非交互式方式配置集群 您可以跳过交互模式,并使用 -p 选项覆盖 postgres 参数,例如:
pg edit-config -p log_min_duration_statement = 1000 pg-test
pg edit-config --force -p shared_preload_libraries = 'timescaledb, pg_cron, pg_stat_statements, auto_explain'
示例:使用 Patroni REST API 更改集群配置 您还可以使用 Patroni REST API 以非交互式方式更改配置,例如:
$ curl -s 10.10.10.11:8008/config | jq . # get current config
$ curl -u 'postgres:Patroni.API' \
-d '{"postgresql":{"parameters": {"log_min_duration_statement":200}}}' \
-s -X PATCH http://10.10.10.11:8008/config | jq .
注意:Patroni 敏感API(例如重启等) 访问仅限于从基础设施/管理节点发起,并且有 HTTP 基本认证(用户名/密码)以及可选的 HTTPS 保护。
示例:使用 patronictl 配置集群
添加实例 若要将新从库添加到现有的 PostgreSQL 集群中,您需要将其定义添加到配置清单:all.children.<cls>.hosts 中,然后:
bin/node-add <ip> # 将节点 <ip> 纳入 Pigsty 管理
bin/pgsql-add <cls> <ip> # 初始化 <ip> ,作为集群 <cls> 的新从库
这将会把节点 <ip> 添加到 pigsty 并将其初始化为集群 <cls> 的一个副本。
集群服务将会重新加载 以接纳新成员。
示例:为 pg-test 添加从库
例如,如果您想将 pg-test-3 / 10.10.10.13 添加到现有的集群 pg-test,您首先需要更新配置清单:
pg-test:
hosts:
10.10.10.11: { pg_seq: 1, pg_role: primary } # 已存在的成员
10.10.10.12: { pg_seq: 2, pg_role: replica } # 已存在的成员
10.10.10.13: { pg_seq: 3, pg_role: replica } # <--- 新成员
vars: { pg_cluster: pg-test }
然后按如下方式应用更改:
bin/node-add 10.10.10.13 # 将节点添加到 pigsty
bin/pgsql-add pg-test 10.10.10.13 # 在 10.10.10.13 上为集群 pg-test 初始化新的副本
这与集群初始化相似,但只在单个实例上工作:
[ OK ] 初始化实例 10.10.10.11 到 pgsql 集群 'pg-test' 中:
[ WARN] 提醒:先将节点添加到 pigsty 中,然后再安装模块 'pgsql'
[ HINT] $ bin/node-add 10.10.10.11 # 除 infra 节点外,先运行此命令
[ WARN] 从集群初始化实例:
[ OK ] $ ./pgsql.yml -l '10.10.10.11,&pg-test'
[ WARN] 重新加载现有实例上的 pg_service:
[ OK ] $ ./pgsql.yml -l 'pg-test,!10.10.10.11' -t pg_service
移除实例 若要从现有的 PostgreSQL 集群中移除副本:
bin/pgsql-rm <cls> <ip...> # ./pgsql-rm.yml -l <ip>
这将从集群 <cls> 中移除实例 <ip>。 集群服务将会重新加载 以从负载均衡器中踢除已移除的实例。
示例:从 pg-test 移除从库
例如,如果您想从现有的集群 pg-test 中移除 pg-test-3 / 10.10.10.13:
bin/pgsql-rm pg-test 10.10.10.13 # 从 pg-test 中移除 pgsql 实例 10.10.10.13
bin/node-rm 10.10.10.13 # 从 pigsty 中移除该节点(可选)
vi pigsty.yml # 从目录中移除实例定义
bin/pgsql-svc pg-test # 刷新现有实例上的 pg_service,以从负载均衡器中踢除已移除的实例
[ OK ] 从 'pg-test' 移除 10.10.10.13 的 pgsql 实例:
[ WARN] 从集群中移除实例:
[ OK ] $ ./pgsql-rm.yml -l '10.10.10.13,&pg-test'
并从配置清单中移除实例定义:
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : replica } # <--- 执行后移除此行
vars : { pg_cluster : pg-test }
最后,您可以重载PG服务 并从负载均衡器中踢除已移除的实例:
bin/pgsql-svc pg-test # 重载 pg-test 上的服务
下线集群 要移除整个 Postgres 集群,只需运行:
bin/pgsql-rm <cls> # ./pgsql-rm.yml -l <cls>
示例:移除集群
示例:强制移除集群 注意:如果为这个集群配置了pg_safeguard (或全局设置为 true),pgsql-rm.yml 将中止,以避免意外移除集群。
您可以使用 playbook 命令行参数明确地覆盖它,以强制执行清除:
./pgsql-rm.yml -l pg-meta -e pg_safeguard = false # 强制移除 pg 集群 pg-meta
主动切换 您可以使用 patroni 命令行工具执行 PostgreSQL 集群的切换操作。
pg switchover <cls> # 交互模式,您可以使用下面的参数组合直接跳过此交互向导
pg switchover --leader pg-test-1 --candidate= pg-test-2 --scheduled= now --force pg-test
示例:pg-test 主从切换
$ pg switchover pg-test
Master [ pg-test-1] :
Candidate [ 'pg-test-2' , 'pg-test-3' ] [] : pg-test-2
When should the switchover take place ( e.g. 2022-12-26T07:39 ) [ now] : now
Current cluster topology
+ Cluster: pg-test ( 7181325041648035869) -----+----+-----------+-----------------+
| Member | Host | Role | State | TL | Lag in MB | Tags |
+-----------+-------------+---------+---------+----+-----------+-----------------+
| pg-test-1 | 10.10.10.11 | Leader | running | 1 | | clonefrom: true |
| | | | | | | conf: tiny.yml |
| | | | | | | spec: 1C.2G.50G |
| | | | | | | version: '15' |
+-----------+-------------+---------+---------+----+-----------+-----------------+
| pg-test-2 | 10.10.10.12 | Replica | running | 1 | 0 | clonefrom: true |
| | | | | | | conf: tiny.yml |
| | | | | | | spec: 1C.2G.50G |
| | | | | | | version: '15' |
+-----------+-------------+---------+---------+----+-----------+-----------------+
| pg-test-3 | 10.10.10.13 | Replica | running | 1 | 0 | clonefrom: true |
| | | | | | | conf: tiny.yml |
| | | | | | | spec: 1C.2G.50G |
| | | | | | | version: '15' |
+-----------+-------------+---------+---------+----+-----------+-----------------+
Are you sure you want to switchover cluster pg-test, demoting current master pg-test-1? [ y/N] : y
2022-12-26 06:39:58.02468 Successfully switched over to "pg-test-2"
+ Cluster: pg-test ( 7181325041648035869) -----+----+-----------+-----------------+
| Member | Host | Role | State | TL | Lag in MB | Tags |
+-----------+-------------+---------+---------+----+-----------+-----------------+
| pg-test-1 | 10.10.10.11 | Replica | stopped | | unknown | clonefrom: true |
| | | | | | | conf: tiny.yml |
| | | | | | | spec: 1C.2G.50G |
| | | | | | | version: '15' |
+-----------+-------------+---------+---------+----+-----------+-----------------+
| pg-test-2 | 10.10.10.12 | Leader | running | 1 | | clonefrom: true |
| | | | | | | conf: tiny.yml |
| | | | | | | spec: 1C.2G.50G |
| | | | | | | version: '15' |
+-----------+-------------+---------+---------+----+-----------+-----------------+
| pg-test-3 | 10.10.10.13 | Replica | running | 1 | 0 | clonefrom: true |
| | | | | | | conf: tiny.yml |
| | | | | | | spec: 1C.2G.50G |
| | | | | | | version: '15' |
+-----------+-------------+---------+---------+----+-----------+-----------------+
要通过 Patroni API 来执行此操作(例如,在指定时间将主库从 2号实例 切换到 1号实例)
curl -u 'postgres:Patroni.API' \
-d '{"leader":"pg-test-2", "candidate": "pg-test-1","scheduled_at":"2022-12-26T14:47+08"}' \
-s -X POST http://10.10.10.11:8008/switchover
无论是主动切换还是故障切换,您都需要在集群成员身份发生变化后,重新刷新服务与HBA规则。您应当在变更发生后及时(例如几个小时,一天内),完成此操作:
bin/pgsql-svc <cls>
bin/pgsql-hba <cls>
备份集群 使用 pgBackRest 创建备份,需要以本地 dbsu (默认为 postgres)的身份运行以下命令:
pg-backup # 执行备份,如有必要,执行增量或全量备份
pg-backup full # 执行全量备份
pg-backup diff # 执行差异备份
pg-backup incr # 执行增量备份
pb info # 打印备份信息 (pgbackrest info)
参阅备份恢复 获取更多信息。
示例:创建备份
示例:创建定时备份任务 您可以将 crontab 添加到 node_crontab 以指定您的备份策略。
# 每天凌晨1点做一次全备份
- '00 01 * * * postgres /pg/bin/pg-backup full'
# 周一凌晨1点进全量备份,其他工作日进行增量备份
- '00 01 * * 1 postgres /pg/bin/pg-backup full'
- '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
恢复集群 要将集群恢复到先前的时间点 (PITR),请以本地 dbsu 用户(默认为postgres)运行 Pigsty 提供的辅助脚本 pg-pitr
pg-pitr -i # 恢复到最近备份完成的时间(不常用)
pg-pitr --time= "2022-12-30 14:44:44+08" # 恢复到指定的时间点(在删除数据库或表的情况下使用)
pg-pitr --name= "my-restore-point" # 恢复到使用 pg_create_restore_point 创建的命名恢复点
pg-pitr --lsn= "0/7C82CB8" -X # 在LSN之前立即恢复
pg-pitr --xid= "1234567" -X -P # 在指定的事务ID之前立即恢复,然后将集群直接提升为主库
pg-pitr --backup= latest # 恢复到最新的备份集
pg-pitr --backup= 20221108-105325 # 恢复到特定备份集,备份集可以使用 pgbackrest info 列出
该命令会输出操作手册,请按照说明进行操作。查看备份恢复-PITR 获取详细信息。
示例:使用原始pgBackRest命令进行 PITR # 恢复到最新可用的点(例如硬件故障)
pgbackrest --stanza= pg-meta restore
# PITR 到特定的时间点(例如意外删除表)
pgbackrest --stanza= pg-meta --type= time --target= "2022-11-08 10:58:48" \
--target-action= promote restore
# 恢复特定的备份点,然后提升(或暂停|关闭)
pgbackrest --stanza= pg-meta --type= immediate --target-action= promote \
--set= 20221108-105325F_20221108-105938I restore
添加软件 要添加新版本的 RPM 包,你需要将它们加入到 repo_packages 和 repo_url_packages 中。
使用 ./infra.yml -t repo_build 子任务在 Infra 节点上重新构建本地软件仓库。然后,你可以使用 ansible 的 package 模块安装这些包:
ansible pg-test -b -m package -a "name=pg_cron_15,topn_15,pg_stat_monitor_15*" # 使用 ansible 安装一些包
示例:手动更本地新软件源中的包 # 在基础设施/管理节点上添加上游软件仓库,然后手工下载所需的软件包
cd ~/pigsty; ./infra.yml -t repo_upstream,repo_cache # 添加上游仓库(互联网)
cd /www/pigsty; repotrack "some_new_package_name" # 下载最新的 RPM 包
# 更新本地软件仓库元数据
cd ~/pigsty; ./infra.yml -t repo_create # 重新创建本地软件仓库
./node.yml -t node_repo # 刷新所有节点上的 YUM/APT 缓存
# 也可以使用 Ansible 手工刷新节点上的 YUM/APT 缓存
ansible all -b -a 'yum clean all' # 清理节点软件仓库缓存
ansible all -b -a 'yum makecache' # 从新的仓库重建yum/apt缓存
ansible all -b -a 'apt clean' # 清理 APT 缓存(Ubuntu/Debian)
ansible all -b -a 'apt update' # 重建 APT 缓存(Ubuntu/Debian)
例如,你可以使用以下方式安装或升级包:
ansible pg-test -b -m package -a "name=postgresql15* state=latest"
安装扩展 如果你想在 PostgreSQL 集群上安装扩展,请将它们加入到 pg_extensions 中,并执行:
./pgsql.yml -t pg_extension # 安装扩展
一部分扩展需要在 shared_preload_libraries 中加载后才能生效。你可以将它们加入到 pg_libs 中,或者配置 一个已有的集群。
最后,在集群的主库上执行 CREATE EXTENSION <extname>; 来完成扩展的安装。
示例:在 pg-test 集群上安装 pg_cron 扩展 ansible pg-test -b -m package -a "name=pg_cron_15" # 在所有节点上安装 pg_cron 包
# 将 pg_cron 添加到 shared_preload_libraries 中
pg edit-config --force -p shared_preload_libraries = 'timescaledb, pg_cron, pg_stat_statements, auto_explain'
pg restart --force pg-test # 重新启动集群
psql -h pg-test -d postgres -c 'CREATE EXTENSION pg_cron;' # 在主库上安装 pg_cron
更多细节,请参考PGSQL扩展安装 。
小版本升级 要执行小版本的服务器升级/降级,您首先需要在本地软件仓库中添加软件 :最新的PG小版本 RPM/DEB。
首先对所有从库执行滚动升级/降级,然后执行集群主从切换 以升级/降级主库。
ansible <cls> -b -a "yum upgrade/downgrade -y <pkg>" # 升级/降级软件包
pg restart --force <cls> # 重启集群
示例:将PostgreSQL 15.2降级到15.1 将15.1的包添加到软件仓库并刷新节点的 yum/apt 缓存:
cd ~/pigsty; ./infra.yml -t repo_upstream # 添加上游仓库
cd /www/pigsty; repotrack postgresql15-*-15.1 # 将15.1的包添加到yum仓库
cd ~/pigsty; ./infra.yml -t repo_create # 重建仓库元数据
ansible pg-test -b -a 'yum clean all' # 清理节点仓库缓存
ansible pg-test -b -a 'yum makecache' # 从新仓库重新生成yum缓存
# 对于 Ubutnu/Debian 用户,使用 apt 替换 yum
ansible pg-test -b -a 'apt clean' # 清理节点仓库缓存
ansible pg-test -b -a 'apt update' # 从新仓库重新生成apt缓存
执行降级并重启集群:
ansible pg-test -b -a "yum downgrade -y postgresql15*" # 降级软件包)
pg restart --force pg-test # 重启整个集群以完成升级
示例:将PostgreSQL 15.1升级回15.2 这次我们采用滚动方式升级:
ansible pg-test -b -a "yum upgrade -y postgresql15*" # 升级软件包(或 apt upgrade)
ansible pg-test -b -a '/usr/pgsql/bin/pg_ctl --version' # 检查二进制版本是否为15.2
pg restart --role replica --force pg-test # 重启从库
pg switchover --leader pg-test-1 --candidate= pg-test-2 --scheduled= now --force pg-test # 切换主从
pg restart --role primary --force pg-test # 重启主库
大版本升级 实现大版本升级的最简单办法是:创建一个使用新版本的新集群,然后通过逻辑复制,蓝绿部署,并进行在线迁移 。
您也可以进行原地大版本升级,当您只使用数据库内核本身时,这并不复杂,使用 PostgreSQL 自带的 pg_upgrade 即可:
假设您想将 PostgreSQL 大版本从 14 升级到 15,您首先需要在仓库中添加软件 ,并确保两个大版本两侧安装的核心扩展插件也具有相同的版本号。
./pgsql.yml -t pg_pkg -e pg_version = 15 # 安装pg 15的包
sudo su - postgres; mkdir -p /data/postgres/pg-meta-15/data/ # 为15准备目录
pg_upgrade -b /usr/pgsql-14/bin/ -B /usr/pgsql-15/bin/ -d /data/postgres/pg-meta-14/data/ -D /data/postgres/pg-meta-15/data/ -v -c # 预检
pg_upgrade -b /usr/pgsql-14/bin/ -B /usr/pgsql-15/bin/ -d /data/postgres/pg-meta-14/data/ -D /data/postgres/pg-meta-15/data/ --link -j8 -v -c
rm -rf /usr/pgsql; ln -s /usr/pgsql-15 /usr/pgsql; # 修复二进制链接
mv /data/postgres/pg-meta-14 /data/postgres/pg-meta-15 # 重命名数据目录
rm -rf /pg; ln -s /data/postgres/pg-meta-15 /pg # 修复数据目录链接
11.8.4 - 集群管理 创建/销毁 PostgreSQL 集群,以及对现有集群进行扩容与缩容的标准操作指南。
创建集群 要创建一个新的Postgres集群,请首先在配置清单中定义,然后进行初始化:
bin/node-add <cls> # 为集群 <cls> 初始化节点 # ./node.yml -l <cls>
bin/pgsql-add <cls> # 初始化集群 <cls> 的pgsql实例 # ./pgsql.yml -l <cls>
请注意,PGSQL 模块需要在 Pigsty 纳管的节点上安装,请先使用 bin/node-add 纳管节点。
示例:创建集群
创建用户 要在现有的Postgres集群上创建一个新的业务用户,请将用户定义添加到 all.children.<cls>.pg_users,然后使用以下命令将其创建:
bin/pgsql-user <cls> <username> # ./pgsql-user.yml -l <cls> -e username=<username>
示例:创建业务用户
创建数据库 要在现有的Postgres集群上创建一个新的数据库用户,请将数据库定义添加到 all.children.<cls>.pg_databases,然后按照以下方式创建数据库:
bin/pgsql-db <cls> <dbname> # ./pgsql-db.yml -l <cls> -e dbname=<dbname>
注意:如果数据库指定了一个非默认的属主,该属主用户应当已存在,否则您必须先创建用户 。
示例:创建业务数据库
重载服务 服务 是 PostgreSQL 对外提供能力的访问点(PGURL可达),由主机节点上的 HAProxy 对外暴露。
当集群成员发生变化时使用此任务,例如:添加 /移除 副本,主从切换 /故障转移 / 暴露新服务,或更新现有服务的配置(例如,LB权重)
要在整个代理集群,或特定实例上创建新服务或重新加载现有服务:
bin/pgsql-svc <cls> # pgsql.yml -l <cls> -t pg_service -e pg_reload=true
bin/pgsql-svc <cls> [ ip...] # pgsql.yml -l ip... -t pg_service -e pg_reload=true
示例:重载PG服务以踢除一个实例
重载HBA 当您的 Postgres/Pgbouncer HBA 规则发生更改时,您 可能 需要重载 HBA 以应用更改。
如果您有任何特定于角色的 HBA 规则,或者在IP地址段中引用了集群成员的别名,那么当主从切换/集群扩缩容后也可能需要重载HBA。
要在整个集群或特定实例上重新加载 postgres 和 pgbouncer 的 HBA 规则:
bin/pgsql-hba <cls> # pgsql.yml -l <cls> -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload -e pg_reload=true
bin/pgsql-hba <cls> [ ip...] # pgsql.yml -l ip... -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload -e pg_reload=true
示例:重载集群 HBA 规则
配置集群 要更改现有的 Postgres 集群配置,您需要在管理节点 上使用管理员用户 (安装Pigsty的用户,nopass ssh/sudo)发起控制命令:
另一种方式是在数据库集群中的任何节点上,使用 dbsu (默认为 postgres) ,也可以执行管理命令,但只能管理本集群。
pg edit-config <cls> # interactive config a cluster with patronictl
更改 patroni 参数和 postgresql.parameters,根据提示保存并应用更改即可。
示例:非交互式方式配置集群 您可以跳过交互模式,并使用 -p 选项覆盖 postgres 参数,例如:
pg edit-config -p log_min_duration_statement = 1000 pg-test
pg edit-config --force -p shared_preload_libraries = 'timescaledb, pg_cron, pg_stat_statements, auto_explain'
示例:使用 Patroni REST API 更改集群配置 您还可以使用 Patroni REST API 以非交互式方式更改配置,例如:
$ curl -s 10.10.10.11:8008/config | jq . # get current config
$ curl -u 'postgres:Patroni.API' \
-d '{"postgresql":{"parameters": {"log_min_duration_statement":200}}}' \
-s -X PATCH http://10.10.10.11:8008/config | jq .
注意:Patroni 敏感API(例如重启等) 访问仅限于从基础设施/管理节点发起,并且有 HTTP 基本认证(用户名/密码)以及可选的 HTTPS 保护。
示例:使用 patronictl 配置集群
添加实例 若要将新从库添加到现有的 PostgreSQL 集群中,您需要将其定义添加到配置清单:all.children.<cls>.hosts 中,然后:
bin/node-add <ip> # 将节点 <ip> 纳入 Pigsty 管理
bin/pgsql-add <cls> <ip> # 初始化 <ip> ,作为集群 <cls> 的新从库
这将会把节点 <ip> 添加到 pigsty 并将其初始化为集群 <cls> 的一个副本。
集群服务将会重新加载 以接纳新成员。
示例:为 pg-test 添加从库
例如,如果您想将 pg-test-3 / 10.10.10.13 添加到现有的集群 pg-test,您首先需要更新配置清单:
pg-test:
hosts:
10.10.10.11: { pg_seq: 1, pg_role: primary } # 已存在的成员
10.10.10.12: { pg_seq: 2, pg_role: replica } # 已存在的成员
10.10.10.13: { pg_seq: 3, pg_role: replica } # <--- 新成员
vars: { pg_cluster: pg-test }
然后按如下方式应用更改:
bin/node-add 10.10.10.13 # 将节点添加到 pigsty
bin/pgsql-add pg-test 10.10.10.13 # 在 10.10.10.13 上为集群 pg-test 初始化新的副本
这与集群初始化相似,但只在单个实例上工作:
[ OK ] 初始化实例 10.10.10.11 到 pgsql 集群 'pg-test' 中:
[ WARN] 提醒:先将节点添加到 pigsty 中,然后再安装模块 'pgsql'
[ HINT] $ bin/node-add 10.10.10.11 # 除 infra 节点外,先运行此命令
[ WARN] 从集群初始化实例:
[ OK ] $ ./pgsql.yml -l '10.10.10.11,&pg-test'
[ WARN] 重新加载现有实例上的 pg_service:
[ OK ] $ ./pgsql.yml -l 'pg-test,!10.10.10.11' -t pg_service
移除实例 若要从现有的 PostgreSQL 集群中移除副本:
bin/pgsql-rm <cls> <ip...> # ./pgsql-rm.yml -l <ip>
这将从集群 <cls> 中移除实例 <ip>。 集群服务将会重新加载 以从负载均衡器中踢除已移除的实例。
示例:从 pg-test 移除从库
例如,如果您想从现有的集群 pg-test 中移除 pg-test-3 / 10.10.10.13:
bin/pgsql-rm pg-test 10.10.10.13 # 从 pg-test 中移除 pgsql 实例 10.10.10.13
bin/node-rm 10.10.10.13 # 从 pigsty 中移除该节点(可选)
vi pigsty.yml # 从目录中移除实例定义
bin/pgsql-svc pg-test # 刷新现有实例上的 pg_service,以从负载均衡器中踢除已移除的实例
[ OK ] 从 'pg-test' 移除 10.10.10.13 的 pgsql 实例:
[ WARN] 从集群中移除实例:
[ OK ] $ ./pgsql-rm.yml -l '10.10.10.13,&pg-test'
并从配置清单中移除实例定义:
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role : primary }
10.10.10.12 : { pg_seq: 2, pg_role : replica }
10.10.10.13 : { pg_seq: 3, pg_role : replica } # <--- 执行后移除此行
vars : { pg_cluster : pg-test }
最后,您可以重载PG服务 并从负载均衡器中踢除已移除的实例:
bin/pgsql-svc pg-test # 重载 pg-test 上的服务
下线集群 要移除整个 Postgres 集群,只需运行:
bin/pgsql-rm <cls> # ./pgsql-rm.yml -l <cls>
示例:移除集群
示例:强制移除集群 注意:如果为这个集群配置了pg_safeguard (或全局设置为 true),pgsql-rm.yml 将中止,以避免意外移除集群。
您可以使用 playbook 命令行参数明确地覆盖它,以强制执行清除:
./pgsql-rm.yml -l pg-meta -e pg_safeguard = false # 强制移除 pg 集群 pg-meta
11.8.5 - 用户管理 用户管理:创建、修改、删除用户,管理角色成员关系,连接池用户配置
在 Pigsty 中,用户管理采用 IaC 的风格,先在配置清单中定义,然后执行剧本执行。
执行 pgsql-user.yml 剧本是幂等的。它会将指定集群中的指定用户调整至配置清单中的目标状态。
请注意,用户的所有属性都可以通过重新执行剧本进行修改,剧本是幂等的。
定义用户 Pigsty通过两个配置参数定义数据库集群中的角色与用户:
前者用于定义了整套环境中共用的角色与用户,后者定义单个集群中特有的业务角色与用户。二者形式相同,均为用户定义对象的数组。
下面是 Pigsty 演示环境中默认集群 pg-meta 中的业务用户定义:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name: postgis, schema : public}, {name: timescaledb}]}
- { name: grafana ,owner: dbuser_grafana ,revokeconn: true ,comment : grafana primary database }
- { name: bytebase ,owner: dbuser_bytebase ,revokeconn: true ,comment : bytebase primary database }
唯一必选的字段是 name,它应该是当前 PostgreSQL 集群中有效且唯一的用户名,其他参数都有合理的默认值。
关于用户定义参数的完整参考,请查阅 用户配置参考 。
创建用户 要在现有的 PostgreSQL 集群上创建新的业务用户,请将用户定义添加到 all.children.<cls>.pg_users,然后执行:
bin/pgsql-user <cls> <username> # 等效于:pgsql-user.yml -l <cls> -e username=<username>
示例:创建名为 dbuser_app 的业务用户
在配置文件中添加用户定义: pg-meta :
vars :
pg_users :
- name : dbuser_app
password : DBUser.App
pgbouncer : true
roles : [ dbrole_readwrite]
comment : application user for myapp
执行创建命令: bin/pgsql-user pg-meta dbuser_app
执行效果:
在主库上创建用户 dbuser_app 设置用户密码 授予 dbrole_readwrite 角色 将用户添加到 Pgbouncer 连接池用户列表 重载 Pgbouncer 配置使其生效 请使用剧本创建用户
不建议手工使用 SQL 创建业务用户,特别是需要使用 Pgbouncer 连接池时。
使用 bin/pgsql-user 工具创建用户会自动处理连接池配置。
示例:创建业务用户
修改用户 修改用户属性可以通过更新配置并重新执行剧本来完成:
bin/pgsql-user <cls> <username> # 幂等操作,可重复执行
不同于数据库,创建用户的剧本总是幂等的。当目标用户已经存在时,Pigsty会修改目标用户的属性使其符合配置。
可修改属性 所有用户属性都可以通过重新执行剧本进行修改:
属性 说明 示例 password用户密码 password: NewPasswordlogin是否允许登录 login: falsesuperuser是否为超级用户 superuser: truecreatedb是否可创建数据库 createdb: truecreaterole是否可创建角色 createrole: trueinherit是否继承角色权限 inherit: falsereplication是否可进行复制 replication: truebypassrls是否可绕过 RLS bypassrls: trueconnlimit连接数限制 connlimit: 100expire_in过期天数 expire_in: 30expire_at过期日期 expire_at: '2024-12-31'comment备注信息 comment: 新的备注roles角色成员(增量操作) 见管理角色成员 parameters角色级参数 见管理用户参数 pgbouncer是否加入连接池 pgbouncer: truepool_mode连接池模式 pool_mode: sessionpool_connlimit连接池连接限制 pool_connlimit: 50
修改密码 - name : dbuser_app
password : NewSecretPassword # 修改密码
bin/pgsql-user pg-meta dbuser_app
执行的 SQL:
SET log_statement TO 'none' ;
ALTER USER "dbuser_app" PASSWORD 'NewSecretPassword' ;
SET log_statement TO DEFAULT ;
注意 :密码修改时会临时禁用日志记录,避免密码泄露到日志中。
修改权限属性 - name : dbuser_app
createdb : true # 允许创建数据库
connlimit : 50 # 限制连接数
执行的 SQL:
ALTER USER "dbuser_app" CREATEDB ;
ALTER USER "dbuser_app" CONNECTION LIMIT 50 ;
修改备注 - name : dbuser_app
comment : '应用主账号 - 已更新'
执行的 SQL:
COMMENT ON ROLE "dbuser_app" IS '应用主账号 - 已更新' ;
删除用户 要删除用户,将其 state 设置为 absent 并执行剧本:
pg_users :
- name : dbuser_old
state : absent
bin/pgsql-user <cls> dbuser_old
删除操作会:
使用 DROP ROLE IF EXISTS 删除用户 从 Pgbouncer 用户列表中移除(如果之前添加过) 重载 Pgbouncer 配置 受保护的系统用户:
以下系统用户无法通过 state: absent 删除,会被自动跳过:
postgres(超级用户)replicator(或 pg_replication_username 配置的用户)dbuser_dba(或 pg_admin_username 配置的用户)dbuser_monitor(或 pg_monitor_username 配置的用户)危险操作警告
删除用户前请确保:
用户没有拥有任何数据库对象(表、视图、函数等) 用户没有被其他对象依赖(如默认权限) 没有活动连接正在使用该用户 如果用户拥有对象,需要先转移对象所有权或删除对象。
删除拥有对象的用户 如果用户拥有数据库对象,直接删除会失败。需要先处理其拥有的对象:
-- 查看用户拥有的对象
SELECT n . nspname as schema , c . relname as name , c . relkind as type
FROM pg_class c
JOIN pg_namespace n ON n . oid = c . relnamespace
JOIN pg_roles r ON r . oid = c . relowner
WHERE r . rolname = 'dbuser_old' ;
-- 转移对象所有权
REASSIGN OWNED BY dbuser_old TO dbuser_new ;
-- 或删除用户拥有的所有对象
DROP OWNED BY dbuser_old ;
处理完对象后,再执行剧本删除用户。
管理角色成员 角色成员关系通过 roles 数组配置,支持简单格式和扩展格式。
授予角色 - name : dbuser_app
roles :
- dbrole_readwrite
- pg_read_all_data
执行的 SQL:
GRANT "dbrole_readwrite" TO "dbuser_app" ;
GRANT "pg_read_all_data" TO "dbuser_app" ;
授予带选项的角色 使用对象格式可以指定更精细的授权选项:
- name : dbuser_admin
roles :
# 普通授予
- dbrole_readwrite
# 可以将此角色授予其他用户
- { name: dbrole_admin, admin : true }
# PG16+: 不能 SET ROLE 到此角色
- { name: pg_monitor, set : false }
# PG16+: 不自动继承此角色的权限
- { name: pg_execute_server_program, inherit : false }
生成的 SQL(PostgreSQL 16+):
GRANT "dbrole_readwrite" TO "dbuser_admin" ;
GRANT "dbrole_admin" TO "dbuser_admin" WITH ADMIN TRUE ;
GRANT "pg_monitor" TO "dbuser_admin" ;
REVOKE SET OPTION FOR "pg_monitor" FROM "dbuser_admin" ;
GRANT "pg_execute_server_program" TO "dbuser_admin" ;
REVOKE INHERIT OPTION FOR "pg_execute_server_program" FROM "dbuser_admin" ;
撤销角色成员关系 使用 state: absent 撤销角色成员关系:
- name : dbuser_app
roles :
- dbrole_readwrite # 保留此角色
- { name: old_role, state : absent } # 撤销此角色
执行的 SQL:
GRANT "dbrole_readwrite" TO "dbuser_app" ;
REVOKE "old_role" FROM "dbuser_app" ;
PostgreSQL 16+ 角色选项 PostgreSQL 16 引入了更细粒度的角色成员关系控制:
选项 说明 用途 adminADMIN OPTION 允许将角色授予其他用户 setSET OPTION 允许 SET ROLE 切换到该角色 inheritINHERIT OPTION 是否自动继承角色权限
注意 :set 和 inherit 选项仅在 PostgreSQL 16+ 中有效,在早期版本会被忽略并在生成的 SQL 中添加警告注释。
管理用户参数 用户级参数通过 parameters 字典配置,会生成 ALTER USER ... SET 语句。
设置参数 - name : dbuser_analyst
parameters :
work_mem : '256MB'
statement_timeout : '5min'
search_path : 'analytics,public'
执行的 SQL:
ALTER USER "dbuser_analyst" SET "work_mem" = '256MB' ;
ALTER USER "dbuser_analyst" SET "statement_timeout" = '5min' ;
ALTER USER "dbuser_analyst" SET "search_path" = 'analytics,public' ;
重置参数为默认值 使用特殊值 DEFAULT(大小写不敏感)将参数重置为 PostgreSQL 默认值:
- name : dbuser_app
parameters :
work_mem : DEFAULT # 重置为默认值
statement_timeout : DEFAULT
执行的 SQL:
ALTER USER "dbuser_app" SET "work_mem" = DEFAULT ;
ALTER USER "dbuser_app" SET "statement_timeout" = DEFAULT ;
常用用户级参数 参数 说明 示例值 work_mem查询工作内存 '64MB'statement_timeout语句超时时间 '30s'lock_timeout锁等待超时 '10s'idle_in_transaction_session_timeout空闲事务超时 '10min'search_pathSchema 搜索路径 'app,public'log_statement日志记录级别 'ddl'temp_file_limit临时文件大小限制 '10GB'
管理用户有效期 设置相对过期时间 使用 expire_in 设置从当前日期起 N 天后过期:
- name : temp_user
expire_in : 30 # 30 天后过期
执行的 SQL(假设当前日期为 2024-01-15):
ALTER USER "temp_user" VALID UNTIL '2024-02-14' ;
注意 :每次执行剧本时会重新计算过期时间,适合需要定期续期的临时用户。
设置绝对过期时间 使用 expire_at 设置固定的过期日期:
- name : contractor_user
expire_at : '2024-12-31' # 指定日期过期
执行的 SQL:
ALTER USER "contractor_user" VALID UNTIL '2024-12-31' ;
设置永不过期 - name : permanent_user
expire_at : 'infinity' # 永不过期
执行的 SQL:
ALTER USER "permanent_user" VALID UNTIL 'infinity' ;
查看用户过期时间 SELECT rolname , rolvaliduntil
FROM pg_roles
WHERE rolvaliduntil IS NOT NULL
ORDER BY rolvaliduntil ;
连接池用户 默认情况下,所有带有 pgbouncer: true 标志的用户都会添加到 Pgbouncer 连接池中。
添加用户到连接池 - name : dbuser_app
password : DBUser.App
pgbouncer : true # 添加到连接池
pool_mode : transaction # 池化模式
pool_connlimit : 50 # 用户最大连接数
执行效果:
将用户添加到 /etc/pgbouncer/userlist.txt 如果指定了 pool_mode 或 pool_connlimit,添加到 /etc/pgbouncer/useropts.txt 重载 Pgbouncer 配置 连接池配置文件 用户列表 /etc/pgbouncer/userlist.txt:
"postgres" ""
"dbuser_app" "SCRAM-SHA-256$4096:xxx$yyy:zzz"
"dbuser_view" "SCRAM-SHA-256$4096:xxx$yyy:zzz"
用户选项 /etc/pgbouncer/useropts.txt:
dbuser_dba = pool_mode=session max_user_connections=16
dbuser_monitor = pool_mode=session max_user_connections=8
dbuser_app = pool_mode=transaction max_user_connections=50
池化模式说明 模式 说明 适用场景 transaction事务结束后归还连接(默认) 大多数 OLTP 应用 session会话结束后归还连接 需要会话状态的应用(如 DBA 操作) statement语句结束后归还连接 无状态简单查询
从连接池移除用户 当用户设置 state: absent 或 pgbouncer: false 时,会从连接池中移除。
- name : dbuser_old
state : absent # 删除用户时自动从连接池移除
或:
- name : dbuser_internal
pgbouncer : false # 仅从连接池移除,保留用户
使用 Auth Query 动态认证 如果启用了 pgbouncer_auth_query ,可以不在 userlist.txt 中维护用户,而是通过查询数据库动态认证。这种方式适合用户数量多、变动频繁的场景。
操作速查 常用命令 操作 命令 创建用户 bin/pgsql-user <cls> <username>修改用户 bin/pgsql-user <cls> <username>删除用户 设置 state: absent 后执行 bin/pgsql-user <cls> <username> 查看用户列表 psql -c '\du'查看用户详情 psql -c '\du+ <username>'查看连接池用户 cat /etc/pgbouncer/userlist.txt查看用户选项 cat /etc/pgbouncer/useropts.txt
常见操作示例 # 创建基本业务用户
- name : dbuser_app
password : DBUser.App
pgbouncer : true
roles : [ dbrole_readwrite]
comment : application user
# 创建只读用户
- name : dbuser_readonly
password : DBUser.Readonly
pgbouncer : true
roles : [ dbrole_readonly]
# 创建 DBA 用户(使用 session 模式)
- name : dbuser_dba
password : DBUser.DBA
pgbouncer : true
pool_mode : session
roles : [ dbrole_admin]
parameters :
log_statement : 'all'
# 创建临时用户(30天后过期)
- name : temp_contractor
password : TempPassword
expire_in : 30
roles : [ dbrole_readonly]
# 创建角色(不可登录)
- name : custom_role
login : false
comment : custom role for special permissions
# 创建带高级角色选项的用户(PG16+)
- name : dbuser_admin
password : DBUser.Admin
pgbouncer : true
roles :
- dbrole_readwrite
- { name: dbrole_admin, admin : true }
- { name: pg_monitor, set : false }
# 删除用户
- name : dbuser_old
state : absent
执行流程 bin/pgsql-user 执行时会依次:
验证 - 检查 username 参数和用户定义,验证用户名格式删除 (如果 state=absent)- 执行 DROP ROLE(跳过受保护的系统用户)创建/修改 - 执行 CREATE USER 或 ALTER USER设置密码 - 执行 ALTER USER PASSWORD(临时禁用日志)设置有效期 - 执行 ALTER USER VALID UNTIL设置连接限制 - 执行 ALTER USER CONNECTION LIMIT设置参数 - 执行 ALTER USER SET设置备注 - 执行 COMMENT ON ROLE授予角色 - 执行 GRANT/REVOKE 处理角色成员关系更新连接池 - 刷新 Pgbouncer 用户列表并重载SQL 查询参考 -- 查看所有用户
SELECT rolname , rolsuper , rolinherit , rolcreaterole , rolcreatedb ,
rolcanlogin , rolreplication , rolbypassrls , rolconnlimit , rolvaliduntil
FROM pg_roles
WHERE rolname NOT LIKE 'pg_%'
ORDER BY rolname ;
-- 查看用户的角色成员关系
SELECT r . rolname AS member , g . rolname AS role ,
m . admin_option , m . set_option , m . inherit_option
FROM pg_auth_members m
JOIN pg_roles r ON r . oid = m . member
JOIN pg_roles g ON g . oid = m . roleid
WHERE r . rolname = 'dbuser_app' ;
-- 查看用户级参数设置
SELECT rolname , setconfig
FROM pg_db_role_setting s
JOIN pg_roles r ON r . oid = s . setrole
WHERE s . setdatabase = 0 ; -- 0 表示用户级设置
-- 查看用户拥有的对象
SELECT n . nspname AS schema , c . relname AS name ,
CASE c . relkind
WHEN 'r' THEN 'table'
WHEN 'v' THEN 'view'
WHEN 'm' THEN 'materialized view'
WHEN 'i' THEN 'index'
WHEN 'S' THEN 'sequence'
WHEN 'f' THEN 'foreign table'
END AS type
FROM pg_class c
JOIN pg_namespace n ON n . oid = c . relnamespace
JOIN pg_roles r ON r . oid = c . relowner
WHERE r . rolname = 'dbuser_app'
AND n . nspname NOT IN ( 'pg_catalog' , 'information_schema' );
-- 查看即将过期的用户
SELECT rolname , rolvaliduntil ,
rolvaliduntil - CURRENT_TIMESTAMP AS time_remaining
FROM pg_roles
WHERE rolvaliduntil IS NOT NULL
AND rolvaliduntil < CURRENT_TIMESTAMP + INTERVAL '30 days'
ORDER BY rolvaliduntil ;
关于用户定义的完整参数参考,请参考 用户配置 一节。
关于用户的访问权限,请参考 ACL:角色权限 一节。
11.8.6 - 参数优化 调整 postgres 参数
Pigsty 默认提供了四套场景化参数模板,可以通过 pg_conf 参数指定并使用。
tiny.yml:为小节点、虚拟机、小型演示优化(1-8核,1-16GB)oltp.yml:为OLTP工作负载和延迟敏感应用优化(4C8GB+)(默认模板)olap.yml:为OLAP工作负载和吞吐量优化(4C8G+)crit.yml:为数据一致性和关键应用优化(4C8G+)Pigsty 会针对这四种默认场景,采取不同的参数优化策略,如下所示:
内存参数调整 Pigsty 默认会检测系统的内存大小,并以此为依据设定最大连接数量与内存相关参数。
默认情况下,Pigsty 使用 25% 的内存作为 PostgreSQL 共享缓冲区,剩余的 75% 作为操作系统缓存。
默认情况下,如果用户没有设置一个 pg_max_conn 最大连接数,Pigsty 会根据以下规则使用默认值:
oltp: 500 (pgbouncer) / 1000 (postgres) crit: 500 (pgbouncer) / 1000 (postgres) tiny: 300 olap: 300 其中对于 OLTP 与 CRIT 模版来说,如果服务没有指向 pgbouncer 连接池,而是直接连接 postgres 数据库,最大连接会翻倍至 1000 条。
决定最大连接数后,work_mem 会根据共享内存数量 / 最大连接数计算得到,并限定在 64MB ~ 1GB 的范围内。
{% raw %}
{% if pg_max_conn != 'auto' and pg_max_conn|int >= 20 %}{% set pg_max_connections = pg_max_conn|int %}{% else %}{% if pg_default_service_dest|default('postgres') == 'pgbouncer' %}{% set pg_max_connections = 500 %}{% else %}{% set pg_max_connections = 1000 %}{% endif %}{% endif %}
{% set pg_max_prepared_transactions = pg_max_connections if 'citus' in pg_libs else 0 %}
{% set pg_max_locks_per_transaction = (2 * pg_max_connections)|int if 'citus' in pg_libs or 'timescaledb' in pg_libs else pg_max_connections %}
{% set pg_shared_buffers = (node_mem_mb|int * pg_shared_buffer_ratio|float) | round(0, 'ceil') | int %}
{% set pg_maintenance_mem = (pg_shared_buffers|int * 0.25)|round(0, 'ceil')|int %}
{% set pg_effective_cache_size = node_mem_mb|int - pg_shared_buffers|int %}
{% set pg_workmem = ([ ([ (pg_shared_buffers / pg_max_connections)|round(0,'floor')|int , 64 ])|max|int , 1024])|min|int %}
{% endraw %}
CPU参数调整 在 PostgreSQL 中,有 4 个与并行查询相关的重要参数,Pigsty 会自动根据当前系统的 CPU 核数进行参数优化。
在所有策略中,总并行进程数量(总预算)通常设置为 CPU 核数 + 8,且保底为 16 个,从而为逻辑复制与扩展预留足够的后台 worker 数量,OLAP 和 TINY 模板根据场景略有不同。
OLTP 设置逻辑 范围限制 max_worker_processesmax(100% CPU + 8, 16) 核数 + 4,保底 12, max_parallel_workersmax(ceil(50% CPU), 2) 1/2 CPU 上取整,最少两个 max_parallel_maintenance_workersmax(ceil(33% CPU), 2) 1/3 CPU 上取整,最少两个 max_parallel_workers_per_gathermin(max(ceil(20% CPU), 2),8) 1/5 CPU 下取整,最少两个,最多 8 个
OLAP 设置逻辑 范围限制 max_worker_processesmax(100% CPU + 12, 20) 核数 + 12,保底 20, max_parallel_workersmax(ceil(80% CPU, 2)) 4/5 CPU 上取整,最少两个 max_parallel_maintenance_workersmax(ceil(33% CPU), 2) 1/3 CPU 上取整,最少两个 max_parallel_workers_per_gathermax(floor(50% CPU), 2) 1/2 CPU 上取整,最少两个
CRIT 设置逻辑 范围限制 max_worker_processesmax(100% CPU + 8, 16) 核数 + 8,保底 16, max_parallel_workersmax(ceil(50% CPU), 2) 1/2 CPU 上取整,最少两个 max_parallel_maintenance_workersmax(ceil(33% CPU), 2) 1/3 CPU 上取整,最少两个 max_parallel_workers_per_gather0, 按需启用
TINY 设置逻辑 范围限制 max_worker_processesmax(100% CPU + 4, 12) 核数 + 4,保底 12, max_parallel_workersmax(ceil(50% CPU) 1) 50% CPU 下取整,最少1个 max_parallel_maintenance_workersmax(ceil(33% CPU), 1) 33% CPU 下取整,最少1个 max_parallel_workers_per_gather0, 按需启用
请注意,CRIT 和 TINY 模板直接通过设置 max_parallel_workers_per_gather = 0 关闭了并行查询。
用户可以按需在需要时设置此参数以启用并行查询。
OLTP 和 CRIT 模板都额外设置了以下参数,将并行查询的 Cost x 2,以降低使用并行查询的倾向。
parallel_setup_cost : 2000 # double from 100 to increase parallel cost
parallel_tuple_cost : 0.2 # double from 0.1 to increase parallel cost
min_parallel_table_scan_size : 16MB # double from 8MB to increase parallel cost
min_parallel_index_scan_size : 1024 # double from 512 to increase parallel cost
请注意 max_worker_processes 参数的调整必须在重启后才能生效。此外,当从库的本参数配置值高于主库时,从库将无法启动。
此参数必须通过 patroni 配置管理进行调整,该参数由 Patroni 管理,用于确保主从配置一致,避免在故障切换时新从库无法启动。
存储空间参数 Pigsty 默认检测 /data/postgres 主数据目录所在磁盘的总空间,并以此作为依据指定下列参数:
{% raw %}
min_wal_size : {{ ([pg_size_twentieth, 200])|min }}GB # 1/20 disk size, max 200GB
max_wal_size : {{ ([pg_size_twentieth * 4, 2000])|min }}GB # 2/10 disk size, max 2000GB
max_slot_wal_keep_size : {{ ([pg_size_twentieth * 6, 3000])|min }}GB # 3/10 disk size, max 3000GB
temp_file_limit : {{ ([pg_size_twentieth, 200])|min }}GB # 1/20 of disk size, max 200GB
{% endraw %}
temp_file_limit 默认为磁盘空间的 5%,封顶不超过 200GB。min_wal_size 默认为磁盘空间的 5%,封顶不超过 200GB。max_wal_size 默认为磁盘空间的 20%,封顶不超过 2TB。max_slot_wal_keep_size 默认为磁盘空间的 30%,封顶不超过 3TB。作为特例, OLAP 模板允许 20% 的 temp_file_limit ,封顶不超过 2TB
手工调整参数 除了使用 Pigsty 自动配置的参数外,您还可以手工调整 PostgreSQL 参数。
使用 pg edit-config <cluster> 命令可以交互式编辑集群配置:
或者使用 -p 参数直接设置参数:
pg edit-config -p log_min_duration_statement = 1000 pg-meta
pg edit-config --force -p shared_preload_libraries = 'timescaledb, pg_cron, pg_stat_statements, auto_explain' pg-meta
您也可以使用 Patroni REST API 来修改配置:
curl -u 'postgres:Patroni.API' \
-d '{"postgresql":{"parameters": {"log_min_duration_statement":200}}}' \
-s -X PATCH http://10.10.10.10:8008/config | jq .
11.8.7 - 故障排查 常见故障与分析排查思路
本文档列举了 PostgreSQL 和 Pigsty 中可能出现的故障,以及定位、处理、分析问题的 SOP。
磁盘空间写满 磁盘空间写满是最常见的故障类型。
现象 当数据库所在磁盘空间耗尽时,PostgreSQL 将无法正常工作,可能出现以下现象:数据库日志反复报错"no space left on device"(磁盘空间不足),
新数据无法写入,甚至 PostgreSQL 可能触发 PANIC 强制关闭。
Pigsty 带有 NodeFsSpaceFull 告警规则,当文件系统可用空间不足 10% 时触发告警。
使用监控系统 NODE Instance 面板查阅 FS 指标面板定位问题。
诊断 您也可以登录数据库节点,使用 df -h 查看各挂载盘符使用率,确定哪个分区被写满。
对于数据库节点,重点检查以下目录及其大小,以判断是哪个类别的文件占满了空间:
数据目录 (/pg/data/base):存放表和索引的数据文件,大量写入与临时文件需要关注WAL目录 (如 pg/data/pg_wal):存放 PG WAL,WAL 堆积/复制槽保留是常见的磁盘写满原因。数据库日志目录 (如 pg/log):如果 PG 日志未及时轮转写大量报错写入,也可能占用大量空间。本地备份目录 (如 data/backups):使用 pgBackRest 等在本机保存备份时,也有可能撑满磁盘。如果问题出在 Pigsty 管理节点或监控节点,还需考虑:
监控数据 :Prometheus 的时序指标和 Loki 日志存储都会占用磁盘,可检查保留策略。对象存储数据 :Pigsty 集成的 MinIO 对象存储可能会被用于 PG 备份保存。明确占用空间最大的目录后,可进一步使用 du -sh <目录> 深入查找特定大型文件或子目录。
处理 磁盘写满属于紧急问题,需立即采取措施释放空间并保证数据库继续运行。
当数据盘并未与系统盘区分时,写满磁盘可能导致 Shell 命令无法执行。这种情况下,可以删除 /pg/dummy 占位文件,释放少量应急空间以便 shell 命令恢复正常。
如果数据库由于 pg_wal 写满已经宕机,清理空间后需要重启数据库服务并仔细检查数据完整性。
事务号回卷 PostgreSQL 循环使用 32 位事务ID (XID),耗尽时会出现"事务号回卷"故障(XID Wraparound)。
现象 第一阶段的典型征兆是 PGSQL Persist - Age Usage 面板年龄饱和度进入警告区域。
数据库日志开始出现:WARNING: database "postgres" must be vacuumed within xxxxxxxx transactions 字样的信息。
若问题持续恶化,PostgreSQL 会进入保护模式:当剩余事务ID不到约100万时数据库切换为只读模式;达到上限约21亿(2^31)时则拒绝任何新事务并迫使服务器停机以避免数据错误。
诊断 PostgreSQL 与 Pigsty 默认启用自动垃圾回收(AutoVacuum),因此此类故障出现通常有更深层次的根因。
常见的原因包括:超长事务(SAGE),Autovacuum 配置失当,复制槽阻塞,资源不足,存储引擎/扩展BUG,磁盘坏块。
首先定位年龄最大的数据库,然后可通过 Pigsty PGCAT Database - Tables 面板来确认表的年龄分布。
同时查阅数据库错误日志,通常可以找到定位根因的线索。
处理 立即冻结老事务 :如果数据库尚未进入只读保护状态,立刻对受影响的库执行一次手动 VACUUM FREEZE。可以从老化最严重的表开始逐个冻结,而不是整库一起做,以加快效果。使用超级用户连接数据库,针对识别出的 relfrozenxid 最大的表运行 VACUUM FREEZE 表名;,优先冻结那些XID年龄最大的表元组。这样可以迅速回收大量事务ID空间。单用户模式救援 :如果数据库已经拒绝写入或宕机保护,此时需要启动数据库到单用户模式执行冻结操作。在单用户模式下运行 VACUUM FREEZE database_name; 对整个数据库进行冻结清理。完成后再以多用户模式重启数据库。这样做可以解除回卷锁定,让数据库重新可写。需要注意在单用户模式下操作要非常谨慎,并确保有足够的事务ID余量完成冻结。备用节点接管 :在某些复杂场景(例如遭遇硬件问题导致 vacuum 无法完成),可考虑提升集群中的只读备节点为主,以获取一个相对干净的环境来处理冻结。例如主库因坏块导致无法 vacuum,此时可以手动Failover提升备库为新的主库,再对其进行紧急 vacuum freeze。确保新主库已冻结老事务后,再将负载切回来。连接耗尽 PostgreSQL 有一个最大连接数配置 (max_connections),当客户端连接数超过此上限时,新的连接请求将被拒绝。典型现象是在应用端看到数据库无法连接,并报出类似
FATAL: remaining connection slots are reserved for non-replication superuser connections 或 too many clients already 的错误。
这表示普通连接数已用完,仅剩下保留给超管或复制的槽位
诊断 连接耗尽通常由客户端大量并发请求引起。您可以通过 PGCAT Instance / PGCAT Database / PGCAT Locks 直接查阅数据库当前的活跃会话。
并判断是什么样的查询填满了系统,并进行进一步的处理。特别需要关注是否存在大量 Idle in Transaction 状态的连接以及长时间运行的事务(以及慢查询)。
处理 杀查询 :对于已经耗尽导致业务受阻的情况,通常立即使用 pg_terminate_backend(pid) 进行紧急降压。
对于使用连接池的情况,则可以调整连接池大小参数,并执行 reload 重载的方式减少数据库层面的连接数量。
您也可以修改 max_connections 参数为更大的值,但本参数需要重启数据库后才能生效。
etcd 配额写满 etcd 配额写满将导致 PG 高可用控制面失效,无法进行配置变更。
诊断 Pigsty 在实现高可用时使用 etcd 作为分布式配置存储(DCS),etcd 自身有一个存储配额(默认约为2GB)。
当 etcd 存储用量达到配额上限时,etcd 将拒绝写入操作,报错 “etcdserver: mvcc: database space exceeded "。在这种情况下,Patroni 无法向 etcd 写入心跳或更新配置,从而导致集群管理功能失效。
解决 在 Pigsty v2.0.0 - v2.5.1 之间的版本默认受此问题影响。Pigsty v2.6.0 为部署的 etcd 新增了自动压实的配置项,如果您仅将其用于 PG 高可用租约,则常规用例下不会再有此问题。
有缺陷的存储引擎 目前,TimescaleDB 的试验性存储引擎 Hypercore 被证实存在缺陷,已经出现 VACUUM 无法回收出现 XID 回卷故障的案例。
请使用该功能的用户及时迁移至 PostgreSQL 原生表或者 TimescaleDB 默认引擎
详细介绍:《PG新存储引擎故障案例 》
11.8.8 - 误删处理 处理误删数据,误删表,误删数据库
误删数据 如果是小批量 DELETE 误操作,可以考虑使用 pg_surgery 或者 pg_dirtyread 扩展进行原地手术恢复。
-- 立即关闭此表上的 Auto Vacuum 并中止 Auto Vacuum 本表的 worker 进程
ALTER TABLE public . some_table SET ( autovacuum_enabled = off , toast . autovacuum_enabled = off );
CREATE EXTENSION pg_dirtyread ;
SELECT * FROM pg_dirtyread ( 'tablename' ) AS t ( col1 type1 , col2 type2 , ...);
如果被删除的数据已经被 VACUUM 回收,那么使用通用的误删处理流程。
误删对象 当出现 DROP/DELETE 类误操作,通常按照以下流程决定恢复方案。
确认此数据是否可以通过业务系统或其他数据系统找回,如果可以,直接从业务侧修复。 确认是否有延迟从库,如果有,推进延迟从库至误删时间点,查询出来恢复。 如果数据已经确认删除,确认备份信息,恢复范围是否覆盖误删时间点,如果覆盖,开始 PITR 确认是整集群原地 PITR 回滚 ,还是新开服务器重放,还是用从库来重放,并执行恢复策略 误删集群 如果出现整个数据库集群通过 Pigsty 管理命令被误删的情况,例如错误的执行 pgsql-rm.yml 剧本或 bin/pgsql-rm 命令。
除非您指定了 pg_rm_backup 参数为 false,否则备份会与数据库集群一起被删除。
警告 :在这种情况,您的数据将无法找回!请务必三思而后行!
建议:对于生产环境,您可以在配置清单中全局配置此参数为 false,在移除集群时保留备份。
11.8.9 - 克隆副本 如何克隆数据库,克隆数据库实例,克隆数据库集群?
PostgreSQL 已经可以通过物理从库,逻辑从库的方式复制数据,
但有时候你可能需要高速 克隆 一个数据库,数据库实例,或者整个数据库集群。
克隆出来的数据库可以写入,独立演进,不影响原有数据库。在 Pigsty 中,有以下几种克隆方法:
克隆数据库 :在同一个集群内,克隆一个新的数据库克隆实例 :在同一个 PG 节点上,克隆一个新的实例克隆集群 :使用 PITR 机制创建一个新的数据库集群,并恢复到指定集群的任意时间点克隆数据库 你可以通过 template 机制复制一个 PostgreSQL 数据库,但在此期间不允许有任何连接到模版数据库的活动连接。
假设你想要克隆 postgres 数据库,那么必须一次性同时执行下面两条语句。
确保清理掉所有连接到 postgres 数据库的连接后执行 Clone
SELECT pg_terminate_backend ( pid ) FROM pg_stat_activity WHERE datname = 'postgres' ;
CREATE DATABASE pgcopy TEMPLATE postgres STRATEGY FILE_COPY ;
瞬间克隆 如果你使用的是 PostgreSQL 18 以上的版本,Pigsty 默认为您设置了 file_copy_method 。
该参数允许你以 O(1) (约 200ms)的时间复杂度克隆一个数据库,而不需要复制数据文件。
但是您必须显式使用 FILE_COPY 策略来创建数据库。
CREATE DATABASE 的 STRATEGY 参数自 PostgreSQL 15 引入以来的默认值为 WAL_LOG,你需要显式指定 FILE_COPY 来进行瞬间克隆。
SELECT pg_terminate_backend ( pid ) FROM pg_stat_activity WHERE datname = 'postgres' ;
CREATE DATABASE pgcopy TEMPLATE postgres STRATEGY FILE_COPY ;
例如,克隆一个 30 GB 的数据库,普通克隆(WAL_LOG)用时 18 秒,而瞬间克隆(FILE_COPY)仅需常数时间 200 毫秒。
但是,您仍然需要确保在克隆期间没有任何连接到模版数据库的活动连接,但这个时间可以非常短暂,因此具有生产环境的实用性。
如果您需要一个新的数据库副本用于测试或开发,瞬间克隆是一个非常好的选择。它并不会引入额外的存储开销,因为它使用了文件系统的 CoW(Copy on Write)机制。
Pigsty v4.0 起,您可以在 pg_databases 参数中使用 strategy: FILE_COPY 来实现瞬间克隆数据库。
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_version : 18
pg_databases :
- name : meta
- name : meta_dev
template : meta
strategy : FILE_COPY # <---- PG 15 引入, PG18 瞬间生效
#comment: "meta clone" # <---- 数据库注释
#pgbouncer: false # <---- 不加入 连接池?
#register_datasource: false # <---- 不加入 Grafana 数据源?
配置完毕后,使用标准数据库创建 SOP 创建该数据库即可:
bin/pgsql-db pg-meta meta_dev
局限性与注意事项 请注意,这个特性仅在支持的文件系统上可用(xfs,brtfs,zfs,apfs),如果文件系统不支持,PostgreSQL 将会报错失败。
默认情况下,主流操作系统发行版的 xfs 都已经默认启用 reflink=1 选项,因此大多数情况下您不需要担心这个问题。
OpenZFS 需要显式配置才能支持 CoW,但因为存在数据损坏的先例,不建议将此特性用于生产。
如果您使用的 PostgreSQL 版本低于 15,指定 strategy 不会有任何效果。
请不要使用 postgres 数据库作为模版数据库进行克隆,因为管理链接通常会连接到 postgres 数据库,这阻止了克隆操作的进行。
如果您确实需要克隆 postgres 数据库,请你手动连接到其他数据库上后,自行执行 SQL 实现。
在极高并发/吞吐的生产环境中使用瞬间克隆需要谨慎,它需要在克隆窗口(200ms)内清理掉所有连接到模版数据库的连接,否则克隆会失败。
11.8.10 - 维护保养 常见系统维护任务
要确保 Pigsty 与 PostgreSQL 集群健康稳定运行,需要进行一些例行维护保养工作。
定期查阅监控 Pigsty 提供了开箱即用的监控平台,我们建议您每天浏览一次监控大盘,关注系统状态。
极端情况下,我们建议您每周至少查阅一次监控,关注出现的告警事件,这样可以提前规避绝大多数故障与问题。
这里列举了 Pigsty 中预先定义的 告警规则 列表。
故障切换善后 Pigsty 的高可用架构允许 PostgreSQL 集群自动进行主从切换,这意味着运维与 DBA 无需即时介入与响应。
然而用户仍然需要在合适的时机(例如第二天工作日)进行以下善后工作,包括:
调查并确认故障出现的原因,避免再次出现 视情况恢复集群原本的主从拓扑,或者修改配置清单以匹配新的主从状态。 通过 bin/pgsql-svc 刷新负载均衡器配置,更新服务的路由状态 通过 bin/pgsql-hba 刷新集群的 HBA 规则,避免主从特定的规则漂移 如果有必要,使用 bin/pgsql-rm 移除故障服务器,并通过 bin/pgsql-add 扩容一台新从库 表膨胀治理 长时间运行的 PostgreSQL 会出现 “表膨胀” / “索引膨胀” 现象, 导致系统性能劣化。
定期使用 pg_repack 对表与索引进行在线重建,有助于维护 PostgreSQL 的良好性能表现。
Pigsty 已经默认在所有数据库中安装并启用了此扩展,因此您可以直接使用。
您可以通过 Pigsty 的 PGCAT Database - Table Bloat 面板,
确认数据库中的表膨胀情况与索引膨胀情况。并选择膨胀率较高(膨胀率高于 50% 的较大表)的表与索引,使用 pg_repack 进行在线重整:
pg_repack dbname -t schema.table
重整期间不会影响正常读写,但重整完毕之后的 切换瞬间 需要获取表上的 AccessExclusive 锁阻塞一切访问。
因此对于高吞吐量业务,建议在业务低峰期或者维护窗口进行。更多细节,请参考:关系膨胀的治理
VACUUM FREEZE 冻结过期事务ID(VACUUM FREEZE)是PostgreSQL重要的维护任务,用于防止事务ID (XID) 用尽导致停机。
尽管 PostgreSQL 已经提供了自动垃圾回收(AutoVacuum)机制,然而对于高标准的生产环境,
我们依然建议结合自动和手动两种方式,定期执行全库级别的 VACUUM FREEZE ,以确保 XID 安全。
您可以使用以下命令手工对数据库执行 VACUUM FREEZE:
-- 对整个数据库执行 VACUUM FREEZE
VACUUM FREEZE ;
-- 对特定表执行 VACUUM FREEZE
VACUUM FREEZE schema . table_name ;
或者通过 crontab 设置定时任务,例如每周日凌晨执行:
# 每周日凌晨3点对所有数据库执行 VACUUM FREEZE
0 3 * * 0 postgres psql -c 'VACUUM FREEZE;' dbname
11.8.11 - 版本升级 如何升级(或降级) PostgreSQL 小版本内核,以及如何进行大版本升级。
小版本升级 要执行小版本的服务器升级/降级,您首先需要在本地软件仓库中 添加软件 :最新的PG小版本 RPM/DEB。
首先对所有从库执行滚动升级/降级,然后执行集群 主从切换 以升级/降级主库。
ansible <cls> -b -a "yum upgrade/downgrade -y <pkg>" # 升级/降级软件包
pg restart --force <cls> # 重启集群
这次我们采用滚动方式升级:
ansible pg-test -b -a "yum upgrade -y postgresql15*" # 升级软件包(或 apt upgrade)
ansible pg-test -b -a '/usr/pgsql/bin/pg_ctl --version' # 检查二进制版本是否为15.2
pg restart --role replica --force pg-test # 重启从库
pg switchover --leader pg-test-1 --candidate= pg-test-2 --scheduled= now --force pg-test # 切换主从
pg restart --role primary --force pg-test # 重启主库
小版本降级 将15.1的包添加到软件仓库并刷新节点的 yum/apt 缓存:
cd ~/pigsty; ./infra.yml -t repo_upstream # 添加上游仓库
cd /www/pigsty; repotrack postgresql15-*-15.1 # 将15.1的包添加到yum仓库
cd ~/pigsty; ./infra.yml -t repo_create # 重建仓库元数据
ansible pg-test -b -a 'yum clean all' # 清理节点仓库缓存
ansible pg-test -b -a 'yum makecache' # 从新仓库重新生成yum缓存
# 对于 Ubutnu/Debian 用户,使用 apt 替换 yum
ansible pg-test -b -a 'apt clean' # 清理节点仓库缓存
ansible pg-test -b -a 'apt update' # 从新仓库重新生成apt缓存
执行降级并重启集群:
ansible pg-test -b -a "yum downgrade -y postgresql15*" # 降级软件包)
pg restart --force pg-test # 重启整个集群以完成升级
大版本升级 实现大版本升级的最简单办法是:创建一个使用新版本的新集群,然后通过逻辑复制,蓝绿部署,并进行 在线迁移 。
您也可以进行原地大版本升级,当您只使用数据库内核本身时,这并不复杂,使用 PostgreSQL 自带的 pg_upgrade 即可:
假设您想将 PostgreSQL 大版本从 14 升级到 15,您首先需要在仓库中 添加软件 ,并确保两个大版本两侧安装的核心扩展插件也具有相同的版本号。
./pgsql.yml -t pg_pkg -e pg_version = 15 # 安装pg 15的包
sudo su - postgres; mkdir -p /data/postgres/pg-meta-15/data/ # 为15准备目录
pg_upgrade -b /usr/pgsql-14/bin/ -B /usr/pgsql-15/bin/ -d /data/postgres/pg-meta-14/data/ -D /data/postgres/pg-meta-15/data/ -v -c # 预检
pg_upgrade -b /usr/pgsql-14/bin/ -B /usr/pgsql-15/bin/ -d /data/postgres/pg-meta-14/data/ -D /data/postgres/pg-meta-15/data/ --link -j8 -v -c
rm -rf /usr/pgsql; ln -s /usr/pgsql-15 /usr/pgsql; # 修复二进制链接
mv /data/postgres/pg-meta-14 /data/postgres/pg-meta-15 # 重命名数据目录
rm -rf /pg; ln -s /data/postgres/pg-meta-15 /pg # 修复数据目录链接
11.9 - 备份恢复 时间点恢复(PITR)备份与恢复
Pigsty 使用 pgBackRest 管理 PostgreSQL 备份,这可能是生态系统中最强大的开源备份工具。
它支持增量/并行备份与恢复、加密、MinIO /S3 等众多特性。Pigsty 默认为每个 PGSQL 集群预配置了备份功能。
章节 内容 机制 备份脚本、定时任务、pgbackrest、仓库与管理 策略 备份策略、磁盘规划、恢复窗口权衡 仓库 配置备份仓库:本地、MinIO、S3 管理 常用备份管理命令 恢复 使用剧本恢复到特定时间点 示例 沙箱示例:手工执行恢复操作
免责声明
Pigsty 尽最大努力提供可靠的 PITR 解决方案,但我们不对 PITR 操作导致的数据丢失承担任何责任,使用需自担风险。如需专业支持,请考虑我们的专业服务 。
快速上手 备份策略 :使用 Crontab 调度基础备份WAL 归档 :持续记录写入活动恢复与还原 :从备份和 WAL 归档中恢复node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ]
./pgsql-pitr.yml -e '{"pg_pitr": { "time": "2025-07-13 10:00:00+00" }}'
11.9.1 - 备份策略 根据您的需求设计备份策略
何时备份 第一个问题是何时 备份您的数据库——这是备份频率和恢复时间之间的权衡。
由于您需要从上一次备份开始重放 WAL 日志到恢复目标点,备份越频繁,需要重放的 WAL 日志就越少,恢复速度就越快。
每日全量备份 对于生产数据库,建议从最简单的每日全量备份策略开始。
这也是 Pigsty 的默认备份策略,通过 crontab 实现。
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ]
pgbackrest_method : local # 选择备份仓库方法:`local`、`minio` 或其他自定义仓库
pgbackrest_repo: # pgbackrest 仓库配置 : https://pgbackrest.org/configuration.html#section-repository
local : # 使用本地 POSIX 文件系统的默认 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按数量保留全量备份
retention_full : 2 # 使用本地文件系统仓库时,保留2个,最多3个全量备份
配合默认的 local 本地文件系统备份仓库使用时,可提供 24~48 小时的恢复窗口。
假设您的数据库大小为 100GB,每天写入 10GB 数据,则备份大小如下:
这将消耗数据库大小的 2~3 倍空间,再加上 2 天的 WAL 日志。
因此在实践中,您可能需要准备至少 3~5 倍数据库大小的备份磁盘才能使用默认备份策略。
全量 + 增量备份 您可以通过调整这些参数来优化备份空间使用。
如果使用 MinIO / S3 作为集中式备份仓库,您可以使用超出本地磁盘限制的存储空间。
此时可以考虑使用全量 + 增量备份配合 2 周保留策略:
node_crontab : # 周一凌晨1点全量备份,工作日增量备份
- '00 01 * * 1 postgres /pg/bin/pg-backup full'
- '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
pgbackrest_method : minio
pgbackrest_repo: # pgbackrest 仓库配置 : https://pgbackrest.org/configuration.html#section-repository
minio : # 可选的 minio 仓库
type : s3 # minio 兼容 S3 协议
s3_endpoint : sss.pigsty # minio 端点域名,默认为 `sss.pigsty`
s3_region : us-east-1 # minio 区域,默认 us-east-1,对 minio 无实际意义
s3_bucket : pgsql # minio 桶名,默认为 `pgsql`
s3_key : pgbackrest # pgbackrest 的 minio 用户访问密钥
s3_key_secret : S3User.Backup # pgbackrest 的 minio 用户密钥
s3_uri_style : path # minio 使用路径风格 URI 而非主机风格
path : /pgbackrest # minio 备份路径,默认为 `/pgbackrest`
storage_port : 9000 # minio 端口,默认 9000
storage_ca_file : /etc/pki/ca.crt # minio CA 证书路径,默认 `/etc/pki/ca.crt`
block : y # 启用块级增量备份
bundle : y # 将小文件打包成单个文件
bundle_limit : 20MiB # 文件包大小限制,对象存储建议 20MiB
bundle_size : 128MiB # 文件包目标大小,对象存储建议 128MiB
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 按时间保留全量备份
retention_full : 14 # 保留最近 14 天的全量备份
配合内置的 minio 备份仓库使用时,可提供保证 1 周的 PITR 恢复窗口。
假设您的数据库大小为 100GB,每天写入 10GB 数据,则备份大小如下:
备份位置 默认情况下,Pigsty 提供两个默认备份仓库定义:local 和 minio 备份仓库。
local:默认选项 ,使用本地 /pg/backup 目录(软链接指向 pg_fs_backup :/data/backups)minio:使用 SNSD 单节点 MinIO 集群(Pigsty 支持,但默认不启用)pgbackrest_method : local # 选择备份仓库方法:`local`、`minio` 或其他自定义仓库
pgbackrest_repo: # pgbackrest 仓库配置 : https://pgbackrest.org/configuration.html#section-repository
local : # 使用本地 POSIX 文件系统的默认 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按数量保留全量备份
retention_full : 2 # 使用本地文件系统仓库时,保留2个,最多3个全量备份
minio : # 可选的 minio 仓库
type : s3 # minio 兼容 S3 协议
s3_endpoint : sss.pigsty # minio 端点域名,默认为 `sss.pigsty`
s3_region : us-east-1 # minio 区域,默认 us-east-1,对 minio 无实际意义
s3_bucket : pgsql # minio 桶名,默认为 `pgsql`
s3_key : pgbackrest # pgbackrest 的 minio 用户访问密钥
s3_key_secret : S3User.Backup # pgbackrest 的 minio 用户密钥
s3_uri_style : path # minio 使用路径风格 URI 而非主机风格
path : /pgbackrest # minio 备份路径,默认为 `/pgbackrest`
storage_port : 9000 # minio 端口,默认 9000
storage_ca_file : /etc/pki/ca.crt # minio CA 证书路径,默认 `/etc/pki/ca.crt`
block : y # 启用块级增量备份
bundle : y # 将小文件打包成单个文件
bundle_limit : 20MiB # 文件包大小限制,对象存储建议 20MiB
bundle_size : 128MiB # 文件包目标大小,对象存储建议 128MiB
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 按时间保留全量备份
retention_full : 14 # 保留最近 14 天的全量备份
11.9.2 - 备份机制 备份脚本、定时任务、备份仓库与基础设施
备份可以通过内置脚本 调用,使用节点 crontab 定时执行,
由 pgbackrest 管理,存储在备份仓库中,
仓库可以是本地磁盘文件系统或 MinIO / S3,并支持不同的保留 策略。
脚本 您可以使用 pg_dbsu 用户(默认为 postgres)执行 pgbackrest 命令创建备份:
备份命令
backup
full
diff
incr
info pgbackrest --stanza= pg-meta --type= full backup # 为集群 pg-meta 创建全量备份 $ pgbackrest --stanza= pg-meta --type= full backup
2025-07-15 01:36:57.007 P00 INFO: backup command begin 2.54.2: --annotation= pg_cluster = pg-meta ...
2025-07-15 01:36:57.030 P00 INFO: execute non-exclusive backup start: backup begins after the requested immediate checkpoint completes
2025-07-15 01:36:57.105 P00 INFO: backup start archive = 000000010000000000000006, lsn = 0/6000028
2025-07-15 01:36:58.540 P00 INFO: new backup label = 20250715-013657F
2025-07-15 01:36:58.588 P00 INFO: full backup size = 44.5MB, file total = 1437
2025-07-15 01:36:58.589 P00 INFO: backup command end: completed successfully ( 1584ms) $ pgbackrest --stanza= pg-meta --type= diff backup
2025-07-15 01:37:24.952 P00 INFO: backup command begin 2.54.2: ...
2025-07-15 01:37:24.985 P00 INFO: last backup label = 20250715-013657F, version = 2.54.2
2025-07-15 01:37:26.337 P00 INFO: new backup label = 20250715-013657F_20250715-013724D
2025-07-15 01:37:26.381 P00 INFO: diff backup size = 424.3KB, file total = 1437
2025-07-15 01:37:26.381 P00 INFO: backup command end: completed successfully ( 1431ms) $ pgbackrest --stanza= pg-meta --type= incr backup
2025-07-15 01:37:30.305 P00 INFO: backup command begin 2.54.2: ...
2025-07-15 01:37:30.337 P00 INFO: last backup label = 20250715-013657F_20250715-013724D, version = 2.54.2
2025-07-15 01:37:31.356 P00 INFO: new backup label = 20250715-013657F_20250715-013730I
2025-07-15 01:37:31.403 P00 INFO: incr backup size = 8.3KB, file total = 1437
2025-07-15 01:37:31.403 P00 INFO: backup command end: completed successfully ( 1099ms) $ pgbackrest --stanza= pg-meta info
stanza: pg-meta
status: ok
cipher: aes-256-cbc
db ( current)
wal archive min/max ( 17) : 000000010000000000000001/00000001000000000000000A
full backup: 20250715-013657F
timestamp start/stop: 2025-07-15 01:36:57+00 / 2025-07-15 01:36:58+00
wal start/stop: 000000010000000000000006 / 000000010000000000000006
database size: 44.5MB, database backup size: 44.5MB
repo1: backup size: 8.7MB
diff backup: 20250715-013657F_20250715-013724D
timestamp start/stop: 2025-07-15 01:37:24+00 / 2025-07-15 01:37:26+00
database size: 44.5MB, database backup size: 424.3KB
repo1: backup size: 94KB
backup reference total: 1 full
incr backup: 20250715-013657F_20250715-013730I
timestamp start/stop: 2025-07-15 01:37:30+00 / 2025-07-15 01:37:31+00
database size: 44.5MB, database backup size: 8.3KB
repo1: backup size: 504B
backup reference total: 1 full, 1 diff 这里的 stanza 是数据库集群名称:pg_cluster ,在默认配置中为 pg-meta。
Pigsty 提供了 pb 别名和 pg-backup 包装脚本,会自动填充当前集群名称作为 stanza:
function pb() {
local stanza = $( grep -o '\[[^][]*]' /etc/pgbackrest/pgbackrest.conf | head -n1 | sed 's/.*\[\([^]]*\)].*/\1/' )
pgbackrest --stanza= $stanza $@
}
pb ... # pgbackrest --stanza=pg-meta ...
pb info # pgbackrest --stanza=pg-meta info
pb backup # pgbackrest --stanza=pg-meta backup
pg-backup full # 执行全量备份 = pgbackrest --stanza=pg-meta --type=full backup
pg-backup incr # 执行增量备份 = pgbackrest --stanza=pg-meta --type=incr backup
pg-backup diff # 执行差异备份 = pgbackrest --stanza=pg-meta --type=diff backup
定时备份 Pigsty 利用 Linux crontab 来调度备份任务。您可以用它定义备份策略。
例如,大多数单节点配置模板都有以下用于备份的 node_crontab :
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ]
您可以使用 crontab 和 pg-backup 脚本设计更复杂的备份策略,例如:
node_crontab : # 周一凌晨1点全量备份,工作日增量备份
- '00 01 * * 1 postgres /pg/bin/pg-backup full'
- '00 01 * * 2,3,4,5,6,7 postgres /pg/bin/pg-backup'
要应用 crontab 变更,使用 node.yml 更新所有节点的 crontab:
./node.yml -t node_crontab -l pg-meta # 将 crontab 变更应用到 pg-meta 组
pgbackrest 以下是 Pigsty 对 pgbackrest 的配置细节:
文件层次结构 bin:/usr/bin/pgbackrest,来自 PGDG 的 pgbackrest 包,在组别名 pgsql-common 中。 conf:/etc/pgbackrest,主配置文件是 /etc/pgbackrest/pgbackrest.conf 。 logs:/pg/log/pgbackrest/*,由 pgbackrest_log_dir 控制 tmp:/pg/spool 用作 pgbackrest 的临时 spool 目录 data:/pg/backup 用于存储数据(当选择默认的 local 文件系统备份仓库时) 此外,在 PITR 恢复 过程中,Pigsty 会创建临时的 /pg/conf/pitr.conf pgbackrest 配置文件,
并将 postgres 恢复日志写入 /pg/tmp/recovery.log 文件。
监控 有一个 pgbackrest_exporter 服务运行在 pgbackrest_exporter_port (9854)端口上,用于导出 pgbackrest 指标。
您可以通过 pgbackrest_exporter_options 自定义它,
或将 pgbackrest_exporter_enabled 设置为 false 来禁用它。
初始备份 当创建 postgres 集群时,Pigsty 会自动创建初始备份。
由于新集群几乎为空,这是一个很小的备份。
它会留下一个 /etc/pgbackrest/initial.done 标记文件,以避免重复创建初始备份。
如果不需要初始备份,请将 pgbackrest_init_backup 设置为 false。
管理 启用备份 如果数据库集群创建时 pgbackrest_enabled 设置为 true,备份将自动启用。
如果创建时该值为 false,您可以使用以下命令启用 pgbackrest 组件:
./pgsql.yml -t pg_backup # 运行 pgbackrest 子任务
删除备份 当移除主实例(pg_role = primary)时,Pigsty 会删除 pgbackrest 备份 stanza。
./pgsql-rm.yml
./pgsql-rm.yml -e pg_rm_backup = false # 保留备份
./pgsql-rm.yml -t pg_backup # 仅删除备份
使用 pg_backup 子任务仅删除备份,使用 keep_backup 参数保留备份。
如果您的备份仓库被锁定 (例如 S3 / MinIO 有锁定选项),此操作将失败。
备份删除
删除备份可能导致永久性数据丢失,这是一个危险操作,请务必谨慎。
列出备份 此命令将列出 pgbackrest 仓库中的所有备份(所有集群共享)
手动备份 Pigsty 提供了内置脚本 /pg/bin/pg-backup,封装了 pgbackrest 备份命令。
pg-backup # 执行增量备份
pg-backup full # 执行全量备份
pg-backup incr # 执行增量备份
pg-backup diff # 执行差异备份
基础备份 Pigsty 提供了一个替代备份脚本 /pg/bin/pg-basebackup,它不依赖 pgbackrest,直接提供数据库集群的物理副本。
默认备份目录为 /pg/backup。
pg-basebackup
help
backup NAME
pg-basebackup -- make base backup from PostgreSQL instance
SYNOPSIS
pg-basebackup -sdfeukr
pg-basebackup --src postgres:/// --dst . --file backup.tar.lz4
DESCRIPTION
-s, --src, --url 备份源 URL,可选,默认为 "postgres:///" ,如需密码应在 url、ENV 或 .pgpass 中提供
-d, --dst, --dir 备份文件存放位置,默认为 "/pg/backup"
-f, --file 覆盖默认备份文件名,"backup_ ${ tag } _ ${ date } .tar.lz4"
-r, --remove 删除 n 分钟前的 .lz4 文件,默认 1200(20小时)
-t, --tag 备份文件标签,未设置时使用目标集群名或本地 IP 地址,也用于默认文件名
-k, --key 指定 --encrypt 时的加密密钥,默认密钥为 ${ tag }
-u, --upload 上传备份文件到云存储(需自行实现)
-e, --encryption 使用 OpenSSL RC4 加密,未指定密钥时使用 tag 作为密钥
-h, --help 打印此帮助信息 postgres@pg-meta-1:~$ pg-basebackup
[ 2025-07-13 06:16:05][ INFO] ================================================================
[ 2025-07-13 06:16:05][ INFO] [ INIT] pg-basebackup begin, checking parameters
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] filename ( -f) : backup_pg-meta_20250713.tar.lz4
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] src ( -s) : postgres:///
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] dst ( -d) : /pg/backup
[ 2025-07-13 06:16:05][ INFO] [ LOCK] lock acquired success on /tmp/backup.lock, pid = 107417
[ 2025-07-13 06:16:05][ INFO] [ BKUP] backup begin, from postgres:/// to /pg/backup/backup_pg-meta_20250713.tar.lz4
pg_basebackup: initiating base backup, waiting for checkpoint to complete
pg_basebackup: checkpoint completed
pg_basebackup: write-ahead log start point: 0/7000028 on timeline 1
pg_basebackup: write-ahead log end point: 0/7000FD8
pg_basebackup: syncing data to disk ...
pg_basebackup: base backup completed
[ 2025-07-13 06:16:06][ INFO] [ BKUP] backup complete!
[ 2025-07-13 06:16:06][ INFO] [ DONE] backup procedure complete!
[ 2025-07-13 06:16:06][ INFO] ================================================================ 备份使用 lz4 压缩。您可以使用以下命令解压并提取 tarball:
mkdir -p /tmp/data # 将备份提取到此目录
cat /pg/backup/backup_pg-meta_20250713.tar.lz4 | unlz4 -d -c | tar -xC /tmp/data
逻辑备份 您也可以使用 pg_dump 命令执行逻辑备份。
逻辑备份不能用于 PITR(时间点恢复),但对于在不同主版本之间迁移数据或实现灵活的数据导出逻辑非常有用。
从仓库引导 假设您有一个现有集群 pg-meta,想要将其克隆 为 pg-meta2:
您需要创建新的 pg-meta2 集群分支,然后在其上运行 pitr。
11.9.3 - 备份仓库 PostgreSQL 备份存储仓库配置
您可以通过指定 pgbackrest_repo 参数来配置备份存储位置 。
您可以在此定义多个仓库,Pigsty 会根据 pgbackrest_method 的值选择使用哪个。
默认仓库 默认情况下,Pigsty 提供两个默认备份仓库定义:local 和 minio 备份仓库。
local:默认选项 ,使用本地 /pg/backup 目录(软链接指向 pg_fs_backup :/data/backups)minio:使用 SNSD 单节点 MinIO 集群(Pigsty 支持,但默认不启用)pgbackrest_method : local # 选择备份仓库方法:`local`、`minio` 或其他自定义仓库
pgbackrest_repo: # pgbackrest 仓库配置 : https://pgbackrest.org/configuration.html#section-repository
local : # 使用本地 POSIX 文件系统的默认 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按数量保留全量备份
retention_full : 2 # 使用本地文件系统仓库时,保留2个,最多3个全量备份
minio : # 可选的 minio 仓库
type : s3 # minio 兼容 S3 协议
s3_endpoint : sss.pigsty # minio 端点域名,默认为 `sss.pigsty`
s3_region : us-east-1 # minio 区域,默认 us-east-1,对 minio 无实际意义
s3_bucket : pgsql # minio 桶名,默认为 `pgsql`
s3_key : pgbackrest # pgbackrest 的 minio 用户访问密钥
s3_key_secret : S3User.Backup # pgbackrest 的 minio 用户密钥
s3_uri_style : path # minio 使用路径风格 URI 而非主机风格
path : /pgbackrest # minio 备份路径,默认为 `/pgbackrest`
storage_port : 9000 # minio 端口,默认 9000
storage_ca_file : /etc/pki/ca.crt # minio CA 证书路径,默认 `/etc/pki/ca.crt`
block : y # 启用块级增量备份
bundle : y # 将小文件打包成单个文件
bundle_limit : 20MiB # 文件包大小限制,对象存储建议 20MiB
bundle_size : 128MiB # 文件包目标大小,对象存储建议 128MiB
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 按时间保留全量备份
retention_full : 14 # 保留最近 14 天的全量备份
仓库保留策略 如果每天备份但不删除旧备份,备份仓库会不断增长并耗尽磁盘空间。
您需要定义保留策略,只保留有限数量的备份。
默认备份策略定义在 pgbackrest_repo 参数中,可按需调整。
local:保留最近 2 个全量备份,备份期间最多允许 3 个minio:保留最近 14 天的所有全量备份空间规划 对象存储提供几乎无限的存储容量,因此无需担心磁盘空间。
您可以使用混合的全量 + 差异备份策略来优化空间使用。
对于本地磁盘备份仓库,Pigsty 建议使用保留最近 2 个全量备份的策略,
这意味着磁盘上保留两个最新的全量备份(运行新备份时可能存在第三个副本)。
这可保证至少 24 小时的恢复窗口。详情请参阅备份策略 。
其他仓库选项 您也可以使用其他服务作为备份仓库,详情请参阅 pgbackrest 文档 :
仓库版本控制 您甚至可以指定 repo target time 来获取对象存储的快照。
您可以通过在 minio_buckets 中添加 versioning 标志来启用 MinIO 版本控制:
minio_buckets :
- { name: pgsql ,versioning : true }
- { name: meta ,versioning : true }
- { name : data }
仓库锁定 某些对象存储服务(S3、MinIO 等)支持锁定 功能,可以防止备份被删除,即使是 DBA 本人也无法删除。
您可以通过在 minio_buckets 中添加 lock 标志来启用 MinIO 锁定功能:
minio_buckets :
- { name: pgsql , lock : true }
- { name: meta ,versioning : true }
- { name : data }
使用对象存储 对象存储服务提供几乎无限的存储容量,并为您的系统提供远程容灾能力。
如果您没有对象存储服务,Pigsty 内置了 MinIO 支持。
MinIO 您可以通过取消注释以下设置来启用 MinIO 备份仓库。
请注意 pgbackrest 只支持 HTTPS / 域名,因此您必须使用域名和 HTTPS 端点运行 MinIO。
all :
vars :
pgbackrest_method : minio # 使用 minio 作为默认备份仓库
children : # 定义一个单节点 minio SNSD 集群
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 }} ,vars : { minio_cluster : minio }}
S3 如果您只有一个 节点,有意义的备份策略可以是使用云厂商的对象存储服务,如 AWS S3、阿里云 OSS 或 Google Cloud 等。
为此,您可以定义一个新仓库:
pgbackrest_method : s3 # 使用 'pgbackrest_repo.s3' 作为备份仓库
pgbackrest_repo: # pgbackrest 仓库配置 : https://pgbackrest.org/configuration.html#section-repository
s3 : # 阿里云 OSS(S3 兼容)对象存储服务
type : s3 # oss 兼容 S3 协议
s3_endpoint : oss-cn-beijing-internal.aliyuncs.com
s3_region : oss-cn-beijing
s3_bucket : <your_bucket_name>
s3_key : <your_access_key>
s3_key_secret : <your_secret_key>
s3_uri_style : host
path : /pgbackrest
bundle : y # 将小文件打包成单个文件
bundle_limit : 20MiB # 文件包大小限制,对象存储建议 20MiB
bundle_size : 128MiB # 文件包目标大小,对象存储建议 128MiB
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 按时间保留全量备份
retention_full : 14 # 保留最近 14 天的全量备份
local : # 使用本地 POSIX 文件系统的默认 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按数量保留全量备份
retention_full : 2 # 使用本地文件系统仓库时,保留2个,最多3个全量备份
管理备份 启用备份 如果数据库集群创建时 pgbackrest_enabled 设置为 true,备份将自动启用。
如果创建时该值为 false,您可以使用以下命令启用 pgbackrest 组件:
./pgsql.yml -t pg_backup # 运行 pgbackrest 子任务
删除备份 当移除主实例(pg_role = primary)时,Pigsty 会删除 pgbackrest 备份 stanza。
./pgsql-rm.yml
./pgsql-rm.yml -e pg_rm_backup = false # 保留备份
./pgsql-rm.yml -t pg_backup # 仅删除备份
使用 pg_backup 子任务仅删除备份,使用 keep_backup 参数保留备份。
如果您的备份仓库被锁定 (例如 S3 / MinIO 有锁定选项),此操作将失败。
备份删除
删除备份可能导致永久性数据丢失,这是一个危险操作,请务必谨慎。
列出备份 此命令将列出 pgbackrest 仓库中的所有备份(所有集群共享)
手动备份 Pigsty 提供了内置脚本 /pg/bin/pg-backup,封装了 pgbackrest 备份命令。
pg-backup # 执行增量备份
pg-backup full # 执行全量备份
pg-backup incr # 执行增量备份
pg-backup diff # 执行差异备份
基础备份 Pigsty 提供了一个替代备份脚本 /pg/bin/pg-basebackup,它不依赖 pgbackrest,直接提供数据库集群的物理副本。
默认备份目录为 /pg/backup。
pg-basebackup
help
backup NAME
pg-basebackup -- make base backup from PostgreSQL instance
SYNOPSIS
pg-basebackup -sdfeukr
pg-basebackup --src postgres:/// --dst . --file backup.tar.lz4
DESCRIPTION
-s, --src, --url 备份源 URL,可选,默认为 "postgres:///" ,如需密码应在 url、ENV 或 .pgpass 中提供
-d, --dst, --dir 备份文件存放位置,默认为 "/pg/backup"
-f, --file 覆盖默认备份文件名,"backup_ ${ tag } _ ${ date } .tar.lz4"
-r, --remove 删除 n 分钟前的 .lz4 文件,默认 1200(20小时)
-t, --tag 备份文件标签,未设置时使用目标集群名或本地 IP 地址,也用于默认文件名
-k, --key 指定 --encrypt 时的加密密钥,默认密钥为 ${ tag }
-u, --upload 上传备份文件到云存储(需自行实现)
-e, --encryption 使用 OpenSSL RC4 加密,未指定密钥时使用 tag 作为密钥
-h, --help 打印此帮助信息 postgres@pg-meta-1:~$ pg-basebackup
[ 2025-07-13 06:16:05][ INFO] ================================================================
[ 2025-07-13 06:16:05][ INFO] [ INIT] pg-basebackup begin, checking parameters
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] filename ( -f) : backup_pg-meta_20250713.tar.lz4
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] src ( -s) : postgres:///
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] dst ( -d) : /pg/backup
[ 2025-07-13 06:16:05][ INFO] [ LOCK] lock acquired success on /tmp/backup.lock, pid = 107417
[ 2025-07-13 06:16:05][ INFO] [ BKUP] backup begin, from postgres:/// to /pg/backup/backup_pg-meta_20250713.tar.lz4
pg_basebackup: initiating base backup, waiting for checkpoint to complete
pg_basebackup: checkpoint completed
pg_basebackup: write-ahead log start point: 0/7000028 on timeline 1
pg_basebackup: write-ahead log end point: 0/7000FD8
pg_basebackup: syncing data to disk ...
pg_basebackup: base backup completed
[ 2025-07-13 06:16:06][ INFO] [ BKUP] backup complete!
[ 2025-07-13 06:16:06][ INFO] [ DONE] backup procedure complete!
[ 2025-07-13 06:16:06][ INFO] ================================================================ 备份使用 lz4 压缩。您可以使用以下命令解压并提取 tarball:
mkdir -p /tmp/data # 将备份提取到此目录
cat /pg/backup/backup_pg-meta_20250713.tar.lz4 | unlz4 -d -c | tar -xC /tmp/data
逻辑备份 您也可以使用 pg_dump 命令执行逻辑备份。
逻辑备份不能用于 PITR(时间点恢复),但对于在不同主版本之间迁移数据或实现灵活的数据导出逻辑非常有用。
从仓库引导 假设您有一个现有集群 pg-meta,想要将其克隆 为 pg-meta2:
您需要创建新的 pg-meta2 集群分支,然后在其上运行 pitr。
11.9.4 - 管理命令 管理备份仓库和备份
启用备份 如果数据库集群创建时 pgbackrest_enabled 设置为 true,备份将自动启用。
如果创建时该值为 false,您可以使用以下命令启用 pgbackrest 组件:
./pgsql.yml -t pg_backup # 运行 pgbackrest 子任务
删除备份 当移除主实例(pg_role = primary)时,Pigsty 会删除 pgbackrest 备份 stanza。
./pgsql-rm.yml
./pgsql-rm.yml -e pg_rm_backup = false # 保留备份
./pgsql-rm.yml -t pg_backup # 仅删除备份
使用 pg_backup 子任务仅删除备份,使用 keep_backup 参数保留备份。
如果您的备份仓库被锁定 (例如 S3 / MinIO 有锁定选项),此操作将失败。
备份删除
删除备份可能导致永久性数据丢失,这是一个危险操作,请务必谨慎。
列出备份 此命令将列出 pgbackrest 仓库中的所有备份(所有集群共享)
手动备份 Pigsty 提供了内置脚本 /pg/bin/pg-backup,封装了 pgbackrest 备份命令。
pg-backup # 执行增量备份
pg-backup full # 执行全量备份
pg-backup incr # 执行增量备份
pg-backup diff # 执行差异备份
基础备份 Pigsty 提供了一个替代备份脚本 /pg/bin/pg-basebackup,它不依赖 pgbackrest,直接提供数据库集群的物理副本。
默认备份目录为 /pg/backup。
pg-basebackup
help
backup NAME
pg-basebackup -- make base backup from PostgreSQL instance
SYNOPSIS
pg-basebackup -sdfeukr
pg-basebackup --src postgres:/// --dst . --file backup.tar.lz4
DESCRIPTION
-s, --src, --url 备份源 URL,可选,默认为 "postgres:///" ,如需密码应在 url、ENV 或 .pgpass 中提供
-d, --dst, --dir 备份文件存放位置,默认为 "/pg/backup"
-f, --file 覆盖默认备份文件名,"backup_ ${ tag } _ ${ date } .tar.lz4"
-r, --remove 删除 n 分钟前的 .lz4 文件,默认 1200(20小时)
-t, --tag 备份文件标签,未设置时使用目标集群名或本地 IP 地址,也用于默认文件名
-k, --key 指定 --encrypt 时的加密密钥,默认密钥为 ${ tag }
-u, --upload 上传备份文件到云存储(需自行实现)
-e, --encryption 使用 OpenSSL RC4 加密,未指定密钥时使用 tag 作为密钥
-h, --help 打印此帮助信息 postgres@pg-meta-1:~$ pg-basebackup
[ 2025-07-13 06:16:05][ INFO] ================================================================
[ 2025-07-13 06:16:05][ INFO] [ INIT] pg-basebackup begin, checking parameters
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] filename ( -f) : backup_pg-meta_20250713.tar.lz4
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] src ( -s) : postgres:///
[ 2025-07-13 06:16:05][ DEBUG] [ INIT] dst ( -d) : /pg/backup
[ 2025-07-13 06:16:05][ INFO] [ LOCK] lock acquired success on /tmp/backup.lock, pid = 107417
[ 2025-07-13 06:16:05][ INFO] [ BKUP] backup begin, from postgres:/// to /pg/backup/backup_pg-meta_20250713.tar.lz4
pg_basebackup: initiating base backup, waiting for checkpoint to complete
pg_basebackup: checkpoint completed
pg_basebackup: write-ahead log start point: 0/7000028 on timeline 1
pg_basebackup: write-ahead log end point: 0/7000FD8
pg_basebackup: syncing data to disk ...
pg_basebackup: base backup completed
[ 2025-07-13 06:16:06][ INFO] [ BKUP] backup complete!
[ 2025-07-13 06:16:06][ INFO] [ DONE] backup procedure complete!
[ 2025-07-13 06:16:06][ INFO] ================================================================ 备份使用 lz4 压缩。您可以使用以下命令解压并提取 tarball:
mkdir -p /tmp/data # 将备份提取到此目录
cat /pg/backup/backup_pg-meta_20250713.tar.lz4 | unlz4 -d -c | tar -xC /tmp/data
逻辑备份 您也可以使用 pg_dump 命令执行逻辑备份。
逻辑备份不能用于 PITR(时间点恢复),但对于在不同主版本之间迁移数据或实现灵活的数据导出逻辑非常有用。
从仓库引导 假设您有一个现有集群 pg-meta,想要将其克隆 为 pg-meta2:
您需要创建新的 pg-meta2 集群分支,然后在其上运行 pitr。
11.9.5 - 恢复操作 从备份恢复 PostgreSQL
您可以使用预配置的 pgbackrest 在 Pigsty 中执行时间点恢复(PITR)。
剧本方式 :使用 pgsql-pitr.yml 剧本自动执行 PITR手动方式 :使用 pg-pitr 脚本手动执行 PITR快速上手 如果您想将 pg-meta 集群回滚到之前的时间点,添加 pg_pitr 参数:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta2
pg_pitr : { time : '2025-07-13 10:00:00+00' } # 从最新备份恢复
然后运行 pgsql-pitr.yml 剧本,它将把 pg-meta 集群回滚到指定时间点。
./pgsql-pitr.yml -l pg-meta
恢复后处理 恢复后的集群会禁用 archive_mode,以防止意外的 WAL 写入。
如果恢复后的数据库状态正常,您可以启用 archive_mode 并执行全量备份。
psql -c 'ALTER SYSTEM RESET archive_mode; SELECT pg_reload_conf();'
pg-backup full # 执行新的全量备份
恢复目标 您可以在 pg_pitr 中指定不同类型的恢复目标,但它们是互斥的:
time :恢复到哪个时间点?name :恢复到命名的恢复点(由 pg_create_restore_point 创建)xid :恢复到特定的事务 ID(TXID/XID)lsn :恢复到特定的 LSN(日志序列号)点如果指定了上述任何参数,恢复类型 会相应设置,
否则将设置为 latest(WAL 归档流的末尾)。
特殊的 immediate 类型可用于指示 pgbackrest 通过在第一个一致点停止来最小化恢复时间。
目标类型
恢复目标类型
latest
time
lsn
xid
name
immediate pg_pitr : { } # 恢复到最新状态(WAL 归档流末尾) pg_pitr : { time : "2025-07-13 10:00:00+00" }pg_pitr : { lsn : "0/4001C80" }pg_pitr : { xid : "250000" }pg_pitr : { name : "some_restore_point" }pg_pitr : { type : "immediate" }按时间恢复 最常用的目标是时间点;您可以指定要恢复到的时间点:
./pgsql-pitr.yml -l pg-meta -e '{"pg_pitr": { "time": "2025-12-27 15:50:00+00" }}'
时间应该是有效的 PostgreSQL TIMESTAMP 格式,建议使用 YYYY-MM-DD HH:MM:SS+TZ。
按名称恢复 您可以使用 pg_create_restore_point 创建命名恢复点:
SELECT pg_create_restore_point ( 'shit_incoming' );
然后在 PITR 中使用该命名恢复点:
./pgsql-pitr.yml -l pg-meta -e '{"pg_pitr": { "name": "shit_incoming" }}'
按 XID 恢复 如果您有一个事务意外删除了某些数据,最好的恢复方式是将数据库恢复到该事务之前的状态。
./pgsql-pitr.yml -e '{"pg_pitr": { "xid": "250000", exclusive: true }}'
您可以从监控仪表盘找到确切的事务 ID,或从 CSVLOG 中的 TXID 字段获取。
包含与排除
目标参数默认是"包含"的,这意味着恢复会包含目标点。
exclusive 标志会排除该确切目标,例如 xid 24999 将是最后一个被重放的事务。
这仅适用于 time、xid、lsn 恢复目标,详情请参阅 recovery_target_inclusive 。
按 LSN 恢复 PostgreSQL 使用 LSN (日志序列号)来标识 WAL 记录的位置。
您可以在很多地方找到它,比如 Pigsty 仪表盘的 PG LSN 面板。
./pgsql-pitr.yml -e '{"pg_pitr": { "lsn": "0/4001C80", timeline: "1" }}'
要恢复到 WAL 流中的确切位置,您还可以指定 timeline 参数(默认为 latest)
恢复来源 cluster:从哪个集群恢复?默认使用当前的 pg_cluster,您可以使用同一 pgbackrest 仓库中的任何其他集群repo:覆盖备份仓库,使用与 pgbackrest_repo 相同的格式set:默认使用 latest 备份集,但您可以通过标签指定特定的 pgbackrest 备份Pigsty 将从 pgbackrest 备份仓库恢复。如果您使用集中式备份仓库(如 MinIO/S3),
可以指定另一个 “stanza”(另一个集群的备份目录)作为恢复来源。
pg-meta2 :
hosts : { 10.10.10.11 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta2
pg_pitr : { cluster : pg-meta } # 从 pg-meta 集群备份恢复
上述配置将标记 PITR 过程使用 pg-meta stanza。
您也可以通过 CLI 参数传递 pg_pitr 参数:
./pgsql-pitr.yml -l pg-meta2 -e '{"pg_pitr": { "cluster": "pg-meta" }}'
从另一个集群 PITR 时也可以使用这些目标:
./pgsql-pitr.yml -l pg-meta2 -e '{"pg_pitr": { "cluster": "pg-meta", "time": "2025-07-14 08:00:00+00" }}'
分步执行 这种方式是半自动的,您将参与 PITR 过程以做出关键决策。
例如,此配置将把 pg-meta 集群本身恢复到指定时间点:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta2
pg_pitr : { time : '2025-07-13 10:00:00+00' } # 从最新备份恢复
让我们逐步执行:
./pgsql-pitr.yml -l pg-meta -t down # 暂停 patroni 高可用
./pgsql-pitr.yml -l pg-meta -t pitr # 运行 pitr 过程
./pgsql-pitr.yml -l pg-meta -t up # 生成 pgbackrest 配置和恢复脚本
# down : # 停止高可用并关闭 patroni 和 postgres
# - pause : # 暂停 patroni 自动故障切换
# - stop : # 停止 patroni 和 postgres 服务
# - stop_patroni : # 停止 patroni 服务
# - stop_postgres : # 停止 postgres 服务
# pitr : # 执行 PITR 过程
# - config : # 生成 pgbackrest 配置和恢复脚本
# - restore : # 运行 pgbackrest 恢复命令
# - recovery : # 启动 postgres 并完成恢复
# - verify : # 验证恢复后的集群控制数据
# up: : # 启动 postgres / patroni 并恢复高可用
# - etcd : # 启动前清理 etcd 元数据
# - start : # 启动 patroni 和 postgres 服务
# - start_postgres : # 启动 postgres 服务
# - start_patroni : # 启动 patroni 服务
# - resume : # 恢复 patroni 自动故障切换
PITR 参数定义 pg_pitr 参数还有更多可用选项:
pg_pitr : # 定义 PITR 任务
cluster : "some_pg_cls_name" # 源集群名称
type : default # 恢复目标类型:time, xid, name, lsn, immediate, default
time : "2025-01-01 10:00:00+00" # 恢复目标:时间,与 xid, name, lsn 互斥
name : "some_restore_point" # 恢复目标:命名恢复点,与 time, xid, lsn 互斥
xid : "100000" # 恢复目标:事务 ID,与 time, name, lsn 互斥
lsn : "0/3000000" # 恢复目标:日志序列号,与 time, name, xid 互斥
timeline : latest # 目标时间线,可以是整数,默认为 latest
exclusive : false # 是否排除目标点,默认为 false
action : pause # 恢复后操作:pause, promote, shutdown
archive : false # 是否保留归档设置?默认为 false
db_exclude : [ template0, template1 ]
db_include : []
link_map :
pg_wal : '/data/wal'
pg_xact : '/data/pg_xact'
process : 4 # 并行恢复进程数
repo : {} # 恢复来源仓库
data : /pg/data # 数据恢复位置
port : 5432 # 恢复实例的监听端口
11.9.6 - 手工恢复 在沙箱环境中按照提示脚本手动执行 PITR
您可以使用 pgsql-pitr.yml 剧本执行 PITR,但在某些情况下,您可能希望手动执行 PITR,直接使用 pgbackrest 原语实现精细的控制。
我们将使用带有 MinIO 备份仓库的四节点沙箱 集群来演示该过程。
初始化沙箱 使用 vagrant 或 terraform 准备四节点沙箱环境,然后:
curl https://repo.pigsty.io/get | bash; cd ~/pigsty/
./configure -c full
./install
现在以管理节点上的管理员用户(或 dbsu)身份操作。
检查备份 要检查备份状态,您需要切换到 postgres 用户并使用 pb 命令:
sudo su - postgres # 切换到 dbsu: postgres 用户
pb info # 打印 pgbackrest 备份信息
pb 是 pgbackrest 的别名,会自动从 pgbackrest 配置中获取 stanza 名称。
function pb() {
local stanza = $( grep -o '\[[^][]*]' /etc/pgbackrest/pgbackrest.conf | head -n1 | sed 's/.*\[\([^]]*\)].*/\1/' )
pgbackrest --stanza= $stanza $@
}
您可以看到初始备份信息,这是一个全量备份:
root@pg-meta-1:~# pb info
stanza: pg-meta
status: ok
cipher: aes-256-cbc
db (current)
wal archive min/max (17): 000000010000000000000001/000000010000000000000007
full backup: 20250713-022731F
timestamp start/stop: 2025-07-13 02:27:31+00 / 2025-07-13 02:27:33+00
wal start/stop: 000000010000000000000004 / 000000010000000000000004
database size: 44MB, database backup size: 44MB
repo1: backup size: 8.4MB
备份完成于 2025-07-13 02:27:33+00,这是您可以恢复到的最早时间。
由于 WAL 归档处于活动状态,您可以恢复到备份之后的任何时间点,直到 WAL 结束(即现在)。
生成心跳 您可以生成一些心跳来模拟工作负载。/pg-bin/pg-heartbeat 就是用于此目的的,
它每秒向 monitor.heartbeat 表写入一个心跳时间戳。
心跳生成
alias
pgbench
output make rh # 运行心跳: ssh 10.10.10.10 'sudo -iu postgres /pg/bin/pg-heartbeat' ssh 10.10.10.10 'sudo -iu postgres /pg/bin/pg-heartbeat' cls | ts | lsn | lsn_int | txid | status | now | elapse
---------+-------------------------------+------------+-----------+------+---------+-----------------+----------
pg-meta | 2025-07-13 03:01:20.318234+00 | 0/115BF5C0 | 291239360 | 4812 | leading | 03:01:20.318234 | 00:00:00 您甚至可以向集群添加更多工作负载,让我们使用 pgbench 生成一些随机写入:
pgbench 负载
alias
pgbench
output make ri # 初始化 pgbench
make rw # 运行 pgbench 读写工作负载 pgbench -is10 postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5433/meta
while true; do pgbench -nv -P1 -c4 --rate= 64 -T10 postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5433/meta; done while true; do pgbench -nv -P1 -c4 --rate= 64 -T10 postgres://dbuser_meta:DBUser.Meta@10.10.10.10:5433/meta; done
pgbench ( 17.5 ( Homebrew) , server 17.4 ( Ubuntu 17.4-1.pgdg24.04+2))
progress: 1.0 s, 60.9 tps, lat 7.295 ms stddev 4.219, 0 failed, lag 1.818 ms
progress: 2.0 s, 69.1 tps, lat 6.296 ms stddev 1.983, 0 failed, lag 1.397 ms
... PITR 手册 现在让我们选择一个恢复时间点,比如 2025-07-13 03:03:03+00,这是初始备份(和心跳)之后的一个时间点。
要执行手动 PITR,使用 pg-pitr 工具:
$ pg-pitr -t "2025-07-13 03:03:00+00"
它会为您生成执行恢复的指令,通常需要四个步骤:
Perform time PITR on pg-meta
[ 1. Stop PostgreSQL] ===========================================
1.1 Pause Patroni ( if there are any replicas)
$ pg pause <cls> # 暂停 patroni 自动故障切换
1.2 Shutdown Patroni
$ pt-stop # sudo systemctl stop patroni
1.3 Shutdown Postgres
$ pg-stop # pg_ctl -D /pg/data stop -m fast
[ 2. Perform PITR] ===========================================
2.1 Restore Backup
$ pgbackrest --stanza= pg-meta --type= time --target= '2025-07-13 03:03:00+00' restore
2.2 Start PG to Replay WAL
$ pg-start # pg_ctl -D /pg/data start
2.3 Validate and Promote
- If database content is ok, promote it to finish recovery, otherwise goto 2.1
$ pg-promote # pg_ctl -D /pg/data promote
[ 3. Restore Primary] ===========================================
3.1 Enable Archive Mode ( Restart Required)
$ psql -c 'ALTER SYSTEM SET archive_mode = on;'
3.1 Restart Postgres to Apply Changes
$ pg-restart # pg_ctl -D /pg/data restart
3.3 Restart Patroni
$ pt-restart # sudo systemctl restart patroni
[ 4. Restore Cluster] ===========================================
4.1 Re-Init All [ **REPLICAS**] ( if any)
- 4.1.1 option 1: restore replicas with same pgbackrest cmd ( require central backup repo)
$ pgbackrest --stanza= pg-meta --type= time --target= '2025-07-13 03:03:00+00' restore
- 4.1.2 option 2: nuke the replica data dir and restart patroni ( may take long time to restore)
$ rm -rf /pg/data/*; pt-restart
- 4.1.3 option 3: reinit with patroni, which may fail if primary lsn < replica lsn
$ pg reinit pg-meta
4.2 Resume Patroni
$ pg resume pg-meta
4.3 Full Backup ( optional)
$ pg-backup full # 建议在 PITR 后执行新的全量备份
单节点示例 让我们从简单的单节点 pg-meta 集群开始,作为一个更简单的示例。
关闭数据库
关闭服务
shutdown patroni
shutdown postgres pt-stop # sudo systemctl stop patroni,关闭 patroni(和 postgres) # 可选,因为如果 patroni 未暂停,postgres 会被 patroni 关闭
$ pg_stop # pg_ctl -D /pg/data stop -m fast,关闭 postgres
pg_ctl: PID file "/pg/data/postmaster.pid" does not exist
Is server running?
$ pg-ps # 打印 postgres 相关进程
UID PID PPID C STIME TTY STAT TIME CMD
postgres 31048 1 0 02:27 ? Ssl 0:19 /usr/sbin/pgbouncer /etc/pgbouncer/pgbouncer.ini
postgres 32026 1 0 02:28 ? Ssl 0:03 /usr/bin/pg_exporter ...
postgres 35510 35480 0 03:01 pts/2 S+ 0:00 /bin/bash /pg/bin/pg-heartbeat 确保本地 postgres 没有运行,然后执行手册中给出的恢复命令:
恢复备份 pgbackrest --stanza= pg-meta --type= time --target= '2025-07-13 03:03:00+00' restore postgres@pg-meta-1:~$ pgbackrest --stanza= pg-meta --type= time --target= '2025-07-13 03:03:00+00' restore
2025-07-13 03:17:07.443 P00 INFO: restore command begin 2.54.2: ...
2025-07-13 03:17:07.470 P00 INFO: repo1: restore backup set 20250713-022731F, recovery will start at 2025-07-13 02:27:31
2025-07-13 03:17:07.471 P00 INFO: remove invalid files/links/paths from '/pg/data'
2025-07-13 03:17:08.523 P00 INFO: write updated /pg/data/postgresql.auto.conf
2025-07-13 03:17:08.527 P00 INFO: restore size = 44MB, file total = 1436
2025-07-13 03:17:08.527 P00 INFO: restore command end: completed successfully ( 1087ms) 验证数据 我们不希望 patroni HA 接管,直到确定数据正确,所以手动启动 postgres:
验证数据
start postgres
output waiting for server to start....2025-07-13 03:19:33.133 UTC [ 39294] LOG: redirecting log output to logging collector process
2025-07-13 03:19:33.133 UTC [ 39294] HINT: Future log output will appear in directory "/pg/log/postgres" .
done
server started 现在您可以检查数据,看看是否处于您想要的时间点。
您可以通过检查业务表中的最新时间戳来验证,或者在本例中通过心跳表检查。
postgres@pg-meta-1:~$ psql -c 'table monitor.heartbeat'
id | ts | lsn | txid
---------+-------------------------------+-----------+------
pg-meta | 2025-07-13 03:02:59.214104+00 | 302005504 | 4912
时间戳正好在我们指定的时间点之前!(2025-07-13 03:03:00+00)。
如果这不是您想要的时间点,可以使用不同的时间点重复恢复。
由于恢复是以增量和并行方式执行的,速度非常快。
可以重试直到找到正确的时间点。
提升主库 恢复后的 postgres 集群处于 recovery 模式,因此在提升为主库之前会拒绝任何写操作。
这些恢复参数是由 pgBackRest 在配置文件中生成的。
postgres@pg-meta-1:~$ cat /pg/data/postgresql.auto.conf
# Do not edit this file or use ALTER SYSTEM manually!
# It is managed by Pigsty & Ansible automatically!
# Recovery settings generated by pgBackRest restore on 2025-07-13 03:17:08
archive_mode = 'off'
restore_command = 'pgbackrest --stanza=pg-meta archive-get %f "%p"'
recovery_target_time = '2025-07-13 03:03:00+00'
如果数据正确,您可以提升 它为主库,将其标记为新的领导者并准备接受写入。
pg-promote
waiting for server to promote.... done
server promoted psql -c 'SELECT pg_is_in_recovery()' # 'f' 表示已提升为主库
pg_is_in_recovery
-------------------
f
( 1 row) 新时间线和脑裂
一旦提升,数据库集群将进入新的时间线(领导者纪元)。
如果有任何写流量,将写入新的时间线。
恢复集群 最后,不仅需要恢复数据,还需要恢复集群状态,例如:
Patroni 接管 您的 postgres 是直接启动的,要恢复 HA 接管,您需要启动 patroni 服务:
Patroni 接管
launch patroni
resume patroni pt-start # sudo systemctl start patroni pg resume pg-meta # 恢复 patroni 自动故障切换(如果之前暂停过) 归档模式 archive_mode 在恢复期间被 pgbackrest 禁用。
如果您希望新领导者的写入归档到备份仓库,还需要启用 archive_mode 配置。
归档模式
check archive_mode
reset archive_mode
edit directly psql -c 'show archive_mode'
archive_mode
--------------
off psql -c 'ALTER SYSTEM RESET archive_mode;'
psql -c 'SELECT pg_reload_conf();'
psql -c 'show archive_mode' # 您也可以直接编辑 postgresql.auto.conf 并使用 pg_ctl 重载
sed -i '/archive_mode/d' /pg/data/postgresql.auto.conf
pg_ctl -D /pg/data reload 备份集 通常建议在 PITR 后执行新的全量备份,但这是可选的。
从库 如果您的 postgres 集群有从库,您也需要在每个从库上执行 PITR。
或者,更简单的方法是删除从库数据目录并重启 patroni,这将从主库重新初始化从库。
我们将在下一个多节点集群示例中介绍这种情况。
多节点示例 现在让我们以三节点 pg-test 集群作为 PITR 示例。
11.9.7 - 克隆数据库集群 如何利用 PITR 创建一个新的 PostgreSQL 集群,并恢复到指定时间点?
快速上手 利用 Standby Cluster 创建现有集群的在线副本 利用 PITR 创建现有集群的时间点快照 在 PITR 完成后进行善后,确保新集群的备份流程正常运行 您可以使用 PG PITR 机制克隆整个数据库集群。
重置一个集群的状态 您也可以考虑创建一个全新的空集群,然后利用 PITR,将其重置为 pg-meta 集群的特定状态。
利用这种技术,您可以将现有集群 pg-meta 的任意时间点(备份保留期内)状态克隆到一个新的集群中。
我们依然以 Pigsty 4 节点沙箱环境为例,使用以下命令将 pg-test 集群重置为 pg-meta 集群的最新状态:
./pgsql-pitr.yml -l pg-test -e '{"pg_pitr": { "cluster": "pg-meta" }}'
PITR 善后工作 当你使用 PITR 恢复一个集群后,这个新集群本身的 PITR 功能是被禁用的。
因为如果它也尝试去生成备份,归档 WAL,有可能会写脏数据之前集群的备份仓库。
因此,当你确认这个 PITR 恢复出来的新集群状态符合预期后,你需要执行以下善后工作。
升级备份仓库 Stanza,允许它接纳来自不同集群的新备份(仅当从别的集群恢复时)。 启用 archive_mode,允许新集群归档 WAL 日志(需要重启集群) 执行一个新的全量备份,确保新集群的数据被纳入(可选,也可以等 crontab 定时执行) pb stanza-upgrade
psql -c 'ALTER SYSTEM RESET archive_mode;'
pg-backup full
通过这些操作,你的新集群将从第一次全量备份开始时,拥有自己的备份历史。
如果你跳过这些步骤,新集群本身的备份将无法进行,WAL 归档也不会生效。
意味着你将无法对新集群执行任何备份或 PITR 操作。
不善后的后果 假设您在 pg-test 集群上执行了 PITR 恢复,使用了另外一个集群 pg-meta 的数据,但没有进行善后工作。
那么在下一次例行备份的时候,你会看到下面的错误:
postgres@pg-test-1:~$ pb backup
2025-12-27 10:20:29.336 P00 INFO: backup command begin 2.57.0: --annotation= pg_cluster = pg-test --compress-type= lz4 --delta --exec-id= 21034-171fb30b --expire-auto --log-level-console= info --log-level-file= info --log-path= /pg/log/pgbackrest --pg1-path= /pg/data --pg1-port= 5432 --repo1-block --repo1-bundle --repo1-bundle-limit= 20MiB --repo1-bundle-size= 128MiB --repo1-cipher-pass= <redacted> --repo1-cipher-type= aes-256-cbc --repo1-path= /pgbackrest --repo1-retention-full= 14 --repo1-retention-full-type= time --repo1-s3-bucket= pgsql --repo1-s3-endpoint= sss.pigsty --repo1-s3-key= <redacted> --repo1-s3-key-secret= <redacted> --repo1-s3-region= us-east-1 --repo1-s3-uri-style= path --repo1-storage-ca-file= /etc/pki/ca.crt --repo1-storage-port= 9000 --repo1-type= s3 --stanza= pg-test --start-fast
2025-12-27 10:20:29.357 P00 ERROR: [ 051] : PostgreSQL version 18, system-id 7588470953413201282 do not match stanza version 18, system-id 7588470974940466058
HINT: is this the correct stanza?
2025-12-27 10:20:29.357 P00 INFO: backup command end: aborted with exception [ 051]
postgres@pg-test-1:~$
WAL 日志归档被 pgBackrest 关闭了,因此也不会有 WAL 归档。
克隆一个新集群 例如,假设您有一个集群 pg-meta,现在你想要从 pg-meta 克隆一个 pg-meta2 的新集群。
您可以考虑使用 备份集群 的方式创建一个新的集群 pg-meta2。
pgBackrest 支持增量备份/还原,因此如果您已经通过物理复制拉取了 pg-meta 的数据,通常增量 PITR 还原会非常快。
pb stop --force
pb stanza-delete --force
pb start
pb stanza-create
./pgsql-rm.yml -t pg_backup -l pg-test -e pg_rm_backup = true
./pgsql.yml -t pg_backup -l pg-test
如果您想要将 pg-test 集群重置为 pg-meta 集群在 2025 年 12 月 26 日 15:30 的状态,可以使用以下命令:
./pgsql-pitr.yml -l pg-test -e '{"pg_pitr": { "cluster": "pg-meta", "time": "2025-12-27 17:50:00+08" ,archive: true }}'
当然,您也可以直接创建一个全新的集群,然后使用 pgsql-pitr.yml 剧本从 pg-meta 恢复数据到新集群 pg-meta2 并顶替新集群的数据目录。
使用这种技术,您不仅可以克隆 pg-meta 集群的最新状态,还可以克隆到任意时间点,例如:
11.9.8 - 实例恢复 在同一台机器上克隆实例并执行时间点恢复
Pigsty 提供了两个实用脚本,用于在同一台机器上快速克隆实例并执行时间点恢复:
这两个脚本可以配合使用:先用 pg-fork 克隆实例,再用 pg-pitr 将克隆实例恢复到指定时间点。
pg-fork pg-fork 可以在同一台机器上快速克隆一个新的 PostgreSQL 实例。
快速上手 使用 postgres 用户(dbsu)执行以下命令,即可创建一个新的实例:
pg-fork 1 # 从 /pg/data 克隆到 /pg/data1,端口 15432
pg-fork 2 -d /pg/data1 # 从 /pg/data1 克隆到 /pg/data2,端口 25432
pg-fork 3 -D /tmp/test -P 5555 # 克隆到自定义目录和端口
克隆完成后,可以启动并访问新实例:
pg_ctl -D /pg/data1 start # 启动克隆实例
psql -p 15432 # 连接克隆实例
命令语法 pg-fork <FORK_ID> [ options]
必填参数:
参数 说明 <FORK_ID>克隆实例编号(1-9),决定默认端口和数据目录
可选参数:
参数 说明 默认值 -d, --data <datadir>源实例数据目录 /pg/data 或 $PG_DATA-D, --dst <dst_dir>目标数据目录 /pg/data<FORK_ID>-p, --port <port>源实例端口 5432 或 $PG_PORT-P, --dst-port <port>目标实例端口 <FORK_ID>5432-s, --skip跳过备份 API,使用冷拷贝模式 - -y, --yes跳过确认提示 - -h, --help显示帮助信息 -
使用示例
pg-fork 示例
基础克隆
指定源端口
链式克隆
自定义位置
冷拷贝模式 # 从默认实例克隆到 /pg/data1,端口 15432
pg-fork 1
# 从默认实例克隆到 /pg/data2,端口 25432
pg-fork 2 # 从端口 5433 的实例克隆
pg-fork 1 -p 5433
# 使用环境变量指定源端口
PG_PORT = 5433 pg-fork 1 # 从 /pg/data1 克隆到 /pg/data2
pg-fork 2 -d /pg/data1
# 从 /pg/data2 克隆到 /pg/data3
pg-fork 3 -d /pg/data2 # 克隆到自定义目录和端口
pg-fork 1 -D /tmp/pgtest -P 5555
# 完全自定义
pg-fork 1 -d /pg/data -D /mnt/backup/pgclone -P 6543 # 源实例已停止时使用冷拷贝
pg-fork 1 -s
# 跳过确认直接执行
pg-fork 1 -s -y 工作原理 pg-fork 支持两种工作模式:
热备份模式 (默认,源实例运行中):
调用 pg_backup_start() 开始备份 使用 cp --reflink=auto 拷贝数据目录 调用 pg_backup_stop() 结束备份 修改配置文件,避免与源实例冲突 冷拷贝模式 (使用 -s 参数或源实例未运行):
直接使用 cp --reflink=auto 拷贝数据目录 修改配置文件 CoW 快速克隆
如果您使用 XFS(启用 reflink)、Btrfs 或 ZFS 文件系统,pg-fork 会利用 Copy-on-Write 特性,
数据目录拷贝在几百毫秒内完成,且几乎不占用额外存储空间。只有在数据被修改时才会分配新的存储块。
克隆后配置 pg-fork 会自动修改克隆实例的以下配置:
配置项 修改内容 port改为目标端口(避免冲突) archive_mode设为 off(避免污染 WAL 归档) log_directory设为 log(使用数据目录下的日志) primary_conninfo移除(创建独立实例) standby.signal移除(创建独立实例) pg_replslot/*清空(避免复制槽冲突)
典型工作流 # 1. 克隆实例用于测试
pg-fork 1 -y
# 2. 启动克隆实例
pg_ctl -D /pg/data1 start
# 3. 在克隆实例上测试(不影响生产)
psql -p 15432 -c "DROP TABLE important_data;" # 安全测试
# 4. 测试完成后清理
pg_ctl -D /pg/data1 stop
rm -rf /pg/data1
pg-pitr pg-pitr 是一个用于手动执行时间点恢复的脚本,基于 pgbackrest。
快速上手 pg-pitr -d # 恢复到最新状态
pg-pitr -i # 恢复到备份完成时间
pg-pitr -t "2025-01-01 12:00:00+08" # 恢复到指定时间点
pg-pitr -n my-savepoint # 恢复到命名恢复点
pg-pitr -l "0/7C82CB8" # 恢复到指定 LSN
pg-pitr -x 12345678 -X # 恢复到事务之前
pg-pitr -b 20251225-120000F # 恢复到指定备份集
命令语法 pg-pitr [ options] [ recovery_target]
恢复目标(选择一个):
参数 说明 -d, --default恢复到 WAL 归档流末尾(最新状态) -i, --immediate恢复到数据库一致性点(最快恢复) -t, --time <timestamp>恢复到指定时间点 -n, --name <restore_point>恢复到命名恢复点 -l, --lsn <lsn>恢复到指定 LSN -x, --xid <xid>恢复到指定事务 ID -b, --backup <label>恢复到指定备份集
可选参数:
参数 说明 默认值 -D, --data <path>恢复目标数据目录 /pg/data-s, --stanza <name>pgbackrest stanza 名称 自动检测 -X, --exclusive排除目标点(恢复到目标之前) - -P, --promote恢复后自动提升(默认暂停) - -c, --check干运行模式,仅打印命令 - -y, --yes跳过确认和倒计时 - -h, --help显示帮助信息 -
恢复目标类型
恢复目标
latest
immediate
time
name
lsn
xid
backup # 恢复到 WAL 归档流末尾(最新状态)
pg-pitr -d
# 这是默认行为,会重放所有可用的 WAL # 恢复到数据库一致性点
pg-pitr -i
# 最快的恢复方式,不重放额外的 WAL
# 适用于快速验证备份是否可用 # 恢复到指定时间点
pg-pitr -t "2025-01-01 12:00:00+08"
# 使用 UTC 时间
pg-pitr -t "2025-01-01 04:00:00+00"
# 时间格式:YYYY-MM-DD HH:MM:SS[.usec][+/-TZ] # 恢复到命名恢复点
pg-pitr -n my-savepoint
# 恢复点需要事先使用 pg_create_restore_point() 创建
# SELECT pg_create_restore_point('my-savepoint'); # 恢复到指定 LSN
pg-pitr -l "0/7C82CB8"
# LSN 可以从监控面板或 pg_current_wal_lsn() 获取 # 恢复到指定事务 ID
pg-pitr -x 12345678
# 恢复到事务之前(不包含该事务)
pg-pitr -x 12345678 -X # 恢复到指定备份集
pg-pitr -b 20251225-120000F
# 查看可用备份集
pgbackrest info 使用示例 恢复到指定时间点:
# 1. 停止 PostgreSQL
pg_ctl -D /pg/data stop -m fast
# 2. 执行 PITR
pg-pitr -t "2025-12-27 10:00:00+08"
# 3. 启动并验证
pg_ctl -D /pg/data start
psql -c "SELECT * FROM important_table;"
# 4. 确认无误后提升
pg_ctl -D /pg/data promote
# 5. 启用归档并执行新备份
psql -c "ALTER SYSTEM SET archive_mode = on;"
pg_ctl -D /pg/data restart
pg-backup full
恢复到克隆实例:
# 1. 克隆实例
pg-fork 1 -y
# 2. 在克隆实例上执行 PITR
pg-pitr -D /pg/data1 -t "2025-12-27 10:00:00+08"
# 3. 启动克隆实例验证
pg_ctl -D /pg/data1 start
psql -p 15432
干运行模式:
# 仅打印命令,不执行
pg-pitr -t "2025-12-27 10:00:00+08" -c
# 输出示例:
# Command:
# pgbackrest --stanza=pg-meta --delta --force --type=time --target="2025-12-27 10:00:00+08" restore
恢复后处理 恢复完成后,实例会处于恢复暂停 状态(除非使用 -P 参数)。您需要:
启动实例 :pg_ctl -D /pg/data start验证数据 :检查数据是否符合预期提升实例 :pg_ctl -D /pg/data promote启用归档 :psql -c "ALTER SYSTEM SET archive_mode = on;"重启实例 :pg_ctl -D /pg/data restart执行备份 :pg-backup full重要提示
恢复后的实例 archive_mode 被设为 off,以防止意外的 WAL 写入污染归档仓库。
确认数据正确后,务必重新启用归档并执行全量备份。
组合使用 pg-fork 和 pg-pitr 可以组合使用,实现安全的 PITR 验证流程:
# 1. 克隆当前实例
pg-fork 1 -y
# 2. 在克隆实例上执行 PITR(不影响生产)
pg-pitr -D /pg/data1 -t "2025-12-27 10:00:00+08"
# 3. 启动克隆实例
pg_ctl -D /pg/data1 start
# 4. 验证恢复结果
psql -p 15432 -c "SELECT count(*) FROM orders WHERE created_at < '2025-12-27 10:00:00';"
# 5. 确认无误后,可以选择:
# - 方案A:在生产实例上执行相同的 PITR
# - 方案B:将克隆实例提升为新的生产实例
# 6. 清理测试实例
pg_ctl -D /pg/data1 stop
rm -rf /pg/data1
注意事项 运行要求 必须以 postgres 用户(或 postgres 组成员)执行 pg-pitr 执行前必须停止目标实例的 PostgreSQLpg-fork 热备份模式需要源实例正在运行文件系统 推荐使用 XFS(启用 reflink)或 Btrfs 文件系统 CoW 文件系统上克隆几乎瞬间完成,且不占用额外空间 非 CoW 文件系统会执行完整拷贝,耗时较长 端口规划 FORK_ID 默认端口 默认数据目录 1 15432 /pg/data1 2 25432 /pg/data2 3 35432 /pg/data3 … … … 9 95432 /pg/data9
安全建议 克隆实例仅用于测试和验证,不应长期运行 验证完成后及时清理克隆实例 生产环境 PITR 建议使用 pgsql-pitr.yml 剧本 重要操作前先使用 -c 干运行模式确认命令 原理剖析 有时候,您想要用现有的 PostgreSQL 实例在 同一台机器 上创建一个新的实例 (用于测试,PITR 恢复),可以使用 postgres 用户执行下面的命令:
psql <<EOF
CHECKPOINT;
SELECT pg_backup_start('pgfork', true);
\! rm -rf /pg/data2 && cp -r --reflink=auto /pg/data /pg/data2 && ls -alhd /pg/data2
SELECT * FROM pg_backup_stop(false);
EOF
# 修改配置,避免与现有实例冲突:端口,日志,归档等
sed -i 's/^port.*/port = 5431/' /pg/data2/postgresql.conf;
sed -i 's/^log_destination.*/log_destination = stderr/' /pg/data2/postgresql.conf;
sed -i 's/^archive_mode.*/archive_mode = off/' /pg/data2/postgresql.conf;
rm -rf /pg/data2/postmaster.pid /pg/data2/postmaster.opts
pg_ctl -D /pg/data2 start -l /pg/log/pgfork.log
pg_ctl -D /pg/data2 stop
psql -p 5431 # 访问新实例
上面的命令会创建一个新的数据目录 /pg/data2,它是现有数据目录 /pg/data 的一个完整拷贝。
如果您使用的是 XFS (启用了 reflink COW 特性),那么同磁盘拷贝目录会非常快,通常几百毫秒的常数时间内即可完成。
您在原地拉起新实例前,务必 修改 postgresql.conf 里的 port / archive_mode / log_destination 参数,避免影响现有生产实例等运行。
您可以使用一个没有被占用的端口,例如 5431,并将日志输出到 /pg/log/xxxx.log 避免写脏现有实例的日志文件。
我们建议同时修改 shared_buffers Pigsty 默认情况通常分配 25% 的系统内存给 PostgreSQL 实例,
开启新实例时,会与现有实例争夺内存资源。您可以适当调小,以减小对现有生产实例的影响。
11.9.9 - 备份数据库 如何在现有 PostgreSQL 集群中,克隆现有数据库,并利用 xfs 瞬间完成
克隆数据库 你可以通过 template 机制复制一个 PostgreSQL 数据库,但在此期间不允许有任何连接到模版数据库的活动连接。
假设你想要克隆 postgres 数据库,那么必须一次性同时执行下面两条语句。
确保清理掉所有连接到 postgres 数据库的连接后执行 Clone
SELECT pg_terminate_backend ( pid ) FROM pg_stat_activity WHERE datname = 'postgres' ;
CREATE DATABASE pgcopy TEMPLATE postgres STRATEGY FILE_COPY ;
瞬间克隆 如果你使用的是 PostgreSQL 18 以上的版本,Pigsty 默认为您设置了 file_copy_method 。
该参数允许你以 O(1) (约 200ms)的时间复杂度克隆一个数据库,而不需要复制数据文件。
但是您必须显式使用 FILE_COPY 策略来创建数据库。
CREATE DATABASE 的 STRATEGY 参数自 PostgreSQL 15 引入以来的默认值为 WAL_LOG,你需要显式指定 FILE_COPY 来进行瞬间克隆。
SELECT pg_terminate_backend ( pid ) FROM pg_stat_activity WHERE datname = 'meta' ;
CREATE DATABASE pgcopy TEMPLATE meta STRATEGY FILE_COPY ;
例如,克隆一个 30 GB 的数据库,普通克隆(WAL_LOG)用时 18 秒,而瞬间克隆(FILE_COPY)仅需常数时间 200 毫秒。
但是,您仍然需要确保在克隆期间没有任何连接到模版数据库的活动连接,但这个时间可以非常短暂,因此具有生产环境的实用性。
如果您需要一个新的数据库副本用于测试或开发,瞬间克隆是一个非常好的选择。它并不会引入额外的存储开销,因为它使用了文件系统的 CoW(Copy on Write)机制。
Pigsty v4.0 起,您可以在 pg_databases 参数中使用 strategy: FILE_COPY 来实现瞬间克隆数据库。
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_version : 18
pg_databases :
- name : meta
- name : meta_dev
template : meta
strategy : FILE_COPY # <---- PG 15 引入, PG18 瞬间生效
#comment: "meta clone" # <---- 数据库注释
#pgbouncer: false # <---- 不加入 连接池?
#register_datasource: false # <---- 不加入 Grafana 数据源?
配置完毕后,使用标准数据库创建 SOP 创建该数据库即可:
bin/pgsql-db pg-meta meta_dev
局限性与注意事项 请注意,这个特性仅在支持的文件系统上可用(xfs,brtfs,zfs,apfs),如果文件系统不支持,PostgreSQL 将会报错失败。
默认情况下,主流操作系统发行版的 xfs 都已经默认启用 reflink=1 选项,因此大多数情况下您不需要担心这个问题。
OpenZFS 需要显式配置才能支持 CoW,但因为存在数据损坏的先例,不建议将此特性用于生产。
如果您使用的 PostgreSQL 版本低于 15,指定 strategy 不会有任何效果。
请不要使用 postgres 数据库作为模版数据库进行克隆,因为管理链接通常会连接到 postgres 数据库,这阻止了克隆操作的进行。
如果您确实需要克隆 postgres 数据库,请你手动连接到其他数据库上后,自行执行 SQL 实现。
在极高并发/吞吐的生产环境中使用瞬间克隆需要谨慎,它需要在克隆窗口(200ms)内清理掉所有连接到模版数据库的连接,否则克隆会失败。
11.10 - 数据迁移 如何将现有的 PostgreSQL 集群以最小的停机时间迁移至新的、由Pigsty管理的 PostgreSQL 集群?
Pigsty 内置了一个剧本 pgsql-migration.yml ,基于逻辑复制来实现在线数据库迁移。
通过预生成的自动化脚本,应用停机时间可以缩减到几秒内。但请注意,逻辑复制需要 PostgreSQL 10 以上的版本才能工作。
当然如果您有充足的停机时间预算,那么总是可以使用 pg_dump | psql 的方式进行停机迁移。
定义迁移任务 想要使用Pigsty提供的在线迁移剧本,您需要创建一个定义文件,来描述迁移任务的细节。
请查看任务定义文件示例作为参考: files/migration/pg-meta.yml 。
这个迁移任务要将 pg-meta.meta 在线迁移到 pg-test.test,前者称为 源集群(SRC) , 后者称为 宿集群(DST) 。
pg-meta-1 10.10.10.10 --> pg-test-1 10.10.10.11 (10.10.10.12,10.10.10.13)
基于逻辑复制的迁移以数据库为单位,您需要指定需要迁移的数据库名称,以及数据库源宿集群主节点的 IP 地址,以及超级用户的连接信息。
---
#-----------------------------------------------------------------
# PG_MIGRATION
#-----------------------------------------------------------------
context_dir : ~/migration # 迁移手册 & 脚本的放置目录
#-----------------------------------------------------------------
# SRC Cluster (旧集群)
#-----------------------------------------------------------------
src_cls : pg-meta # 源集群名称 <必填>
src_db : meta # 源数据库名称 <必填>
src_ip : 10.10.10.10 # 源集群主 IP <必填>
#src_pg: '' # 如果定义,使用此作为源 dbsu pgurl 代替:
# # postgres://{{ pg_admin_username }}@{{ src_ip }}/{{ src_db }}
# # 例如: 'postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta'
#sub_conn: '' # 如果定义,使用此作为订阅连接字符串代替:
# # host={{ src_ip }} dbname={{ src_db }} user={{ pg_replication_username }}'
# # 例如: 'host=10.10.10.10 dbname=meta user=replicator password=DBUser.Replicator'
#-----------------------------------------------------------------
# DST Cluster (新集群)
#-----------------------------------------------------------------
dst_cls : pg-test # 宿集群名称 <必填>
dst_db : test # 宿数据库名称 <必填>
dst_ip : 10.10.10.11 # 宿集群主 IP <必填>
#dst_pg: '' # 如果定义,使用此作为目标 dbsu pgurl 代替:
# # postgres://{{ pg_admin_username }}@{{ dst_ip }}/{{ dst_db }}
# # 例如: 'postgres://dbuser_dba:DBUser.DBA@10.10.10.11:5432/test'
#-----------------------------------------------------------------
# PGSQL
#-----------------------------------------------------------------
pg_dbsu : postgres
pg_replication_username : replicator
pg_replication_password : DBUser.Replicator
pg_admin_username : dbuser_dba
pg_admin_password : DBUser.DBA
pg_monitor_username : dbuser_monitor
pg_monitor_password : DBUser.Monitor
#-----------------------------------------------------------------
...
默认情况下,源宿集群两侧的超级用户连接串会使用全局的管理员用户和各自主库的 IP 地址拼接而成,但您总是可以通过 src_pg 和 dst_pg 参数来覆盖这些默认值。
同理,您也可以通过 sub_conn 参数来覆盖订阅连接串的默认值。
生成迁移计划 此剧本不会主动完成集群的迁移工作,但它会生成迁移所需的操作手册与自动化脚本。
默认情况下,你会在 ~/migration/pg-meta.meta 下找到迁移上下文目录。
按照 README.md 的说明,依次执行这些脚本,你就可以完成数据库迁移了!
# 激活迁移上下文:启用相关环境变量
. ~/migration/pg-meta.meta/activate
# 这些脚本用于检查 src 集群状态,并帮助在 pigsty 中生成新的集群定义
./check-user # 检查 src 用户
./check-db # 检查 src 数据库
./check-hba # 检查 src hba 规则
./check-repl # 检查 src 复制身份
./check-misc # 检查 src 特殊对象
# 这些脚本用于在现有的 src 集群和由 pigsty 管理的 dst 集群之间建立逻辑复制,除序列外的数据将实时同步
./copy-schema # 将模式复制到目标
./create-pub # 在 src 上创建发布
./create-sub # 在 dst 上创建订阅
./copy-progress # 打印逻辑复制进度
./copy-diff # 通过计数表快速比较 src 和 dst 的差异
# 这些脚本将在在线迁移中运行,该迁移将停止 src 集群,复制序列号(逻辑复制不复制序列号!)
./copy-seq [ n] # 同步序列号,如果给出了 n,则会应用额外的偏移
# 你必须根据你的访问方式(dns,vip,haproxy,pgbouncer等),将应用流量切换至新的集群!
#./disable-src # 将 src 集群访问限制为管理节点和新集群(你的实现)
#./re-routing # 从 SRC 到 DST 重新路由应用流量!(你的实现)
# 然后进行清理以删除订阅和发布
./drop-sub # 迁移后在 dst 上删除订阅
./drop-pub # 迁移后在 src 上删除发布
注意事项
如果担心拷贝序列号时出现主键冲突,您可以在拷贝时将所有序列号向前推进一段距离,例如 +1000 ,你可以使用 ./copy-seq 加一个参数 1000 来实现这一点。
你必须实现自己的 ./re-routing 脚本,以将你的应用流量从 src 路由到 dst。 因为我们不知道你的流量是如何路由的(例如 dns, VIP, haproxy 或 pgbouncer)。 当然,您也可以手动完成这项操作…
你可以实现一个 ./disable-src 脚本来限制应用对 src 集群的访问,这是可选的:如果你能确保所有应用流量都在 ./re-routing 中干净利落地切完,其实不用这一步。
但如果您有未知来源的各种访问无法梳理干净,那么最好使用更为彻底的方式:更改 HBA 规则并重新加载来实现(推荐),或者只是简单粗暴地关停源主库上的 postgres、pgbouncer 或 haproxy 进程。
11.11 - 监控系统 Pigsty监控系统架构概览,以及如何监控现存的 PostgreSQL 实例?
本文介绍了 Pigsty 的监控系统架构,包括监控指标,日志,与目标管理的方式。以及如何监控现有PG集群 与远程 RDS服务 。
监控概览 Pigsty使用现代的可观测技术栈对 PostgreSQL 进行监控:
使用 Grafana 进行指标可视化和 PostgreSQL 数据源。 使用 Prometheus 来采集 PostgreSQL / Pgbouncer / Patroni / HAProxy / Node 的指标 使用 Loki 来记录 PostgreSQL / Pgbouncer / Patroni / pgBackRest 以及主机组件的日志 Pigsty 提供了开箱即用的 Grafana 仪表盘 ,展示与 PostgreSQL 有关的方方面面。 监控指标
PostgreSQL 本身的监控指标完全由 pg_exporter 配置文件所定义:pg_exporter.yml
它将进一步被 Prometheus 记录规则和告警规则进行加工处理:files/prometheus/rules/pgsql.yml 。
Pigsty使用三个身份标签:cls、ins、ip,它们将附加到所有指标和日志上。此外,Pgbouncer的监控指标,主机节点 NODE,与负载均衡器的监控指标也会被 Pigsty 所使用,并尽可能地使用相同的标签以便于关联分析。
{ cls: pg-meta, ins: pg-meta-1, ip : 10.10.10.10 }
{ cls: pg-meta, ins: pg-test-1, ip : 10.10.10.11 }
{ cls: pg-meta, ins: pg-test-2, ip : 10.10.10.12 }
{ cls: pg-meta, ins: pg-test-3, ip : 10.10.10.13 }
日志
与 PostgreSQL 有关的日志由 promtail 负责收集,并发送至 infra 节点上的 Loki 日志存储/查询服务。
目标管理
Prometheus的监控目标在 /etc/prometheus/targets/pgsql/ 下的静态文件中定义,每个实例都有一个相应的文件。以 pg-meta-1 为例:
# pg-meta-1 [primary] @ 10.10.10.10
- labels : { cls: pg-meta, ins: pg-meta-1, ip : 10.10.10.10 }
targets :
- 10.10.10.10 : 9630 # <--- pg_exporter 用于PostgreSQL指标
- 10.10.10.10 : 9631 # <--- pg_exporter 用于pgbouncer指标
- 10.10.10.10 : 8008 # <--- patroni指标(未启用 API SSL 时)
当全局标志 patroni_ssl_enabled 被设置时,patroni目标将被移动到单独的文件 /etc/prometheus/targets/patroni/<ins>.yml。 因为此时使用的是 https 抓取端点。当您监控RDS 实例时,监控目标会被单独放置于: /etc/prometheus/targets/pgrds/ 目录下,并以集群 为单位进行管理。
当使用 bin/pgsql-rm 或 pgsql-rm.yml 移除集群时,Prometheus监控目标将被移除。您也可以手动移除它,或使用剧本里的子任务:
bin/pgmon-rm <cls| ins> # 从所有infra节点中移除 prometheus 监控目标
远程 RDS 监控目标会被放置于 /etc/prometheus/targets/pgrds/<cls>.yml,它们是由 pgsql-monitor.yml 剧本或 bin/pgmon-add 脚本所创建的。
监控模式 Pigsty 提供三种监控模式,以适应不同的监控需求。
事项\等级 L1 L2 L3 名称 基础部署 托管部署 标准部署 英文 RDS MANAGED FULL 场景 只有连接串,例如RDS DB已存在,节点可管理 实例由 Pigsty 创建 PGCAT功能 ✅ 完整可用 ✅ 完整可用 ✅ 完整可用 PGSQL功能 ✅ 限PG指标 ✅ 限PG与节点指标 ✅ 完整功能 连接池指标 ❌ 不可用 ⚠️ 选装 ✅ 预装项 负载均衡器指标 ❌ 不可用 ⚠️ 选装 ✅ 预装项 PGLOG功能 ❌ 不可用 ⚠️ 选装 ✅ 预装项 PG Exporter ⚠️ 部署于Infra节点 ✅ 部署于DB节点 ✅ 部署于DB节点 Node Exporter ❌ 不部署 ✅ 部署于DB节点 ✅ 部署于DB节点 侵入DB节点 ✅ 无侵入 ⚠️ 安装Exporter ⚠️ 完全由Pigsty管理 监控现有实例 ✅ 可支持 ✅ 可支持 ❌ 仅用于Pigsty托管实例 监控用户与视图 人工创建 人工创建 Pigsty自动创建 部署使用剧本 bin/pgmon-add <cls>部分执行 pgsql.ym/node.yml pgsql.yml所需权限 Infra 节点可达的 PGURL DB节点ssh与sudo权限 DB节点ssh与sudo权限 功能概述 PGCAT + PGRDS 大部分功能 完整功能
由Pigsty完全管理的数据库会自动纳入监控,并拥有最好的监控支持,通常不需要任何配置。对于现有的 PostgreSQL 集群或者 RDS 服务,如果如果目标DB节点可以被Pigsty所管理 (ssh可达,sudo可用),那么您可以考虑 托管部署 ,实现与 Pigsty 基本类似的监控管理体验。如果您只能通过PGURL (数据库连接串)的方式访问目标数据库,例如远程的RDS服务,则可以考虑使用 精简模式 监控目标数据库。
监控现有集群 如果目标DB节点可以被Pigsty所管理 (ssh可达且sudo可用),那么您可以使用 pgsql.yml 剧本中的pg_exporter任务,
使用与标准部署相同的的方式,在目标节点上部署监控组件:PG Exporter。您也可以使用该剧本的 pgbouncer,pgbouncer_exporter 任务在已有实例节点上部署连接池及其监控。此外,您也可以使用 node.yml 中的 node_exporter, haproxy, promtail 部署主机监控,负载均衡,日志收集组件。从而获得与原生Pigsty数据库实例完全一致的使用体验。
现有集群的定义方式与 Pigsty 所管理的集群定义方式完全相同,您只是选择性执行 pgsql.yml 剧本中的部分任务,而不是执行整个剧本。
./node.yml -l <cls> -t node_repo,node_pkg # 在主机节点上添加 INFRA节点的 YUM 源并安装软件包。
./node.yml -l <cls> -t node_exporter,node_register # 配置主机监控,并加入 Prometheus
./node.yml -l <cls> -t promtail # 配置主机日志采集,并发送至 Loki
./pgsql.yml -l <cls> -t pg_exporter,pg_register # 配置 PostgreSQL 监控,并注册至 Prometheus/Grafana
因为目标数据库集群已存在,所以您需要手工在目标数据库集群上创建监控用户、模式与扩展 。
监控RDS 如果您只能通过PGURL (数据库连接串)的方式访问目标数据库,那么可以参照这里的说明进行配置。在这种模式下,Pigsty 在 INFRA节点 上部署对应的 PG Exporter,抓取远端数据库指标信息。如下图所示:
------ infra ------
| |
| prometheus | v---- pg-foo-1 ----v
| ^ | metrics | ^ |
| pg_exporter <-|------------|---- postgres |
| (port: 20001) | | 10.10.10.10:5432 |
| ^ | ^------------------^
| ^ | ^
| ^ | v---- pg-foo-2 ----v
| ^ | metrics | ^ |
| pg_exporter <-|------------|---- postgres |
| (port: 20002) | | 10.10.10.11:5433 |
------------------- ^------------------^
在这种模式下,监控系统不会有主机,连接池,负载均衡器,高可用组件的相关指标,但数据库本身,以及数据目录(Catalog)中的实时状态信息仍然可用。Pigsty提供了两个专用的监控面板,专注于 PostgreSQL 本身的监控指标: PGRDS Cluster 与 PGRDS Instance ,总览与数据库内监控则复用现有监控面板。因为Pigsty不能管理您的RDS,所以用户需要在目标数据库上提前配置好监控对象 。
监控外部 Postgres 实例时的局限性
pgBoucner 连接池指标不可用 Patroni 高可用组件指标不可用 主机节点监控指标不可用,以及节点 HAProxy,Keepalived 指标亦不可用。 日志收集与日志衍生指标不可用 下面我们使用沙箱环境作为示例:现在我们假设 pg-meta 集群是一个有待监控的 RDS 实例 pg-foo-1,而 pg-test 集群则是一个有待监控的RDS集群 pg-bar:
在目标上创建监控模式、用户和权限。详情请参考监控对象配置
在配置清单中声明集群。例如,假设我们想要监控“远端”的 pg-meta & pg-test 集群:
infra : # 代理、监控、警报等的infra集群..
hosts : { 10.10.10.10 : { infra_seq : 1 } }
vars : # 在组'infra'上为远程postgres RDS安装pg_exporter
pg_exporters : # 在此列出所有远程实例,为k分配一个唯一的未使用的本地端口
20001 : { pg_cluster: pg-foo, pg_seq: 1, pg_host: 10.10.10.10 , pg_databases : [ { name : meta }] } # 注册 meta 数据库为 Grafana 数据源
20002 : { pg_cluster: pg-bar, pg_seq: 1, pg_host: 10.10.10.11 , pg_port : 5432 } # 几种不同的连接串拼接方法
20003 : { pg_cluster: pg-bar, pg_seq: 2, pg_host: 10.10.10.12 , pg_exporter_url : 'postgres://dbuser_monitor:DBUser.Monitor@10.10.10.12:5432/postgres?sslmode=disable' }
20004 : { pg_cluster: pg-bar, pg_seq: 3, pg_host: 10.10.10.13 , pg_monitor_username: dbuser_monitor, pg_monitor_password : DBUser.Monitor }
其中, pg_databases 字段中所列出的数据库,将会被注册至 Grafana 中,成为一个 PostgreSQL 数据源,为 PGCAT 监控面板提供数据支持。如果您不想使用PGCAT,将注册数据库到Grafana中,只需要将 pg_databases 设置为空数组或直接留空即可。
执行添加监控命令:bin/pgmon-add <clsname>
bin/pgmon-add pg-foo # 将 pg-foo 集群纳入监控
bin/pgmon-add pg-bar # 将 pg-bar 集群纳入监控
要删除远程集群的监控目标,可以使用 bin/pgmon-rm <clsname>
bin/pgmon-rm pg-foo # 将 pg-foo 从 Pigsty 监控中移除
bin/pgmon-rm pg-bar # 将 pg-bar 从 Pigsty 监控中移除
您可以使用更多的参数来覆盖默认 pg_exporter 的选项,下面是一个使用 Pigsty 监控阿里云 RDS 与 PolarDB 的配置样例:
示例:监控阿里云 RDS for PostgreSQL 与 PolarDB 详情请参考:remote.yml
infra : # 代理、监控、警报等的infra集群..
hosts : { 10.10.10.10 : { infra_seq : 1 } }
vars :
pg_exporters : # 在此列出所有待监控的远程 RDS PG 实例
20001 : # 分配一个唯一的未使用的本地端口,供本地监控 Agent 使用,这里是一个 PolarDB 的主库
pg_cluster : pg-polar # RDS 集群名 (身份参数,手工指定分配监控系统内名称)
pg_seq : 1 # RDS 实例号 (身份参数,手工指定分配监控系统内名称)
pg_host : pc-2ze379wb1d4irc18x.polardbpg.rds.aliyuncs.com # RDS 主机地址
pg_port : 1921 # RDS 端口(从控制台连接信息获取)
pg_exporter_auto_discovery : true # 禁用新数据库自动发现功能
pg_exporter_include_database : 'test' # 仅监控这个列表中的数据库(多个数据库用逗号分隔)
pg_monitor_username : dbuser_monitor # 监控用的用户名,覆盖全局配置
pg_monitor_password : DBUser_Monitor # 监控用的密码,覆盖全局配置
pg_databases : [ { name : test }] # 希望启用PGCAT的数据库列表,只要name字段即可,register_datasource设置为false则不注册。
20002 : # 这是一个 PolarDB 从库
pg_cluster : pg-polar # RDS 集群名 (身份参数,手工指定分配监控系统内名称)
pg_seq : 2 # RDS 实例号 (身份参数,手工指定分配监控系统内名称)
pg_host : pe-2ze7tg620e317ufj4.polarpgmxs.rds.aliyuncs.com # RDS 主机地址
pg_port : 1521 # RDS 端口(从控制台连接信息获取)
pg_exporter_auto_discovery : true # 禁用新数据库自动发现功能
pg_exporter_include_database : 'test,postgres' # 仅监控这个列表中的数据库(多个数据库用逗号分隔)
pg_monitor_username : dbuser_monitor # 监控用的用户名
pg_monitor_password : DBUser_Monitor # 监控用的密码
pg_databases : [ { name : test } ] # 希望启用PGCAT的数据库列表,只要name字段即可,register_datasource设置为false则不注册。
20004 : # 这是一个基础版的单节点 RDS for PostgreSQL 实例
pg_cluster : pg-rds # RDS 集群名 (身份参数,手工指定分配监控系统内名称)
pg_seq : 1 # RDS 实例号 (身份参数,手工指定分配监控系统内名称)
pg_host : pgm-2zern3d323fe9ewk.pg.rds.aliyuncs.com # RDS 主机地址
pg_port : 5432 # RDS 端口(从控制台连接信息获取)
pg_exporter_auto_discovery : true # 禁用新数据库自动发现功能
pg_exporter_include_database : 'rds' # 仅监控这个列表中的数据库(多个数据库用逗号分隔)
pg_monitor_username : dbuser_monitor # 监控用的用户名
pg_monitor_password : DBUser_Monitor # 监控用的密码
pg_databases : [ { name : rds } ] # 希望启用PGCAT的数据库列表,只要name字段即可,register_datasource设置为false则不注册。
20005 : # 这是一个高可用版的 RDS for PostgreSQL 集群主库
pg_cluster : pg-rdsha # RDS 集群名 (身份参数,手工指定分配监控系统内名称)
pg_seq : 1 # RDS 实例号 (身份参数,手工指定分配监控系统内名称)
pg_host : pgm-2ze3d35d27bq08wu.pg.rds.aliyuncs.com # RDS 主机地址
pg_port : 5432 # RDS 端口(从控制台连接信息获取)
pg_exporter_include_database : 'rds' # 仅监控这个列表中的数据库(多个数据库用逗号分隔)
pg_databases : [ { name : rds }, {name : test} ] # 将这两个数据库纳入 PGCAT 管理,注册为 Grafana 数据源
20006 : # 这是一个高可用版的 RDS for PostgreSQL 集群只读实例(从库)
pg_cluster : pg-rdsha # RDS 集群名 (身份参数,手工指定分配监控系统内名称)
pg_seq : 2 # RDS 实例号 (身份参数,手工指定分配监控系统内名称)
pg_host : pgr-2zexqxalk7d37edt.pg.rds.aliyuncs.com # RDS 主机地址
pg_port : 5432 # RDS 端口(从控制台连接信息获取)
pg_exporter_include_database : 'rds' # 仅监控这个列表中的数据库(多个数据库用逗号分隔)
pg_databases : [ { name : rds }, {name : test} ] # 将这两个数据库纳入 PGCAT 管理,注册为 Grafana 数据源
监控对象配置 当您想要监控现有实例时,不论是 RDS,还是自建的 PostgreSQL 实例,您都需要在目标数据库上进行一些配置,以便 Pigsty 可以访问它们。
为了将外部现存PostgreSQL实例纳入监控,您需要有一个可用于访问该实例/集群的连接串。任何可达连接串(业务用户,超级用户)均可使用,但我们建议使用一个专用监控用户以避免权限泄漏。
监控用户 以Pigsty默认使用的监控用户dbuser_monitor为例,在目标数据库集群创建以下用户。
CREATE USER dbuser_monitor ; -- 创建监控用户
COMMENT ON ROLE dbuser_monitor IS 'system monitor user' ; -- 监控用户备注
GRANT pg_monitor TO dbuser_monitor ; -- 授予监控用户 pg_monitor 权限,否则一些指标将无法采集
ALTER USER dbuser_monitor PASSWORD 'DBUser.Monitor' ; -- 按需修改监控用户密码(强烈建议修改!但请与Pigsty配置一致)
ALTER USER dbuser_monitor SET log_min_duration_statement = 1000 ; -- 建议设置此参数,避免日志塞满监控慢查询
ALTER USER dbuser_monitor SET search_path = monitor , public ; -- 建议设置此参数,避免 pg_stat_statements 扩展无法生效
请注意,这里创建的监控用户与密码需要与 pg_monitor_username 与 pg_monitor_password 保持一致。
监控认证 配置数据库 pg_hba.conf 文件,添加以下规则以允许监控用户从本地,以及管理机使用密码访问所有数据库。
# allow local role monitor with password
local all dbuser_monitor md5
host all dbuser_monitor 127.0.0.1/32 md5
host all dbuser_monitor <管理机器IP地址>/32 md5
如果您的 RDS 不支持定义 HBA,那么把安装 Pigsty 机器的内网 IP 地址开白即可。
监控模式 监控模式可选项 ,即使没有,Pigsty监控系统的主体也可以正常工作,但我们强烈建议设置此模式。
CREATE SCHEMA IF NOT EXISTS monitor ; -- 创建监控专用模式
GRANT USAGE ON SCHEMA monitor TO dbuser_monitor ; -- 允许监控用户使用
监控扩展 监控扩展是可选项,但我们强烈建议启用 pg_stat_statements 扩展该扩展提供了关于查询性能的重要数据。
注意:该扩展必须列入数据库参数 shared_preload_libraries 中方可生效,而修改该参数需要重启数据库。
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements" WITH SCHEMA "monitor" ;
请注意,您应当在默认的管理数据库 postgres 中安装此扩展。有些时候,RDS不允许您在 postgres 数据库中创建监控模式,
在这种情况下,您可以将 pg_stat_statements 插件安装到默认的 public 下,只要确保监控用户的 search_path 按照上面的配置,能够找到 pg_stat_statements 视图即可。
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements" ;
ALTER USER dbuser_monitor SET search_path = monitor , public ; -- 建议设置此参数,避免 pg_stat_statements 扩展无法生效
监控视图 监控视图提供了若干常用的预处理结果,并对某些需要高权限的监控指标进行权限封装(例如共享内存分配),便于查询与使用。强烈建议在所有需要监控的数据库中创建
监控模式与监控视图定义 ----------------------------------------------------------------------
-- Table bloat estimate : monitor.pg_table_bloat
----------------------------------------------------------------------
DROP VIEW IF EXISTS monitor . pg_table_bloat CASCADE ;
CREATE OR REPLACE VIEW monitor . pg_table_bloat AS
SELECT CURRENT_CATALOG AS datname , nspname , relname , tblid , bs * tblpages AS size ,
CASE WHEN tblpages - est_tblpages_ff > 0 THEN ( tblpages - est_tblpages_ff ) / tblpages :: FLOAT ELSE 0 END AS ratio
FROM (
SELECT ceil ( reltuples / ( ( bs - page_hdr ) * fillfactor / ( tpl_size * 100 ) ) ) + ceil ( toasttuples / 4 ) AS est_tblpages_ff ,
tblpages , fillfactor , bs , tblid , nspname , relname , is_na
FROM (
SELECT
( 4 + tpl_hdr_size + tpl_data_size + ( 2 * ma )
- CASE WHEN tpl_hdr_size % ma = 0 THEN ma ELSE tpl_hdr_size % ma END
- CASE WHEN ceil ( tpl_data_size ):: INT % ma = 0 THEN ma ELSE ceil ( tpl_data_size ):: INT % ma END
) AS tpl_size , ( heappages + toastpages ) AS tblpages , heappages ,
toastpages , reltuples , toasttuples , bs , page_hdr , tblid , nspname , relname , fillfactor , is_na
FROM (
SELECT
tbl . oid AS tblid , ns . nspname , tbl . relname , tbl . reltuples ,
tbl . relpages AS heappages , coalesce ( toast . relpages , 0 ) AS toastpages ,
coalesce ( toast . reltuples , 0 ) AS toasttuples ,
coalesce ( substring ( array_to_string ( tbl . reloptions , ' ' ) FROM 'fillfactor=([0-9]+)' ):: smallint , 100 ) AS fillfactor ,
current_setting ( 'block_size' ):: numeric AS bs ,
CASE WHEN version () ~ 'mingw32' OR version () ~ '64-bit|x86_64|ppc64|ia64|amd64' THEN 8 ELSE 4 END AS ma ,
24 AS page_hdr ,
23 + CASE WHEN MAX ( coalesce ( s . null_frac , 0 )) > 0 THEN ( 7 + count ( s . attname ) ) / 8 ELSE 0 :: int END
+ CASE WHEN bool_or ( att . attname = 'oid' and att . attnum < 0 ) THEN 4 ELSE 0 END AS tpl_hdr_size ,
sum ( ( 1 - coalesce ( s . null_frac , 0 )) * coalesce ( s . avg_width , 0 ) ) AS tpl_data_size ,
bool_or ( att . atttypid = 'pg_catalog.name' :: regtype )
OR sum ( CASE WHEN att . attnum > 0 THEN 1 ELSE 0 END ) <> count ( s . attname ) AS is_na
FROM pg_attribute AS att
JOIN pg_class AS tbl ON att . attrelid = tbl . oid
JOIN pg_namespace AS ns ON ns . oid = tbl . relnamespace
LEFT JOIN pg_stats AS s ON s . schemaname = ns . nspname AND s . tablename = tbl . relname AND s . inherited = false AND s . attname = att . attname
LEFT JOIN pg_class AS toast ON tbl . reltoastrelid = toast . oid
WHERE NOT att . attisdropped AND tbl . relkind = 'r' AND nspname NOT IN ( 'pg_catalog' , 'information_schema' )
GROUP BY 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10
) AS s
) AS s2
) AS s3
WHERE NOT is_na ;
COMMENT ON VIEW monitor . pg_table_bloat IS 'postgres table bloat estimate' ;
GRANT SELECT ON monitor . pg_table_bloat TO pg_monitor ;
----------------------------------------------------------------------
-- Index bloat estimate : monitor.pg_index_bloat
----------------------------------------------------------------------
DROP VIEW IF EXISTS monitor . pg_index_bloat CASCADE ;
CREATE OR REPLACE VIEW monitor . pg_index_bloat AS
SELECT CURRENT_CATALOG AS datname , nspname , idxname AS relname , tblid , idxid , relpages :: BIGINT * bs AS size ,
COALESCE (( relpages - ( reltuples * ( 6 + ma - ( CASE WHEN index_tuple_hdr % ma = 0 THEN ma ELSE index_tuple_hdr % ma END )
+ nulldatawidth + ma - ( CASE WHEN nulldatawidth % ma = 0 THEN ma ELSE nulldatawidth % ma END ))
/ ( bs - pagehdr ):: FLOAT + 1 )), 0 ) / relpages :: FLOAT AS ratio
FROM (
SELECT nspname , idxname , indrelid AS tblid , indexrelid AS idxid ,
reltuples , relpages ,
current_setting ( 'block_size' ):: INTEGER AS bs ,
( CASE WHEN version () ~ 'mingw32' OR version () ~ '64-bit|x86_64|ppc64|ia64|amd64' THEN 8 ELSE 4 END ) AS ma ,
24 AS pagehdr ,
( CASE WHEN max ( COALESCE ( pg_stats . null_frac , 0 )) = 0 THEN 2 ELSE 6 END ) AS index_tuple_hdr ,
sum (( 1 . 0 - COALESCE ( pg_stats . null_frac , 0 . 0 )) *
COALESCE ( pg_stats . avg_width , 1024 )):: INTEGER AS nulldatawidth
FROM pg_attribute
JOIN (
SELECT pg_namespace . nspname ,
ic . relname AS idxname ,
ic . reltuples ,
ic . relpages ,
pg_index . indrelid ,
pg_index . indexrelid ,
tc . relname AS tablename ,
regexp_split_to_table ( pg_index . indkey :: TEXT , ' ' ) :: INTEGER AS attnum ,
pg_index . indexrelid AS index_oid
FROM pg_index
JOIN pg_class ic ON pg_index . indexrelid = ic . oid
JOIN pg_class tc ON pg_index . indrelid = tc . oid
JOIN pg_namespace ON pg_namespace . oid = ic . relnamespace
JOIN pg_am ON ic . relam = pg_am . oid
WHERE pg_am . amname = 'btree' AND ic . relpages > 0 AND nspname NOT IN ( 'pg_catalog' , 'information_schema' )
) ind_atts ON pg_attribute . attrelid = ind_atts . indexrelid AND pg_attribute . attnum = ind_atts . attnum
JOIN pg_stats ON pg_stats . schemaname = ind_atts . nspname
AND (( pg_stats . tablename = ind_atts . tablename AND pg_stats . attname = pg_get_indexdef ( pg_attribute . attrelid , pg_attribute . attnum , TRUE ))
OR ( pg_stats . tablename = ind_atts . idxname AND pg_stats . attname = pg_attribute . attname ))
WHERE pg_attribute . attnum > 0
GROUP BY 1 , 2 , 3 , 4 , 5 , 6
) est ;
COMMENT ON VIEW monitor . pg_index_bloat IS 'postgres index bloat estimate (btree-only)' ;
GRANT SELECT ON monitor . pg_index_bloat TO pg_monitor ;
----------------------------------------------------------------------
-- Relation Bloat : monitor.pg_bloat
----------------------------------------------------------------------
DROP VIEW IF EXISTS monitor . pg_bloat CASCADE ;
CREATE OR REPLACE VIEW monitor . pg_bloat AS
SELECT coalesce ( ib . datname , tb . datname ) AS datname ,
coalesce ( ib . nspname , tb . nspname ) AS nspname ,
coalesce ( ib . tblid , tb . tblid ) AS tblid ,
coalesce ( tb . nspname || '.' || tb . relname , ib . nspname || '.' || ib . tblid :: RegClass ) AS tblname ,
tb . size AS tbl_size ,
CASE WHEN tb . ratio < 0 THEN 0 ELSE round ( tb . ratio :: NUMERIC , 6 ) END AS tbl_ratio ,
( tb . size * ( CASE WHEN tb . ratio < 0 THEN 0 ELSE tb . ratio :: NUMERIC END )) :: BIGINT AS tbl_wasted ,
ib . idxid ,
ib . nspname || '.' || ib . relname AS idxname ,
ib . size AS idx_size ,
CASE WHEN ib . ratio < 0 THEN 0 ELSE round ( ib . ratio :: NUMERIC , 5 ) END AS idx_ratio ,
( ib . size * ( CASE WHEN ib . ratio < 0 THEN 0 ELSE ib . ratio :: NUMERIC END )) :: BIGINT AS idx_wasted
FROM monitor . pg_index_bloat ib
FULL OUTER JOIN monitor . pg_table_bloat tb ON ib . tblid = tb . tblid ;
COMMENT ON VIEW monitor . pg_bloat IS 'postgres relation bloat detail' ;
GRANT SELECT ON monitor . pg_bloat TO pg_monitor ;
----------------------------------------------------------------------
-- monitor.pg_index_bloat_human
----------------------------------------------------------------------
DROP VIEW IF EXISTS monitor . pg_index_bloat_human CASCADE ;
CREATE OR REPLACE VIEW monitor . pg_index_bloat_human AS
SELECT idxname AS name ,
tblname ,
idx_wasted AS wasted ,
pg_size_pretty ( idx_size ) AS idx_size ,
round ( 100 * idx_ratio :: NUMERIC , 2 ) AS idx_ratio ,
pg_size_pretty ( idx_wasted ) AS idx_wasted ,
pg_size_pretty ( tbl_size ) AS tbl_size ,
round ( 100 * tbl_ratio :: NUMERIC , 2 ) AS tbl_ratio ,
pg_size_pretty ( tbl_wasted ) AS tbl_wasted
FROM monitor . pg_bloat
WHERE idxname IS NOT NULL ;
COMMENT ON VIEW monitor . pg_index_bloat_human IS 'postgres index bloat info in human-readable format' ;
GRANT SELECT ON monitor . pg_index_bloat_human TO pg_monitor ;
----------------------------------------------------------------------
-- monitor.pg_table_bloat_human
----------------------------------------------------------------------
DROP VIEW IF EXISTS monitor . pg_table_bloat_human CASCADE ;
CREATE OR REPLACE VIEW monitor . pg_table_bloat_human AS
SELECT tblname AS name ,
idx_wasted + tbl_wasted AS wasted ,
pg_size_pretty ( idx_wasted + tbl_wasted ) AS all_wasted ,
pg_size_pretty ( tbl_wasted ) AS tbl_wasted ,
pg_size_pretty ( tbl_size ) AS tbl_size ,
tbl_ratio ,
pg_size_pretty ( idx_wasted ) AS idx_wasted ,
pg_size_pretty ( idx_size ) AS idx_size ,
round ( idx_wasted :: NUMERIC * 100 . 0 / idx_size , 2 ) AS idx_ratio
FROM ( SELECT datname ,
nspname ,
tblname ,
coalesce ( max ( tbl_wasted ), 0 ) AS tbl_wasted ,
coalesce ( max ( tbl_size ), 1 ) AS tbl_size ,
round ( 100 * coalesce ( max ( tbl_ratio ), 0 ):: NUMERIC , 2 ) AS tbl_ratio ,
coalesce ( sum ( idx_wasted ), 0 ) AS idx_wasted ,
coalesce ( sum ( idx_size ), 1 ) AS idx_size
FROM monitor . pg_bloat
WHERE tblname IS NOT NULL
GROUP BY 1 , 2 , 3
) d ;
COMMENT ON VIEW monitor . pg_table_bloat_human IS 'postgres table bloat info in human-readable format' ;
GRANT SELECT ON monitor . pg_table_bloat_human TO pg_monitor ;
----------------------------------------------------------------------
-- Activity Overview: monitor.pg_session
----------------------------------------------------------------------
DROP VIEW IF EXISTS monitor . pg_session CASCADE ;
CREATE OR REPLACE VIEW monitor . pg_session AS
SELECT coalesce ( datname , 'all' ) AS datname , numbackends , active , idle , ixact , max_duration , max_tx_duration , max_conn_duration
FROM (
SELECT datname ,
count ( * ) AS numbackends ,
count ( * ) FILTER ( WHERE state = 'active' ) AS active ,
count ( * ) FILTER ( WHERE state = 'idle' ) AS idle ,
count ( * ) FILTER ( WHERE state = 'idle in transaction'
OR state = 'idle in transaction (aborted)' ) AS ixact ,
max ( extract ( epoch from now () - state_change ))
FILTER ( WHERE state = 'active' ) AS max_duration ,
max ( extract ( epoch from now () - xact_start )) AS max_tx_duration ,
max ( extract ( epoch from now () - backend_start )) AS max_conn_duration
FROM pg_stat_activity
WHERE backend_type = 'client backend'
AND pid <> pg_backend_pid ()
GROUP BY ROLLUP ( 1 )
ORDER BY 1 NULLS FIRST
) t ;
COMMENT ON VIEW monitor . pg_session IS 'postgres activity group by session' ;
GRANT SELECT ON monitor . pg_session TO pg_monitor ;
----------------------------------------------------------------------
-- Sequential Scan: monitor.pg_seq_scan
----------------------------------------------------------------------
DROP VIEW IF EXISTS monitor . pg_seq_scan CASCADE ;
CREATE OR REPLACE VIEW monitor . pg_seq_scan AS
SELECT schemaname AS nspname ,
relname ,
seq_scan ,
seq_tup_read ,
seq_tup_read / seq_scan AS seq_tup_avg ,
idx_scan ,
n_live_tup + n_dead_tup AS tuples ,
round ( n_live_tup * 100 . 0 :: NUMERIC / ( n_live_tup + n_dead_tup ), 2 ) AS live_ratio
FROM pg_stat_user_tables
WHERE seq_scan > 0
and ( n_live_tup + n_dead_tup ) > 0
ORDER BY seq_scan DESC ;
COMMENT ON VIEW monitor . pg_seq_scan IS 'table that have seq scan' ;
GRANT SELECT ON monitor . pg_seq_scan TO pg_monitor ;
查看共享内存分配的函数(PG13以上可用) DROP FUNCTION IF EXISTS monitor . pg_shmem () CASCADE ;
CREATE OR REPLACE FUNCTION monitor . pg_shmem () RETURNS SETOF
pg_shmem_allocations AS $$ SELECT * FROM pg_shmem_allocations ; $$ LANGUAGE SQL SECURITY DEFINER ;
COMMENT ON FUNCTION monitor . pg_shmem () IS 'security wrapper for system view pg_shmem' ;
REVOKE ALL ON FUNCTION monitor . pg_shmem () FROM PUBLIC ;
GRANT EXECUTE ON FUNCTION monitor . pg_shmem () TO pg_monitor ;
11.11.1 - 监控面板 Pigsty 为 PostgreSQL 提供了诸多开箱即用的 Grafana 监控仪表盘
Pigsty 为 PostgreSQL 提供了诸多开箱即用的 Grafana 监控仪表盘: Demo & Gallery 。
在 Pigsty 中共有 26 个与 PostgreSQL 相关的监控面板,按照层次分为 总览,集群,实例,数据库四大类,按照数据来源又分为 PGSQL ,PGCAT ,PGLOG 三大类。
总览 概览
集群
实例
数据库
总览 PGSQL Overview :PGSQL模块的主仪表板
PGSQL Overview
PGSQL Alert :PGSQL 全局核心指标总览与告警事件一览
PGSQL Alert
PGSQL Shard :展示一个PGSQL 水平分片集群内的横向指标对比:例如 CITUS / GPSQL 集群。
PGSQL Shard
集群 PGSQL Cluster :一个PGSQL集群的主仪表板
PGSQL Cluster
PGRDS Cluster :PGSQL Cluster 的RDS版本,专注于所有 PostgreSQL 本身的指标
PGRDS Cluster
PGSQL Service :关注PGSQL集群服务、代理、路由和负载均衡。
PGSQL Service
PGSQL Activity :关注PGSQL集群的会话/负载/QPS/TPS/锁定情况
PGSQL Activity
PGSQL Replication :关注PGSQL集群复制、插槽和发布/订阅。
PGSQL Replication
PGSQL Databases :关注所有实例的数据库CRUD、慢查询和表统计信息。
PGSQL Databases
PGSQL Patroni :关注集群高可用状态,Patroni组件状态
PGSQL Patroni
PGSQL PITR :关注集群 PITR 过程的上下文,用于辅助时间点恢复
PGSQL PITR
实例 PGSQL Instance :单个PGSQL实例的主仪表板
PGSQL Instance
PGRDS Instance :PGSQL Instance 的RDS版本,专注于所有 PostgreSQL 本身的指标
PGRDS Instance
PGSQL Proxy :单个haproxy负载均衡器的详细指标
PGSQL Proxy
PGSQL Pgbouncer :单个Pgbouncer连接池实例中的指标总览
PGSQL Pgbouncer
PGSQL Persist :持久性指标:WAL、XID、检查点、存档、IO
PGSQL Persist
PGSQL Xacts :关于事务、锁、TPS/QPS相关的指标
PGSQL Xacts
PGSQL Session :单个实例中的会话和活动/空闲时间的指标
PGSQL Session
PGSQL Exporter :Postgres/Pgbouncer 监控组件自我监控指标
PGSQL Exporter
数据库 PGSQL Database :单个PGSQL数据库的主仪表板
PGSQL Database
PGSQL Tables :单个数据库内的表/索引访问指标
PGSQL Tables
PGSQL Table :单个表的详细信息(QPS/RT/索引/序列…)
PGSQL Table
PGSQL Query :单类查询的详细信息(QPS/RT)
PGSQL Query
PGCAT PGCAT Instance :直接从数据库目录获取的实例信息
PGCAT Instance
PGCAT Database :直接从数据库目录获取的数据库信息
PGCAT Database
PGCAT Schema :直接从数据库目录获取关于模式的信息(表/索引/序列…)
PGCAT Schema
PGCAT Table :直接从数据库目录获取的单个表的详细信息(统计/膨胀…)
PGCAT Table
PGCAT Query :直接从数据库目录获取的单类查询的详细信息(SQL/统计)
PGCAT Query
PGCAT Locks :直接从数据库目录获取的关于活动与锁等待的信息
PGCAT Locks
PGLOG PGLOG Overview :总览 Pigsty CMDB 中的CSV日志样本
PGLOG Overview
PGLOG Overview :Pigsty CMDB 中的CSV日志样本中某一条会话的日志详情
PGLOG Session
画廊 详情请参考 pigsty/wiki/gallery 。
PGSQL Overview
PGSQL Shard
PGSQL Cluster
PGSQL Service
PGSQL Activity
PGSQL Replication
PGSQL Databases
PGSQL Instance
PGSQL Proxy
PGSQL Pgbouncer
PGSQL Session
PGSQL Xacts
PGSQL Persist
PGSQL Database
PGSQL Tables
PGSQL Table
PGSQL Query
PGCAT Instance
PGCAT Database
PGCAT Schema
PGCAT Table
PGCAT Lock
PGCAT Query
PGLOG Overview
PGLOG Session
11.11.2 - 指标列表 Pigsty PGSQL 模块提供的完整监控指标列表与释义
PGSQL 模块包含有 638 类可用监控指标。
Metric Name Type Labels Description ALERTS Unknown category, job, level, ins, severity, ip, alertname, alertstate, instance, clsN/A ALERTS_FOR_STATE Unknown category, job, level, ins, severity, ip, alertname, instance, clsN/A cls:pressure1 Unknown job, clsN/A cls:pressure15 Unknown job, clsN/A cls:pressure5 Unknown job, clsN/A go_gc_duration_seconds summary job, ins, ip, instance, quantile, clsA summary of the pause duration of garbage collection cycles. go_gc_duration_seconds_count Unknown job, ins, ip, instance, clsN/A go_gc_duration_seconds_sum Unknown job, ins, ip, instance, clsN/A go_goroutines gauge job, ins, ip, instance, clsNumber of goroutines that currently exist. go_info gauge version, job, ins, ip, instance, clsInformation about the Go environment. go_memstats_alloc_bytes gauge job, ins, ip, instance, clsNumber of bytes allocated and still in use. go_memstats_alloc_bytes_total counter job, ins, ip, instance, clsTotal number of bytes allocated, even if freed. go_memstats_buck_hash_sys_bytes gauge job, ins, ip, instance, clsNumber of bytes used by the profiling bucket hash table. go_memstats_frees_total counter job, ins, ip, instance, clsTotal number of frees. go_memstats_gc_sys_bytes gauge job, ins, ip, instance, clsNumber of bytes used for garbage collection system metadata. go_memstats_heap_alloc_bytes gauge job, ins, ip, instance, clsNumber of heap bytes allocated and still in use. go_memstats_heap_idle_bytes gauge job, ins, ip, instance, clsNumber of heap bytes waiting to be used. go_memstats_heap_inuse_bytes gauge job, ins, ip, instance, clsNumber of heap bytes that are in use. go_memstats_heap_objects gauge job, ins, ip, instance, clsNumber of allocated objects. go_memstats_heap_released_bytes gauge job, ins, ip, instance, clsNumber of heap bytes released to OS. go_memstats_heap_sys_bytes gauge job, ins, ip, instance, clsNumber of heap bytes obtained from system. go_memstats_last_gc_time_seconds gauge job, ins, ip, instance, clsNumber of seconds since 1970 of last garbage collection. go_memstats_lookups_total counter job, ins, ip, instance, clsTotal number of pointer lookups. go_memstats_mallocs_total counter job, ins, ip, instance, clsTotal number of mallocs. go_memstats_mcache_inuse_bytes gauge job, ins, ip, instance, clsNumber of bytes in use by mcache structures. go_memstats_mcache_sys_bytes gauge job, ins, ip, instance, clsNumber of bytes used for mcache structures obtained from system. go_memstats_mspan_inuse_bytes gauge job, ins, ip, instance, clsNumber of bytes in use by mspan structures. go_memstats_mspan_sys_bytes gauge job, ins, ip, instance, clsNumber of bytes used for mspan structures obtained from system. go_memstats_next_gc_bytes gauge job, ins, ip, instance, clsNumber of heap bytes when next garbage collection will take place. go_memstats_other_sys_bytes gauge job, ins, ip, instance, clsNumber of bytes used for other system allocations. go_memstats_stack_inuse_bytes gauge job, ins, ip, instance, clsNumber of bytes in use by the stack allocator. go_memstats_stack_sys_bytes gauge job, ins, ip, instance, clsNumber of bytes obtained from system for stack allocator. go_memstats_sys_bytes gauge job, ins, ip, instance, clsNumber of bytes obtained from system. go_threads gauge job, ins, ip, instance, clsNumber of OS threads created. ins:pressure1 Unknown job, ins, ip, clsN/A ins:pressure15 Unknown job, ins, ip, clsN/A ins:pressure5 Unknown job, ins, ip, clsN/A patroni_cluster_unlocked gauge job, ins, ip, instance, cls, scopeValue is 1 if the cluster is unlocked, 0 if locked. patroni_dcs_last_seen gauge job, ins, ip, instance, cls, scopeEpoch timestamp when DCS was last contacted successfully by Patroni. patroni_failsafe_mode_is_active gauge job, ins, ip, instance, cls, scopeValue is 1 if failsafe mode is active, 0 if inactive. patroni_is_paused gauge job, ins, ip, instance, cls, scopeValue is 1 if auto failover is disabled, 0 otherwise. patroni_master gauge job, ins, ip, instance, cls, scopeValue is 1 if this node is the leader, 0 otherwise. patroni_pending_restart gauge job, ins, ip, instance, cls, scopeValue is 1 if the node needs a restart, 0 otherwise. patroni_postgres_in_archive_recovery gauge job, ins, ip, instance, cls, scopeValue is 1 if Postgres is replicating from archive, 0 otherwise. patroni_postgres_running gauge job, ins, ip, instance, cls, scopeValue is 1 if Postgres is running, 0 otherwise. patroni_postgres_server_version gauge job, ins, ip, instance, cls, scopeVersion of Postgres (if running), 0 otherwise. patroni_postgres_streaming gauge job, ins, ip, instance, cls, scopeValue is 1 if Postgres is streaming, 0 otherwise. patroni_postgres_timeline counter job, ins, ip, instance, cls, scopePostgres timeline of this node (if running), 0 otherwise. patroni_postmaster_start_time gauge job, ins, ip, instance, cls, scopeEpoch seconds since Postgres started. patroni_primary gauge job, ins, ip, instance, cls, scopeValue is 1 if this node is the leader, 0 otherwise. patroni_replica gauge job, ins, ip, instance, cls, scopeValue is 1 if this node is a replica, 0 otherwise. patroni_standby_leader gauge job, ins, ip, instance, cls, scopeValue is 1 if this node is the standby_leader, 0 otherwise. patroni_sync_standby gauge job, ins, ip, instance, cls, scopeValue is 1 if this node is a sync standby replica, 0 otherwise. patroni_up Unknown job, ins, ip, instance, clsN/A patroni_version gauge job, ins, ip, instance, cls, scopePatroni semver without periods. patroni_xlog_location counter job, ins, ip, instance, cls, scopeCurrent location of the Postgres transaction log, 0 if this node is not the leader. patroni_xlog_paused gauge job, ins, ip, instance, cls, scopeValue is 1 if the Postgres xlog is paused, 0 otherwise. patroni_xlog_received_location counter job, ins, ip, instance, cls, scopeCurrent location of the received Postgres transaction log, 0 if this node is not a replica. patroni_xlog_replayed_location counter job, ins, ip, instance, cls, scopeCurrent location of the replayed Postgres transaction log, 0 if this node is not a replica. patroni_xlog_replayed_timestamp gauge job, ins, ip, instance, cls, scopeCurrent timestamp of the replayed Postgres transaction log, 0 if null. pg:cls:active_backends Unknown job, clsN/A pg:cls:active_time_rate15m Unknown job, clsN/A pg:cls:active_time_rate1m Unknown job, clsN/A pg:cls:active_time_rate5m Unknown job, clsN/A pg:cls:age Unknown job, clsN/A pg:cls:buf_alloc_rate1m Unknown job, clsN/A pg:cls:buf_clean_rate1m Unknown job, clsN/A pg:cls:buf_flush_backend_rate1m Unknown job, clsN/A pg:cls:buf_flush_checkpoint_rate1m Unknown job, clsN/A pg:cls:cpu_count Unknown job, clsN/A pg:cls:cpu_usage Unknown job, clsN/A pg:cls:cpu_usage_15m Unknown job, clsN/A pg:cls:cpu_usage_1m Unknown job, clsN/A pg:cls:cpu_usage_5m Unknown job, clsN/A pg:cls:db_size Unknown job, clsN/A pg:cls:file_size Unknown job, clsN/A pg:cls:ixact_backends Unknown job, clsN/A pg:cls:ixact_time_rate1m Unknown job, clsN/A pg:cls:lag_bytes Unknown job, clsN/A pg:cls:lag_seconds Unknown job, clsN/A pg:cls:leader Unknown job, ins, ip, instance, clsN/A pg:cls:load1 Unknown job, clsN/A pg:cls:load15 Unknown job, clsN/A pg:cls:load5 Unknown job, clsN/A pg:cls:lock_count Unknown job, clsN/A pg:cls:locks Unknown job, cls, modeN/A pg:cls:log_size Unknown job, clsN/A pg:cls:lsn_rate1m Unknown job, clsN/A pg:cls:members Unknown job, ins, ip, clsN/A pg:cls:num_backends Unknown job, clsN/A pg:cls:partition Unknown job, clsN/A pg:cls:receiver Unknown state, slot_name, job, appname, ip, cls, sender_host, sender_portN/A pg:cls:rlock_count Unknown job, clsN/A pg:cls:saturation1 Unknown job, clsN/A pg:cls:saturation15 Unknown job, clsN/A pg:cls:saturation5 Unknown job, clsN/A pg:cls:sender Unknown pid, usename, address, job, ins, appname, ip, clsN/A pg:cls:session_time_rate1m Unknown job, clsN/A pg:cls:size Unknown job, clsN/A pg:cls:slot_count Unknown job, clsN/A pg:cls:slot_retained_bytes Unknown job, clsN/A pg:cls:standby_count Unknown job, clsN/A pg:cls:sync_state Unknown job, clsN/A pg:cls:timeline Unknown job, clsN/A pg:cls:tup_deleted_rate1m Unknown job, clsN/A pg:cls:tup_fetched_rate1m Unknown job, clsN/A pg:cls:tup_inserted_rate1m Unknown job, clsN/A pg:cls:tup_modified_rate1m Unknown job, clsN/A pg:cls:tup_returned_rate1m Unknown job, clsN/A pg:cls:wal_size Unknown job, clsN/A pg:cls:xact_commit_rate15m Unknown job, clsN/A pg:cls:xact_commit_rate1m Unknown job, clsN/A pg:cls:xact_commit_rate5m Unknown job, clsN/A pg:cls:xact_rollback_rate15m Unknown job, clsN/A pg:cls:xact_rollback_rate1m Unknown job, clsN/A pg:cls:xact_rollback_rate5m Unknown job, clsN/A pg:cls:xact_total_rate15m Unknown job, clsN/A pg:cls:xact_total_rate1m Unknown job, clsN/A pg:cls:xact_total_sigma15m Unknown job, clsN/A pg:cls:xlock_count Unknown job, clsN/A pg:db:active_backends Unknown datname, job, ins, ip, instance, clsN/A pg:db:active_time_rate15m Unknown datname, job, ins, ip, instance, clsN/A pg:db:active_time_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:active_time_rate5m Unknown datname, job, ins, ip, instance, clsN/A pg:db:age Unknown datname, job, ins, ip, instance, clsN/A pg:db:age_deriv1h Unknown datname, job, ins, ip, instance, clsN/A pg:db:age_exhaust Unknown datname, job, ins, ip, instance, clsN/A pg:db:blk_io_time_seconds_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:blk_read_time_seconds_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:blk_write_time_seconds_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:blks_access_1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:blks_hit_1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:blks_hit_ratio1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:blks_read_1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:conn_limit Unknown datname, job, ins, ip, instance, clsN/A pg:db:conn_usage Unknown datname, job, ins, ip, instance, clsN/A pg:db:db_size Unknown datname, job, ins, ip, instance, clsN/A pg:db:ixact_backends Unknown datname, job, ins, ip, instance, clsN/A pg:db:ixact_time_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:lock_count Unknown datname, job, ins, ip, instance, clsN/A pg:db:num_backends Unknown datname, job, ins, ip, instance, clsN/A pg:db:rlock_count Unknown datname, job, ins, ip, instance, clsN/A pg:db:session_time_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:temp_bytes_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:temp_files_1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:tup_deleted_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:tup_fetched_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:tup_inserted_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:tup_modified_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:tup_returned_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:wlock_count Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_commit_rate15m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_commit_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_commit_rate5m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_rollback_rate15m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_rollback_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_rollback_rate5m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_total_rate15m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_total_rate1m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_total_rate5m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xact_total_sigma15m Unknown datname, job, ins, ip, instance, clsN/A pg:db:xlock_count Unknown datname, job, ins, ip, instance, clsN/A pg:env:active_backends Unknown jobN/A pg:env:active_time_rate15m Unknown jobN/A pg:env:active_time_rate1m Unknown jobN/A pg:env:active_time_rate5m Unknown jobN/A pg:env:age Unknown jobN/A pg:env:cpu_count Unknown jobN/A pg:env:cpu_usage Unknown jobN/A pg:env:cpu_usage_15m Unknown jobN/A pg:env:cpu_usage_1m Unknown jobN/A pg:env:cpu_usage_5m Unknown jobN/A pg:env:ixact_backends Unknown jobN/A pg:env:ixact_time_rate1m Unknown jobN/A pg:env:lag_bytes Unknown jobN/A pg:env:lag_seconds Unknown jobN/A pg:env:lsn_rate1m Unknown jobN/A pg:env:session_time_rate1m Unknown jobN/A pg:env:tup_deleted_rate1m Unknown jobN/A pg:env:tup_fetched_rate1m Unknown jobN/A pg:env:tup_inserted_rate1m Unknown jobN/A pg:env:tup_modified_rate1m Unknown jobN/A pg:env:tup_returned_rate1m Unknown jobN/A pg:env:xact_commit_rate15m Unknown jobN/A pg:env:xact_commit_rate1m Unknown jobN/A pg:env:xact_commit_rate5m Unknown jobN/A pg:env:xact_rollback_rate15m Unknown jobN/A pg:env:xact_rollback_rate1m Unknown jobN/A pg:env:xact_rollback_rate5m Unknown jobN/A pg:env:xact_total_rate15m Unknown jobN/A pg:env:xact_total_rate1m Unknown jobN/A pg:env:xact_total_sigma15m Unknown jobN/A pg:ins:active_backends Unknown job, ins, ip, instance, clsN/A pg:ins:active_time_rate15m Unknown job, ins, ip, instance, clsN/A pg:ins:active_time_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:active_time_rate5m Unknown job, ins, ip, instance, clsN/A pg:ins:age Unknown job, ins, ip, instance, clsN/A pg:ins:blks_hit_ratio1m Unknown job, ins, ip, instance, clsN/A pg:ins:buf_alloc_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:buf_clean_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:buf_flush_backend_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:buf_flush_checkpoint_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:ckpt_1h Unknown job, ins, ip, instance, clsN/A pg:ins:ckpt_req_1m Unknown job, ins, ip, instance, clsN/A pg:ins:ckpt_timed_1m Unknown job, ins, ip, instance, clsN/A pg:ins:conn_limit Unknown job, ins, ip, instance, clsN/A pg:ins:conn_usage Unknown job, ins, ip, instance, clsN/A pg:ins:cpu_count Unknown job, ins, ip, instance, clsN/A pg:ins:cpu_usage Unknown job, ins, ip, instance, clsN/A pg:ins:cpu_usage_15m Unknown job, ins, ip, instance, clsN/A pg:ins:cpu_usage_1m Unknown job, ins, ip, instance, clsN/A pg:ins:cpu_usage_5m Unknown job, ins, ip, instance, clsN/A pg:ins:db_size Unknown job, ins, ip, instance, clsN/A pg:ins:file_size Unknown job, ins, ip, instance, clsN/A pg:ins:fs_size Unknown job, ins, ip, instance, clsN/A pg:ins:is_leader Unknown job, ins, ip, instance, clsN/A pg:ins:ixact_backends Unknown job, ins, ip, instance, clsN/A pg:ins:ixact_time_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:lag_bytes Unknown job, ins, ip, instance, clsN/A pg:ins:lag_seconds Unknown job, ins, ip, instance, clsN/A pg:ins:load1 Unknown job, ins, ip, instance, clsN/A pg:ins:load15 Unknown job, ins, ip, instance, clsN/A pg:ins:load5 Unknown job, ins, ip, instance, clsN/A pg:ins:lock_count Unknown job, ins, ip, instance, clsN/A pg:ins:locks Unknown job, ins, ip, mode, instance, clsN/A pg:ins:log_size Unknown job, ins, ip, instance, clsN/A pg:ins:lsn_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:mem_size Unknown job, ins, ip, instance, clsN/A pg:ins:num_backends Unknown job, ins, ip, instance, clsN/A pg:ins:rlock_count Unknown job, ins, ip, instance, clsN/A pg:ins:saturation1 Unknown job, ins, ip, clsN/A pg:ins:saturation15 Unknown job, ins, ip, clsN/A pg:ins:saturation5 Unknown job, ins, ip, clsN/A pg:ins:session_time_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:slot_retained_bytes Unknown job, ins, ip, instance, clsN/A pg:ins:space_usage Unknown job, ins, ip, instance, clsN/A pg:ins:status Unknown job, ins, ip, instance, clsN/A pg:ins:sync_state Unknown job, ins, instance, clsN/A pg:ins:target_count Unknown job, cls, insN/A pg:ins:timeline Unknown job, ins, ip, instance, clsN/A pg:ins:tup_deleted_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:tup_fetched_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:tup_inserted_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:tup_modified_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:tup_returned_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:wal_size Unknown job, ins, ip, instance, clsN/A pg:ins:wlock_count Unknown job, ins, ip, instance, clsN/A pg:ins:xact_commit_rate15m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_commit_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_commit_rate5m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_rollback_rate15m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_rollback_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_rollback_rate5m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_total_rate15m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_total_rate1m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_total_rate5m Unknown job, ins, ip, instance, clsN/A pg:ins:xact_total_sigma15m Unknown job, ins, ip, instance, clsN/A pg:ins:xlock_count Unknown job, ins, ip, instance, clsN/A pg:query:call_rate1m Unknown datname, query, job, ins, ip, instance, clsN/A pg:query:rt_1m Unknown datname, query, job, ins, ip, instance, clsN/A pg:table:scan_rate1m Unknown datname, relname, job, ins, ip, instance, clsN/A pg_activity_count gauge datname, state, job, ins, ip, instance, clsCount of connection among (datname,state) pg_activity_max_conn_duration gauge datname, state, job, ins, ip, instance, clsMax backend session duration since state change among (datname, state) pg_activity_max_duration gauge datname, state, job, ins, ip, instance, clsMax duration since last state change among (datname, state) pg_activity_max_tx_duration gauge datname, state, job, ins, ip, instance, clsMax transaction duration since state change among (datname, state) pg_archiver_failed_count counter job, ins, ip, instance, clsNumber of failed attempts for archiving WAL files pg_archiver_finish_count counter job, ins, ip, instance, clsNumber of WAL files that have been successfully archived pg_archiver_last_failed_time counter job, ins, ip, instance, clsTime of the last failed archival operation pg_archiver_last_finish_time counter job, ins, ip, instance, clsTime of the last successful archive operation pg_archiver_reset_time gauge job, ins, ip, instance, clsTime at which archive statistics were last reset pg_backend_count gauge type, job, ins, ip, instance, clsDatabase backend process count by backend_type pg_bgwriter_buffers_alloc counter job, ins, ip, instance, clsNumber of buffers allocated pg_bgwriter_buffers_backend counter job, ins, ip, instance, clsNumber of buffers written directly by a backend pg_bgwriter_buffers_backend_fsync counter job, ins, ip, instance, clsNumber of times a backend had to execute its own fsync call pg_bgwriter_buffers_checkpoint counter job, ins, ip, instance, clsNumber of buffers written during checkpoints pg_bgwriter_buffers_clean counter job, ins, ip, instance, clsNumber of buffers written by the background writer pg_bgwriter_checkpoint_sync_time counter job, ins, ip, instance, clsTotal amount of time that has been spent in the portion of checkpoint processing where files are synchronized to disk, in seconds pg_bgwriter_checkpoint_write_time counter job, ins, ip, instance, clsTotal amount of time that has been spent in the portion of checkpoint processing where files are written to disk, in seconds pg_bgwriter_checkpoints_req counter job, ins, ip, instance, clsNumber of requested checkpoints that have been performed pg_bgwriter_checkpoints_timed counter job, ins, ip, instance, clsNumber of scheduled checkpoints that have been performed pg_bgwriter_maxwritten_clean counter job, ins, ip, instance, clsNumber of times the background writer stopped a cleaning scan because it had written too many buffers pg_bgwriter_reset_time counter job, ins, ip, instance, clsTime at which bgwriter statistics were last reset pg_boot_time gauge job, ins, ip, instance, clsunix timestamp when postmaster boot pg_checkpoint_checkpoint_lsn counter job, ins, ip, instance, clsLatest checkpoint location pg_checkpoint_elapse gauge job, ins, ip, instance, clsSeconds elapsed since latest checkpoint in seconds pg_checkpoint_full_page_writes gauge job, ins, ip, instance, clsLatest checkpoint’s full_page_writes enabled pg_checkpoint_newest_commit_ts_xid counter job, ins, ip, instance, clsLatest checkpoint’s newestCommitTsXid pg_checkpoint_next_multi_offset counter job, ins, ip, instance, clsLatest checkpoint’s NextMultiOffset pg_checkpoint_next_multixact_id counter job, ins, ip, instance, clsLatest checkpoint’s NextMultiXactId pg_checkpoint_next_oid counter job, ins, ip, instance, clsLatest checkpoint’s NextOID pg_checkpoint_next_xid counter job, ins, ip, instance, clsLatest checkpoint’s NextXID xid pg_checkpoint_next_xid_epoch counter job, ins, ip, instance, clsLatest checkpoint’s NextXID epoch pg_checkpoint_oldest_active_xid counter job, ins, ip, instance, clsLatest checkpoint’s oldestActiveXID pg_checkpoint_oldest_commit_ts_xid counter job, ins, ip, instance, clsLatest checkpoint’s oldestCommitTsXid pg_checkpoint_oldest_multi_dbid gauge job, ins, ip, instance, clsLatest checkpoint’s oldestMulti’s DB OID pg_checkpoint_oldest_multi_xid counter job, ins, ip, instance, clsLatest checkpoint’s oldestMultiXid pg_checkpoint_oldest_xid counter job, ins, ip, instance, clsLatest checkpoint’s oldestXID pg_checkpoint_oldest_xid_dbid gauge job, ins, ip, instance, clsLatest checkpoint’s oldestXID’s DB OID pg_checkpoint_prev_tli counter job, ins, ip, instance, clsLatest checkpoint’s PrevTimeLineID pg_checkpoint_redo_lsn counter job, ins, ip, instance, clsLatest checkpoint’s REDO location pg_checkpoint_time counter job, ins, ip, instance, clsTime of latest checkpoint pg_checkpoint_tli counter job, ins, ip, instance, clsLatest checkpoint’s TimeLineID pg_conf_reload_time gauge job, ins, ip, instance, clsseconds since last configuration reload pg_db_active_time counter datname, job, ins, ip, instance, clsTime spent executing SQL statements in this database, in seconds pg_db_age gauge datname, job, ins, ip, instance, clsAge of database calculated from datfrozenxid pg_db_allow_conn gauge datname, job, ins, ip, instance, clsIf false(0) then no one can connect to this database. pg_db_blk_read_time counter datname, job, ins, ip, instance, clsTime spent reading data file blocks by backends in this database, in seconds pg_db_blk_write_time counter datname, job, ins, ip, instance, clsTime spent writing data file blocks by backends in this database, in seconds pg_db_blks_access counter datname, job, ins, ip, instance, clsNumber of times disk blocks that accessed read+hit pg_db_blks_hit counter datname, job, ins, ip, instance, clsNumber of times disk blocks were found already in the buffer cache pg_db_blks_read counter datname, job, ins, ip, instance, clsNumber of disk blocks read in this database pg_db_cks_fail_time gauge datname, job, ins, ip, instance, clsTime at which the last data page checksum failure was detected in this database pg_db_cks_fails counter datname, job, ins, ip, instance, clsNumber of data page checksum failures detected in this database, -1 for not enabled pg_db_confl_confl_bufferpin counter datname, job, ins, ip, instance, clsNumber of queries in this database that have been canceled due to pinned buffers pg_db_confl_confl_deadlock counter datname, job, ins, ip, instance, clsNumber of queries in this database that have been canceled due to deadlocks pg_db_confl_confl_lock counter datname, job, ins, ip, instance, clsNumber of queries in this database that have been canceled due to lock timeouts pg_db_confl_confl_snapshot counter datname, job, ins, ip, instance, clsNumber of queries in this database that have been canceled due to old snapshots pg_db_confl_confl_tablespace counter datname, job, ins, ip, instance, clsNumber of queries in this database that have been canceled due to dropped tablespaces pg_db_conflicts counter datname, job, ins, ip, instance, clsNumber of queries canceled due to conflicts with recovery in this database pg_db_conn_limit gauge datname, job, ins, ip, instance, clsSets maximum number of concurrent connections that can be made to this database. -1 means no limit. pg_db_datid gauge datname, job, ins, ip, instance, clsOID of the database pg_db_deadlocks counter datname, job, ins, ip, instance, clsNumber of deadlocks detected in this database pg_db_frozen_xid gauge datname, job, ins, ip, instance, clsAll transaction IDs before this one have been frozened pg_db_is_template gauge datname, job, ins, ip, instance, clsIf true(1), then this database can be cloned by any user with CREATEDB privileges pg_db_ixact_time counter datname, job, ins, ip, instance, clsTime spent idling while in a transaction in this database, in seconds pg_db_numbackends gauge datname, job, ins, ip, instance, clsNumber of backends currently connected to this database pg_db_reset_time counter datname, job, ins, ip, instance, clsTime at which database statistics were last reset pg_db_session_time counter datname, job, ins, ip, instance, clsTime spent by database sessions in this database, in seconds pg_db_sessions counter datname, job, ins, ip, instance, clsTotal number of sessions established to this database pg_db_sessions_abandoned counter datname, job, ins, ip, instance, clsNumber of database sessions to this database that were terminated because connection to the client was lost pg_db_sessions_fatal counter datname, job, ins, ip, instance, clsNumber of database sessions to this database that were terminated by fatal errors pg_db_sessions_killed counter datname, job, ins, ip, instance, clsNumber of database sessions to this database that were terminated by operator intervention pg_db_temp_bytes counter datname, job, ins, ip, instance, clsTotal amount of data written to temporary files by queries in this database. pg_db_temp_files counter datname, job, ins, ip, instance, clsNumber of temporary files created by queries in this database pg_db_tup_deleted counter datname, job, ins, ip, instance, clsNumber of rows deleted by queries in this database pg_db_tup_fetched counter datname, job, ins, ip, instance, clsNumber of rows fetched by queries in this database pg_db_tup_inserted counter datname, job, ins, ip, instance, clsNumber of rows inserted by queries in this database pg_db_tup_modified counter datname, job, ins, ip, instance, clsNumber of rows modified by queries in this database pg_db_tup_returned counter datname, job, ins, ip, instance, clsNumber of rows returned by queries in this database pg_db_tup_updated counter datname, job, ins, ip, instance, clsNumber of rows updated by queries in this database pg_db_xact_commit counter datname, job, ins, ip, instance, clsNumber of transactions in this database that have been committed pg_db_xact_rollback counter datname, job, ins, ip, instance, clsNumber of transactions in this database that have been rolled back pg_db_xact_total counter datname, job, ins, ip, instance, clsNumber of transactions in this database pg_downstream_count gauge state, job, ins, ip, instance, clsCount of corresponding state pg_exporter_agent_up Unknown job, ins, ip, instance, clsN/A pg_exporter_last_scrape_time gauge job, ins, ip, instance, clsseconds exporter spending on scrapping pg_exporter_query_cache_ttl gauge datname, query, job, ins, ip, instance, clstimes to live of query cache pg_exporter_query_scrape_duration gauge datname, query, job, ins, ip, instance, clsseconds query spending on scrapping pg_exporter_query_scrape_error_count gauge datname, query, job, ins, ip, instance, clstimes the query failed pg_exporter_query_scrape_hit_count gauge datname, query, job, ins, ip, instance, clsnumbers been scrapped from this query pg_exporter_query_scrape_metric_count gauge datname, query, job, ins, ip, instance, clsnumbers of metrics been scrapped from this query pg_exporter_query_scrape_total_count gauge datname, query, job, ins, ip, instance, clstimes exporter server was scraped for metrics pg_exporter_scrape_duration gauge job, ins, ip, instance, clsseconds exporter spending on scrapping pg_exporter_scrape_error_count counter job, ins, ip, instance, clstimes exporter was scraped for metrics and failed pg_exporter_scrape_total_count counter job, ins, ip, instance, clstimes exporter was scraped for metrics pg_exporter_server_scrape_duration gauge datname, job, ins, ip, instance, clsseconds exporter server spending on scrapping pg_exporter_server_scrape_error_count Unknown datname, job, ins, ip, instance, clsN/A pg_exporter_server_scrape_total_count gauge datname, job, ins, ip, instance, clstimes exporter server was scraped for metrics pg_exporter_server_scrape_total_seconds gauge datname, job, ins, ip, instance, clsseconds exporter server spending on scrapping pg_exporter_up gauge job, ins, ip, instance, clsalways be 1 if your could retrieve metrics pg_exporter_uptime gauge job, ins, ip, instance, clsseconds since exporter primary server inited pg_flush_lsn counter job, ins, ip, instance, clsprimary only, location of current wal syncing pg_func_calls counter datname, funcname, job, ins, ip, instance, clsNumber of times this function has been called pg_func_self_time counter datname, funcname, job, ins, ip, instance, clsTotal time spent in this function itself, not including other functions called by it, in ms pg_func_total_time counter datname, funcname, job, ins, ip, instance, clsTotal time spent in this function and all other functions called by it, in ms pg_in_recovery gauge job, ins, ip, instance, clsserver is in recovery mode? 1 for yes 0 for no pg_index_idx_blks_hit counter datname, relname, job, ins, relid, ip, instance, cls, idxnameNumber of buffer hits in this index pg_index_idx_blks_read counter datname, relname, job, ins, relid, ip, instance, cls, idxnameNumber of disk blocks read from this index pg_index_idx_scan counter datname, relname, job, ins, relid, ip, instance, cls, idxnameNumber of index scans initiated on this index pg_index_idx_tup_fetch counter datname, relname, job, ins, relid, ip, instance, cls, idxnameNumber of live table rows fetched by simple index scans using this index pg_index_idx_tup_read counter datname, relname, job, ins, relid, ip, instance, cls, idxnameNumber of index entries returned by scans on this index pg_index_relpages gauge datname, relname, job, ins, relid, ip, instance, cls, idxnameSize of the on-disk representation of this index in pages pg_index_reltuples gauge datname, relname, job, ins, relid, ip, instance, cls, idxnameEstimate relation tuples pg_insert_lsn counter job, ins, ip, instance, clsprimary only, location of current wal inserting pg_io_evictions counter type, job, ins, object, ip, context, instance, clsNumber of times a block has been written out from a shared or local buffer pg_io_extend_time counter type, job, ins, object, ip, context, instance, clsTime spent in extend operations in seconds pg_io_extends counter type, job, ins, object, ip, context, instance, clsNumber of relation extend operations, each of the size specified in op_bytes. pg_io_fsync_time counter type, job, ins, object, ip, context, instance, clsTime spent in fsync operations in seconds pg_io_fsyncs counter type, job, ins, object, ip, context, instance, clsNumber of fsync calls. These are only tracked in context normal pg_io_hits counter type, job, ins, object, ip, context, instance, clsThe number of times a desired block was found in a shared buffer. pg_io_op_bytes gauge type, job, ins, object, ip, context, instance, clsThe number of bytes per unit of I/O read, written, or extended. 8192 by default pg_io_read_time counter type, job, ins, object, ip, context, instance, clsTime spent in read operations in seconds pg_io_reads counter type, job, ins, object, ip, context, instance, clsNumber of read operations, each of the size specified in op_bytes. pg_io_reset_time gauge type, job, ins, object, ip, context, instance, clsTimestamp at which these statistics were last reset pg_io_reuses counter type, job, ins, object, ip, context, instance, clsThe number of times an existing buffer in reused pg_io_write_time counter type, job, ins, object, ip, context, instance, clsTime spent in write operations in seconds pg_io_writeback_time counter type, job, ins, object, ip, context, instance, clsTime spent in writeback operations in seconds pg_io_writebacks counter type, job, ins, object, ip, context, instance, clsNumber of units of size op_bytes which the process requested the kernel write out to permanent storage. pg_io_writes counter type, job, ins, object, ip, context, instance, clsNumber of write operations, each of the size specified in op_bytes. pg_is_in_recovery gauge job, ins, ip, instance, cls1 if in recovery mode pg_is_wal_replay_paused gauge job, ins, ip, instance, cls1 if wal play paused pg_lag gauge job, ins, ip, instance, clsreplica only, replication lag in seconds pg_last_replay_time gauge job, ins, ip, instance, clstime when last transaction been replayed pg_lock_count gauge datname, job, ins, ip, mode, instance, clsNumber of locks of corresponding mode and database pg_lsn counter job, ins, ip, instance, clslog sequence number, current write location pg_meta_info gauge cls, extensions, version, job, ins, primary_conninfo, conf_path, hba_path, ip, cluster_id, instance, listen_port, wal_level, ver_num, cluster_name, data_dirconstant 1 pg_query_calls counter datname, query, job, ins, ip, instance, clsNumber of times the statement was executed pg_query_exec_time counter datname, query, job, ins, ip, instance, clsTotal time spent executing the statement, in seconds pg_query_io_time counter datname, query, job, ins, ip, instance, clsTotal time the statement spent reading and writing blocks, in seconds pg_query_rows counter datname, query, job, ins, ip, instance, clsTotal number of rows retrieved or affected by the statement pg_query_sblk_dirtied counter datname, query, job, ins, ip, instance, clsTotal number of shared blocks dirtied by the statement pg_query_sblk_hit counter datname, query, job, ins, ip, instance, clsTotal number of shared block cache hits by the statement pg_query_sblk_read counter datname, query, job, ins, ip, instance, clsTotal number of shared blocks read by the statement pg_query_sblk_written counter datname, query, job, ins, ip, instance, clsTotal number of shared blocks written by the statement pg_query_wal_bytes counter datname, query, job, ins, ip, instance, clsTotal amount of WAL bytes generated by the statement pg_receive_lsn counter job, ins, ip, instance, clsreplica only, location of wal synced to disk pg_recovery_backup_end_lsn counter job, ins, ip, instance, clsBackup end location pg_recovery_backup_start_lsn counter job, ins, ip, instance, clsBackup start location pg_recovery_min_lsn counter job, ins, ip, instance, clsMinimum recovery ending location pg_recovery_min_timeline counter job, ins, ip, instance, clsMin recovery ending loc’s timeline pg_recovery_prefetch_block_distance gauge job, ins, ip, instance, clsHow many blocks ahead the prefetcher is looking pg_recovery_prefetch_hit counter job, ins, ip, instance, clsNumber of blocks not prefetched because they were already in the buffer pool pg_recovery_prefetch_io_depth gauge job, ins, ip, instance, clsHow many prefetches have been initiated but are not yet known to have completed pg_recovery_prefetch_prefetch counter job, ins, ip, instance, clsNumber of blocks prefetched because they were not in the buffer pool pg_recovery_prefetch_reset_time counter job, ins, ip, instance, clsTime at which these recovery prefetch statistics were last reset pg_recovery_prefetch_skip_fpw gauge job, ins, ip, instance, clsNumber of blocks not prefetched because a full page image was included in the WAL pg_recovery_prefetch_skip_init counter job, ins, ip, instance, clsNumber of blocks not prefetched because they would be zero-initialized pg_recovery_prefetch_skip_new counter job, ins, ip, instance, clsNumber of blocks not prefetched because they didn’t exist yet pg_recovery_prefetch_skip_rep counter job, ins, ip, instance, clsNumber of blocks not prefetched because they were already recently prefetched pg_recovery_prefetch_wal_distance gauge job, ins, ip, instance, clsHow many bytes ahead the prefetcher is looking pg_recovery_require_record gauge job, ins, ip, instance, clsEnd-of-backup record required pg_recv_flush_lsn counter state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portLast write-ahead log location already received and flushed to disk pg_recv_flush_tli counter state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portTimeline number of last write-ahead log location received and flushed to disk pg_recv_init_lsn counter state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portFirst write-ahead log location used when WAL receiver is started pg_recv_init_tli counter state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portFirst timeline number used when WAL receiver is started pg_recv_msg_recv_time gauge state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portReceipt time of last message received from origin WAL sender pg_recv_msg_send_time gauge state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portSend time of last message received from origin WAL sender pg_recv_pid gauge state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portProcess ID of the WAL receiver process pg_recv_reported_lsn counter state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portLast write-ahead log location reported to origin WAL sender pg_recv_reported_time gauge state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portTime of last write-ahead log location reported to origin WAL sender pg_recv_time gauge state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portTime of current snapshot pg_recv_write_lsn counter state, slot_name, job, ins, ip, instance, cls, sender_host, sender_portLast write-ahead log location already received and written to disk, but not flushed. pg_relkind_count gauge datname, job, ins, ip, instance, cls, relkindNumber of relations of corresponding relkind pg_repl_backend_xmin counter pid, usename, address, job, ins, appname, ip, instance, clsThis standby’s xmin horizon reported by hot_standby_feedback. pg_repl_client_port gauge pid, usename, address, job, ins, appname, ip, instance, clsTCP port number that the client is using for communication with this WAL sender, or -1 if a Unix socket is used pg_repl_flush_diff gauge pid, usename, address, job, ins, appname, ip, instance, clsLast log position flushed to disk by this standby server diff with current lsn pg_repl_flush_lag gauge pid, usename, address, job, ins, appname, ip, instance, clsTime elapsed between flushing recent WAL locally and receiving notification that this standby server has written and flushed it pg_repl_flush_lsn counter pid, usename, address, job, ins, appname, ip, instance, clsLast write-ahead log location flushed to disk by this standby server pg_repl_launch_time counter pid, usename, address, job, ins, appname, ip, instance, clsTime when this process was started, i.e., when the client connected to this WAL sender pg_repl_lsn counter pid, usename, address, job, ins, appname, ip, instance, clsCurrent log position on this server pg_repl_replay_diff gauge pid, usename, address, job, ins, appname, ip, instance, clsLast log position replayed into the database on this standby server diff with current lsn pg_repl_replay_lag gauge pid, usename, address, job, ins, appname, ip, instance, clsTime elapsed between flushing recent WAL locally and receiving notification that this standby server has written, flushed and applied it pg_repl_replay_lsn counter pid, usename, address, job, ins, appname, ip, instance, clsLast write-ahead log location replayed into the database on this standby server pg_repl_reply_time gauge pid, usename, address, job, ins, appname, ip, instance, clsSend time of last reply message received from standby server pg_repl_sent_diff gauge pid, usename, address, job, ins, appname, ip, instance, clsLast log position sent to this standby server diff with current lsn pg_repl_sent_lsn counter pid, usename, address, job, ins, appname, ip, instance, clsLast write-ahead log location sent on this connection pg_repl_state gauge pid, usename, address, job, ins, appname, ip, instance, clsCurrent WAL sender encoded state 0-4 for streaming startup catchup backup stopping pg_repl_sync_priority gauge pid, usename, address, job, ins, appname, ip, instance, clsPriority of this standby server for being chosen as the synchronous standby pg_repl_sync_state gauge pid, usename, address, job, ins, appname, ip, instance, clsEncoded synchronous state of this standby server, 0-3 for async potential sync quorum pg_repl_time counter pid, usename, address, job, ins, appname, ip, instance, clsCurrent timestamp in unix epoch pg_repl_write_diff gauge pid, usename, address, job, ins, appname, ip, instance, clsLast log position written to disk by this standby server diff with current lsn pg_repl_write_lag gauge pid, usename, address, job, ins, appname, ip, instance, clsTime elapsed between flushing recent WAL locally and receiving notification that this standby server has written it pg_repl_write_lsn counter pid, usename, address, job, ins, appname, ip, instance, clsLast write-ahead log location written to disk by this standby server pg_replay_lsn counter job, ins, ip, instance, clsreplica only, location of wal applied pg_seq_blks_hit counter datname, job, ins, ip, instance, cls, seqnameNumber of buffer hits in this sequence pg_seq_blks_read counter datname, job, ins, ip, instance, cls, seqnameNumber of disk blocks read from this sequence pg_seq_last_value counter datname, job, ins, ip, instance, cls, seqnameThe last sequence value written to disk pg_setting_block_size gauge job, ins, ip, instance, clspg page block size, 8192 by default pg_setting_data_checksums gauge job, ins, ip, instance, clswhether data checksum is enabled, 1 enabled 0 disabled pg_setting_max_connections gauge job, ins, ip, instance, clsnumber of concurrent connections to the database server pg_setting_max_locks_per_transaction gauge job, ins, ip, instance, clsno more than this many distinct objects can be locked at any one time pg_setting_max_prepared_transactions gauge job, ins, ip, instance, clsmaximum number of transactions that can be in the prepared state simultaneously pg_setting_max_replication_slots gauge job, ins, ip, instance, clsmaximum number of replication slots pg_setting_max_wal_senders gauge job, ins, ip, instance, clsmaximum number of concurrent connections from standby servers pg_setting_max_worker_processes gauge job, ins, ip, instance, clsmaximum number of background processes that the system can support pg_setting_wal_log_hints gauge job, ins, ip, instance, clswhether wal_log_hints is enabled, 1 enabled 0 disabled pg_size_bytes gauge datname, job, ins, ip, instance, clsFile size in bytes pg_slot_active gauge slot_name, job, ins, ip, instance, clsTrue(1) if this slot is currently actively being used pg_slot_catalog_xmin counter slot_name, job, ins, ip, instance, clsThe oldest transaction affecting the system catalogs that this slot needs the database to retain. pg_slot_confirm_lsn counter slot_name, job, ins, ip, instance, clsThe address (LSN) up to which the logical slot’s consumer has confirmed receiving data. pg_slot_reset_time counter slot_name, job, ins, ip, instance, clsWhen statistics were last reset pg_slot_restart_lsn counter slot_name, job, ins, ip, instance, clsThe address (LSN) of oldest WAL which still might be required by the consumer of this slot pg_slot_retained_bytes gauge slot_name, job, ins, ip, instance, clsSize of bytes that retained for this slot pg_slot_safe_wal_size gauge slot_name, job, ins, ip, instance, clsbytes that can be written to WAL which will not make slot into lost pg_slot_spill_bytes counter slot_name, job, ins, ip, instance, clsBytes that spilled to disk due to logical decode mem exceeding pg_slot_spill_count counter slot_name, job, ins, ip, instance, clsXacts that spilled to disk due to logical decode mem exceeding (a xact can be spilled multiple times) pg_slot_spill_txns counter slot_name, job, ins, ip, instance, clsXacts that spilled to disk due to logical decode mem exceeding (subtrans included) pg_slot_stream_bytes counter slot_name, job, ins, ip, instance, clsBytes that streamed to decoding output plugin after mem exceed pg_slot_stream_count counter slot_name, job, ins, ip, instance, clsXacts that streamed to decoding output plugin after mem exceed (a xact can be streamed multiple times) pg_slot_stream_txns counter slot_name, job, ins, ip, instance, clsXacts that streamed to decoding output plugin after mem exceed pg_slot_temporary gauge slot_name, job, ins, ip, instance, clsTrue(1) if this is a temporary replication slot. pg_slot_total_bytes counter slot_name, job, ins, ip, instance, clsNumber of decoded bytes sent to the decoding output plugin for this slot pg_slot_total_txns counter slot_name, job, ins, ip, instance, clsNumber of decoded xacts sent to the decoding output plugin for this slot pg_slot_wal_status gauge slot_name, job, ins, ip, instance, clsWAL reserve status 0-3 means reserved,extended,unreserved,lost, -1 means other pg_slot_xmin counter slot_name, job, ins, ip, instance, clsThe oldest transaction that this slot needs the database to retain. pg_slru_blks_exists counter job, ins, ip, instance, clsNumber of blocks checked for existence for this SLRU pg_slru_blks_hit counter job, ins, ip, instance, clsNumber of times disk blocks were found already in the SLRU, so that a read was not necessary pg_slru_blks_read counter job, ins, ip, instance, clsNumber of disk blocks read for this SLRU pg_slru_blks_written counter job, ins, ip, instance, clsNumber of disk blocks written for this SLRU pg_slru_blks_zeroed counter job, ins, ip, instance, clsNumber of blocks zeroed during initializations pg_slru_flushes counter job, ins, ip, instance, clsNumber of flushes of dirty data for this SLRU pg_slru_reset_time counter job, ins, ip, instance, clsTime at which these statistics were last reset pg_slru_truncates counter job, ins, ip, instance, clsNumber of truncates for this SLRU pg_ssl_disabled gauge job, ins, ip, instance, clsNumber of client connection that does not use ssl pg_ssl_enabled gauge job, ins, ip, instance, clsNumber of client connection that use ssl pg_sync_standby_enabled gauge job, ins, ip, names, instance, clsSynchronous commit enabled, 1 if enabled, 0 if disabled pg_table_age gauge datname, relname, job, ins, ip, instance, clsAge of this table in vacuum cycles pg_table_analyze_count counter datname, relname, job, ins, ip, instance, clsNumber of times this table has been manually analyzed pg_table_autoanalyze_count counter datname, relname, job, ins, ip, instance, clsNumber of times this table has been analyzed by the autovacuum daemon pg_table_autovacuum_count counter datname, relname, job, ins, ip, instance, clsNumber of times this table has been vacuumed by the autovacuum daemon pg_table_frozenxid counter datname, relname, job, ins, ip, instance, clsAll txid before this have been frozen on this table pg_table_heap_blks_hit counter datname, relname, job, ins, ip, instance, clsNumber of buffer hits in this table pg_table_heap_blks_read counter datname, relname, job, ins, ip, instance, clsNumber of disk blocks read from this table pg_table_idx_blks_hit counter datname, relname, job, ins, ip, instance, clsNumber of buffer hits in all indexes on this table pg_table_idx_blks_read counter datname, relname, job, ins, ip, instance, clsNumber of disk blocks read from all indexes on this table pg_table_idx_scan counter datname, relname, job, ins, ip, instance, clsNumber of index scans initiated on this table pg_table_idx_tup_fetch counter datname, relname, job, ins, ip, instance, clsNumber of live rows fetched by index scans pg_table_kind gauge datname, relname, job, ins, ip, instance, clsRelation kind r/table/114 pg_table_n_dead_tup gauge datname, relname, job, ins, ip, instance, clsEstimated number of dead rows pg_table_n_ins_since_vacuum gauge datname, relname, job, ins, ip, instance, clsEstimated number of rows inserted since this table was last vacuumed pg_table_n_live_tup gauge datname, relname, job, ins, ip, instance, clsEstimated number of live rows pg_table_n_mod_since_analyze gauge datname, relname, job, ins, ip, instance, clsEstimated number of rows modified since this table was last analyzed pg_table_n_tup_del counter datname, relname, job, ins, ip, instance, clsNumber of rows deleted pg_table_n_tup_hot_upd counter datname, relname, job, ins, ip, instance, clsNumber of rows HOT updated (i.e with no separate index update required) pg_table_n_tup_ins counter datname, relname, job, ins, ip, instance, clsNumber of rows inserted pg_table_n_tup_mod counter datname, relname, job, ins, ip, instance, clsNumber of rows modified (insert + update + delete) pg_table_n_tup_newpage_upd counter datname, relname, job, ins, ip, instance, clsNumber of rows updated where the successor version goes onto a new heap page pg_table_n_tup_upd counter datname, relname, job, ins, ip, instance, clsNumber of rows updated (includes HOT updated rows) pg_table_ncols gauge datname, relname, job, ins, ip, instance, clsNumber of columns in the table pg_table_pages gauge datname, relname, job, ins, ip, instance, clsSize of the on-disk representation of this table in pages pg_table_relid gauge datname, relname, job, ins, ip, instance, clsRelation oid of this table pg_table_seq_scan counter datname, relname, job, ins, ip, instance, clsNumber of sequential scans initiated on this table pg_table_seq_tup_read counter datname, relname, job, ins, ip, instance, clsNumber of live rows fetched by sequential scans pg_table_size_bytes gauge datname, relname, job, ins, ip, instance, clsTotal bytes of this table (including toast, index, toast index) pg_table_size_indexsize gauge datname, relname, job, ins, ip, instance, clsBytes of all related indexes of this table pg_table_size_relsize gauge datname, relname, job, ins, ip, instance, clsBytes of this table itself (main, vm, fsm) pg_table_size_toastsize gauge datname, relname, job, ins, ip, instance, clsBytes of toast tables of this table pg_table_tbl_scan counter datname, relname, job, ins, ip, instance, clsNumber of scans initiated on this table pg_table_tup_read counter datname, relname, job, ins, ip, instance, clsNumber of live rows fetched by scans pg_table_tuples counter datname, relname, job, ins, ip, instance, clsAll txid before this have been frozen on this table pg_table_vacuum_count counter datname, relname, job, ins, ip, instance, clsNumber of times this table has been manually vacuumed (not counting VACUUM FULL) pg_timestamp gauge job, ins, ip, instance, clsdatabase current timestamp pg_up gauge job, ins, ip, instance, clslast scrape was able to connect to the server: 1 for yes, 0 for no pg_uptime gauge job, ins, ip, instance, clsseconds since postmaster start pg_version gauge job, ins, ip, instance, clsserver version number pg_wait_count gauge datname, job, ins, event, ip, instance, clsCount of WaitEvent on target database pg_wal_buffers_full counter job, ins, ip, instance, clsNumber of times WAL data was written to disk because WAL buffers became full pg_wal_bytes counter job, ins, ip, instance, clsTotal amount of WAL generated in bytes pg_wal_fpi counter job, ins, ip, instance, clsTotal number of WAL full page images generated pg_wal_records counter job, ins, ip, instance, clsTotal number of WAL records generated pg_wal_reset_time counter job, ins, ip, instance, clsWhen statistics were last reset pg_wal_sync counter job, ins, ip, instance, clsNumber of times WAL files were synced to disk via issue_xlog_fsync request pg_wal_sync_time counter job, ins, ip, instance, clsTotal amount of time spent syncing WAL files to disk via issue_xlog_fsync request, in seconds pg_wal_write counter job, ins, ip, instance, clsNumber of times WAL buffers were written out to disk via XLogWrite request. pg_wal_write_time counter job, ins, ip, instance, clsTotal amount of time spent writing WAL buffers to disk via XLogWrite request in seconds pg_write_lsn counter job, ins, ip, instance, clsprimary only, location of current wal writing pg_xact_xmax counter job, ins, ip, instance, clsFirst as-yet-unassigned txid. txid >= this are invisible. pg_xact_xmin counter job, ins, ip, instance, clsEarliest txid that is still active pg_xact_xnum gauge job, ins, ip, instance, clsCurrent active transaction count pgbouncer:cls:load1 Unknown job, clsN/A pgbouncer:cls:load15 Unknown job, clsN/A pgbouncer:cls:load5 Unknown job, clsN/A pgbouncer:db:conn_usage Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:db:conn_usage_reserve Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:db:pool_current_conn Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:db:pool_disabled Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:db:pool_max_conn Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:db:pool_paused Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:db:pool_reserve_size Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:db:pool_size Unknown datname, job, ins, ip, instance, host, cls, real_datname, portN/A pgbouncer:ins:free_clients Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:free_servers Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:load1 Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:load15 Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:load5 Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:login_clients Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:pool_databases Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:pool_users Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:pools Unknown job, ins, ip, instance, clsN/A pgbouncer:ins:used_clients Unknown job, ins, ip, instance, clsN/A pgbouncer_database_current_connections gauge datname, job, ins, ip, instance, host, cls, real_datname, portCurrent number of connections for this database pgbouncer_database_disabled gauge datname, job, ins, ip, instance, host, cls, real_datname, portTrue(1) if this database is currently disabled, else 0 pgbouncer_database_max_connections gauge datname, job, ins, ip, instance, host, cls, real_datname, portMaximum number of allowed connections for this database pgbouncer_database_min_pool_size gauge datname, job, ins, ip, instance, host, cls, real_datname, portMinimum number of server connections pgbouncer_database_paused gauge datname, job, ins, ip, instance, host, cls, real_datname, portTrue(1) if this database is currently paused, else 0 pgbouncer_database_pool_size gauge datname, job, ins, ip, instance, host, cls, real_datname, portMaximum number of server connections pgbouncer_database_reserve_pool gauge datname, job, ins, ip, instance, host, cls, real_datname, portMaximum number of additional connections for this database pgbouncer_exporter_agent_up Unknown job, ins, ip, instance, clsN/A pgbouncer_exporter_last_scrape_time gauge job, ins, ip, instance, clsseconds exporter spending on scrapping pgbouncer_exporter_query_cache_ttl gauge datname, query, job, ins, ip, instance, clstimes to live of query cache pgbouncer_exporter_query_scrape_duration gauge datname, query, job, ins, ip, instance, clsseconds query spending on scrapping pgbouncer_exporter_query_scrape_error_count gauge datname, query, job, ins, ip, instance, clstimes the query failed pgbouncer_exporter_query_scrape_hit_count gauge datname, query, job, ins, ip, instance, clsnumbers been scrapped from this query pgbouncer_exporter_query_scrape_metric_count gauge datname, query, job, ins, ip, instance, clsnumbers of metrics been scrapped from this query pgbouncer_exporter_query_scrape_total_count gauge datname, query, job, ins, ip, instance, clstimes exporter server was scraped for metrics pgbouncer_exporter_scrape_duration gauge job, ins, ip, instance, clsseconds exporter spending on scrapping pgbouncer_exporter_scrape_error_count counter job, ins, ip, instance, clstimes exporter was scraped for metrics and failed pgbouncer_exporter_scrape_total_count counter job, ins, ip, instance, clstimes exporter was scraped for metrics pgbouncer_exporter_server_scrape_duration gauge datname, job, ins, ip, instance, clsseconds exporter server spending on scrapping pgbouncer_exporter_server_scrape_total_count gauge datname, job, ins, ip, instance, clstimes exporter server was scraped for metrics pgbouncer_exporter_server_scrape_total_seconds gauge datname, job, ins, ip, instance, clsseconds exporter server spending on scrapping pgbouncer_exporter_up gauge job, ins, ip, instance, clsalways be 1 if your could retrieve metrics pgbouncer_exporter_uptime gauge job, ins, ip, instance, clsseconds since exporter primary server inited pgbouncer_in_recovery gauge job, ins, ip, instance, clsserver is in recovery mode? 1 for yes 0 for no pgbouncer_list_items gauge job, ins, ip, instance, list, clsNumber of corresponding pgbouncer object pgbouncer_pool_active_cancel_clients gauge datname, job, ins, ip, instance, user, cls, pool_modeClient connections that have forwarded query cancellations to the server and are waiting for the server response. pgbouncer_pool_active_cancel_servers gauge datname, job, ins, ip, instance, user, cls, pool_modeServer connections that are currently forwarding a cancel request pgbouncer_pool_active_clients gauge datname, job, ins, ip, instance, user, cls, pool_modeClient connections that are linked to server connection and can process queries pgbouncer_pool_active_servers gauge datname, job, ins, ip, instance, user, cls, pool_modeServer connections that are linked to a client pgbouncer_pool_cancel_clients gauge datname, job, ins, ip, instance, user, cls, pool_modeClient connections that have not forwarded query cancellations to the server yet. pgbouncer_pool_cancel_servers gauge datname, job, ins, ip, instance, user, cls, pool_modecancel requests have completed that were sent to cancel a query on this server pgbouncer_pool_idle_servers gauge datname, job, ins, ip, instance, user, cls, pool_modeServer connections that are unused and immediately usable for client queries pgbouncer_pool_login_servers gauge datname, job, ins, ip, instance, user, cls, pool_modeServer connections currently in the process of logging in pgbouncer_pool_maxwait gauge datname, job, ins, ip, instance, user, cls, pool_modeHow long the first(oldest) client in the queue has waited, in seconds, key metric pgbouncer_pool_maxwait_us gauge datname, job, ins, ip, instance, user, cls, pool_modeMicrosecond part of the maximum waiting time. pgbouncer_pool_tested_servers gauge datname, job, ins, ip, instance, user, cls, pool_modeServer connections that are currently running reset or check query pgbouncer_pool_used_servers gauge datname, job, ins, ip, instance, user, cls, pool_modeServer connections that have been idle for more than server_check_delay (means have to run check query) pgbouncer_pool_waiting_clients gauge datname, job, ins, ip, instance, user, cls, pool_modeClient connections that have sent queries but have not yet got a server connection pgbouncer_stat_avg_query_count gauge datname, job, ins, ip, instance, clsAverage queries per second in last stat period pgbouncer_stat_avg_query_time gauge datname, job, ins, ip, instance, clsAverage query duration, in seconds pgbouncer_stat_avg_recv gauge datname, job, ins, ip, instance, clsAverage received (from clients) bytes per second pgbouncer_stat_avg_sent gauge datname, job, ins, ip, instance, clsAverage sent (to clients) bytes per second pgbouncer_stat_avg_wait_time gauge datname, job, ins, ip, instance, clsTime spent by clients waiting for a server, in seconds (average per second). pgbouncer_stat_avg_xact_count gauge datname, job, ins, ip, instance, clsAverage transactions per second in last stat period pgbouncer_stat_avg_xact_time gauge datname, job, ins, ip, instance, clsAverage transaction duration, in seconds pgbouncer_stat_total_query_count gauge datname, job, ins, ip, instance, clsTotal number of SQL queries pooled by pgbouncer pgbouncer_stat_total_query_time counter datname, job, ins, ip, instance, clsTotal number of seconds spent when executing queries pgbouncer_stat_total_received counter datname, job, ins, ip, instance, clsTotal volume in bytes of network traffic received by pgbouncer pgbouncer_stat_total_sent counter datname, job, ins, ip, instance, clsTotal volume in bytes of network traffic sent by pgbouncer pgbouncer_stat_total_wait_time counter datname, job, ins, ip, instance, clsTime spent by clients waiting for a server, in seconds pgbouncer_stat_total_xact_count gauge datname, job, ins, ip, instance, clsTotal number of SQL transactions pooled by pgbouncer pgbouncer_stat_total_xact_time counter datname, job, ins, ip, instance, clsTotal number of seconds spent when in a transaction pgbouncer_up gauge job, ins, ip, instance, clslast scrape was able to connect to the server: 1 for yes, 0 for no pgbouncer_version gauge job, ins, ip, instance, clsserver version number process_cpu_seconds_total counter job, ins, ip, instance, clsTotal user and system CPU time spent in seconds. process_max_fds gauge job, ins, ip, instance, clsMaximum number of open file descriptors. process_open_fds gauge job, ins, ip, instance, clsNumber of open file descriptors. process_resident_memory_bytes gauge job, ins, ip, instance, clsResident memory size in bytes. process_start_time_seconds gauge job, ins, ip, instance, clsStart time of the process since unix epoch in seconds. process_virtual_memory_bytes gauge job, ins, ip, instance, clsVirtual memory size in bytes. process_virtual_memory_max_bytes gauge job, ins, ip, instance, clsMaximum amount of virtual memory available in bytes. promhttp_metric_handler_requests_in_flight gauge job, ins, ip, instance, clsCurrent number of scrapes being served. promhttp_metric_handler_requests_total counter code, job, ins, ip, instance, clsTotal number of scrapes by HTTP status code. scrape_duration_seconds Unknown job, ins, ip, instance, clsN/A scrape_samples_post_metric_relabeling Unknown job, ins, ip, instance, clsN/A scrape_samples_scraped Unknown job, ins, ip, instance, clsN/A scrape_series_added Unknown job, ins, ip, instance, clsN/A up Unknown job, ins, ip, instance, clsN/A
11.13 - 内核分支 如何在 Pigsty 中使用其他 PostgreSQL 内核分支?例如 Citus,Babelfish,IvorySQL,PolarDB 等
在 Pigsty 中,您可以使用不同 “风味 ” 的 PostgreSQL 分支替换 “原生PG内核”,实现特殊的功能与效果。
Pigsty 支持各种 PostgreSQL 内核和兼容分支,使您能够模拟不同的数据库系统,同时利用 PostgreSQL 的生态系统。每个内核都能提供独特的功能和兼容性层。
11.13.1 - PostgreSQL 带有 440 扩展的原版 PostgreSQL 内核
PostgreSQL 是世界上最先进和最受欢迎的开源数据库。
Pigsty 支持 PostgreSQL 13 ~ 18,并提供 440 个 PG 扩展。
快速开始 使用 pgsql 配置模板 安装 Pigsty。
./configure -c pgsql # 使用 postgres 内核
./install.yml # 使用 pigsty 设置一切
大多数配置模板 默认使用 PostgreSQL 内核,例如:
meta : 默认 ,带有核心扩展(vector、postgis、timescale)的 postgresrich : 安装了所有扩展的 postgresslim : 仅 postgres,无监控基础设施full : 用于 HA 演示的 4 节点沙盒pgsql : 最小的 postgres 内核配置示例配置 原版 PostgreSQL 内核不需要特殊调整:
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
pg_databases :
- { name: meta, baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ vector ]}
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # 每天凌晨 1 点进行全量备份
pg_packages : [ pgsql-main, pgsql-common ] # pg 内核和通用工具
#pg_extensions: [ pg18-time ,pg18-gis ,pg18-rag ,pg18-fts ,pg18-olap ,pg18-feat ,pg18-lang ,pg18-type ,pg18-util ,pg18-func ,pg18-admin ,pg18-stat ,pg18-sec ,pg18-fdw ,pg18-sim ,pg18-etl]
版本选择 要使用不同的 PostgreSQL 主版本,您可以使用 -v 参数进行配置:
./configure -c pgsql # 默认就是 postgresql 18,无需显式指定
./configure -c pgsql -v 17 # 使用 postgresql 17
./configure -c pgsql -v 16 # 使用 postgresql 16
./configure -c pgsql -v 15 # 使用 postgresql 15
./configure -c pgsql -v 14 # 使用 postgresql 14
./configure -c pgsql -v 13 # 使用 postgresql 13
如果 PostgreSQL 集群已经安装,您需要在安装新版本之前卸载它:
./pgsql-rm.yml # -l pg-meta
扩展生态 Pigsty 为 PostgreSQL 提供了丰富的扩展生态,包括:
时序类 :timescaledb, pg_cron, periods地理类 :postgis, h3, pgrouting向量类 :pgvector, pgml, vchord搜索类 :pg_trgm, zhparser, pgroonga分析类 :citus, pg_duckdb, pg_analytics特性类 :age, pg_graphql, rum语言类 :plpython3u, pljava, plv8类型类 :hstore, ltree, citext工具类 :http, pg_net, pgjwt函数类 :pgcrypto, uuid-ossp, pg_uuidv7管理类 :pg_repack, pgagent, pg_squeeze统计类 :pg_stat_statements, pg_qualstats, auto_explain安全类 :pgaudit, pgcrypto, pgsodium外部类 :postgres_fdw, mysql_fdw, oracle_fdw兼容类 :orafce, babelfishpg_tds数据类 :pglogical, wal2json, decoderbufs详情请参考 扩展目录 。
11.13.2 - Supabase 如何使用Pigsty自建Supabase,一键拉起开源Firebase替代,后端全栈全家桶。
Supabase —— Build in a weekend, Scale to millions
Supabase 是一个开源的 Firebase 替代,对 PostgreSQL 进行了封装,并提供了认证,开箱即用的 API,边缘函数,实时订阅,对象存储,向量嵌入能力。
这是一个低代码的一站式后端平台,能让你几乎告别大部分后端开发的工作,只需要懂数据库设计与前端即可快速出活!
Supabase 的口号是:“花个周末写写,随便扩容至百万 ”。诚然,在小微规模(4c8g)内的 Supabase 极有性价比 ,堪称赛博菩萨。
—— 但当你真的增长到百万用户时 —— 确实应该认真考虑托管自建 Supabase 了 —— 无论是出于功能,性能,还是成本上的考虑。
Pigsty 为您提供完整的 Supabase 一键自建方案。自建的 Supabase 可以享受完整的 PostgreSQL 监控,IaC,PITR 与高可用,
而且相比 Supabase 云服务,提供了多达 440 个开箱即用的 PostgreSQL 扩展,并能够更充分地利用现代硬件的性能与成本优势。
完整自建教程,请参考:《Supabase自建手册 》
快速上手 Pigsty 默认提供的 supa.yml 配置模板定义了一套单节点 Supabase。
首先,使用 Pigsty 标准安装流程 安装 Supabase 所需的 MinIO 与 PostgreSQL 实例:
curl -fsSL https://repo.pigsty.io/get | bash
./bootstrap # 环境检查,安装依赖
./configure -c supa # 重要:请在配置文件中修改密码等关键信息!
./install.yml # 安装 Pigsty,拉起 PGSQL 与 MINIO!
请在部署 Supabase 前,根据您的实际情况,修改 pigsty.yml 配置文件中关于 Supabase 的参数 (主要是密码!)
然后,运行 supabase.yml 完成剩余的工作,拉起 Supabase 容器
./supabase.yml # 安装 Docker 并拉起 Supabase 无状态部分!
中国区域用户注意,请您配置合适的 Docker 镜像站点或代理服务器绕过 GFW 以拉取 DockerHub 镜像。
对于 专业订阅 ,我们提供在没有互联网访问的情况下,离线安装 Pigsty 与 Supabase 的能力。
Pigsty 默认通过管理节点/INFRA节点上的 Nginx 对外暴露 Web 服务,您可以在本地添加 supa.pigsty 的 DNS 解析指向该节点,
然后通过浏览器访问 https://supa.pigsty 即可进入 Supabase Studio 管理界面。
默认用户名与密码:supabase / pigsty
架构概览 Pigsty 以 Supabase 提供的 Docker Compose 模板为蓝本,提取了其中的无状态部分,由 Docker Compose 负责处理。而有状态的数据库和对象存储容器则替换为外部由 Pigsty 托管的 PostgreSQL 集群与 MinIO 服务。
Supabase: 使用 Docker 自建
经过改造后,Supabase 本体是无状态的,因此您可以随意运行,停止,甚至在同一套 PGSQL/MINIO 上同时运行多个无状态 Supabase 容器以实现扩容。
Pigsty 默认使用本机上的单机 PostgreSQL 实例作为 Supabase 的核心后端数据库。对于严肃的生产部署,我们建议使用 Pigsty 部署一套至少由三节点的 PG 高可用集群。或至少使用外部对象存储作为 PITR 备份仓库,提供兜底。
Pigsty 默认使用本机上的 SNSD MinIO 服务作为文件存储。对于严肃的生产环境部署,您可以使用外部的 S3 兼容对象存储服务,或者使用其他由 Pigsty 独立部署的 多机多盘 MinIO 集群。
配置细节 自建 Supabase 时,包含 Docker Compose 所需资源的目录 app/supabase 会被整个拷贝到目标节点(默认为 supabase 分组)上的 /opt/supabase,并使用 docker compose up -d 在后台拉起。
所有配置参数都定义在 .env 文件与 docker-compose.yml 模板中。
但您通常不需要直接修改这两个模板,你可以在 supa_config 中指定 .env 中的参数,这些配置会自动覆盖或追加到最终的 /opt/supabase/.env 核心配置文件中。
这里最关键的参数是 jwt_secret,以及对应的 anon_key 与 service_role_key。对于严肃的生产使用,请您务必参考Supabase自建手册 中的说明与工具设置 。
如果您希望使用域名对外提供服务,您可以在 site_url, api_external_url,以及 supabase_public_url 中指定您的域名。
Pigsty 默认使用本机 MinIO,如果您希望使用 S3 或 MinIO 作为文件存储,您需要配置 s3_bucket,s3_endpoint,s3_access_key,s3_secret_key 等参数。
通常来说,您还需要使用一个外部的 SMTP 服务来发送邮件,邮件服务不建议自建,请考虑使用成熟的第三方服务,如 Mailchimp,Aliyun 邮件推送等。
对于中国大陆用户来说,我们建议您配置 docker_registry_mirrors 镜像站点,或使用 proxy_env 指定可用的代理服务器翻墙,否则从 DockerHub 上拉取镜像可能会失败或极为缓慢!
# launch supabase stateless part with docker compose:
# ./supabase.yml
supabase :
hosts :
10.10.10.10 : { supa_seq : 1 } # instance id
vars :
supa_cluster : supa # cluster name
docker_enabled : true # enable docker
# use these to pull docker images via proxy and mirror registries
#docker_registry_mirrors: ['https://docker.xxxxx.io']
#proxy_env: # add [OPTIONAL] proxy env to /etc/docker/daemon.json configuration file
# no_proxy: "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# #all_proxy: http://user:pass@host:port
# these configuration entries will OVERWRITE or APPEND to /opt/supabase/.env file (src template: app/supabase/.env)
# check https://github.com/Vonng/pigsty/blob/main/app/supabase/.env for default values
supa_config :
# IMPORTANT: CHANGE JWT_SECRET AND REGENERATE CREDENTIAL ACCORDING!!!!!!!!!!!
# https://supabase.com/docs/guides/self-hosting/docker#securing-your-services
jwt_secret : your-super-secret-jwt-token-with-at-least-32-characters-long
anon_key : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE
service_role_key : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q
dashboard_username : supabase
dashboard_password : pigsty
# postgres connection string (use the correct ip and port)
postgres_host : 10.10.10.10
postgres_port : 5436 # access via the 'default' service, which always route to the primary postgres
postgres_db : postgres
postgres_password : DBUser.Supa # password for supabase_admin and multiple supabase users
# expose supabase via domain name
site_url : http://supa.pigsty
api_external_url : http://supa.pigsty
supabase_public_url : http://supa.pigsty
# if using s3/minio as file storage
s3_bucket : supa
s3_endpoint : https://sss.pigsty:9000
s3_access_key : supabase
s3_secret_key : S3User.Supabase
s3_force_path_style : true
s3_protocol : https
s3_region : stub
minio_domain_ip : 10.10.10.10 # sss.pigsty domain name will resolve to this ip statically
# if using SMTP (optional)
#smtp_admin_email: admin@example.com
#smtp_host: supabase-mail
#smtp_port: 2500
#smtp_user: fake_mail_user
#smtp_pass: fake_mail_password
#smtp_sender_name: fake_sender
#enable_anonymous_users: false
11.13.3 - Citus 使用 Pigsty 部署原生高可用的 Citus 水平分片集群,将 PostgreSQL 无缝伸缩到多套分片并加速 OLTP/OLAP 查询。
Pigsty 原生支持 Citus。这是一个基于原生 PostgreSQL 内核的分布式水平扩展插件。
安装 Citus 是一个 PostgreSQL 扩展插件 ,可以按照标准插件安装的流程,在原生 PostgreSQL 集群上加装启用。
./pgsql.yml -t pg_extension -e '{"pg_extensions":["citus"]}'
配置 要定义一个 citus 集群,您需要指定以下参数:
此外,还需要额外的 hba 规则,允许从本地和其他数据节点进行 SSL 访问。
您可以将每个 Citus 集群分别定义为独立的分组,像标准的 PostgreSQL 集群一样,如 conf/dbms/citus.yml 所示:
all :
children :
pg-citus0 : # citus 0号分片
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus0 , pg_group : 0 }
pg-citus1 : # citus 1号分片
hosts : { 10.10.10.11 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus1 , pg_group : 1 }
pg-citus2 : # citus 2号分片
hosts : { 10.10.10.12 : { pg_seq: 1, pg_role : primary } }
vars : { pg_cluster: pg-citus2 , pg_group : 2 }
pg-citus3 : # citus 3号分片
hosts :
10.10.10.13 : { pg_seq: 1, pg_role : primary }
10.10.10.14 : { pg_seq: 2, pg_role : replica }
vars : { pg_cluster: pg-citus3 , pg_group : 3 }
vars : # 所有 Citus 集群的全局参数
pg_mode : citus # pgsql 集群模式需要设置为: citus
pg_shard : pg-citus # citus 水平分片名称: pg-citus
patroni_citus_db : meta # citus 数据库名称:meta
pg_dbsu_password : DBUser.Postgres # 如果使用 dbsu ,那么需要为其配置一个密码
pg_users : [ { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles : [ dbrole_admin ] } ]
pg_databases : [ { name: meta ,extensions : [ { name : citus }, { name: postgis }, { name: timescaledb } ] } ]
pg_hba_rules :
- { user: 'all' ,db: all ,addr: 127.0.0.1/32 ,auth: ssl ,title : 'all user ssl access from localhost' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'all user ssl access from intranet' }
您也可以在一个分组内指定所有 Citus 集群成员的身份参数,如 prod.yml 所示:
#==========================================================#
# pg-citus: 10 node citus cluster (5 x primary-replica pair)
#==========================================================#
pg-citus : # citus group
hosts :
10.10.10.50 : { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.60/24 ,pg_seq: 0, pg_role : primary }
10.10.10.51 : { pg_group: 0, pg_cluster: pg-citus0 ,pg_vip_address: 10.10.10.60/24 ,pg_seq: 1, pg_role : replica }
10.10.10.52 : { pg_group: 1, pg_cluster: pg-citus1 ,pg_vip_address: 10.10.10.61/24 ,pg_seq: 0, pg_role : primary }
10.10.10.53 : { pg_group: 1, pg_cluster: pg-citus1 ,pg_vip_address: 10.10.10.61/24 ,pg_seq: 1, pg_role : replica }
10.10.10.54 : { pg_group: 2, pg_cluster: pg-citus2 ,pg_vip_address: 10.10.10.62/24 ,pg_seq: 0, pg_role : primary }
10.10.10.55 : { pg_group: 2, pg_cluster: pg-citus2 ,pg_vip_address: 10.10.10.62/24 ,pg_seq: 1, pg_role : replica }
10.10.10.56 : { pg_group: 3, pg_cluster: pg-citus3 ,pg_vip_address: 10.10.10.63/24 ,pg_seq: 0, pg_role : primary }
10.10.10.57 : { pg_group: 3, pg_cluster: pg-citus3 ,pg_vip_address: 10.10.10.63/24 ,pg_seq: 1, pg_role : replica }
10.10.10.58 : { pg_group: 4, pg_cluster: pg-citus4 ,pg_vip_address: 10.10.10.64/24 ,pg_seq: 0, pg_role : primary }
10.10.10.59 : { pg_group: 4, pg_cluster: pg-citus4 ,pg_vip_address: 10.10.10.64/24 ,pg_seq: 1, pg_role : replica }
vars :
pg_mode: citus # pgsql cluster mode : citus
pg_shard: pg-citus # citus shard name : pg-citus
pg_primary_db : test # primary database used by citus
pg_dbsu_password : DBUser.Postgres # all dbsu password access for citus cluster
pg_vip_enabled : true
pg_vip_interface : eth1
pg_extensions : [ 'citus postgis timescaledb pgvector' ]
pg_libs : 'citus, timescaledb, pg_stat_statements, auto_explain' # citus will be added by patroni automatically
pg_users : [ { name: test ,password: test ,pgbouncer: true ,roles : [ dbrole_admin ] } ]
pg_databases : [ { name: test ,owner: test ,extensions : [ { name : citus }, { name: postgis } ] } ]
pg_hba_rules :
- { user: 'all' ,db: all ,addr: 10.10.10.0/24 ,auth: trust ,title : 'trust citus cluster members' }
- { user: 'all' ,db: all ,addr: 127.0.0.1/32 ,auth: ssl ,title : 'all user ssl access from localhost' }
- { user: 'all' ,db: all ,addr: intra ,auth: ssl ,title : 'all user ssl access from intranet' }
使用 您可以像访问普通集群一样,访问任意节点:
pgbench -i postgres://test:test@pg-citus0/test
pgbench -nv -P1 -T1000 -c 2 postgres://test:test@pg-citus0/test
默认情况下,您对某一个 Shard 进行的变更,都只发生在这套集群上,而不会同步到其他 Shard。
如果你希望将写入分布到所有 Shard,可以使用 Citus 提供的 API 函数,将表标记为:
水平分片表 (自动分区,需要指定分区键)引用表 (全量复制:不需要指定分区键):从 Citus 11.2 开始,任何 Citus 数据库节点都可以扮演协调者的角色,即,任意一个主节点都可以写入:
psql -h pg-citus0 -d test -c "SELECT create_distributed_table('pgbench_accounts', 'aid'); SELECT truncate_local_data_after_distributing_table('public.pgbench_accounts');"
psql -h pg-citus0 -d test -c "SELECT create_reference_table('pgbench_branches') ; SELECT truncate_local_data_after_distributing_table('public.pgbench_branches');"
psql -h pg-citus0 -d test -c "SELECT create_reference_table('pgbench_history') ; SELECT truncate_local_data_after_distributing_table('public.pgbench_history');"
psql -h pg-citus0 -d test -c "SELECT create_reference_table('pgbench_tellers') ; SELECT truncate_local_data_after_distributing_table('public.pgbench_tellers');"
将表分布出去后,你可以在其他节点上也访问到:
psql -h pg-citus1 -d test -c '\dt+'
例如,全表扫描可以发现执行计划已经变为分布式计划
vagrant@meta-1:~$ psql -h pg-citus3 -d test -c 'explain select * from pgbench_accounts'
QUERY PLAN
---------------------------------------------------------------------------------------------------------
Custom Scan ( Citus Adaptive) ( cost = 0.00..0.00 rows = 100000 width = 352)
Task Count: 32
Tasks Shown: One of 32
-> Task
Node: host = 10.10.10.52 port = 5432 dbname = test
-> Seq Scan on pgbench_accounts_102008 pgbench_accounts ( cost = 0.00..81.66 rows = 3066 width = 97)
( 6 rows)
你可以从几个不同的主节点发起写入:
pgbench -nv -P1 -T1000 -c 2 postgres://test:test@pg-citus1/test
pgbench -nv -P1 -T1000 -c 2 postgres://test:test@pg-citus2/test
pgbench -nv -P1 -T1000 -c 2 postgres://test:test@pg-citus3/test
pgbench -nv -P1 -T1000 -c 2 postgres://test:test@pg-citus4/test
当某个节点出现故障时,Patroni 提供的原生高可用支持会将备用节点提升并自动顶上。
test = # select * from pg_dist_node;
nodeid | groupid | nodename | nodeport | noderack | hasmetadata | isactive | noderole | nodecluster | metadatasynced | shouldhaveshards
--------+---------+-------------+----------+----------+-------------+----------+----------+-------------+----------------+------------------
1 | 0 | 10.10.10.51 | 5432 | default | t | t | primary | default | t | f
2 | 2 | 10.10.10.54 | 5432 | default | t | t | primary | default | t | t
5 | 1 | 10.10.10.52 | 5432 | default | t | t | primary | default | t | t
3 | 4 | 10.10.10.58 | 5432 | default | t | t | primary | default | t | t
4 | 3 | 10.10.10.56 | 5432 | default | t | t | primary | default | t | t
11.13.4 - Babelfish 使用 WiltonDB 与 Babelfish 创建兼容 Microsoft SQL Server 的 PostgreSQL 数据库集群!(线缆协议级仿真)
Babelfish 是一个基于 PostgreSQL 的 MSSQL(微软 SQL Server)兼容性方案,由 AWS 开源。
概览 Pigsty 允许用户使用 Babelfish 与 WiltonDB 创建 Microsoft SQL Server 兼容的 PostgreSQL 集群!
Babelfish :一个由 AWS 开源的 MSSQL(微软 SQL Server) 兼容性扩展插件WiltonDB : 一个专注于整合 Babelfish 的 PostgreSQL 内核发行版Babelfish 是一个 PostgreSQL 扩展插件,但只能在一个轻微修改过的 PostgreSQL 内核 Fork 上工作,WiltonDB 在 EL/Ubuntu 系统下提供了编译后的Fork内核二进制与扩展二进制软件包。
Pigsty 可以使用 WiltonDB 替代原生的 PostgreSQL 内核,提供开箱即用的 MSSQL 兼容集群。MSSQL集群使用与管理与一套标准的 PostgreSQL 15 集群并无差异,您可以使用 Pigsty 提供的所有功能,如高可用,备份,监控等。
WiltonDB 带有包括 Babelfish 在内的若干扩展插件,但不能使用 PostgreSQL 原生的扩展插件。
MSSQL 兼容集群在启动后,除了监听 PostgreSQL 默认的端口外,还会监听 MSSQL 默认的 1433 端口,并在此端口上通过 TDS WireProtocol 提供 MSSQL 服务。
您可以用任何 MSSQL 客户端连接至 Pigsty 提供的 MSSQL 服务,如 SQL Server Management Studio,或者使用 sqlcmd 命令行工具。
安装 WiltonDB 与原生 PostgreSQL 内核冲突,在一个节点上只能选择一个内核进行安装,使用以下命令在线安装 WiltonDB 内核。
./node.yml -t node_install -e '{"node_repo_modules":"local,mssql","node_packages":["wiltondb"]}'
请注意 WiltonDB 仅在 EL 与 Ubuntu 系统中可用,目前尚未提供 Debian 支持。
Pigsty 专业版提供了 WiltonDB 离线安装包,可以从本地软件源安装 WiltonDB。
配置 在安装部署 MSSQL 模块时需要特别注意以下事项:
WiltonDB 在 EL (7/8/9) 和 Ubuntu (20.04/22.04) 中可用,在Debian系统中不可用 。 WiltonDB 目前基于 PostgreSQL 15 编译,因此需要指定 pg_version: 15 。 在 EL 系统上,wiltondb 的二进制默认会安装至 /usr/bin/ 目录下,而在 Ubuntu 系统上则会安装至 /usr/lib/postgresql/15/bin/ 目录下,与 PostgreSQL 官方二进制文件放置位置不同。 WiltonDB 兼容模式下,HBA 密码认证规则需要使用 md5,而非 scram-sha-256,因此需要覆盖 Pigsty 默认的 HBA 规则集,将 SQL Server 需要的 md5 认证规则,插入到 dbrole_readonly 通配认证规则之前 WiltonDB 只能针对一个首要数据库启用,同时应当指定一个用户作为 Babelfish 的超级用户,以便 Babelfish 可以创建数据库和用户,默认为 mssql 与 dbuser_myssql,如果修改,请一并修改 files/mssql.sql 中的用户。 WiltonDB TDS 线缆协议兼容插件 babelfishpg_tds 需要在 shared_preload_libraries 中启用 WiltonDB 扩展在启用后,默认监听 MSSQL 1433 端口,您可以覆盖 Pigsty 默认的服务定义,将 primary 与 replica 服务的端口指向 1433 ,而不是 5432 / 6432 端口。 以下参数需要针对 MSSQL 数据库集群进行配置:
#----------------------------------#
# PGSQL & MSSQL (Babelfish & Wilton)
#----------------------------------#
# PG Installation
node_repo_modules : local,node,mssql # add mssql and os upstream repos
pg_mode : mssql # Microsoft SQL Server Compatible Mode
pg_libs : 'babelfishpg_tds, pg_stat_statements, auto_explain' # add timescaledb to shared_preload_libraries
pg_version : 15 # The current WiltonDB major version is 15
pg_packages :
- wiltondb # install forked version of postgresql with babelfishpg support
- patroni pgbouncer pgbackrest pg_exporter pgbadger vip-manager
pg_extensions : [] # do not install any vanilla postgresql extensions
# PG Provision
pg_default_hba_rules : # overwrite default HBA rules for babelfish cluster
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title : 'replicator replication from localhost' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title : 'replicator replication from intranet' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title : 'replicator postgres db from intranet' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title : 'monitor from infra host with password' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title : 'admin @ everywhere with ssl & pwd' }
- {user: dbuser_mssql ,db: mssql ,addr: intra ,auth: md5 ,title : 'allow mssql dbsu intranet access' } # <--- use md5 auth method for mssql user
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title : 'pgbouncer read/write via local socket' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title : 'read/write biz user via password' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title : 'allow etl offline tasks from intranet' }
pg_default_services : # route primary & replica service to mssql port 1433
- { name: primary ,port: 5433 ,dest: 1433 ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: 1433 ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
您可以定义 MSSQL 业务数据库与业务用户:
#----------------------------------#
# pgsql (singleton on current node)
#----------------------------------#
# this is an example single-node postgres cluster with postgis & timescaledb installed, with one biz database & two biz users
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary } # <---- primary instance with read-write capability
vars :
pg_cluster : pg-test
pg_users : # create MSSQL superuser
- {name: dbuser_mssql ,password: DBUser.MSSQL ,superuser: true, pgbouncer: true ,roles: [dbrole_admin], comment : superuser & owner for babelfish }
pg_primary_db : mssql # use `mssql` as the primary sql server database
pg_databases :
- name : mssql
baseline : mssql.sql # init babelfish database & user
extensions :
- { name : uuid-ossp }
- { name : babelfishpg_common }
- { name : babelfishpg_tsql }
- { name : babelfishpg_tds }
- { name : babelfishpg_money }
- { name : pg_hint_plan }
- { name : system_stats }
- { name : tds_fdw }
owner : dbuser_mssql
parameters : { 'babelfishpg_tsql.migration_mode' : 'multi-db' }
comment : babelfish cluster, a MSSQL compatible pg cluster
访问 您可以使用任何 SQL Server 兼容的客户端工具来访问这个数据库集群。
Microsoft 提供了 sqlcmd 作为官方的命令行工具。
除此之外,他们还提供了一个 Go 语言版本的命令行工具 go-sqlcmd 。
安装 go-sqlcmd:
curl -LO https://github.com/microsoft/go-sqlcmd/releases/download/v1.4.0/sqlcmd-v1.4.0-linux-amd64.tar.bz2
tar xjvf sqlcmd-v1.4.0-linux-amd64.tar.bz2
sudo mv sqlcmd* /usr/bin/
快速上手 go-sqlcmd
$ sqlcmd -S 10.10.10.10,1433 -U dbuser_mssql -P DBUser.MSSQL
1> select @@version
2> go
version
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Babelfish for PostgreSQL with SQL Server Compatibility - 12.0.2000.8
Oct 22 2023 17:48:32
Copyright ( c) Amazon Web Services
PostgreSQL 15.4 ( EL 1:15.4.wiltondb3.3_2-2.el8) on x86_64-redhat-linux-gnu ( Babelfish 3.3.0)
( 1 row affected)
使用 Pigsty 提供的服务机制,可以使用 5433 / 5434 端口始终连接到主库/从库上的 1433 端口。
# 访问任意集群成员上的 5433 端口,指向主库上的 1433 MSSQL 端口
sqlcmd -S 10.10.10.11,5433 -U dbuser_mssql -P DBUser.MSSQL
# 访问任意集群成员上的 5434 端口,指向任意可读库上的 1433 MSSQL 端口
sqlcmd -S 10.10.10.11,5434 -U dbuser_mssql -P DBUser.MSSQL
扩展 绝大多数 PGSQL 模块的 扩展插件 (非纯 SQL 类)都无法直接在 MSSQL 模块的 WiltonDB 内核上使用,需要重新编译。
目前 WiltonDB 自带了以下扩展插件,除了 PostgreSQL Contrib 扩展,四个 BabelfishPG 核心扩展之外,还提供了 pg_hint_pan,tds_fdw,以及 system_stats 三个第三方扩展。
扩展名 版本 说明 dblink 1.2 connect to other PostgreSQL databases from within a database adminpack 2.1 administrative functions for PostgreSQL dict_int 1.0 text search dictionary template for integers intagg 1.1 integer aggregator and enumerator (obsolete) dict_xsyn 1.0 text search dictionary template for extended synonym processing amcheck 1.3 functions for verifying relation integrity autoinc 1.0 functions for autoincrementing fields bloom 1.0 bloom access method - signature file based index fuzzystrmatch 1.1 determine similarities and distance between strings intarray 1.5 functions, operators, and index support for 1-D arrays of integers btree_gin 1.3 support for indexing common datatypes in GIN btree_gist 1.7 support for indexing common datatypes in GiST hstore 1.8 data type for storing sets of (key, value) pairs hstore_plperl 1.0 transform between hstore and plperl isn 1.2 data types for international product numbering standards hstore_plperlu 1.0 transform between hstore and plperlu jsonb_plperl 1.0 transform between jsonb and plperl citext 1.6 data type for case-insensitive character strings jsonb_plperlu 1.0 transform between jsonb and plperlu jsonb_plpython3u 1.0 transform between jsonb and plpython3u cube 1.5 data type for multidimensional cubes hstore_plpython3u 1.0 transform between hstore and plpython3u earthdistance 1.1 calculate great-circle distances on the surface of the Earth lo 1.1 Large Object maintenance file_fdw 1.0 foreign-data wrapper for flat file access insert_username 1.0 functions for tracking who changed a table ltree 1.2 data type for hierarchical tree-like structures ltree_plpython3u 1.0 transform between ltree and plpython3u pg_walinspect 1.0 functions to inspect contents of PostgreSQL Write-Ahead Log moddatetime 1.0 functions for tracking last modification time old_snapshot 1.0 utilities in support of old_snapshot_threshold pgcrypto 1.3 cryptographic functions pgrowlocks 1.2 show row-level locking information pageinspect 1.11 inspect the contents of database pages at a low level pg_surgery 1.0 extension to perform surgery on a damaged relation seg 1.4 data type for representing line segments or floating-point intervals pgstattuple 1.5 show tuple-level statistics pg_buffercache 1.3 examine the shared buffer cache pg_freespacemap 1.2 examine the free space map (FSM) postgres_fdw 1.1 foreign-data wrapper for remote PostgreSQL servers pg_prewarm 1.2 prewarm relation data tcn 1.0 Triggered change notifications pg_trgm 1.6 text similarity measurement and index searching based on trigrams xml2 1.1 XPath querying and XSLT refint 1.0 functions for implementing referential integrity (obsolete) pg_visibility 1.2 examine the visibility map (VM) and page-level visibility info pg_stat_statements 1.10 track planning and execution statistics of all SQL statements executed sslinfo 1.2 information about SSL certificates tablefunc 1.0 functions that manipulate whole tables, including crosstab tsm_system_rows 1.0 TABLESAMPLE method which accepts number of rows as a limit tsm_system_time 1.0 TABLESAMPLE method which accepts time in milliseconds as a limit unaccent 1.1 text search dictionary that removes accents uuid-ossp 1.1 generate universally unique identifiers (UUIDs) plpgsql 1.0 PL/pgSQL procedural language babelfishpg_money 1.1.0 babelfishpg_money system_stats 2.0 EnterpriseDB system statistics for PostgreSQL tds_fdw 2.0.3 Foreign data wrapper for querying a TDS database (Sybase or Microsoft SQL Server) babelfishpg_common 3.3.3 Transact SQL Datatype Support babelfishpg_tds 1.0.0 TDS protocol extension pg_hint_plan 1.5.1 babelfishpg_tsql 3.3.1 Transact SQL compatibility
Pigsty 专业版提供离线安装 MSSQL 兼容模块的能力 Pigsty 专业版 提供可选的 MSSQL 兼容内核扩展移植定制服务,可以将 PGSQL 模块中可用的 扩展 移植到 MSSQL 集群中。 11.13.5 - IvorySQL 使用瀚高开源的 IvorySQL 内核,基于 PostgreSQL 集群实现 Oracle 语法/PLSQL 兼容性。
IvorySQL 是一个开源的,旨在基于 PG 提供 “Oracle兼容性” 的 PostgreSQL 内核分支。
概览 IvorySQL 内核支持在 Pigsty 开源版本中提供,您的服务器需要互联网访问,直接从 IvorySQL 的官方仓库下载相关软件包。
请注意,直接将 IvorySQL 加入 Pigsty 默认软件仓库中会影响原生 PostgreSQL 内核的安装。Pigsty 专业版提供包括 IvorySQL 内核在内的离线安装解决方案。
当前 IvorySQL 的最新版本为 3.4 ,对应的 PostgreSQL 版本为 16.4 。请注意,IvorySQL 当前仅在 EL8/EL9 上可用。
最后一个支持 EL7 的 IvorySQL 版本为 3.3,对应 PostgreSQL 16.3
安装 如果您的环境有互联网访问,您可以使用以下方式,直接将 IvorySQL 仓库加入到节点上,然后执行 PGSQL 剧本进行安装
./node.yml -t node_repo -e '{"node_repo_modules":"local,node,pgsql,ivory"}'
配置 以下参数需要针对 IvorySQL 数据库集群进行配置:
#----------------------------------#
# Ivory SQL Configuration
#----------------------------------#
node_repo_modules : local,node,pgsql,ivory # add ivorysql upstream repo
pg_mode : ivory # IvorySQL Oracle Compatible Mode
pg_packages : [ 'ivorysql patroni pgbouncer pgbackrest pg_exporter pgbadger vip-manager' ]
pg_libs : 'liboracle_parser, pg_stat_statements, auto_explain'
pg_extensions : [ ] # do not install any vanilla postgresql extensions
使用 Oracle 兼容性模式时,需要动态加载 liboracle_parser 扩展插件。
客户端访问 IvorySQL 等效于 PostgreSQL 16,任何兼容 PostgreSQL 线缆协议的客户端工具都可以访问 IvorySQL 集群。
扩展列表 绝大多数 PGSQL 模块的 扩展插件 (非纯 SQL 类)都无法直接在 IvorySQL 内核上使用,如果需要使用,请针对新内核从源码重新编译安装。
目前 IvorySQL 内核自带了以下 101 个扩展插件。
name version comment hstore_plperl 1.0 transform between hstore and plperl plisql 1.0 PL/iSQL procedural language hstore_plperlu 1.0 transform between hstore and plperlu adminpack 2.1 administrative functions for PostgreSQL insert_username 1.0 functions for tracking who changed a table dblink 1.2 connect to other PostgreSQL databases from within a database dict_int 1.0 text search dictionary template for integers amcheck 1.3 functions for verifying relation integrity intagg 1.1 integer aggregator and enumerator (obsolete) autoinc 1.0 functions for autoincrementing fields bloom 1.0 bloom access method - signature file based index dict_xsyn 1.0 text search dictionary template for extended synonym processing btree_gin 1.3 support for indexing common datatypes in GIN earthdistance 1.1 calculate great-circle distances on the surface of the Earth file_fdw 1.0 foreign-data wrapper for flat file access fuzzystrmatch 1.2 determine similarities and distance between strings btree_gist 1.7 support for indexing common datatypes in GiST intarray 1.5 functions, operators, and index support for 1-D arrays of integers citext 1.6 data type for case-insensitive character strings isn 1.2 data types for international product numbering standards ivorysql_ora 1.0 Oracle Compatible extenison on Postgres Database jsonb_plperl 1.0 transform between jsonb and plperl cube 1.5 data type for multidimensional cubes dummy_index_am 1.0 dummy_index_am - index access method template dummy_seclabel 1.0 Test code for SECURITY LABEL feature hstore 1.8 data type for storing sets of (key, value) pairs jsonb_plperlu 1.0 transform between jsonb and plperlu lo 1.1 Large Object maintenance ltree 1.2 data type for hierarchical tree-like structures moddatetime 1.0 functions for tracking last modification time old_snapshot 1.0 utilities in support of old_snapshot_threshold ora_btree_gin 1.0 support for indexing oracle datatypes in GIN pg_trgm 1.6 text similarity measurement and index searching based on trigrams ora_btree_gist 1.0 support for oracle indexing common datatypes in GiST pg_visibility 1.2 examine the visibility map (VM) and page-level visibility info pg_walinspect 1.1 functions to inspect contents of PostgreSQL Write-Ahead Log pgcrypto 1.3 cryptographic functions pgstattuple 1.5 show tuple-level statistics pageinspect 1.12 inspect the contents of database pages at a low level pgrowlocks 1.2 show row-level locking information pg_buffercache 1.4 examine the shared buffer cache pg_stat_statements 1.10 track planning and execution statistics of all SQL statements executed pg_freespacemap 1.2 examine the free space map (FSM) plsample 1.0 PL/Sample pg_prewarm 1.2 prewarm relation data pg_surgery 1.0 extension to perform surgery on a damaged relation seg 1.4 data type for representing line segments or floating-point intervals postgres_fdw 1.1 foreign-data wrapper for remote PostgreSQL servers refint 1.0 functions for implementing referential integrity (obsolete) test_ext_req_schema1 1.0 Required extension to be referenced spgist_name_ops 1.0 Test opclass for SP-GiST test_ext_req_schema2 1.0 Test schema referencing of required extensions test_shm_mq 1.0 Test code for shared memory message queues sslinfo 1.2 information about SSL certificates test_slru 1.0 Test code for SLRU tablefunc 1.0 functions that manipulate whole tables, including crosstab bool_plperl 1.0 transform between bool and plperl tcn 1.0 Triggered change notifications test_ext_req_schema3 1.0 Test schema referencing of 2 required extensions test_bloomfilter 1.0 Test code for Bloom filter library test_copy_callbacks 1.0 Test code for COPY callbacks test_ginpostinglist 1.0 Test code for ginpostinglist.c test_custom_rmgrs 1.0 Test code for custom WAL resource managers test_integerset 1.0 Test code for integerset test_ddl_deparse 1.0 Test code for DDL deparse feature tsm_system_rows 1.0 TABLESAMPLE method which accepts number of rows as a limit test_ext1 1.0 Test extension 1 tsm_system_time 1.0 TABLESAMPLE method which accepts time in milliseconds as a limit test_ext2 1.0 Test extension 2 unaccent 1.1 text search dictionary that removes accents test_ext3 1.0 Test extension 3 test_ext4 1.0 Test extension 4 uuid-ossp 1.1 generate universally unique identifiers (UUIDs) test_ext5 1.0 Test extension 5 worker_spi 1.0 Sample background worker test_ext6 1.0 test_ext6 test_lfind 1.0 Test code for optimized linear search functions xml2 1.1 XPath querying and XSLT test_ext7 1.0 Test extension 7 plpgsql 1.0 PL/pgSQL procedural language test_ext8 1.0 Test extension 8 test_parser 1.0 example of a custom parser for full-text search test_pg_dump 1.0 Test pg_dump with an extension test_ext_cine 1.0 Test extension using CREATE IF NOT EXISTS test_predtest 1.0 Test code for optimizer/util/predtest.c test_ext_cor 1.0 Test extension using CREATE OR REPLACE test_rbtree 1.0 Test code for red-black tree library test_ext_cyclic1 1.0 Test extension cyclic 1 test_ext_cyclic2 1.0 Test extension cyclic 2 test_ext_extschema 1.0 test @extschema@ test_regex 1.0 Test code for backend/regex/ test_ext_evttrig 1.0 Test extension - event trigger bool_plperlu 1.0 transform between bool and plperlu plperl 1.0 PL/Perl procedural language plperlu 1.0 PL/PerlU untrusted procedural language hstore_plpython3u 1.0 transform between hstore and plpython3u jsonb_plpython3u 1.0 transform between jsonb and plpython3u ltree_plpython3u 1.0 transform between ltree and plpython3u plpython3u 1.0 PL/Python3U untrusted procedural language pltcl 1.0 PL/Tcl procedural language pltclu 1.0 PL/TclU untrusted procedural language
请注意,Pigsty 不对使用 IvorySQL 内核承担任何质保责任,使用此内核遇到的任何问题与需求请联系原厂解决。
11.13.6 - PolarDB PG 使用阿里云开源的 PolarDB for PostgreSQL 内核提供国产信创资质支持,与类似 Oracle RAC 的使用体验。
概览 Pigsty 允许使用 PolarDB 创建带有 “国产化信创资质” 的 PostgreSQL 集群!
PolarDB for PostgreSQL 基本等效于 PostgreSQL 15,任何兼容 PostgreSQL 线缆协议的客户端工具都可以访问 PolarDB 集群。
Pigsty 的 PGSQL 仓库中提供了 EL7 / EL8 的 PolarDB PG 开源版安装包,但不会在 Pigsty 安装时下载到本地软件仓库。
如果您需要 PolarDB PG 的离线安装支持,请考虑我们的 专业订阅服务
安装 如果您的环境有互联网访问,您可以使用以下方式,直接将 Pigsty PGSQL 及依赖仓库加入到节点上,
node_repo_modules : local,node,pgsql
然后在 pg_packages 中,使用 polardb 替换原生的 postgresql 软件包。
配置 以下参数需要针对 PolarDB 数据库集群进行特殊配置:
#----------------------------------#
# PGSQL & PolarDB
#----------------------------------#
pg_version : 15
pg_packages : [ 'polardb patroni pgbouncer pgbackrest pg_exporter pgbadger vip-manager' ]
pg_extensions : [ ] # do not install any vanilla postgresql extensions
pg_mode : polar # PolarDB Compatible Mode
pg_default_roles : # default roles and users in postgres cluster
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,superuser: true ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator } # <- superuser is required for replication
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
这里特别注意,PolarDB PG 要求 replicator 复制用户为 Superuser,与原生 PG 不同。
扩展列表 绝大多数 PGSQL 模块的 扩展插件 (非纯 SQL 类)都无法直接在 PolarDB 内核上使用,如果需要使用,请针对新内核从源码重新编译安装。
目前 PolarDB 内核自带了以下 61 个扩展插件,除去 Contrib 扩展外,提供的额外扩展包括:
polar_csn 1.0 : polar_csnpolar_monitor 1.2 : examine the polardb informationpolar_monitor_preload 1.1 : examine the polardb informationpolar_parameter_check 1.0 : kernel extension for parameter validationpolar_px 1.0 : Parallel Execution extensionpolar_stat_env 1.0 : env stat functions for PolarDBpolar_stat_sql 1.3 : Kernel statistics gathering, and sql plan nodes information gatheringpolar_tde_utils 1.0 : Internal extension for TDEpolar_vfs 1.0 : polar_vfspolar_worker 1.0 : polar_workertimetravel 1.0 : functions for implementing time travelvector 0.5.1 : vector data type and ivfflat and hnsw access methodssmlar 1.0 : compute similary of any one-dimensional arraysPolarDB 可用的完整插件列表:
name version comment hstore_plpython2u 1.0 transform between hstore and plpython2u dict_int 1.0 text search dictionary template for integers adminpack 2.0 administrative functions for PostgreSQL hstore_plpython3u 1.0 transform between hstore and plpython3u amcheck 1.1 functions for verifying relation integrity hstore_plpythonu 1.0 transform between hstore and plpythonu autoinc 1.0 functions for autoincrementing fields insert_username 1.0 functions for tracking who changed a table bloom 1.0 bloom access method - signature file based index file_fdw 1.0 foreign-data wrapper for flat file access dblink 1.2 connect to other PostgreSQL databases from within a database btree_gin 1.3 support for indexing common datatypes in GIN fuzzystrmatch 1.1 determine similarities and distance between strings lo 1.1 Large Object maintenance intagg 1.1 integer aggregator and enumerator (obsolete) btree_gist 1.5 support for indexing common datatypes in GiST hstore 1.5 data type for storing sets of (key, value) pairs intarray 1.2 functions, operators, and index support for 1-D arrays of integers citext 1.5 data type for case-insensitive character strings cube 1.4 data type for multidimensional cubes hstore_plperl 1.0 transform between hstore and plperl isn 1.2 data types for international product numbering standards jsonb_plperl 1.0 transform between jsonb and plperl dict_xsyn 1.0 text search dictionary template for extended synonym processing hstore_plperlu 1.0 transform between hstore and plperlu earthdistance 1.1 calculate great-circle distances on the surface of the Earth pg_prewarm 1.2 prewarm relation data jsonb_plperlu 1.0 transform between jsonb and plperlu pg_stat_statements 1.6 track execution statistics of all SQL statements executed jsonb_plpython2u 1.0 transform between jsonb and plpython2u jsonb_plpython3u 1.0 transform between jsonb and plpython3u jsonb_plpythonu 1.0 transform between jsonb and plpythonu pg_trgm 1.4 text similarity measurement and index searching based on trigrams pgstattuple 1.5 show tuple-level statistics ltree 1.1 data type for hierarchical tree-like structures ltree_plpython2u 1.0 transform between ltree and plpython2u pg_visibility 1.2 examine the visibility map (VM) and page-level visibility info ltree_plpython3u 1.0 transform between ltree and plpython3u ltree_plpythonu 1.0 transform between ltree and plpythonu seg 1.3 data type for representing line segments or floating-point intervals moddatetime 1.0 functions for tracking last modification time pgcrypto 1.3 cryptographic functions pgrowlocks 1.2 show row-level locking information pageinspect 1.7 inspect the contents of database pages at a low level pg_buffercache 1.3 examine the shared buffer cache pg_freespacemap 1.2 examine the free space map (FSM) tcn 1.0 Triggered change notifications plperl 1.0 PL/Perl procedural language uuid-ossp 1.1 generate universally unique identifiers (UUIDs) plperlu 1.0 PL/PerlU untrusted procedural language refint 1.0 functions for implementing referential integrity (obsolete) xml2 1.1 XPath querying and XSLT plpgsql 1.0 PL/pgSQL procedural language plpython3u 1.0 PL/Python3U untrusted procedural language pltcl 1.0 PL/Tcl procedural language pltclu 1.0 PL/TclU untrusted procedural language polar_csn 1.0 polar_csn sslinfo 1.2 information about SSL certificates polar_monitor 1.2 examine the polardb information polar_monitor_preload 1.1 examine the polardb information polar_parameter_check 1.0 kernel extension for parameter validation polar_px 1.0 Parallel Execution extension tablefunc 1.0 functions that manipulate whole tables, including crosstab polar_stat_env 1.0 env stat functions for PolarDB smlar 1.0 compute similary of any one-dimensional arrays timetravel 1.0 functions for implementing time travel tsm_system_rows 1.0 TABLESAMPLE method which accepts number of rows as a limit polar_stat_sql 1.3 Kernel statistics gathering, and sql plan nodes information gathering tsm_system_time 1.0 TABLESAMPLE method which accepts time in milliseconds as a limit polar_tde_utils 1.0 Internal extension for TDE polar_vfs 1.0 polar_vfs polar_worker 1.0 polar_worker unaccent 1.1 text search dictionary that removes accents postgres_fdw 1.0 foreign-data wrapper for remote PostgreSQL servers
Pigsty 专业版提供 PolarDB 离线安装支持,扩展插件编译支持,以及针对 PolarDB 集群进行专门适配的监控与管控支持。 Pigsty 与阿里云内核团队有合作,可以提供有偿内核兜底支持服务。 11.13.7 - PolarDB Oracle 使用阿里云商业版本的 PolarDB for Oracle 内核(闭源,PG14,仅在特殊企业版定制中可用)
Pigsty 允许使用 PolarDB 创建带有 “国产化信创资质” 的 PolarDB for Oracle 集群!
根据 【安全可靠测评结果公告(2023年第1号) 】,附表三、集中式数据库。PolarDB v2.0 属于自主可控,安全可靠的国产信创数据库。
PolarDB for Oracle 是基于 PolarDB for PostgreSQL 进行二次开发的 Oracle 兼容版本,两者共用同一套内核,通过 --compatibility-mode 参数进行区分。
我们与阿里云内核团队合作,提供基于 PolarDB v2.0 内核与 Pigsty v3.0 RDS 的完整数据库解决方案,请联系销售咨询,或在阿里云市场自行采购。
PolarDB for Oracle 内核目前仅在 EL 系统中可用。
扩展 目前 PolarDB 2.0 (Oracle兼容) 内核自带了以下 188 个扩展插件:
name default_version comment cube 1.5 data type for multidimensional cubes ip4r 2.4 NULL adminpack 2.1 administrative functions for PostgreSQL dict_xsyn 1.0 text search dictionary template for extended synonym processing amcheck 1.4 functions for verifying relation integrity autoinc 1.0 functions for autoincrementing fields hstore 1.8 data type for storing sets of (key, value) pairs bloom 1.0 bloom access method - signature file based index earthdistance 1.1 calculate great-circle distances on the surface of the Earth hstore_plperl 1.0 transform between hstore and plperl bool_plperl 1.0 transform between bool and plperl file_fdw 1.0 foreign-data wrapper for flat file access bool_plperlu 1.0 transform between bool and plperlu fuzzystrmatch 1.1 determine similarities and distance between strings hstore_plperlu 1.0 transform between hstore and plperlu btree_gin 1.3 support for indexing common datatypes in GIN hstore_plpython2u 1.0 transform between hstore and plpython2u btree_gist 1.6 support for indexing common datatypes in GiST hll 2.17 type for storing hyperloglog data hstore_plpython3u 1.0 transform between hstore and plpython3u citext 1.6 data type for case-insensitive character strings hstore_plpythonu 1.0 transform between hstore and plpythonu hypopg 1.3.1 Hypothetical indexes for PostgreSQL insert_username 1.0 functions for tracking who changed a table dblink 1.2 connect to other PostgreSQL databases from within a database decoderbufs 0.1.0 Logical decoding plugin that delivers WAL stream changes using a Protocol Buffer format intagg 1.1 integer aggregator and enumerator (obsolete) dict_int 1.0 text search dictionary template for integers intarray 1.5 functions, operators, and index support for 1-D arrays of integers isn 1.2 data types for international product numbering standards jsonb_plperl 1.0 transform between jsonb and plperl jsonb_plperlu 1.0 transform between jsonb and plperlu jsonb_plpython2u 1.0 transform between jsonb and plpython2u jsonb_plpython3u 1.0 transform between jsonb and plpython3u jsonb_plpythonu 1.0 transform between jsonb and plpythonu lo 1.1 Large Object maintenance log_fdw 1.0 foreign-data wrapper for csvlog ltree 1.2 data type for hierarchical tree-like structures ltree_plpython2u 1.0 transform between ltree and plpython2u ltree_plpython3u 1.0 transform between ltree and plpython3u ltree_plpythonu 1.0 transform between ltree and plpythonu moddatetime 1.0 functions for tracking last modification time old_snapshot 1.0 utilities in support of old_snapshot_threshold oracle_fdw 1.2 foreign data wrapper for Oracle access oss_fdw 1.1 foreign-data wrapper for OSS access pageinspect 2.1 inspect the contents of database pages at a low level pase 0.0.1 ant ai similarity search pg_bigm 1.2 text similarity measurement and index searching based on bigrams pg_freespacemap 1.2 examine the free space map (FSM) pg_hint_plan 1.4 controls execution plan with hinting phrases in comment of special form pg_buffercache 1.5 examine the shared buffer cache pg_prewarm 1.2 prewarm relation data pg_repack 1.4.8-1 Reorganize tables in PostgreSQL databases with minimal locks pg_sphere 1.0 spherical objects with useful functions, operators and index support pg_cron 1.5 Job scheduler for PostgreSQL pg_jieba 1.1.0 a parser for full-text search of Chinese pg_stat_kcache 2.2.1 Kernel statistics gathering pg_stat_statements 1.9 track planning and execution statistics of all SQL statements executed pg_surgery 1.0 extension to perform surgery on a damaged relation pg_trgm 1.6 text similarity measurement and index searching based on trigrams pg_visibility 1.2 examine the visibility map (VM) and page-level visibility info pg_wait_sampling 1.1 sampling based statistics of wait events pgaudit 1.6.2 provides auditing functionality pgcrypto 1.3 cryptographic functions pgrowlocks 1.2 show row-level locking information pgstattuple 1.5 show tuple-level statistics pgtap 1.2.0 Unit testing for PostgreSQL pldbgapi 1.1 server-side support for debugging PL/pgSQL functions plperl 1.0 PL/Perl procedural language plperlu 1.0 PL/PerlU untrusted procedural language plpgsql 1.0 PL/pgSQL procedural language plpython2u 1.0 PL/Python2U untrusted procedural language plpythonu 1.0 PL/PythonU untrusted procedural language plsql 1.0 Oracle compatible PL/SQL procedural language pltcl 1.0 PL/Tcl procedural language pltclu 1.0 PL/TclU untrusted procedural language polar_bfile 1.0 The BFILE data type enables access to binary file LOBs that are stored in file systems outside Database polar_bpe 1.0 polar_bpe polar_builtin_cast 1.1 Internal extension for builtin casts polar_builtin_funcs 2.0 implement polar builtin functions polar_builtin_type 1.5 polar_builtin_type for PolarDB polar_builtin_view 1.5 polar_builtin_view polar_catalog 1.2 polardb pg extend catalog polar_channel 1.0 polar_channel polar_constraint 1.0 polar_constraint polar_csn 1.0 polar_csn polar_dba_views 1.0 polar_dba_views polar_dbms_alert 1.2 implement polar_dbms_alert - supports asynchronous notification of database events. polar_dbms_application_info 1.0 implement polar_dbms_application_info - record names of executing modules or transactions in the database. polar_dbms_pipe 1.1 implements polar_dbms_pipe - package lets two or more sessions in the same instance communicate. polar_dbms_aq 1.2 implement dbms_aq - provides an interface to Advanced Queuing. polar_dbms_lob 1.3 implement dbms_lob - provides subprograms to operate on BLOBs, CLOBs, and NCLOBs. polar_dbms_output 1.2 implement polar_dbms_output - enables you to send messages from stored procedures. polar_dbms_lock 1.0 implement polar_dbms_lock - provides an interface to Oracle Lock Management services. polar_dbms_aqadm 1.3 polar_dbms_aqadm - procedures to manage Advanced Queuing configuration and administration information. polar_dbms_assert 1.0 implement polar_dbms_assert - provide an interface to validate properties of the input value. polar_dbms_metadata 1.0 implement polar_dbms_metadata - provides a way for you to retrieve metadata from the database dictionary. polar_dbms_random 1.0 implement polar_dbms_random - a built-in random number generator, not intended for cryptography polar_dbms_crypto 1.1 implement dbms_crypto - provides an interface to encrypt and decrypt stored data. polar_dbms_redact 1.0 implement polar_dbms_redact - provides an interface to mask data from queries by an application. polar_dbms_debug 1.1 server-side support for debugging PL/SQL functions polar_dbms_job 1.0 polar_dbms_job polar_dbms_mview 1.1 implement polar_dbms_mview - enables to refresh materialized views. polar_dbms_job_preload 1.0 polar_dbms_job_preload polar_dbms_obfuscation_toolkit 1.1 implement polar_dbms_obfuscation_toolkit - enables an application to get data md5. polar_dbms_rls 1.1 implement polar_dbms_rls - a fine-grained access control administrative built-in package polar_multi_toast_utils 1.0 polar_multi_toast_utils polar_dbms_session 1.2 implement polar_dbms_session - support to set preferences and security levels. polar_odciconst 1.0 implement ODCIConst - Provide some built-in constants in Oracle. polar_dbms_sql 1.2 implement polar_dbms_sql - provides an interface to execute dynamic SQL. polar_osfs_toolkit 1.0 osfs library tools and functions extension polar_dbms_stats 14.0 stabilize plans by fixing statistics polar_monitor 1.5 monitor functions for PolarDB polar_osfs_utils 1.0 osfs library utils extension polar_dbms_utility 1.3 implement polar_dbms_utility - provides various utility subprograms. polar_parameter_check 1.0 kernel extension for parameter validation polar_dbms_xmldom 1.0 implement dbms_xmldom and dbms_xmlparser - support standard DOM interface and xml parser object polar_parameter_manager 1.1 Extension to select parameters for manger. polar_faults 1.0.0 simulate some database faults for end user or testing system. polar_monitor_preload 1.1 examine the polardb information polar_proxy_utils 1.0 Extension to provide operations about proxy. polar_feature_utils 1.2 PolarDB feature utilization polar_global_awr 1.0 PolarDB Global AWR Report polar_publication 1.0 support polardb pg logical replication polar_global_cache 1.0 polar_global_cache polar_px 1.0 Parallel Execution extension polar_serverless 1.0 polar serverless extension polar_resource_manager 1.0 a background process that forcibly frees user session process memory polar_sys_context 1.1 implement polar_sys_context - returns the value of parameter associated with the context namespace at the current instant. polar_gpc 1.3 polar_gpc polar_tde_utils 1.0 Internal extension for TDE polar_gtt 1.1 polar_gtt polar_utl_encode 1.2 implement polar_utl_encode - provides functions that encode RAW data into a standard encoded format polar_htap 1.1 extension for PolarDB HTAP polar_htap_db 1.0 extension for PolarDB HTAP database level operation polar_io_stat 1.0 polar io stat in multi dimension polar_utl_file 1.0 implement utl_file - support PL/SQL programs can read and write operating system text files polar_ivm 1.0 polar_ivm polar_sql_mapping 1.2 Record error sqls and mapping them to correct one polar_stat_sql 1.0 Kernel statistics gathering, and sql plan nodes information gathering tds_fdw 2.0.2 Foreign data wrapper for querying a TDS database (Sybase or Microsoft SQL Server) xml2 1.1 XPath querying and XSLT polar_upgrade_catalogs 1.1 Upgrade catalogs for old version instance polar_utl_i18n 1.1 polar_utl_i18n polar_utl_raw 1.0 implement utl_raw - provides SQL functions for manipulating RAW datatypes. timescaledb 2.9.2 Enables scalable inserts and complex queries for time-series data polar_vfs 1.0 polar virtual file system for different storage polar_worker 1.0 polar_worker postgres_fdw 1.1 foreign-data wrapper for remote PostgreSQL servers refint 1.0 functions for implementing referential integrity (obsolete) roaringbitmap 0.5 support for Roaring Bitmaps tsm_system_time 1.0 TABLESAMPLE method which accepts time in milliseconds as a limit vector 0.5.0 vector data type and ivfflat and hnsw access methods rum 1.3 RUM index access method unaccent 1.1 text search dictionary that removes accents seg 1.4 data type for representing line segments or floating-point intervals sequential_uuids 1.0.2 generator of sequential UUIDs uuid-ossp 1.1 generate universally unique identifiers (UUIDs) smlar 1.0 compute similary of any one-dimensional arrays varbitx 1.1 varbit functions pack sslinfo 1.2 information about SSL certificates tablefunc 1.0 functions that manipulate whole tables, including crosstab tcn 1.0 Triggered change notifications zhparser 1.0 a parser for full-text search of Chinese address_standardizer 3.3.2 Ganos PostGIS address standardizer address_standardizer_data_us 3.3.2 Ganos PostGIS address standardizer data us ganos_fdw 6.0 Ganos Spatial FDW extension for POLARDB ganos_geometry 6.0 Ganos geometry lite extension for POLARDB ganos_geometry_pyramid 6.0 Ganos Geometry Pyramid extension for POLARDB ganos_geometry_sfcgal 6.0 Ganos geometry lite sfcgal extension for POLARDB ganos_geomgrid 6.0 Ganos geometry grid extension for POLARDB ganos_importer 6.0 Ganos Spatial importer extension for POLARDB ganos_networking 6.0 Ganos networking ganos_pointcloud 6.0 Ganos pointcloud extension For POLARDB ganos_pointcloud_geometry 6.0 Ganos_pointcloud LIDAR data and ganos_geometry data for POLARDB ganos_raster 6.0 Ganos raster extension for POLARDB ganos_scene 6.0 Ganos scene extension for POLARDB ganos_sfmesh 6.0 Ganos surface mesh extension for POLARDB ganos_spatialref 6.0 Ganos spatial reference extension for POLARDB ganos_trajectory 6.0 Ganos trajectory extension for POLARDB ganos_vomesh 6.0 Ganos volumn mesh extension for POLARDB postgis_tiger_geocoder 3.3.2 Ganos PostGIS tiger geocoder postgis_topology 3.3.2 Ganos PostGIS topology
11.13.8 - Percona 支持 TDE 透明加密的 Percona Postgres 发行版
Percona Postgres 是一个带有 pg_tde (透明数据加密)扩展的补丁 Postgres 内核。
它与 PostgreSQL 18.1 兼容,在所有 Pigsty 支持的平台上都可用。
快速开始 使用 Pigsty 标准安装流程 ,配合 pgtde 配置模板。
curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty;
./configure -c pgtde # 使用 percona postgres 内核
./install.yml # 使用 pigsty 设置一切
配置 需要调整以下参数来部署 Percona 集群:
pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin ] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer }
pg_databases :
- name : meta
baseline : cmdb.sql
comment : pigsty tde database
schemas : [ pigsty]
extensions : [ vector, postgis, pg_tde ,pgaudit, { name: pg_stat_monitor, schema: monitor } ]
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # 每天凌晨 1 点进行全量备份
# Percona PostgreSQL TDE 临时设置
pg_packages : [ percona-main, pgsql-common ] # 安装 percona postgres 包
pg_libs : 'pg_tde, pgaudit, pg_stat_statements, pg_stat_monitor, auto_explain'
扩展 Percona 提供了 80 个可用的扩展,包括 pg_tde, pgvector, postgis, pgaudit, set_user, pg_stat_monitor 等实用三方扩展。
扩展名 版本 说明 pg_tde 2.1 Percona 透明数据加密访问方法 vector 0.8.1 向量数据类型及 ivfflat 和 hnsw 访问方法 postgis 3.5.4 PostGIS 几何和地理空间类型及函数 pgaudit 18.0 提供审计功能 pg_stat_monitor 2.3 PostgreSQL 查询性能监控工具 set_user 4.2.0 类似 SET ROLE 但带有额外日志记录 pg_repack 1.5.3 以最小锁定重组 PostgreSQL 数据库中的表 hstore 1.8 用于存储(键,值)对集合的数据类型 ltree 1.3 用于层次树状结构的数据类型 pg_trgm 1.6 基于三元组的文本相似度测量和索引搜索
完整的 80 个扩展列表请参考 Percona Postgres 官方文档 。
关键特性 透明数据加密 :使用 pg_tde 扩展提供静态数据加密PostgreSQL 18 兼容 :基于最新 PostgreSQL 18 版本企业级扩展 :包含 pgaudit、pg_stat_monitor 等企业级功能完整生态 :支持 pgvector、PostGIS 等流行扩展注意 :目前处于稳定阶段 - 在生产使用前请彻底评估。
11.13.9 - PostgresML 如何使用 Pigsty 部署 PostgresML,在数据库内进行机器学习、模型训练、推理、Embedding 与 RAG。
PostgresML 是一个 PostgreSQL 扩展,支持最新的大语言模型(LLM)、向量操作、经典机器学习以及传统的 Postgres 应用负载。
PostgresML (pgml) 是一个用 Rust 编写的 PostgreSQL 扩展。您可以运行独立的 Docker 镜像,但本文档不是 docker-compose 模板介绍,仅供参考。
PostgresML 官方支持 Ubuntu 22.04,但我们也为 EL 8/9 维护了 RPM 版本,如果您不需要 CUDA 和 NVIDIA 相关功能的话。
您需要在数据库节点上能够访问互联网,以便从 PyPI 下载 Python 依赖,并从 HuggingFace 下载模型。
配置 PostgresML 是一个用 Rust 编写的扩展,官方支持 Ubuntu。Pigsty 在 EL8 和 EL9 上维护了 PostgresML 的 RPM 版本。
创建新集群
PostgresML 2.7.9 可用于 PostgreSQL 15,支持 Ubuntu 22.04(官方)、Debian 12 和 EL 8/9(Pigsty 维护)。要启用 pgml,首先需要安装扩展:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- { name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ {name: postgis, schema : public}, {name: timescaledb}]}
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
pg_libs : 'pgml, pg_stat_statements, auto_explain'
pg_extensions : [ 'pgml_15 pgvector_15 wal2json_15 repack_15' ] # ubuntu
#pg_extensions: [ 'postgresql-pgml-15 postgresql-15-pgvector postgresql-15-wal2json postgresql-15-repack' ] # ubuntu
在 EL 8/9 中,扩展名为 pgml_15,对应的 Ubuntu/Debian 名称为 postgresql-pgml-15。同时需要将 pgml 添加到 pg_libs 中。
在现有集群上启用
要在现有集群上启用 pgml,可以使用 Ansible 的 package 模块安装:
ansible pg-meta -m package -b -a 'name=pgml_15'
# ansible el8,el9 -m package -b -a 'name=pgml_15' # EL 8/9
# ansible u22 -m package -b -a 'name=postgresql-pgml-15' # Ubuntu 22.04 jammy
Python 依赖 您还需要在集群节点上安装 PostgresML 的 Python 依赖。官方教程:安装指南
安装 Python 和 PIP
确保已安装 python3、pip 和 venv:
# Ubuntu 22.04 (python3.10),需要使用 apt 安装 pip 和 venv
sudo apt install -y python3 python3-pip python3-venv
对于 EL 8 / EL9 及兼容发行版,可以使用 python3.11:
# EL 8/9,可以升级默认的 pip 和 virtualenv
sudo yum install -y python3.11 python3.11-pip # 安装最新的 python3.11
python3.11 -m pip install --upgrade pip virtualenv # 在 EL8 / EL9 上使用 python3.11
使用 PyPI 镜像 对于中国大陆用户,建议使用清华大学 PyPI 镜像 。
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple # 设置全局镜像(推荐)
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package # 单次安装时使用
安装依赖包
创建 Python 虚拟环境,并使用 pip 从 requirements.txt 和 requirements-xformers.txt 安装依赖。
如果您使用的是 EL 8/9,需要将以下命令中的 python3 替换为 python3.11。
su - postgres; # 使用数据库超级用户创建虚拟环境
mkdir -p /data/pgml; cd /data/pgml; # 创建虚拟环境目录
python3 -m venv /data/pgml # 创建虚拟环境目录(Ubuntu 22.04)
source /data/pgml/bin/activate # 激活虚拟环境
# 写入 Python 依赖并使用 pip 安装
cat > /data/pgml/requirments.txt <<EOF
accelerate==0.22.0
auto-gptq==0.4.2
bitsandbytes==0.41.1
catboost==1.2
ctransformers==0.2.27
datasets==2.14.5
deepspeed==0.10.3
huggingface-hub==0.17.1
InstructorEmbedding==1.0.1
lightgbm==4.1.0
orjson==3.9.7
pandas==2.1.0
rich==13.5.2
rouge==1.0.1
sacrebleu==2.3.1
sacremoses==0.0.53
scikit-learn==1.3.0
sentencepiece==0.1.99
sentence-transformers==2.2.2
tokenizers==0.13.3
torch==2.0.1
torchaudio==2.0.2
torchvision==0.15.2
tqdm==4.66.1
transformers==4.33.1
xgboost==2.0.0
langchain==0.0.287
einops==0.6.1
pynvml==11.5.0
EOF
# 在虚拟环境中使用 pip 安装依赖
python3 -m pip install -r /data/pgml/requirments.txt
python3 -m pip install xformers == 0.0.21 --no-dependencies
# 此外,有 3 个 Python 包需要使用 sudo 全局安装!
sudo python3 -m pip install xgboost lightgbm scikit-learn
启用 PostgresML 在所有集群节点上安装 pgml 扩展和 Python 依赖后,就可以在 PostgreSQL 集群上启用 pgml 了。
使用 patronictl 命令配置集群 ,将 pgml 添加到 shared_preload_libraries,并在 pgml.venv 中指定您的虚拟环境目录:
shared_preload_libraries : pgml, timescaledb, pg_stat_statements, auto_explain
pgml.venv : '/data/pgml'
然后重启数据库集群,并使用 SQL 命令创建扩展:
CREATE EXTENSION vector ; -- 建议同时安装 pgvector!
CREATE EXTENSION pgml ; -- 在当前数据库中创建 PostgresML
SELECT pgml . version (); -- 打印 PostgresML 版本信息
如果一切正常,您应该会看到类似以下输出:
# create extension pgml;
INFO: Python version: 3.11.2 ( main, Oct 5 2023, 16:06:03) [ GCC 8.5.0 20210514 ( Red Hat 8.5.0-18)]
INFO: Scikit-learn 1.3.0, XGBoost 2.0.0, LightGBM 4.1.0, NumPy 1.26.1
CREATE EXTENSION
# SELECT pgml.version(); -- 打印 PostgresML 版本信息
version
---------
2.7.8
大功告成!更多详情请参阅 PostgresML 官方文档:https://postgresml.org/docs/guides/use-cases/
11.13.10 - OpenHalo MySQL 兼容的 Postgres 14 分支
OpenHalo 是一个开源的 PostgreSQL 内核,提供 MySQL 线协议兼容性。
OpenHalo 基于 PostgreSQL 14.10 内核版本,提供与 MySQL 5.7.32-log / 8.0 版本的线协议兼容性。
Pigsty 在所有支持的 Linux 平台上为 OpenHalo 提供部署支持。
快速开始 使用 Pigsty 的 标准安装流程 和 mysql 配置模板。
curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty;
./configure -c mysql # 使用 MySQL(openHalo)配置模板
./install.yml # 安装,生产部署请先在 pigsty.yml 中修改密码
对于生产部署,请确保在运行安装剧本之前修改 pigsty.yml 配置文件中的密码参数。
配置 pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- {name: postgres, extensions : [ aux_mysql]} # mysql 兼容数据库
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas : [ pigsty]}
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # 每天凌晨 1 点进行全量备份
# OpenHalo 临时设置
pg_mode : mysql # HaloDB 的 MySQL 兼容模式
pg_version : 14 # 当前 HaloDB 兼容 PG 主版本 14
pg_packages : [ openhalodb, pgsql-common ] # 安装 openhalodb 而不是 postgresql 内核
使用 访问 MySQL 时,实际连接使用的是 postgres 数据库。请注意,MySQL 中的"数据库"概念实际上对应于 PostgreSQL 中的"Schema"。因此,use mysql 实际上使用的是 postgres 数据库内的 mysql Schema。
用于 MySQL 的用户名和密码与 PostgreSQL 中的相同。您可以使用标准的 PostgreSQL 方法管理用户和权限。
客户端访问 OpenHalo 提供 MySQL 线协议兼容性,默认监听端口 3306,允许 MySQL 客户端和驱动程序直接连接。
Pigsty 的 conf/mysql 配置默认安装 mysql 客户端工具。
您可以使用以下命令访问 MySQL:
mysql -h 127.0.0.1 -u dbuser_dba
目前,OpenHalo 官方确保 Navicat 可以正常访问此 MySQL 端口,但 Intellij IDEA 的 DataGrip 访问会导致错误。
修改说明 Pigsty 安装的 OpenHalo 内核基于 HaloTech-Co-Ltd/openHalo 内核进行了少量修改:
将默认数据库名称从 halo0root 改回 postgres 从默认版本号中删除 1.0. 前缀,恢复为 14.10 修改默认配置文件以启用 MySQL 兼容性并默认监听端口 3306 请注意,Pigsty 不为使用 OpenHalo 内核提供任何保证。使用此内核时遇到的任何问题或需求应与原始供应商联系。
警告 :目前处于实验阶段 - 在生产使用前请彻底评估。
11.13.11 - Greenplum 使用 Pigsty 部署/监控 Greenplum 集群,构建大规模并行处理(MPP)的 PostgreSQL 数据仓库集群!
Pigsty 支持部署 Greenplum 集群,及其衍生发行版 YMatrixDB,并提供了将现有 Greenplum 部署纳入 Pigsty 监控的能力。
概览 Greenplum / YMatrix 集群部署能力仅在专业版本/企业版本中提供,目前不对外开源。
安装 Pigsty 提供了 Greenplum 6 (@el7) 与 Greenplum 7 (@el8) 的安装包,开源版本用户可以自行安装配置。
# EL 7 Only (Greenplum6)
./node.yml -t node_install -e '{"node_repo_modules":"pgsql","node_packages":["open-source-greenplum-db-6"]}'
# EL 8 Only (Greenplum7)
./node.yml -t node_install -e '{"node_repo_modules":"pgsql","node_packages":["open-source-greenplum-db-7"]}'
配置 要定义 Greenplum 集群,需要用到 pg_mode = gpsql,并使用额外的身份参数 pg_shard 与 gp_role。
#================================================================#
# GPSQL Clusters #
#================================================================#
#----------------------------------#
# cluster: mx-mdw (gp master)
#----------------------------------#
mx-mdw :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role: primary , nodename : mx-mdw-1 }
vars :
gp_role : master # this cluster is used as greenplum master
pg_shard : mx # pgsql sharding name & gpsql deployment name
pg_cluster : mx-mdw # this master cluster name is mx-mdw
pg_databases :
- { name: matrixmgr , extensions : [ { name : matrixdbts } ] }
- { name : meta }
pg_users :
- { name: meta , password: DBUser.Meta , pgbouncer : true }
- { name: dbuser_monitor , password: DBUser.Monitor , roles: [ dbrole_readonly ], superuser : true }
pgbouncer_enabled : true # enable pgbouncer for greenplum master
pgbouncer_exporter_enabled : false # enable pgbouncer_exporter for greenplum master
pg_exporter_params : 'host=127.0.0.1&sslmode=disable' # use 127.0.0.1 as local monitor host
#----------------------------------#
# cluster: mx-sdw (gp master)
#----------------------------------#
mx-sdw :
hosts :
10.10.10.11 :
nodename : mx-sdw-1 # greenplum segment node
pg_instances : # greenplum segment instances
6000 : { pg_cluster: mx-seg1, pg_seq: 1, pg_role: primary , pg_exporter_port : 9633 }
6001 : { pg_cluster: mx-seg2, pg_seq: 2, pg_role: replica , pg_exporter_port : 9634 }
10.10.10.12 :
nodename : mx-sdw-2
pg_instances :
6000 : { pg_cluster: mx-seg2, pg_seq: 1, pg_role: primary , pg_exporter_port : 9633 }
6001 : { pg_cluster: mx-seg3, pg_seq: 2, pg_role: replica , pg_exporter_port : 9634 }
10.10.10.13 :
nodename : mx-sdw-3
pg_instances :
6000 : { pg_cluster: mx-seg3, pg_seq: 1, pg_role: primary , pg_exporter_port : 9633 }
6001 : { pg_cluster: mx-seg1, pg_seq: 2, pg_role: replica , pg_exporter_port : 9634 }
vars :
gp_role : segment # these are nodes for gp segments
pg_shard : mx # pgsql sharding name & gpsql deployment name
pg_cluster : mx-sdw # these segment clusters name is mx-sdw
pg_preflight_skip : true # skip preflight check (since pg_seq & pg_role & pg_cluster not exists)
pg_exporter_config : pg_exporter_basic.yml # use basic config to avoid segment server crash
pg_exporter_params : 'options=-c%20gp_role%3Dutility&sslmode=disable' # use gp_role = utility to connect to segments
此外,PG Exporter 需要额外的连接参数,才能连接到 Greenplum Segment 实例上采集监控指标。
11.13.12 - OrioleDB PostgreSQL 的下一代 OLTP 引擎
OrioleDB 是一个 PostgreSQL 存储引擎扩展,声称能够提供 4 倍 OLTP 性能,没有 xid 环绕和表膨胀问题,并具有"云原生"(数据存储在 S3)能力。
OrioleDB 的最新版本基于 补丁版 PostgreSQL 17.0 和一个额外的扩展
您可以使用 Pigsty 将 OrioleDB 作为 RDS 运行,它与 PG 17 兼容,在所有支持的 Linux 平台上都可用。
最新版本为 beta12,基于 PG 17_11 补丁。
快速开始 按照 Pigsty 标准安装 流程,使用 oriole 配置模板。
curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty;
./configure -c oriole # 使用 OrioleDB 配置模板
./install.yml # 使用 OrioleDB 安装 Pigsty
对于生产部署,请确保在运行 install 剧本之前修改 pigsty.yml 配置中的密码参数。
配置 pg-meta :
hosts :
10.10.10.10 : { pg_seq: 1, pg_role : primary }
vars :
pg_cluster : pg-meta
pg_users :
- {name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- {name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- {name: meta ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty], extensions : [ orioledb]}
pg_hba_rules :
- {user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
node_crontab : [ '00 01 * * * postgres /pg/bin/pg-backup full' ] # 每天凌晨 1 点进行全量备份
# OrioleDB 临时设置
pg_mode : oriole # oriole 兼容模式
pg_packages : [ orioledb, pgsql-common ] # 安装 OrioleDB 内核
pg_libs : 'orioledb, pg_stat_statements, auto_explain' # 加载 OrioleDB 扩展
使用 要使用 OrioleDB,您需要安装 orioledb_17 和 oriolepg_17 包(目前仅提供 RPM 版本)。
使用 pgbench 初始化类似 TPC-B 的表,包含 100 个仓库:
pgbench -is 100 meta
pgbench -nv -P1 -c10 -S -T1000 meta
pgbench -nv -P1 -c50 -S -T1000 meta
pgbench -nv -P1 -c10 -T1000 meta
pgbench -nv -P1 -c50 -T1000 meta
接下来,您可以使用 orioledb 存储引擎重建这些表并观察性能差异:
-- 创建 OrioleDB 表
CREATE TABLE pgbench_accounts_o ( LIKE pgbench_accounts INCLUDING ALL ) USING orioledb ;
CREATE TABLE pgbench_branches_o ( LIKE pgbench_branches INCLUDING ALL ) USING orioledb ;
CREATE TABLE pgbench_history_o ( LIKE pgbench_history INCLUDING ALL ) USING orioledb ;
CREATE TABLE pgbench_tellers_o ( LIKE pgbench_tellers INCLUDING ALL ) USING orioledb ;
-- 从常规表复制数据到 OrioleDB 表
INSERT INTO pgbench_accounts_o SELECT * FROM pgbench_accounts ;
INSERT INTO pgbench_branches_o SELECT * FROM pgbench_branches ;
INSERT INTO pgbench_history_o SELECT * FROM pgbench_history ;
INSERT INTO pgbench_tellers_o SELECT * FROM pgbench_tellers ;
-- 删除原始表并重命名 OrioleDB 表
DROP TABLE pgbench_accounts , pgbench_branches , pgbench_history , pgbench_tellers ;
ALTER TABLE pgbench_accounts_o RENAME TO pgbench_accounts ;
ALTER TABLE pgbench_branches_o RENAME TO pgbench_branches ;
ALTER TABLE pgbench_history_o RENAME TO pgbench_history ;
ALTER TABLE pgbench_tellers_o RENAME TO pgbench_tellers ;
关键特性 无 XID 回绕 :消除事务 ID 回绕维护无表膨胀 :高级存储管理防止表膨胀云存储 :对 S3 兼容对象存储的原生支持OLTP 优化 :专为事务工作负载设计改进性能 :更好的空间利用率和查询性能注意 :目前处于 Beta 阶段 - 在生产使用前请彻底评估。
11.13.13 - Cloudberry 使用 Pigsty 部署/监控 Cloudberry 集群,一个由 Greenplum 分叉而来的 MPP 数据仓库集群!
安装 Pigsty 提供了 Greenplum 6 (@el7) 与 Greenplum 7 (@el8) 的安装包,开源版本用户可以自行安装配置。
# EL 7 Only (Greenplum6)
./node.yml -t node_install -e '{"node_repo_modules":"pgsql","node_packages":["cloudberrydb"]}'
# EL 8 Only (Greenplum7)
./node.yml -t node_install -e '{"node_repo_modules":"pgsql","node_packages":["cloudberrydb"]}'
11.13.14 - Neon 使用 Neon 开源的 Serverless 版本 PostgreSQL 内核,自建灵活伸缩,Scale To Zero,灵活分叉的PG服务。
Neon 采用了存储与计算分离架构,提供了丝滑的自动扩缩容,Scale to Zero,以及数据库版本分叉等独家能力。
Neon 官网:https://neon.tech/
Neon 编译后的二进制产物过于庞大,目前不对开源版用户提供,目前处于试点阶段,有需求请联系 Pigsty 销售。
11.14 - 扩展插件 利用 PostgreSQL 扩展的协同超能力
Pigsty 提供 440+ 扩展 ,覆盖时序、地理、向量、全文检索、分析、特性增强等 16 大类别,开箱即用。
在 Pigsty 中使用扩展涉及四个核心步骤:下载 、安装 、配置/加载 与 启用 。
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_databases :
- name : meta
extensions : [ postgis, timescaledb, vector ] # 启用:在数据库中创建扩展
pg_libs : 'timescaledb, pg_stat_statements, auto_explain' # 配置:预加载扩展库
pg_extensions : [ postgis, timescaledb, pgvector ] # 安装:安装扩展软件包
11.14.1 - 快速开始 使用扩展的四步流程速览
在 Pigsty 中使用扩展需要四个步骤:下载 、安装 、配置 、启用 。
下载 :将扩展软件包下载到本地仓库(Pigsty 默认已下载主流扩展)安装 :在集群节点上安装扩展软件包配置 :部分扩展需要预加载或配置参数启用 :在数据库中执行 CREATE EXTENSION 创建扩展声明式配置 在 Pigsty 配置清单中声明扩展,集群初始化时自动完成安装与启用:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_databases :
- name : meta
extensions : [ postgis, timescaledb, vector ] # 在数据库中启用扩展
pg_libs : 'timescaledb, pg_stat_statements, auto_explain' # 预加载扩展库
pg_extensions : [ postgis, timescaledb, pgvector ] # 安装扩展软件包
执行 ./pgsql.yml 初始化集群后,postgis、timescaledb、vector 三个扩展即在 meta 数据库中可用。
命令式操作 对于已有集群,可以使用命令行方式添加扩展:
# 1. 安装扩展软件包
./pgsql.yml -l pg-meta -t pg_extension -e '{"pg_extensions":["pgvector"]}'
# 2. 预加载扩展(如需要,修改后需重启)
pg edit-config pg-meta --force -p shared_preload_libraries = 'timescaledb, pg_stat_statements, auto_explain'
# 3. 在数据库中启用扩展
psql -d meta -c 'CREATE EXTENSION vector;'
也可以使用 pig 包管理器直接安装:
pig install pgvector # 安装扩展包
pig extension create vector # 在数据库中启用
流程速查 详细说明请参阅各子章节:下载 、安装 、配置 、启用
11.14.2 - 扩展简介 PostgreSQL 扩展的核心概念与 Pigsty 扩展生态
扩展是 PostgreSQL 的灵魂所在。Pigsty 收录了 440+ 个预编译、开箱即用的扩展插件,充分释放 PostgreSQL 的潜能。
扩展是什么 PostgreSQL 扩展(Extension)是一种模块化机制,允许在不修改核心代码的情况下增强数据库功能。
一个扩展通常包含三部分:
控制文件 (.control):必需,包含扩展元数据SQL 脚本 (.sql):可选,定义函数、类型、操作符等数据库对象动态库 (.so):可选,提供 C 语言实现的高性能功能扩展可以为 PostgreSQL 添加:新数据类型、索引方法、函数与操作符、外部数据访问、过程语言、性能监控、安全审计等能力。
核心扩展 Pigsty 收录的扩展中,以下是最具代表性的:
绝大多数扩展可以并存甚至组合使用,产生 1+1 远大于 2 的协同效应。
扩展类别 Pigsty 将扩展划分为 16 个类别:
类别 别名 说明 典型扩展 时序 time时序数据处理 timescaledb, pg_cron, periods 地理 gis地理空间数据 postgis, h3, pgrouting 向量 rag向量检索与 AI pgvector, vchord, pg_vectorize 搜索 fts全文检索 pgroonga, zhparser, pg_bigm 分析 olapOLAP 与分析 pg_duckdb, pg_mooncake, citus 特性 feat功能增强 age, pg_graphql, hll, rum 语言 lang过程语言 plpython3u, pljava, plv8 类型 type数据类型 hstore, ltree, ip4r 工具 util实用工具 http, pg_net, pgjwt 函数 func函数库 pg_uuidv7, topn, tdigest 管理 admin运维管理 pg_repack, pg_squeeze, pgagent 统计 stat监控统计 pg_stat_statements, pg_qualstats, auto_explain 安全 sec安全审计 pgaudit, pgsodium, pg_tde 外联 fdw外部数据访问 postgres_fdw, mysql_fdw, oracle_fdw 兼容 sim数据库兼容 orafce, babelfish 同步 etl数据同步 pglogical, wal2json, decoderbufs
使用类别别名可以批量安装整个类别的扩展,例如 pg_extensions: [ pgsql-gis, pgsql-rag ]。
预定义扩展集 Pigsty 提供了若干预定义的扩展集(Stack),方便按场景选用:
扩展集 包含扩展 gis-stackpostgis, pgrouting, pointcloud, h3, q3c, ogr_fdw rag-stackpgvector, vchord, pgvectorscale, pg_similarity, pg_tiktoken fts-stackpgroonga, pg_bigm, zhparser, hunspell olap-stackpg_duckdb, pg_mooncake, timescaledb, pg_partman, plproxy feat-stackage, hll, rum, pg_graphql, pg_jsonschema, jsquery stat-stackpg_show_plans, pg_stat_kcache, pg_qualstats, pg_wait_sampling supa-stackpg_graphql, pg_jsonschema, wrappers, pgvector, pgsodium, vault
在 pg_extensions 中直接使用这些名称即可安装整套扩展。
扩展资源 11.14.3 - 软件包 扩展包别名与类别命名规则
Pigsty 使用包别名 机制简化扩展的安装与管理。
包别名机制 管理扩展涉及多个层面的名称映射:
层面 示例 pgvector 示例 postgis 扩展名 vectorpostgis, postgis_topology, …包别名 pgvectorpostgisRPM 包名 pgvector_18postgis36_18*DEB 包名 postgresql-18-pgvectorpostgresql-18-postgis-3*
Pigsty 提供包别名 抽象层,让用户无需关心具体的 RPM/DEB 包名:
pg_extensions : [ pgvector, postgis, timescaledb ] # 使用包别名
Pigsty 会根据操作系统和 PostgreSQL 版本自动翻译为正确的包名。
注意:CREATE EXTENSION 时使用的是扩展名 (如 vector),而非包别名(pgvector)。
类别别名 所有扩展被划分为 16 个类别,可使用类别别名批量安装:
# 使用通用类别别名(自动适配当前 PG 版本)
pg_extensions : [ pgsql-gis, pgsql-rag, pgsql-fts ]
# 或使用版本特定的类别别名
pg_extensions : [ pg18-gis, pg18-rag, pg18-fts ]
除 olap 类别外,所有类别的扩展都可以同时安装。olap 类别中存在互斥:pg_duckdb 与 pg_mooncake 冲突。
类别列表 类别 说明 典型扩展 time时序类 timescaledb, pg_cron, periods gis地理类 postgis, h3, pgrouting rag向量类 pgvector, pgml, vchord fts搜索类 pg_trgm, zhparser, pgroonga olap分析类 citus, pg_duckdb, pg_analytics feat特性类 age, pg_graphql, rum lang语言类 plpython3u, pljava, plv8 type类型类 hstore, ltree, citext util工具类 http, pg_net, pgjwt func函数类 pgcrypto, uuid-ossp, pg_uuidv7 admin管理类 pg_repack, pgagent, pg_squeeze stat统计类 pg_stat_statements, pg_qualstats, auto_explain sec安全类 pgaudit, pgcrypto, pgsodium fdw外部类 postgres_fdw, mysql_fdw, oracle_fdw sim兼容类 orafce, babelfishpg_tds etl数据类 pglogical, wal2json, decoderbufs
查阅扩展目录 您可以在 Pigsty 扩展目录 网站上查阅所有可用扩展的详细信息,包括:
扩展名称、描述、版本 支持的 PostgreSQL 版本 支持的操作系统发行版 安装方式、预加载需求 许可证、来源仓库 11.14.4 - 下载扩展 从软件仓库下载扩展包到本地
在安装扩展前,需要确保扩展软件包已下载到本地仓库或可从上游获取。
默认行为 Pigsty 在安装过程中会自动下载默认 PostgreSQL 版本可用的主流扩展到本地软件仓库。
使用本地仓库的优势:
加速安装,避免重复下载 减少网络流量消耗 提高交付可靠性 确保版本一致性 下载新扩展 要下载额外的扩展,将其添加到 repo_extra_packages 并重建仓库:
all :
vars :
repo_extra_packages : [ pgvector, postgis, timescaledb, pg_duckdb ]
# 重新下载软件包到本地仓库
./infra.yml -t repo_build
# 刷新所有节点的软件源缓存
./node.yml -t node_repo
使用上游仓库 也可以直接从互联网上游仓库安装,无需预先下载:
# 在节点上添加上游软件源
./node.yml -t node_repo -e node_repo_modules = node,pgsql
这种方式适合:
但可能面临:
扩展来源 扩展软件包来自两个主要源:
仓库 说明 PGDG PostgreSQL 官方仓库,提供核心扩展 Pigsty Pigsty 补充仓库,提供额外扩展
Pigsty 仓库只收录 PGDG 仓库中不存在的扩展。一旦某扩展进入 PGDG 仓库,Pigsty 仓库会移除或与其保持一致。
仓库地址:
详细的仓库配置请参阅 扩展仓库 。
11.14.5 - 安装扩展 在集群节点上安装扩展软件包
Pigsty 使用操作系统的包管理器(yum/apt)安装扩展软件包。
相关参数 两个参数用于指定要安装的扩展:
pg_packages 通常用于指定所有集群都需要的基础组件(PostgreSQL 内核、Patroni、pgBouncer 等)和必选扩展。
pg_extensions 用于指定特定集群需要的扩展。
pg_packages : # 全局基础包
- pgsql-main pgsql-common
pg_extensions : # 集群扩展
- postgis timescaledb pgvector
集群初始化时安装 在集群配置中声明扩展,初始化时自动安装:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_extensions : [ postgis, timescaledb, pgvector, pg_duckdb ]
执行 ./pgsql.yml 初始化集群时,扩展会自动安装。
已有集群安装扩展 对于已初始化的集群,有多种方式安装扩展:
使用 Pigsty 剧本 # 修改配置后使用剧本安装
./pgsql.yml -l pg-meta -t pg_extension
# 或直接在命令行指定扩展
./pgsql.yml -l pg-meta -t pg_extension -e '{"pg_extensions":["pg_duckdb"]}'
使用 pig 包管理器 # 使用 pig 安装扩展
pig install pg_duckdb
# 批量安装
ansible pg-meta -b -a 'pig install pg_duckdb pgvector'
直接使用包管理器 # EL 系统
sudo yum install -y pg_duckdb_18*
# Debian/Ubuntu 系统
sudo apt install -y postgresql-18-pg-duckdb
使用包别名 Pigsty 支持使用标准化的包别名,自动翻译为对应 PG 版本的包名:
pg_extensions :
- pgvector # 自动翻译为 pgvector_18* (EL) 或 postgresql-18-pgvector (Debian)
- postgis # 自动翻译为 postgis36_18* (EL) 或 postgresql-18-postgis-3* (Debian)
- pgsql-gis # 类别别名,安装整个 GIS 类别的扩展
也可以直接使用原始包名:
pg_extensions :
- pgvector_18* # EL 系统的原始包名
- postgresql-18-pgvector # Debian 系统的原始包名
包别名定义参见:
验证安装 安装后可在数据库中验证:
-- 查看已安装的扩展
SELECT * FROM pg_available_extensions WHERE name = 'vector' ;
-- 查看扩展文件是否存在
\ dx
11.14.6 - 配置扩展 预加载扩展库与配置扩展参数
部分扩展需要预加载动态库或配置参数后才能使用,本节介绍如何配置扩展。
预加载扩展 大多数扩展安装后可直接使用 CREATE EXTENSION 启用,但部分使用 PostgreSQL Hook 机制的扩展需要预加载 。
预加载通过 shared_preload_libraries 参数指定,修改后需重启数据库 生效。
需要预加载的扩展 以下是常见的需要预加载的扩展:
扩展 说明 timescaledb时序数据库扩展,必须放在最前面 citus分布式数据库扩展,必须放在最前面 pg_stat_statementsSQL 语句统计,Pigsty 默认启用 auto_explain自动记录慢查询执行计划,Pigsty 默认启用 pg_cron定时任务调度 pg_net异步 HTTP 请求 pg_tle可信语言扩展 pgaudit审计日志 pg_stat_kcache内核统计信息 pg_squeeze在线表空间回收 pgmlPostgresML 机器学习
完整列表请参阅 扩展目录 (带 LOAD 标记)。
预加载顺序 shared_preload_libraries 中扩展的加载顺序很重要:
timescaledb 和 citus 必须放在最前面 如果同时使用,citus 应在 timescaledb 之前 统计类扩展应在 pg_stat_statements 之后,以使用相同的 query_id pg_libs : 'citus, timescaledb, pg_stat_statements, auto_explain'
集群初始化时配置 在创建新集群时,使用 pg_libs 参数指定预加载的扩展:
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_libs : 'timescaledb, pg_stat_statements, auto_explain'
pg_extensions : [ timescaledb, postgis, pgvector ]
pg_libs 的值将在集群初始化时写入 shared_preload_libraries。
默认值 pg_libs 的默认值是 pg_stat_statements, auto_explain,这两个 Contrib 扩展提供基本的可观测性:
pg_stat_statements:跟踪所有 SQL 语句的执行统计auto_explain:自动记录慢查询的执行计划已有集群修改配置 对于已初始化的集群,使用 patronictl 修改 shared_preload_libraries:
# 添加 timescaledb 到预加载库
pg edit-config pg-meta --force -p shared_preload_libraries = 'timescaledb, pg_stat_statements, auto_explain'
# 重启集群使配置生效
pg restart pg-meta
也可以直接修改 postgresql.conf 或使用 ALTER SYSTEM:
ALTER SYSTEM SET shared_preload_libraries = 'timescaledb, pg_stat_statements, auto_explain' ;
修改后需重启 PostgreSQL 服务生效。
扩展参数配置 许多扩展有可配置的参数,可以在以下位置设置:
集群初始化时 使用 pg_parameters 参数指定:
pg-meta :
vars :
pg_cluster : pg-meta
pg_libs : 'pg_cron, pg_stat_statements, auto_explain'
pg_parameters :
cron.database_name : postgres # pg_cron 使用的数据库
pg_stat_statements.track : all # 跟踪所有语句
auto_explain.log_min_duration : 1000 # 记录超过 1 秒的查询
运行时修改 使用 ALTER SYSTEM 或 patronictl:
-- 修改参数
ALTER SYSTEM SET pg_stat_statements . track = 'all' ;
-- 重新加载配置
SELECT pg_reload_conf ();
# 使用 patronictl 修改
pg edit-config pg-meta --force -p 'pg_stat_statements.track=all'
注意事项 预加载错误会阻止启动 :如果 shared_preload_libraries 中的扩展不存在或加载失败,PostgreSQL 将无法启动。确保扩展已正确安装后再添加预加载。
修改需重启 :shared_preload_libraries 的修改需要重启 PostgreSQL 服务才能生效。
部分功能可用 :某些扩展在不预加载的情况下可以部分使用,但完整功能需要预加载。
查看当前配置 :使用以下命令查看当前的预加载库:
SHOW shared_preload_libraries ;
11.14.7 - 启用扩展 在数据库中创建和启用扩展
安装扩展软件包后,需要在数据库中执行 CREATE EXTENSION 才能使用扩展功能。
查看可用扩展 安装扩展软件包后,可以查看可用的扩展:
-- 查看所有可用扩展
SELECT * FROM pg_available_extensions ;
-- 查看特定扩展
SELECT * FROM pg_available_extensions WHERE name = 'vector' ;
-- 查看已启用的扩展
SELECT * FROM pg_extension ;
创建扩展 使用 CREATE EXTENSION 在数据库中启用扩展:
-- 创建扩展
CREATE EXTENSION vector ;
-- 创建扩展到指定 Schema
CREATE EXTENSION postgis SCHEMA public ;
-- 自动安装依赖的扩展
CREATE EXTENSION postgis_topology CASCADE ;
-- 如果不存在则创建
CREATE EXTENSION IF NOT EXISTS vector ;
注意:CREATE EXTENSION 使用的是扩展名 (如 vector),而非包别名(pgvector)。
集群初始化时启用 在 pg_databases 中声明扩展,集群初始化时自动创建:
pg-meta :
vars :
pg_cluster : pg-meta
pg_databases :
- name : meta
extensions :
- { name : vector } # 使用默认 Schema
- { name: postgis, schema : public } # 指定 Schema
- { name: pg_stat_statements, schema : monitor }
Pigsty 会在数据库创建后自动执行 CREATE EXTENSION。
需要预加载的扩展 部分扩展需要先添加到 shared_preload_libraries 并重启后才能创建:
pg-meta :
vars :
pg_cluster : pg-meta
pg_libs : 'timescaledb, pg_stat_statements, auto_explain'
pg_databases :
- name : meta
extensions :
- { name : timescaledb } # 需要预加载
如果未预加载就尝试创建,会收到错误信息。
需要预加载的常见扩展:timescaledb, citus, pg_cron, pg_net, pgaudit 等。详见 配置扩展 。
扩展依赖 某些扩展依赖于其他扩展,需要按顺序创建:
-- postgis_topology 依赖 postgis
CREATE EXTENSION postgis ;
CREATE EXTENSION postgis_topology ;
-- 或使用 CASCADE 自动安装依赖
CREATE EXTENSION postgis_topology CASCADE ;
不需要创建的扩展 少数扩展不通过 SQL 接口对外服务,无需执行 CREATE EXTENSION:
扩展 说明 wal2json逻辑解码插件,直接在复制槽中使用 decoderbufs逻辑解码插件 decoder_raw逻辑解码插件
这些扩展安装后即可使用,例如:
-- 使用 wal2json 创建逻辑复制槽
SELECT * FROM pg_create_logical_replication_slot ( 'test_slot' , 'wal2json' );
查看扩展信息 -- 查看扩展详情
\ dx + vector
-- 查看扩展包含的对象
SELECT * FROM pg_extension_config_dump ( 'vector' );
-- 查看扩展版本
SELECT extversion FROM pg_extension WHERE extname = 'vector' ;
11.14.8 - 更新扩展 升级 PostgreSQL 扩展版本
扩展更新涉及两个层面:软件包更新 (操作系统层面)和扩展对象更新 (数据库层面)。
更新软件包 使用包管理器更新扩展的软件包:
# EL 系统
sudo yum update pgvector_18*
# Debian/Ubuntu 系统
sudo apt update && sudo apt upgrade postgresql-18-pgvector
使用 Pigsty 批量更新:
# 更新指定集群的扩展包
./pgsql.yml -l pg-meta -t pg_extension -e '{"pg_extensions":["pgvector"]}'
# 使用 pig 包管理器
pig update pgvector
更新扩展对象 软件包更新后,数据库中的扩展对象可能需要同步更新。
查看可更新的扩展 -- 查看已安装扩展及其版本
SELECT name , default_version , installed_version
FROM pg_available_extensions
WHERE installed_version IS NOT NULL ;
-- 查看可升级的扩展
SELECT name , installed_version , default_version
FROM pg_available_extensions
WHERE installed_version IS NOT NULL
AND installed_version <> default_version ;
执行扩展更新 -- 更新到最新版本
ALTER EXTENSION pgvector UPDATE ;
-- 更新到指定版本
ALTER EXTENSION pgvector UPDATE TO '0.8.0' ;
查看更新路径 -- 查看扩展的可用升级路径
SELECT * FROM pg_extension_update_paths ( 'pgvector' );
注意事项 备份优先 :更新扩展前建议先备份数据库,特别是涉及数据类型变更的扩展。
检查兼容性 :某些扩展的大版本升级可能不兼容,需查阅扩展的升级文档。
预加载扩展 :如果更新的是需要预加载的扩展(如 timescaledb),更新后可能需要重启数据库。
依赖关系 :如果其他扩展依赖于被更新的扩展,需要按依赖顺序更新。
复制环境 :在主从复制环境中,应先在从库测试更新,确认无误后再更新主库。
常见问题 更新失败 如果 ALTER EXTENSION UPDATE 失败,可能是因为:
-- 查看扩展依赖
SELECT * FROM pg_depend WHERE refobjid = ( SELECT oid FROM pg_extension WHERE extname = 'pgvector' );
回滚更新 PostgreSQL 扩展通常不支持直接回滚。如需回滚:
从备份恢复 或者:卸载新版本扩展,安装旧版本软件包,重新创建扩展 11.14.9 - 移除扩展 卸载 PostgreSQL 扩展
移除扩展涉及两个层面:删除扩展对象 (数据库层面)和卸载软件包 (操作系统层面)。
删除扩展对象 使用 DROP EXTENSION 从数据库中删除扩展:
-- 删除扩展
DROP EXTENSION pgvector ;
-- 如果有依赖对象,需要级联删除
DROP EXTENSION pgvector CASCADE ;
警告 :CASCADE 会删除所有依赖于该扩展的对象(表、函数、视图等),请谨慎使用。
查看扩展依赖 删除前建议先检查依赖关系:
-- 查看依赖于某扩展的对象
SELECT
classid :: regclass ,
objid ,
deptype
FROM pg_depend
WHERE refobjid = ( SELECT oid FROM pg_extension WHERE extname = 'pgvector' );
-- 查看使用了扩展类型的表
SELECT
c . relname AS table_name ,
a . attname AS column_name ,
t . typname AS type_name
FROM pg_attribute a
JOIN pg_class c ON a . attrelid = c . oid
JOIN pg_type t ON a . atttypid = t . oid
WHERE t . typname = 'vector' ;
移除预加载 如果扩展在 shared_preload_libraries 中,删除后需要从预加载列表移除:
# 修改 shared_preload_libraries,移除扩展
pg edit-config pg-meta --force -p shared_preload_libraries = 'pg_stat_statements, auto_explain'
# 重启使配置生效
pg restart pg-meta
卸载软件包 从数据库中删除扩展后,可以选择卸载软件包:
# EL 系统
sudo yum remove pgvector_18*
# Debian/Ubuntu 系统
sudo apt remove postgresql-18-pgvector
# 使用 pig 包管理器
pig remove pgvector
通常保留软件包不会有问题,仅在需要释放磁盘空间或解决冲突时才需要卸载。
注意事项 数据丢失风险 :使用 CASCADE 会删除依赖对象,可能导致数据丢失。
应用兼容性 :删除扩展前确保应用程序不再使用该扩展的功能。
预加载顺序 :如果删除的是预加载扩展,务必同时从 shared_preload_libraries 中移除,否则数据库可能无法启动。
主从环境 :在主从复制环境中,DROP EXTENSION 会自动复制到从库。
操作顺序 完整的扩展移除流程:
# 1. 检查依赖关系
psql -d mydb -c "SELECT * FROM pg_depend WHERE refobjid = (SELECT oid FROM pg_extension WHERE extname = 'pgvector');"
# 2. 删除数据库中的扩展
psql -d mydb -c "DROP EXTENSION pgvector;"
# 3. 如果是预加载扩展,从 shared_preload_libraries 移除
pg edit-config pg-meta --force -p shared_preload_libraries = 'pg_stat_statements, auto_explain'
# 4. 重启数据库(如果修改了预加载配置)
pg restart pg-meta
# 5. 可选:卸载软件包
sudo yum remove pgvector_18*
11.14.10 - 默认扩展 Pigsty 默认安装的 PostgreSQL 扩展
Pigsty 在初始化 PostgreSQL 集群时,会默认安装和启用一些核心扩展。
默认安装的扩展 通过 pg_packages 默认安装的扩展:
扩展 说明 pg_repack在线处理表膨胀,重要的维护工具 wal2json逻辑解码输出 JSON 格式变更,CDC 场景常用
通过 pg_extensions 可选安装的扩展(默认注释):
扩展 说明 postgis地理空间数据库扩展 timescaledb时序数据库扩展 pgvector向量数据类型与索引
默认启用的扩展 通过 pg_default_extensions 在所有数据库中默认启用的扩展:
扩展 Schema 说明 pg_stat_statementsmonitor SQL 语句执行统计 pgstattuplemonitor 元组级统计信息 pg_buffercachemonitor 缓冲区缓存检查 pageinspectmonitor 页面级检查 pg_prewarmmonitor 关系预热 pg_visibilitymonitor 可见性映射检查 pg_freespacemapmonitor 空闲空间映射检查 postgres_fdwpublic PostgreSQL 外部数据包装器 file_fdwpublic 文件外部数据包装器 btree_gistpublic B-tree GiST 操作符类 btree_ginpublic B-tree GIN 操作符类 pg_trgmpublic 三元组匹配 intaggpublic 整数聚合器 intarraypublic 整数数组函数 pg_repack- 在线重组表
这些扩展提供基础的监控、运维和功能增强能力。
默认预加载的扩展 通过 pg_libs 默认预加载到 shared_preload_libraries 的扩展:
扩展 说明 pg_stat_statements跟踪所有 SQL 语句的执行统计 auto_explain自动记录慢查询的执行计划
这两个扩展提供基本的可观测性,强烈建议保留。
自定义默认扩展 可以通过修改配置参数来自定义默认安装和启用的扩展:
all :
vars :
# 修改默认安装的扩展包
pg_packages :
- pgsql-main pgsql-common
- pg_repack_$v* wal2json_$v*
# 修改默认安装的扩展
pg_extensions : [ postgis, timescaledb, pgvector ]
# 修改默认预加载的扩展
pg_libs : 'timescaledb, pg_stat_statements, auto_explain'
# 修改默认启用的扩展
pg_default_extensions :
- { name: pg_stat_statements, schema : monitor }
- { name : pg_repack }
# ... 添加更多
详细的扩展使用方法请参阅:
11.14.11 - 扩展仓库 Pigsty 扩展软件仓库配置
Pigsty 提供补充扩展仓库,在 PGDG 官方仓库基础上提供额外的扩展包。
YUM 仓库 适用于 EL 7/8/9/10 及其兼容系统(RHEL、Rocky、AlmaLinux、CentOS 等)。
添加仓库 # 添加 GPG 公钥
curl -fsSL https://repo.pigsty.io/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
# 添加仓库配置
curl -fsSL https://repo.pigsty.io/yum/repo | sudo tee /etc/yum.repos.d/pigsty.repo >/dev/null
# 刷新缓存
sudo yum makecache
中国大陆镜像 curl -fsSL https://repo.pigsty.cc/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
curl -fsSL https://repo.pigsty.cc/yum/repo | sudo tee /etc/yum.repos.d/pigsty.repo >/dev/null
仓库地址 APT 仓库 适用于 Debian 11/12/13 和 Ubuntu 22.04/24.04 及其兼容系统。
添加仓库 # 添加 GPG 公钥
curl -fsSL https://repo.pigsty.io/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
# 获取发行版代号并添加仓库
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty.list > /dev/null <<EOF
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.io/apt/infra generic main
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.io/apt/pgsql ${distro_codename} main
EOF
# 刷新缓存
sudo apt update
中国大陆镜像 curl -fsSL https://repo.pigsty.cc/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty.list > /dev/null <<EOF
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.cc/apt/infra generic main
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.cc/apt/pgsql/${distro_codename} ${distro_codename} main
EOF
仓库地址 GPG 签名 所有软件包均使用 GPG 签名:
指纹: 9592A7BC7A682E7333376E09E7935D8DB9BD8B20 短 ID: B9BD8B20 仓库策略 Pigsty 仓库遵循以下原则:
补充性 :只收录 PGDG 仓库中不存在的扩展一致性 :扩展进入 PGDG 仓库后,Pigsty 仓库会移除或保持一致兼容性 :支持 PostgreSQL 13-18 多个大版本多平台 :支持 x86_64 和 aarch64 架构相关资源 11.15 - 参数列表 PGSQL 模块提供的 PostgreSQL 相关配置参数详解
PGSQL 模块需要在 Pigsty 管理的节点上安装(即节点已经配置了 NODE 模块),同时还要求您的部署中有一套可用的 ETCD 集群来存储集群元数据。
在单个节点上安装 PGSQL 模块将创建一个独立的 PGSQL 服务器/实例,即主实例 。
在额外节点上安装将创建只读副本 ,可以作为备用实例,并用于承载分担只读请求。
您还可以创建用于 ETL/OLAP/交互式查询的离线 实例, 使用同步备库 和 法定人数提交 来提高数据一致性,
甚至搭建备份集群 和 延迟集群 以快速应对人为失误与软件缺陷导致的数据损失。
您可以定义多个 PGSQL 集群并进一步组建一个水平分片集群: Pigsty 支持原生的 citus 集群组 ,可以将您的标准 PGSQL 集群原地升级为一个分布式的数据库集群。
Pigsty v4.0 默认使用 PostgreSQL 18,并新增了 pg_io_method、pgbackrest_exporter 等参数。
参数概览 PG_ID 参数组用于定义 PostgreSQL 集群与实例的身份标识,包括集群名称、实例序号、角色、分片等核心身份参数。
参数 类型 级别 说明 pg_modeenumCpgsql 集群模式: pgsql,citus,mssql,mysql,polar,ivory,oracle,gpsql pg_clusterstringCpgsql 集群名称, 必选身份参数 pg_seqintIpgsql 实例号, 必选身份参数 pg_roleenumIpgsql 实例角色, 必选身份参数, 可为 primary,replica,offline pg_instancesdictI在一个节点上定义多个 pg 实例,使用 {port:ins_vars} 格式 pg_upstreamipI级联从库或备份集群或的复制上游节点IP地址 pg_shardstringCpgsql 分片名,对 citus 与 gpsql 等水平分片集群为必选身份参数 pg_groupintCpgsql 分片号,正整数,对 citus 与 gpsql 等水平分片集群为必选身份参数 gp_roleenumC这个集群的 greenplum 角色,可以是 master 或 segment pg_exportersdictC在该节点上设置额外的 pg_exporters 用于监控远程 postgres 实例 pg_offline_queryboolI设置为 true 将此只读实例标记为特殊的离线从库,承载 Offline 服务,允许离线查询
PG_BUSINESS 参数组用于定义业务用户、数据库、服务与访问控制规则,以及默认的系统用户凭据。
PG_INSTALL 参数组用于配置 PostgreSQL 安装相关选项,包括版本、路径、软件包与扩展插件。
PG_BOOTSTRAP 参数组用于配置 PostgreSQL 集群初始化引导,包括 Patroni 高可用、数据目录、存储、连接、编码等核心设置。
参数 类型 级别 说明 pg_datapathCpostgres 数据目录,默认为 /pg/data pg_fs_mainpathCpostgres 主数据的挂载点/路径,默认为 /data/postgres pg_fs_backuppathCpg 备份数据的挂载点/路径,默认为 /data/backups pg_storage_typeenumCpg 主数据的存储类型,SSD、HDD,默认为 SSD,影响自动优化的参数。 pg_dummy_filesizesizeC/pg/dummy 的大小,默认保留 64MB 磁盘空间用于紧急抢修pg_listenip(s)C/Ipostgres/pgbouncer 的监听地址,用逗号分隔的IP列表,默认为 0.0.0.0 pg_portportCpostgres 监听端口,默认为 5432 pg_localhostpathCpostgres 的 Unix 套接字目录,用于本地连接 pg_namespacepathC在 etcd 中的顶级键命名空间,被 patroni & vip 用于高可用管理 patroni_enabledboolC如果禁用,初始化期间不会创建 postgres 集群 patroni_modeenumCpatroni 工作模式:default,pause,remove patroni_portportCpatroni 监听端口,默认为 8008 patroni_log_dirpathCpatroni 日志目录,默认为 /pg/log/patroni patroni_ssl_enabledboolG使用 SSL 保护 patroni RestAPI 通信? patroni_watchdog_modeenumCpatroni 看门狗模式:automatic,required,off,默认为 off patroni_usernameusernameCpatroni restapi 用户名,默认为 postgres patroni_passwordpasswordCpatroni restapi 密码,默认为 Patroni.API pg_primary_dbstringC指定集群中首要使用的数据库名,Citus等模式会用到,默认为 postgres pg_parametersdictC覆盖 postgresql.auto.conf 中的 PostgreSQL 参数 pg_filespath[]C拷贝至PGDATA目录中的额外文件列表 (例如许可证文件) pg_confenumC配置模板:oltp,olap,crit,tiny,默认为 oltp.yml pg_max_connintCpostgres 最大连接数,auto 将使用推荐值 pg_shared_buffer_ratiofloatCpostgres 共享缓冲区内存比率,默认为 0.25,范围 0.1~0.4 pg_rtointC恢复时间目标(秒),默认为 30s pg_rpointC恢复点目标(字节),默认为 1MiB pg_libsstringC预加载的库,默认为 pg_stat_statements,auto_explain pg_delayintervalI备份集群主库的WAL重放应用延迟,用于制备延迟从库 pg_checksumboolC为 postgres 集群启用数据校验和? pg_pwd_encenumC密码加密算法:固定为 scram-sha-256 pg_encodingenumC数据库集群编码,默认为 UTF8 pg_localeenumC数据库集群本地化设置,默认为 C pg_lc_collateenumC数据库集群排序,默认为 C pg_lc_ctypeenumC数据库字符类型,默认为 C pg_io_methodenumCPostgreSQL IO 方法:auto, sync, worker, io_uring pg_etcd_passwordpasswordC此 PostgreSQL 集群在 etcd 中使用的密码,默认使用集群名 pgsodium_keystringCpgsodium 加密主密钥,64 位十六进制数字,默认使用 sha256(pg_cluster) pgsodium_getkey_scriptpathCpgsodium 获取密钥脚本路径,默认使用模板中的 pgsodium_getkey
PG_PROVISION 参数组用于配置 PostgreSQL 集群模板置备,包括默认角色、权限、模式、扩展与 HBA 规则。
PG_BACKUP 参数组用于配置 pgBackRest 备份与恢复,包括仓库类型、路径、保留策略等。
PG_ACCESS 参数组用于配置服务暴露、连接池、VIP、DNS 等客户端访问相关选项。
PG_MONITOR 参数组用于配置 PostgreSQL 监控 Exporter,包括 pg_exporter、pgbouncer_exporter 和 pgbackrest_exporter。
PG_REMOVE 参数组用于配置 PostgreSQL 实例清理与卸载行为,包括数据目录、备份、软件包的删除控制。
PG_ID以下是一些常用的参数,用于标识 PGSQL 模块中的实体 :集群、实例、服务等…
# pg_cluster: #CLUSTER # pgsql 集群名称,必需的标识参数
# pg_seq: 0 #INSTANCE # pgsql 实例序列号,必需的标识参数
# pg_role: replica #INSTANCE # pgsql 角色,必需的,可以是 primary,replica,offline
# pg_instances: {} #INSTANCE # 在节点上定义多个 pg 实例,使用 `{port:ins_vars}` 格式
# pg_upstream: #INSTANCE # 备用集群或级联副本的 repl 上游 ip 地址
# pg_shard: #CLUSTER # pgsql 分片名称,分片集群的可选标识
# pg_group: 0 #CLUSTER # pgsql 分片索引号,分片集群的可选标识
# gp_role: master #CLUSTER # 此集群的 greenplum 角色,可以是 master 或 segment
pg_offline_query : false #INSTANCE # 设置为 true 以在此实例上启用离线查询
您必须显式指定这些身份参数 ,它们没有默认值:
pg_cluster : 它标识集群的名称,该名称在集群级别配置。pg_role : 在实例级别配置,标识 ins 的角色。只有 primary 角色会特别处理。如果不填写,默认为 replica 角色和特殊的 delayed 和 offline 角色。pg_seq : 用于在集群内标识 ins,通常是从 0 或 1 递增的整数,一旦分配就不会更改。{{ pg_cluster }}-{{ pg_seq }} 用于唯一标识 ins,即 pg_instance。{{ pg_cluster }}-{{ pg_role }} 用于标识集群内的服务,即 pg_service。pg_shard 和 pg_group 用于水平分片集群,仅用于 citus、greenplum 和 matrixdb。pg_cluster 、pg_role 、pg_seq 是核心标识参数 ,对于任何 Postgres 集群都是必选 的,并且必须显式指定。以下是一个示例:
pg-test :
hosts :
10.10.10.11 : {pg_seq: 1, pg_role : replica}
10.10.10.12 : {pg_seq: 2, pg_role : primary}
10.10.10.13 : {pg_seq: 3, pg_role : replica}
vars :
pg_cluster : pg-test
所有其他参数都可以从全局配置或默认配置继承,但标识参数必须明确指定 和手动分配 。
pg_mode参数名称: pg_mode, 类型: enum, 层次:C
PostgreSQL 集群模式,默认值为 pgsql,即标准的 PostgreSQL 集群。
可用的模式选项包括:
pgsql:标准的 PostgreSQL 集群citus:Citus 分布式数据库集群mssql:Babelfish MSSQL 线缆协议兼容内核mysql:OpenHalo/HaloDB MySQL 线协议兼容内核ivory:IvorySQL Oracle 兼容内核polar:PolarDB for PostgreSQL 内核oracle:PolarDB for Oracle 内核gpsql:Greenplum 并行数据库集群(监控)如果 pg_mode 设置为 citus 或 gpsql,则需要两个额外的必选身份参数 pg_shard 和 pg_group 来定义水平分片集群的身份。
在这两种情况下,每一个 PostgreSQL 集群都是一组更大的业务单元的一部分。
pg_cluster参数名称: pg_cluster, 类型: string, 层次:C
PostgreSQL 集群名称,必选的身份标识参数,没有默认值
集群名将用作资源的命名空间。
集群命名需要遵循特定的命名模式:[a-z][a-z0-9-]*,即,只使用数字与小写字母,且不以数字开头,以符合标识上的不同约束的要求。
pg_seq参数名称: pg_seq, 类型: int, 层次:I
PostgreSQL 实例序列号,必选的身份标识参数,无默认值。
此实例的序号,在其集群 内是唯一分配的,通常使用自然数,从0或1开始分配,通常不会回收重用。
pg_role参数名称: pg_role, 类型: enum, 层次:I
PostgreSQL 实例角色,必选的身份标识参数,无默认值。取值可以是:primary, replica, offline
PGSQL 实例的角色,可以是:primary、replica、standby 或 offline。
primary: 主实例,在集群中有且仅有一个。replica: 用于承载在线只读流量的副本,高负载下可能会有轻微复制延迟(10ms~100ms, 100KB)。offline: 用于处理离线只读流量的离线副本,如统计分析/ETL/个人查询等。pg_instances参数名称: pg_instances, 类型: dict, 层次:I
使用 {port:ins_vars} 的形式在一台主机上定义多个 PostgreSQL 实例。
此参数是为在单个节点上的多实例部署保留的参数,Pigsty 尚未实现此功能,并强烈建议独占节点部署。
pg_upstream参数名称: pg_upstream, 类型: ip, 层次:I
备份集群 或级联从库的上游实例 IP 地址。
在集群的 primary 实例上设置 pg_upstream ,表示此集群是一个备份集群 ,该实例将作为 standby leader,从上游集群接收并应用更改。
对非 primary 实例设置 pg_upstream 参数将指定一个具体实例作为物理复制的上游,如果与主实例 ip 地址不同,此实例将成为 级联副本 。确保上游 IP 地址是同一集群中的另一个实例是用户的责任。
pg_shard参数名称: pg_shard, 类型: string, 层次:C
PostgreSQL 水平分片名称,对于分片集群来说(例如 citus 集群),这是的必选标识参数。
当多个标准的 PostgreSQL 集群一起以水平分片方式为同一业务提供服务时,Pigsty 将此组集群标记为 水平分片集群 。
pg_shard 是分片组名称。它通常是 pg_cluster 的前缀。
例如,如果我们有一个分片组 pg-citus,并且其中有4个集群,它们的标识参数将是:
cls pg_shard: pg-citus
cls pg_group = 0: pg-citus0
cls pg_group = 1: pg-citus1
cls pg_group = 2: pg-citus2
cls pg_group = 3: pg-citus3
pg_group参数名称: pg_group, 类型: int, 层次:C
PostgreSQL 水平分片集群的分片索引号,对于分片集群来说(例如 citus 集群),这是的必选标识参数。
此参数与 pg_shard 配对使用,通常可以使用非负整数作为索引号。
gp_role参数名称: gp_role, 类型: enum, 层次:C
PostgreSQL 集群的 Greenplum/Matrixdb 角色,可以是 master 或 segment。
master: 标记 postgres 集群为 greenplum 主实例(协调节点),这是默认值。segment 标记 postgres 集群为 greenplum 段集群(数据节点)。此参数仅用于 Greenplum/MatrixDB 数据库 (pg_mode 为 gpsql),对于普通的 PostgreSQL 集群没有意义。
pg_exporters参数名称: pg_exporters, 类型: dict, 层次:C
额外用于监控 远程 PostgreSQL 实例的 Exporter 定义,默认值:{}
如果您希望监控远程 PostgreSQL 实例,请在监控系统所在节点(Infra节点)集群上的 pg_exporters 参数中定义它们,并使用 pgsql-monitor.yml 剧本来完成部署。
pg_exporters : # list all remote instances here, alloc a unique unused local port as k
20001 : { pg_cluster: pg-foo, pg_seq: 1, pg_host : 10.10.10.10 }
20004 : { pg_cluster: pg-foo, pg_seq: 2, pg_host : 10.10.10.11 }
20002 : { pg_cluster: pg-bar, pg_seq: 1, pg_host : 10.10.10.12 }
20003 : { pg_cluster: pg-bar, pg_seq: 1, pg_host : 10.10.10.13 }
pg_offline_query参数名称: pg_offline_query, 类型: bool, 层次:I
设置为 true 以在此实例上启用离线查询,默认为 false。
当某个 PostgreSQL 实例启用此参数时, 属于 dbrole_offline 分组的用户可以直接连接到该 PostgreSQL 实例上执行离线查询(慢查询,交互式查询,ETL/分析类查询)。
带有此标记的实例在效果上类似于为实例设置 pg_role = offline ,唯一的区别在于 offline 实例默认不会承载 replica 服务的请求,是作为专用的离线/分析从库实例而存在的。
如果您没有富余的实例可以专门用于此目的,则可以挑选一台普通的从库,在实例层次启用此参数,以便在需要时承载离线查询。
PG_BUSINESS定制集群模板:用户,数据库,服务,权限规则。
用户需重点关注 此部分参数,因为这里是业务声明自己所需数据库对象的地方。
默认 的数据库用户及其凭据,强烈建议在生产环境中修改这些用户的密码。
# postgres business object definition, overwrite in group vars
pg_users : [] # postgres business users
pg_databases : [] # postgres business databases
pg_services : [] # postgres business services
pg_hba_rules : [] # business hba rules for postgres
pgb_hba_rules : [] # business hba rules for pgbouncer
# global credentials, overwrite in global vars
pg_dbsu_password : '' # dbsu password, empty string means no dbsu password by default
pg_replication_username : replicator
pg_replication_password : DBUser.Replicator
pg_admin_username : dbuser_dba
pg_admin_password : DBUser.DBA
pg_monitor_username : dbuser_monitor
pg_monitor_password : DBUser.Monitor
pg_users参数名称: pg_users, 类型: user[], 层次:C
PostgreSQL 业务用户列表,需要在 PG 集群层面进行定义。默认值为:[] 空列表。
每一个数组元素都是一个 用户/角色 定义,例如:
- name : dbuser_meta # 必需,`name` 是用户定义的唯一必选字段
password : DBUser.Meta # 可选,密码,可以是 scram-sha-256 哈希字符串或明文
login : true # 可选,默认情况下可以登录
superuser : false # 可选,默认为 false,是超级用户吗?
createdb : false # 可选,默认为 false,可以创建数据库吗?
createrole : false # 可选,默认为 false,可以创建角色吗?
inherit : true # 可选,默认情况下,此角色可以使用继承的权限吗?
replication : false # 可选,默认为 false,此角色可以进行复制吗?
bypassrls : false # 可选,默认为 false,此角色可以绕过行级安全吗?
pgbouncer : true # 可选,默认为 false,将此用户添加到 pgbouncer 用户列表吗?(使用连接池的生产用户应该显式定义为 true)
connlimit : -1 # 可选,用户连接限制,默认 -1 禁用限制
expire_in : 3650 # 可选,此角色过期时间:从创建时 + n天计算(优先级比 expire_at 更高)
expire_at : '2030-12-31' # 可选,此角色过期的时间点,使用 YYYY-MM-DD 格式的字符串指定一个特定日期(优先级没 expire_in 高)
comment : pigsty admin user # 可选,此用户/角色的说明与备注字符串
roles : [ dbrole_admin] # 可选,默认角色为:dbrole_{admin,readonly,readwrite,offline}
parameters : {} # 可选,使用 `ALTER ROLE SET` 针对这个角色,配置角色级的数据库参数
pool_mode : transaction # 可选,默认为 transaction 的 pgbouncer 池模式,用户级别
pool_connlimit : -1 # 可选,用户级别的最大数据库连接数,默认 -1 禁用限制
search_path : public # 可选,根据 postgresql 文档的键值配置参数(例如:使用 pigsty 作为默认 search_path)
pg_databases参数名称: pg_databases, 类型: database[], 层次:C
PostgreSQL 业务数据库列表,需要在 PG 集群层面进行定义。默认值为:[] 空列表。
每一个数组元素都是一个 业务数据库 定义,例如:
- name : meta # 必选,`name` 是数据库定义的唯一必选字段
baseline : cmdb.sql # 可选,数据库 sql 的基线定义文件路径(ansible 搜索路径中的相对路径,如 files/)
pgbouncer : true # 可选,是否将此数据库添加到 pgbouncer 数据库列表?默认为 true
schemas : [ pigsty] # 可选,要创建的附加模式,由模式名称字符串组成的数组
extensions : # 可选,要安装的附加扩展: 扩展对象的数组
- { name: postgis , schema : public } # 可以指定将扩展安装到某个模式中,也可以不指定(不指定则安装到 search_path 首位模式中)
- { name : timescaledb } # 例如有的扩展会创建并使用固定的模式,就不需要指定模式。
comment : pigsty meta database # 可选,数据库的说明与备注信息
owner : postgres # 可选,数据库所有者,默认为 postgres
template : template1 # 可选,要使用的模板,默认为 template1,目标必须是一个模板数据库
encoding : UTF8 # 可选,数据库编码,默认为 UTF8(必须与模板数据库相同)
locale : C # 可选,数据库地区设置,默认为 C(必须与模板数据库相同)
lc_collate : C # 可选,数据库 collate 排序规则,默认为 C(必须与模板数据库相同),没有理由不建议更改。
lc_ctype : C # 可选,数据库 ctype 字符集,默认为 C(必须与模板数据库相同)
tablespace : pg_default # 可选,默认表空间,默认为 'pg_default'
allowconn : true # 可选,是否允许连接,默认为 true。显式设置 false 将完全禁止连接到此数据库
revokeconn : false # 可选,撤销公共连接权限。默认为 false,设置为 true 时,属主和管理员之外用户的 CONNECT 权限会被回收
register_datasource : true # 可选,是否将此数据库注册到 grafana 数据源?默认为 true,显式设置为 false 会跳过注册
connlimit : -1 # 可选,数据库连接限制,默认为 -1 ,不限制,设置为正整数则会限制连接数。
pool_auth_user : dbuser_meta # 可选,连接到此 pgbouncer 数据库的所有连接都将使用此用户进行验证(启用 pgbouncer_auth_query 才有用)
pool_mode : transaction # 可选,数据库级别的 pgbouncer 池化模式,默认为 transaction
pool_size : 64 # 可选,数据库级别的 pgbouncer 默认池子大小,默认为 64
pool_size_reserve : 32 # 可选,数据库级别的 pgbouncer 池子保留空间,默认为 32,当默认池子不够用时,最多再申请这么多条突发连接。
pool_size_min : 0 # 可选,数据库级别的 pgbouncer 池的最小大小,默认为 0
pool_max_db_conn : 100 # 可选,数据库级别的最大数据库连接数,默认为 100
在每个数据库定义对象中,只有 name 是必选字段,其他的字段都是可选项。
pg_services参数名称: pg_services, 类型: service[], 层次:C
PostgreSQL 服务列表,需要在 PG 集群层面进行定义。默认值为:[] ,空列表。
用于在数据库集群层面定义额外的服务,数组中的每一个对象定义了一个服务 ,一个完整的服务定义样例如下:
- name : standby # 必选,服务名称,最终的 svc 名称会使用 `pg_cluster` 作为前缀,例如:pg-meta-standby
port : 5435 # 必选,暴露的服务端口(作为 kubernetes 服务节点端口模式)
ip : "*" # 可选,服务绑定的 IP 地址,默认情况下为所有 IP 地址
selector : "[]" # 必选,服务成员选择器,使用 JMESPath 来筛选配置清单
backup : "[? pg_role == `primary`]" # 可选,服务成员选择器(备份),也就是当默认选择器选中的实例都宕机后,服务才会由这里选中的实例成员来承载
dest : default # 可选,目标端口,default|postgres|pgbouncer|<port_number>,默认为 'default',Default的意思就是使用 pg_default_service_dest 的取值来最终决定
check : /sync # 可选,健康检查 URL 路径,默认为 /,这里使用 Patroni API:/sync ,只有同步备库和主库才会返回 200 健康状态码
maxconn : 5000 # 可选,允许的前端连接最大数,默认为5000
balance : roundrobin # 可选,haproxy 负载均衡算法(默认为 roundrobin,其他选项:leastconn)
options : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
请注意,本参数用于在集群层面添加额外的服务。如果您想在全局定义所有 PostgreSQL 数据库都要提供的服务,可以使用 pg_default_services 参数。
pg_hba_rules参数名称: pg_hba_rules, 类型: hba[], 层次:C
数据库集群/实例的客户端IP黑白名单规则。默认为:[] 空列表。
对象数组,每一个对象都代表一条规则, hba 规则对象的定义形式如下:
- title : allow intranet password access
role : common
rules :
- host all all 10.0.0.0/8 md5
- host all all 172.16.0.0/12 md5
- host all all 192.168.0.0/16 md5
title: 规则的标题名称,会被渲染为 HBA 文件中的注释。rules:规则数组,每个元素是一条标准的 HBA 规则字符串。role:规则的应用范围,哪些实例角色会启用这条规则?common:对于所有实例生效primary, replica,offline: 只针对特定的角色 pg_role 实例生效。特例:role: 'offline' 的规则除了会应用在 pg_role : offline 的实例上,对于带有 pg_offline_query 标记的实例也生效。 除了上面这种原生 HBA 规则定义形式,Pigsty 还提供了另外一种更为简便的别名形式:
- addr : 'intra' # world|intra|infra|admin|local|localhost|cluster|<cidr>
auth : 'pwd' # trust|pwd|ssl|cert|deny|<official auth method>
user : 'all' # all|${dbsu}|${repl}|${admin}|${monitor}|<user>|<group>
db : 'all' # all|replication|....
rules : [] # raw hba string precedence over above all
title : allow intranet password access
pg_default_hba_rules 与本参数基本类似,但它是用于定义全局的 HBA 规则,而本参数通常用于定制某个集群/实例的 HBA 规则。
pgb_hba_rules参数名称: pgb_hba_rules, 类型: hba[], 层次:C
Pgbouncer 业务HBA规则,默认值为: [], 空数组。
此参数与 pg_hba_rules 基本类似,都是 hba 规则对象的数组,区别在于本参数是为 Pgbouncer 准备的。
pgb_default_hba_rules 与本参数基本类似,但它是用于定义全局连接池 HBA 规则,而本参数通常用于定制某个连接池集群/实例的 HBA 规则。
pg_replication_username参数名称: pg_replication_username, 类型: username, 层次:G
PostgreSQL 物理复制用户名,默认使用 replicator,不建议修改此参数。
pg_replication_password参数名称: pg_replication_password, 类型: password, 层次:G
PostgreSQL 物理复制用户密码,默认值为:DBUser.Replicator。
警告:请在生产环境中修改此密码!
pg_admin_username参数名称: pg_admin_username, 类型: username, 层次:G
PostgreSQL / Pgbouncer 管理员名称,默认为:dbuser_dba。
这是全局使用的数据库管理员,具有数据库的 Superuser 权限与连接池的流量管理权限,请务必控制使用范围。
pg_admin_password参数名称: pg_admin_password, 类型: password, 层次:G
PostgreSQL / Pgbouncer 管理员密码,默认为: DBUser.DBA。
警告:请在生产环境中修改此密码!
pg_monitor_username参数名称: pg_monitor_username, 类型: username, 层次:G
PostgreSQL/Pgbouncer 监控用户名,默认为:dbuser_monitor。
这是一个用于监控的数据库/连接池用户,不建议修改此用户名。
但如果您的现有数据库使用了不同的监控用户,可以在指定监控目标时使用此参数传入使用的监控用户名。
pg_monitor_password参数名称: pg_monitor_password, 类型: password, 层次:G
PostgreSQL/Pgbouncer 监控用户使用的密码,默认为:DBUser.Monitor。
请尽可能不要在密码中使用 @:/ 这些容易与 URL 分隔符混淆的字符,减少不必要的麻烦。
警告:请在生产环境中修改此密码!
pg_dbsu_password参数名称: pg_dbsu_password, 类型: password, 层次:G/C
PostgreSQL pg_dbsu 超级用户密码,默认是空字符串,即不为其设置密码。
我们不建议为 dbsu 配置密码登陆,这会增大攻击面。例外情况是:pg_mode = citus,这时候需要为每个分片集群的 dbsu 配置密码,以便在分片集群内部进行连接。
PG_INSTALL本节负责安装 PostgreSQL 及其扩展。如果您希望安装不同大版本与扩展插件,修改 pg_version 与 pg_extensions 即可,不过请注意,并不是所有扩展都在所有大版本可用。
pg_dbsu : postgres # os 数据库超级用户名称,默认为 postgres,最好不要更改
pg_dbsu_uid : 26 # os 数据库超级用户 uid 和 gid,默认为 26,适用于默认的 postgres 用户和组
pg_dbsu_sudo : limit # 数据库超级用户 sudo 权限,可选 none,limit,all,nopass。默认为 limit
pg_dbsu_home : /var/lib/pgsql # postgresql 主目录,默认为 `/var/lib/pgsql`
pg_dbsu_ssh_exchange : true # 是否在相同的 pgsql 集群中交换 postgres 数据库超级用户的 ssh 密钥
pg_version : 18 # 要安装的 postgres 主版本,默认为 18
pg_bin_dir : /usr/pgsql/bin # postgres 二进制目录,默认为 `/usr/pgsql/bin`
pg_log_dir : /pg/log/postgres # postgres 日志目录,默认为 `/pg/log/postgres`
pg_packages : # pg packages to be installed, alias can be used
- pgsql-main pgsql-common
pg_extensions : [] # pg extensions to be installed, alias can be used
pg_dbsu参数名称: pg_dbsu, 类型: username, 层次:C
PostgreSQL 使用的操作系统 dbsu 用户名, 默认为 postgres,改这个用户名是不太明智的。
不过在特定情况下,您可能会使用到不同于 postgres 的用户名,例如在安装配置 Greenplum / MatrixDB 时,需要使用 gpadmin / mxadmin 作为相应的操作系统超级用户。
pg_dbsu_uid参数名称: pg_dbsu_uid, 类型: int, 层次:C
操作系统数据库超级用户的 uid 和 gid,26 是 PGDG RPM 默认的 postgres 用户 UID/GID。
对于 Debian/Ubuntu 系统,没有默认值,且 26 号用户经常被占用。因此Pigsty 在检测到安装环境为 Debian 系,且 uid 为 26 时,会自动使用替换的 pg_dbsu_uid = 543。
pg_dbsu_sudo参数名称: pg_dbsu_sudo, 类型: enum, 层次:C
数据库超级用户的 sudo 权限,可以是 none、limit、all 或 nopass。默认为 limit
none: 无 Sudo 权限
limit: 有限的 sudo 权限,用于执行与数据库相关的组件的 systemctl 命令(默认选项)。
all: 完全的 sudo 权限,需要密码。
nopass: 不需要密码的完全 sudo 权限(不推荐)。
默认值为 limit,只允许执行 sudo systemctl <start|stop|reload> <postgres|patroni|pgbouncer|...> 。
pg_dbsu_home参数名称: pg_dbsu_home, 类型: path, 层次:C
postgresql 主目录,默认为 /var/lib/pgsql,与官方的 pgdg RPM 保持一致。
pg_dbsu_ssh_exchange参数名称: pg_dbsu_ssh_exchange, 类型: bool, 层次:C
是否在同一 PostgreSQL 集群中交换操作系统 dbsu 的 ssh 密钥?
默认值为 true,意味着同一集群中的数据库超级用户可以互相 ssh 访问。
pg_version参数名称: pg_version, 类型: enum, 层次:C
要安装的 postgres 主版本,默认为 18。
请注意,PostgreSQL 的物理流复制不能跨主要版本,因此最好不要在实例级别上配置此项。
您可以使用 pg_packages 和 pg_extensions 中的参数来为特定的 PG 大版本安装不同的软件包与扩展。
pg_bin_dir参数名称: pg_bin_dir, 类型: path, 层次:C
PostgreSQL 二进制程序目录,默认为 /usr/pgsql/bin。
默认值是在安装过程中手动创建的软链接,指向安装的特定的 Postgres 版本目录。
例如 /usr/pgsql -> /usr/pgsql-15。在 Ubuntu/Debian 上则指向 /usr/lib/postgresql/15/bin。
更多详细信息,请查看 PGSQL 文件结构 。
pg_log_dir参数名称: pg_log_dir, 类型: path, 层次:C
PostgreSQL 日志目录,默认为:/pg/log/postgres,Vector 日志代理会使用此变量收集 PostgreSQL 日志。
请注意,如果日志目录 pg_log_dir 以数据库目录 pg_data 作为前缀,则不会显式创建(数据库目录初始化时自动创建)。
pg_packages参数名称: pg_packages, 类型: string[], 层次:C
要安装的 PostgreSQL 软件包(RPM/DEB),这是一个包名数组,元素可以是空格或逗号分隔的包别名。
Pigsty v4 将默认值收敛为两个别名:
pg_packages :
- pgsql-main pgsql-common
pgsql-main:映射到当前平台上的 PostgreSQL 内核、客户端、PL 语言以及 pg_repack、wal2json、pgvector 等核心扩展。pgsql-common:映射到运行数据库必需的配套组件,例如 Patroni、Pgbouncer、pgBackRest、pg_exporter、vip-manager 等守护进程。别名的具体定义可以在 roles/node_id/vars/ 中的 pg_package_map 查到,Pigsty 会先根据操作系统和架构解析别名,再将 $v/${pg_version} 替换为实际主版本 pg_version ,最后安装真实的软件包。这样可以屏蔽不同发行版之间的包名差异。
如果需要额外的软件包(例如特定 FDW 或扩展),可以直接在 pg_packages 中追加别名或真实包名。但请记得保留 pgsql-main pgsql-common,否则会缺失核心组件。
pg_extensions参数名称: pg_extensions, 类型: string[], 层次:G/C
要安装的 PostgreSQL 扩展包(RPM/DEB),这是一个由扩展包名或别名组成的数组。
从 v4 开始默认值为空列表 [],Pigsty 不再强制安装大体量扩展,用户可以按需选择,避免占用额外的磁盘与依赖。
如果需要安装扩展,请像下面这样填充:
pg_extensions :
- postgis timescaledb pgvector
- pgsql-fdw # 使用别名一次性安装常用 FDW
pg_package_map 中提供了大量别名,方便在不同发行版之间屏蔽包名差异。以下是 EL9 平台可用的扩展组合供参考(按需挑选即可):
pg_extensions: # extensions to be installed on this cluster
- timescaledb periods temporal_tables emaj table_version pg_cron pg_later pg_background pg_timetable
- postgis pgrouting pointcloud pg_h3 q3c ogr_fdw geoip #pg_geohash #mobilitydb
- pgvector pgvectorscale pg_vectorize pg_similarity pg_tiktoken pgml #smlar
- pg_search pg_bigm zhparser hunspell
- hydra pg_analytics pg_lakehouse pg_duckdb duckdb_fdw pg_fkpart pg_partman plproxy #pg_strom citus
- pg_hint_plan age hll rum pg_graphql pg_jsonschema jsquery index_advisor hypopg imgsmlr pg_ivm pgmq pgq #rdkit
- pg_tle plv8 pllua plprql pldebugger plpgsql_check plprofiler plsh #pljava plr pgtap faker dbt2
- prefix semver pgunit md5hash asn1oid roaringbitmap pgfaceting pgsphere pg_country pg_currency pgmp numeral pg_rational pguint ip4r timestamp9 chkpass #pg_uri #pgemailaddr #acl #debversion #pg_rrule
- topn pg_gzip pg_http pg_net pg_html5_email_address pgsql_tweaks pg_extra_time pg_timeit count_distinct extra_window_functions first_last_agg tdigest aggs_for_arrays pg_arraymath pg_idkit pg_uuidv7 permuteseq pg_hashids
- sequential_uuids pg_math pg_random pg_base36 pg_base62 floatvec pg_financial pgjwt pg_hashlib shacrypt cryptint pg_ecdsa pgpcre icu_ext envvar url_encode #pg_zstd #aggs_for_vecs #quantile #lower_quantile #pgqr #pg_protobuf
- pg_repack pg_squeeze pg_dirtyread pgfincore pgdd ddlx pg_prioritize pg_checksums pg_readonly safeupdate pg_permissions pgautofailover pg_catcheck preprepare pgcozy pg_orphaned pg_crash pg_cheat_funcs pg_savior table_log pg_fio #pgpool pgagent
- pg_profile pg_show_plans pg_stat_kcache pg_stat_monitor pg_qualstats pg_store_plans pg_track_settings pg_wait_sampling system_stats pg_meta pgnodemx pg_sqlog bgw_replstatus pgmeminfo toastinfo pagevis powa pg_top #pg_statviz #pgexporter_ext #pg_mon
- passwordcheck supautils pgsodium pg_vault anonymizer pg_tde pgsmcrypto pgaudit pgauditlogtofile pg_auth_mon credcheck pgcryptokey pg_jobmon logerrors login_hook set_user pg_snakeoil pgextwlist pg_auditor noset #sslutils
- wrappers multicorn odbc_fdw mysql_fdw tds_fdw sqlite_fdw pgbouncer_fdw mongo_fdw redis_fdw pg_redis_pubsub kafka_fdw hdfs_fdw firebird_fdw aws_s3 log_fdw #oracle_fdw #db2_fdw #jdbc_fdw
- orafce pgtt session_variable pg_statement_rollback pg_dbms_metadata pg_dbms_lock pgmemcache #pg_dbms_job #wiltondb
- pglogical pgl_ddl_deploy pg_failover_slots wal2json wal2mongo decoderbufs decoder_raw mimeo pgcopydb pgloader pg_fact_loader pg_bulkload pg_comparator pgimportdoc pgexportdoc #repmgr #slony
- gis-stack rag-stack fdw-stack fts-stack etl-stack feat-stack olap-stack supa-stack stat-stack json-stack
完整列表请参考:roles/node_id/vars
PG_BOOTSTRAP使用 Patroni 引导拉起 PostgreSQL 集群,并设置 1:1 对应的 Pgbouncer 连接池。
它还会使用 PG_PROVISION 中定义的默认角色、用户、权限、模式、扩展来初始化数据库集群
pg_data : /pg/data # postgres data directory, `/pg/data` by default
pg_fs_main : /data/postgres # postgres main data directory, `/data/postgres` by default
pg_fs_backup : /data/backups # postgres backup data directory, `/data/backups` by default
pg_storage_type : SSD # storage type for pg main data, SSD,HDD, SSD by default
pg_dummy_filesize : 64MiB # size of `/pg/dummy`, hold 64MB disk space for emergency use
pg_listen : '0.0.0.0' # postgres/pgbouncer listen addresses, comma separated list
pg_port : 5432 # postgres listen port, 5432 by default
pg_localhost : /var/run/postgresql # postgres unix socket dir for localhost connection
patroni_enabled : true # if disabled, no postgres cluster will be created during init
patroni_mode: default # patroni working mode : default,pause,remove
pg_namespace : /pg # top level key namespace in etcd, used by patroni & vip
patroni_port : 8008 # patroni listen port, 8008 by default
patroni_log_dir : /pg/log/patroni # patroni log dir, `/pg/log/patroni` by default
patroni_ssl_enabled : false # secure patroni RestAPI communications with SSL?
patroni_watchdog_mode: off # patroni watchdog mode : automatic,required,off. off by default
patroni_username : postgres # patroni restapi username, `postgres` by default
patroni_password : Patroni.API # patroni restapi password, `Patroni.API` by default
pg_etcd_password : '' # etcd password for this pg cluster, '' to use pg_cluster
pg_primary_db : postgres # primary database name, used by citus,etc... ,postgres by default
pg_parameters : {} # extra parameters in postgresql.auto.conf
pg_files : [] # extra files to be copied to postgres data directory (e.g. license)
pg_conf: oltp.yml # config template : oltp,olap,crit,tiny. `oltp.yml` by default
pg_max_conn : auto # postgres max connections, `auto` will use recommended value
pg_shared_buffer_ratio : 0.25 # postgres shared buffers ratio, 0.25 by default, 0.1~0.4
pg_io_method : worker # io method for postgres, auto,fsync,worker,io_uring, auto by default
pg_rto : 30 # recovery time objective in seconds, `30s` by default
pg_rpo : 1048576 # recovery point objective in bytes, `1MiB` at most by default
pg_libs : 'pg_stat_statements, auto_explain' # preloaded libraries, `pg_stat_statements,auto_explain` by default
pg_delay : 0 # replication apply delay for standby cluster leader
pg_checksum : true # enable data checksum for postgres cluster?
pg_pwd_enc: scram-sha-256 # passwords encryption algorithm : fixed to scram-sha-256
pg_encoding : UTF8 # database cluster encoding, `UTF8` by default
pg_locale : C # database cluster local, `C` by default
pg_lc_collate : C # database cluster collate, `C` by default
pg_lc_ctype : C # database character type, `C` by default
#pgsodium_key: "" # pgsodium key, 64 hex digit, default to sha256(pg_cluster)
#pgsodium_getkey_script: "" # pgsodium getkey script path, pgsodium_getkey by default
pg_data参数名称: pg_data, 类型: path, 层次:C
Postgres 数据目录,默认为 /pg/data。
这是一个指向底层实际数据目录的符号链接,在多处被使用,请不要修改它。参阅 PGSQL文件结构 获取详细信息。
pg_fs_main参数名称: pg_fs_main, 类型: path, 层次:C
PostgreSQL 主数据盘的挂载点/文件系统路径,默认为/data/postgres。
默认值:/data/postgres,它将直接用作 PostgreSQL 主数据目录的父目录。
建议使用 NVME SSD 作为 PostgreSQL 主数据存储,Pigsty默认为SSD存储进行了优化,但是也支持HDD。
您可以更改pg_storage_type 为HDD以针对HDD存储进行优化。
pg_fs_backup参数名称: pg_fs_backup, 类型: path, 层次:C
PostgreSQL 备份数据盘的挂载点/文件系统路径,默认为/data/backups。
如果您使用的是默认的 pgbackrest_method = local,建议为备份存储使用一个单独的磁盘。
备份磁盘应足够大,以容纳所有的备份,至少足以容纳3个基础备份+2天的WAL归档。 通常容量不是什么大问题,因为您可以使用便宜且大的机械硬盘作为备份盘。
建议为备份存储使用一个单独的磁盘,否则 Pigsty 将回退到主数据磁盘,并占用主数据盘的容量与IO。
pg_storage_type参数名称: pg_storage_type, 类型: enum, 层次:C
PostgreSQL 数据存储介质的类型:SSD或HDD,默认为SSD。
默认值:SSD,它会影响一些调优参数,如 random_page_cost 和 effective_io_concurrency 。
pg_dummy_filesize参数名称: pg_dummy_filesize, 类型: size, 层次:C
/pg/dummy的大小,默认值为64MiB,用于紧急使用的64MB磁盘空间。
当磁盘已满时,删除占位符文件可以为紧急使用释放一些空间,建议生产使用至少8GiB。
pg_listen参数名称: pg_listen, 类型: ip, 层次:C
PostgreSQL / Pgbouncer 的监听地址,默认为0.0.0.0(所有ipv4地址)。
您可以在此变量中使用占位符,例如:'${ip},${lo}'或'${ip},${vip},${lo}':
对于高安全性要求的生产环境,建议限制监听的IP地址。
pg_port参数名称: pg_port, 类型: port, 层次:C
PostgreSQL 服务器监听的端口,默认为 5432。
pg_localhost参数名称: pg_localhost, 类型: path, 层次:C
本地主机连接 PostgreSQL 使用的 Unix套接字目录,默认值为/var/run/postgresql。
PostgreSQL 和 Pgbouncer 本地连接的Unix套接字目录,pg_exporter 和 patroni 都会优先使用 Unix 套接字访问 PostgreSQL。
pg_namespace参数名称: pg_namespace, 类型: path, 层次:C
在 etcd 中使用的顶级命名空间,由 patroni 和 vip-manager 使用,默认值是:/pg,不建议更改。
patroni_enabled参数名称: patroni_enabled, 类型: bool, 层次:C
是否启用 Patroni ?默认值为:true。
如果禁用,则在初始化期间不会创建Postgres集群。Pigsty将跳过拉起 patroni的任务,当试图向现有的postgres实例添加一些组件时,可以使用此参数。
patroni_mode参数名称: patroni_mode, 类型: enum, 层次:C
Patroni 工作模式:default,pause,remove。默认值:default。
default:正常使用 Patroni 引导 PostgreSQL 集群pause:与default相似,但在引导后进入维护模式remove:使用Patroni初始化集群,然后删除Patroni并使用原始 PostgreSQL。patroni_port参数名称: patroni_port, 类型: port, 层次:C
patroni监听端口,默认为8008,不建议更改。
Patroni API服务器在此端口上监听健康检查和API请求。
patroni_log_dir参数名称: patroni_log_dir, 类型: path, 层次:C
patroni 日志目录,默认为 /pg/log/patroni,由 Vector 日志代理收集。
patroni_ssl_enabled参数名称: patroni_ssl_enabled, 类型: bool, 层次:G
使用SSL保护patroni RestAPI通信吗?默认值为false。
此参数是一个全局标志,只能在部署之前预先设置。因为如果为 patroni 启用了SSL,您将必须使用 HTTPS 而不是 HTTP 执行健康检查、获取指标,调用API。
patroni_watchdog_mode参数名称: patroni_watchdog_mode, 类型: string, 层次:C
patroni看门狗模式:automatic,required,off,默认值为 off。
在主库故障的情况下,Patroni 可以使用看门狗 来强制关机旧主库节点以避免脑裂。
off:不使用看门狗。完全不进行 Fencing (默认行为)automatic:如果内核启用了softdog模块并且看门狗属于dbsu,则启用 watchdog。required:强制启用 watchdog,如果softdog不可用则拒绝启动 Patroni/PostgreSQL。默认值为off,您不应该在 Infra节点 启用看门狗,数据一致性优先于可用性的关键系统,特别是与钱有关的业务集群可以考虑打开此选项。
请注意,如果您的所有访问流量都使用 HAproxy 健康检查服务接入 ,正常是不存在脑裂风险的。
patroni_username参数名称: patroni_username, 类型: username, 层次:C
Patroni REST API 用户名,默认为postgres,与patroni_password 配对使用。
Patroni的危险 REST API (比如重启集群)由额外的用户名/密码保护,查看配置集群 和Patroni RESTAPI 以获取详细信息。
patroni_password参数名称: patroni_password, 类型: password, 层次:C
Patroni REST API 密码,默认为Patroni.API。
警告:务必生产环境中修改此参数!
pg_primary_db参数名称: pg_primary_db, 类型: string, 层次:C
指定集群中的主数据库名称,用于 citus 等业务数据库,默认为 postgres。
例如,在使用 Patroni 管理高可用的 Citus 集群时,您必须选择一个 “主数据库”。
此外,在这里指定的数据库名称,将在 PGSQL 模块安装完成后,显示在打印的连接串中。
pg_parameters参数名称: pg_parameters, 类型: dict, 层次:G/C/I
可用于指定并管理 postgresql.auto.conf 中的配置参数。
当集群所有实例完成初始化后,pg_param 任务将会把本字典中的 key / value 键值对依次覆盖写入 /pg/data/postgresql.auto.conf 中。
注意:请不要手工修改该配置文件,或通过 ALTER SYSTEM 修改集群配置参数,修改会在下一次配置同步时被覆盖。
该变量的优先级大于 Patroni / DCS 中的集群配置(即优先级高于集群配置,由 Patroni edit-config 编辑的配置),因此通常可以在实例级别覆盖集群默认参数。
当您的集群成员有着不同的规格(不推荐的行为!)时,您可以通过本参数对每个实例的配置进行精细化管理。
pg-test :
hosts :
10.10.10.11 : { pg_seq: 1, pg_role: primary , pg_parameters : { shared_buffers : '5GB' } }
10.10.10.12 : { pg_seq: 2, pg_role: replica , pg_parameters : { shared_buffers : '4GB' } }
10.10.10.13 : { pg_seq: 3, pg_role: replica , pg_parameters : { shared_buffers : '3GB' } }
请注意,一些 重要的集群参数 (对主从库参数值有要求)是 Patroni 直接通过命令行参数管理的,具有最高优先级,无法通过此方式覆盖,对于这些参数,您必须使用 Patroni edit-config 进行管理与配置。
在主从上必须保持一致的 PostgreSQL 参数(不一致会导致从库无法启动!):
wal_levelmax_connectionsmax_locks_per_transactionmax_worker_processesmax_prepared_transactionstrack_commit_timestamp在主从上最好保持一致的参数(考虑到主从切换的可能性):
listen_addressesportcluster_namehot_standbywal_log_hintsmax_wal_sendersmax_replication_slotswal_keep_segmentswal_keep_size您可以设置不存在的参数(例如来自扩展的 GUC,从而配置 ALTER SYSTEM 无法修改的“尚未存在”的参数),但将现有配置修改为非法值可能会导致 PostgreSQL 无法启动,请谨慎配置!
pg_files参数名称: pg_files, 类型: path[], 层次:C
用于指定需要拷贝至PGDATA目录的文件列表,默认为空数组:[]
在本参数中指定的文件将会被拷贝至 {{ pg_data }} 目录下,这主要用于下发特殊商业版本 PostgreSQL 内核要求的 License 文件。
目前仅有 PolarDB (Oracle兼容)内核需要许可证文件,例如,您可以将 license.lic 文件放置在 files/ 目录下,并在 pg_files 中指定:
pg_files : [ license.lic ]
pg_conf参数名称: pg_conf, 类型: enum, 层次:C
配置模板:{oltp,olap,crit,tiny}.yml,默认为oltp.yml。
tiny.yml:为小节点、虚拟机、小型演示优化(1-8核,1-16GB)oltp.yml:为OLTP工作负载和延迟敏感应用优化(4C8GB+)(默认模板)olap.yml:为OLAP工作负载和吞吐量优化(4C8G+)crit.yml:为数据一致性和关键应用优化(4C8G+)默认值:oltp.yml,但是配置 程序将在当前节点为小节点时将此值设置为 tiny.yml。
您可以拥有自己的模板,只需将其放在templates/<mode>.yml下,并将此值设置为模板名称即可使用。
pg_max_conn参数名称: pg_max_conn, 类型: int, 层次:C
PostgreSQL 服务器最大连接数。你可以选择一个介于 50 到 5000 之间的值,或使用 auto 选择推荐值。
默认值为 auto,会根据 pg_conf 和 pg_default_service_dest 来设定最大连接数。
tiny: 100 olap: 200 oltp: 200 (pgbouncer) / 1000 (postgres)pg_default_service_dest = pgbouncer : 200 pg_default_service_dest = postgres : 1000 crit: 200 (pgbouncer) / 1000 (postgres)pg_default_service_dest = pgbouncer : 200 pg_default_service_dest = postgres : 1000 不建议将此值设定为超过 5000,否则你还需要手动增加 haproxy 服务的连接限制。
Pgbouncer 的事务池可以缓解过多的 OLTP 连接问题,因此默认情况下不建议设置很大的连接数。
对于 OLAP 场景, pg_default_service_dest 修改为 postgres 可以绕过连接池。
pg_shared_buffer_ratio参数名称: pg_shared_buffer_ratio, 类型: float, 层次:C
Postgres 共享缓冲区内存比例,默认为 0.25,正常范围在 0.1~0.4 之间。
默认值:0.25,意味着节点内存的 25% 将被用作 PostgreSQL 的分片缓冲区。如果您想为 PostgreSQL 启用大页,那么此参数值应当适当小于 node_hugepage_ratio 。
将此值设定为大于 0.4(40%)通常不是好主意,但在极端情况下可能有用。
注意,共享缓冲区只是 PostgreSQL 中共享内存的一部分,要计算总共享内存,使用 show shared_memory_size_in_huge_pages;。
pg_rto参数名称: pg_rto, 类型: int, 层次:C
以秒为单位的恢复时间目标(RTO)。这将用于计算 Patroni 的 TTL 值,默认为 30 秒。
如果主实例在这么长时间内失踪,将触发新的领导者选举,此值并非越低越好,它涉及到利弊权衡:
减小这个值可以减少集群故障转移期间的不可用时间(无法写入), 但会使集群对短期网络抖动更加敏感,从而增加误报触发故障转移的几率。
您需要根据网络状况和业务约束来配置这个值,在故障几率和故障影响之间做出权衡 , 默认值是 30s,它将影响以下的 Patroni 参数:
# 获取领导者租约的 TTL(以秒为单位)。将其视为启动自动故障转移过程之前的时间长度。默认值:30
ttl : {{ pg_rto }}
# 循环将休眠的秒数。默认值:10,这是 patroni 检查循环间隔
loop_wait : {{ (pg_rto / 3)|round(0, 'ceil')|int }}
# DCS 和 PostgreSQL 操作重试的超时时间(以秒为单位)。比这短的 DCS 或网络问题不会导致 Patroni 降级领导。默认值:10
retry_timeout : {{ (pg_rto / 3)|round(0, 'ceil')|int }}
# 主实例在触发故障转移之前允许从故障中恢复的时间(以秒为单位),最大 RTO:2 倍循环等待 + primary_start_timeout
primary_start_timeout : {{ (pg_rto / 3)|round(0, 'ceil')|int }}
pg_rpo参数名称: pg_rpo, 类型: int, 层次:C
以字节为单位的恢复点目标(RPO),默认值:1048576。
默认为 1MiB,这意味着在故障转移期间最多可以容忍 1MiB 的数据丢失。
当主节点宕机并且所有副本都滞后时,你必须做出一个艰难的选择,在可用性和一致性之间进行权衡 :
提升一个从库成为新的主库,并尽快将系统恢复服务,但要付出可接受的数据丢失代价(例如,少于 1MB)。 等待主库重新上线(可能永远不会),或人工干预以避免任何数据丢失。 你可以使用 crit.yml conf 模板来确保在故障转移期间没有数据丢失,但这会牺牲一些性能。
pg_libs参数名称: pg_libs, 类型: string, 层次:C
预加载的动态共享库,默认为 pg_stat_statements,auto_explain,这是两个 PostgreSQL 自带的扩展,强烈建议启用。
对于现有集群,您可以直接配置集群 的 shared_preload_libraries 参数并应用生效。
如果您想使用 TimescaleDB 或 Citus 扩展,您需要将 timescaledb 或 citus 添加到此列表中。timescaledb 和 citus 应当放在这个列表的最前面,例如:
citus,timescaledb,pg_stat_statements,auto_explain
其他需要动态加载的扩展也可以添加到这个列表中,例如 pg_cron, pgml 等,通常 citus 和 timescaledb 有着最高的优先级,应该添加到列表的最前面。
pg_delay参数名称: pg_delay, 类型: interval, 层次:I
延迟备库复制延迟,默认值:0。
如果此值被设置为一个正值,备用集群主库在应用 WAL 变更之前将被延迟这个时间。设置为 1h 意味着该集群中的数据将始终滞后原集群一个小时。
查看 延迟备用集群 以获取详细信息。
pg_checksum参数名称: pg_checksum, 类型: bool, 层次:C
为 PostgreSQL 集群启用数据校验和吗?默认值是 true,启用。
这个参数只能在 PGSQL 部署之前设置(但你可以稍后手动启用它)。
数据校验和可以帮助检测磁盘损坏和硬件故障,从 Pigsty v3.5 开始默认启用此功能以确保数据完整性。
pg_pwd_enc参数名称: pg_pwd_enc, 类型: enum, 层次:C
密码加密算法,Pigsty v4 以后固定为 scram-sha-256。
所有新建用户都会使用 SCRAM 凭据。md5 已被淘汰,如需兼容旧客户端,请在业务连接池或客户端驱动中升级至 SCRAM。
pg_encoding参数名称: pg_encoding, 类型: enum, 层次:C
数据库集群编码,默认为 UTF8。
不建议使用其他非 UTF8 系编码。
pg_locale参数名称: pg_locale, 类型: enum, 层次:C
数据库集群本地化规则集 (Locale),默认为 C。
此参数控制数据库的默认 Locale 设置,影响排序规则、字符分类等行为。使用 C 或 POSIX 可以获得最佳的性能和可预测的排序行为。
如果您需要特定语言的本地化支持,可以设置为相应的 Locale,例如 en_US.UTF-8 或 zh_CN.UTF-8。请注意,Locale 设置会影响索引的排序顺序,因此在集群初始化后无法更改。
pg_lc_collate参数名称: pg_lc_collate, 类型: enum, 层次:C
数据库集群本地化排序规则,默认为 C。
除非您知道自己在做什么,否则不建议修改集群级别的本地排序规则设置。
pg_lc_ctype参数名称: pg_lc_ctype, 类型: enum, 层次:C
数据库字符集 CTYPE,默认为 C。
从 Pigsty v3.5 开始,为了与 pg_lc_collate 保持一致,默认值改为 C。
pg_io_method参数名称: pg_io_method, 类型: enum, 层次:C
PostgreSQL 的 IO 方法,默认为 worker。可选值包括:
auto:根据操作系统自动选择,在 Debian 系列或 EL 10+ 上使用 io_uring,否则使用 workersync:使用传统的同步 IO 方式worker:使用后台工作进程处理 IO(默认选项)io_uring:使用 Linux 的 io_uring 异步 IO 接口此参数仅适用于 PostgreSQL 17 及以上版本,控制 PostgreSQL 数据块层的 IO 策略。
在 PostgreSQL 17 中,io_uring 可以提供更高的 IO 性能,但需要操作系统内核支持(Linux 5.1+)并安装 liburing 库。 在 PostgreSQL 18 中,默认 IO 方法已从 sync 改为 worker,使用后台工作进程处理异步 IO,无需额外依赖。 如果您使用 Debian 12/Ubuntu 22+ 或 EL 10+ 系统,并希望获得最佳 IO 性能,可以考虑设置为 io_uring。 请注意,在不支持 io_uring 的系统上设置此值可能导致 PostgreSQL 启动失败,因此 auto 或 worker 是更安全的选择。
pg_etcd_password参数名称: pg_etcd_password, 类型: password, 层次:C
此 PostgreSQL 集群在 etcd 中使用的密码,默认为空字符串 ''。
如果设置为空字符串,则会使用 pg_cluster 参数值作为密码(对于 Citus 集群则使用 pg_shard 参数值)。
此密码用于 Patroni 连接 etcd 以及 vip-manager 访问 etcd 时的认证。
pgsodium_key参数名称: pgsodium_key, 类型: string, 层次:C
用于 pgsodium 扩展的加密主密钥,由 64 位十六进制数字组成。
默认不设置此参数,如果未指定,Pigsty 会使用 sha256(pg_cluster) 的值自动生成一个确定性的密钥。
pgsodium 是一个基于 libsodium 的 PostgreSQL 扩展,提供加密函数和透明列加密功能。
如果您需要使用 pgsodium 的加密功能,建议显式指定一个安全的随机密钥,并妥善保管。
生成随机密钥的命令示例:
openssl rand -hex 32 # 生成 64 位十六进制密钥
pgsodium_getkey_script参数名称: pgsodium_getkey_script, 类型: path, 层次:C
pgsodium 获取密钥脚本的路径,默认使用 Pigsty 模板中的 pgsodium_getkey 脚本。
此脚本用于在 PostgreSQL 启动时获取 pgsodium 的主密钥。默认脚本会从环境变量或配置文件中读取密钥。
如果您有自定义的密钥管理需求(如使用 HashiCorp Vault、AWS KMS 等),可以提供自定义脚本路径。
PG_PROVISION如果说 PG_BOOTSTRAP 是创建一个新的集群,那么 PG_PROVISION 就是在集群中创建默认的对象,包括:
pg_provision : true # 在引导后提供postgres集群
pg_init : pg-init # 集群模板的初始化脚本,默认为`pg-init`
pg_default_roles : # postgres集群中的默认角色和用户
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 ,comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor, dbrole_readonly] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
pg_default_privileges : # 管理员用户创建时的默认权限
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
pg_default_schemas : [ monitor ] # 默认模式
pg_default_extensions : # 默认扩展
- { name: pg_stat_statements ,schema : monitor }
- { name: pgstattuple ,schema : monitor }
- { name: pg_buffercache ,schema : monitor }
- { name: pageinspect ,schema : monitor }
- { name: pg_prewarm ,schema : monitor }
- { name: pg_visibility ,schema : monitor }
- { name: pg_freespacemap ,schema : monitor }
- { name: postgres_fdw ,schema : public }
- { name: file_fdw ,schema : public }
- { name: btree_gist ,schema : public }
- { name: btree_gin ,schema : public }
- { name: pg_trgm ,schema : public }
- { name: intagg ,schema : public }
- { name: intarray ,schema : public }
- { name : pg_repack }
pg_reload : true # HBA变化后是否重载配置?
pg_default_hba_rules : # postgres 默认 HBA 规则集
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title : 'replicator replication from localhost' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title : 'replicator replication from intranet' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title : 'replicator postgres db from intranet' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title : 'monitor from infra host with password' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title : 'admin @ everywhere with ssl & pwd' }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title : 'pgbouncer read/write via local socket' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title : 'read/write biz user via password' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title : 'allow etl offline tasks from intranet' }
pgb_default_hba_rules : # pgbouncer 默认 HBA 规则集
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title : 'dbsu local admin access with os ident' }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title : 'allow all user local access with pwd' }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: pwd ,title : 'monitor access via intranet with pwd' }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other monitor access addr' }
- {user : '${admin}' ,db: all ,addr: intra ,auth: pwd ,title : 'admin access via intranet with pwd' }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other admin access addr' }
- {user: 'all' ,db: all ,addr: intra ,auth: pwd ,title : 'allow all user intra access with pwd' }
pg_provision参数名称: pg_provision, 类型: bool, 层次:C
在集群拉起后,完整本节定义的 PostgreSQL 集群置备工作。默认值为true。
如果禁用,不会置备 PostgreSQL 集群。对于一些特殊的 “PostgreSQL” 集群,比如 Greenplum,可以关闭此选项跳过置备阶段。
pg_init参数名称: pg_init, 类型: string, 层次:G/C
用于初始化数据库模板的Shell脚本位置,默认为 pg-init,该脚本会被拷贝至/pg/bin/pg-init后执行。
该脚本位于 roles/pgsql/templates/pg-init
你可以在该脚本中添加自己的逻辑,或者提供一个新的脚本放置在 templates/ 目录下,并将 pg_init 设置为新的脚本名称。使用自定义脚本时请保留现有的初始化逻辑。
pg_default_roles参数名称: pg_default_roles, 类型: role[], 层次:G/C
Postgres 集群中的默认角色和用户。
Pigsty有一个内置的角色系统,请查看PGSQL访问控制:角色系统 了解详情。
pg_default_roles : # postgres集群中的默认角色和用户
- { name: dbrole_readonly ,login: false ,comment : role for global read-only access }
- { name: dbrole_offline ,login: false ,comment : role for restricted read-only access }
- { name: dbrole_readwrite ,login: false ,roles: [dbrole_readonly] ,comment : role for global read-write access }
- { name: dbrole_admin ,login: false ,roles: [pg_monitor, dbrole_readwrite] ,comment : role for object creation }
- { name: postgres ,superuser: true ,comment : system superuser }
- { name: replicator ,replication: true ,roles: [pg_monitor, dbrole_readonly] ,comment : system replicator }
- { name: dbuser_dba ,superuser: true ,roles: [dbrole_admin] ,pgbouncer: true ,pool_mode: session, pool_connlimit: 16 , comment : pgsql admin user }
- { name: dbuser_monitor ,roles: [pg_monitor, dbrole_readonly] ,pgbouncer: true ,parameters : {log_min_duration_statement: 1000 } ,pool_mode: session ,pool_connlimit: 8 ,comment : pgsql monitor user }
pg_default_privileges参数名称: pg_default_privileges, 类型: string[], 层次:G/C
每个数据库中的默认权限(DEFAULT PRIVILEGE)设置:
pg_default_privileges : # 管理员用户创建时的默认权限
- GRANT USAGE ON SCHEMAS TO dbrole_readonly
- GRANT SELECT ON TABLES TO dbrole_readonly
- GRANT SELECT ON SEQUENCES TO dbrole_readonly
- GRANT EXECUTE ON FUNCTIONS TO dbrole_readonly
- GRANT USAGE ON SCHEMAS TO dbrole_offline
- GRANT SELECT ON TABLES TO dbrole_offline
- GRANT SELECT ON SEQUENCES TO dbrole_offline
- GRANT EXECUTE ON FUNCTIONS TO dbrole_offline
- GRANT INSERT ON TABLES TO dbrole_readwrite
- GRANT UPDATE ON TABLES TO dbrole_readwrite
- GRANT DELETE ON TABLES TO dbrole_readwrite
- GRANT USAGE ON SEQUENCES TO dbrole_readwrite
- GRANT UPDATE ON SEQUENCES TO dbrole_readwrite
- GRANT TRUNCATE ON TABLES TO dbrole_admin
- GRANT REFERENCES ON TABLES TO dbrole_admin
- GRANT TRIGGER ON TABLES TO dbrole_admin
- GRANT CREATE ON SCHEMAS TO dbrole_admin
Pigsty 基于默认角色系统提供了相应的默认权限设置,请查看PGSQL访问控制:权限 了解详情。
pg_default_schemas参数名称: pg_default_schemas, 类型: string[], 层次:G/C
要创建的默认模式,默认值为:[ monitor ],这将在所有数据库上创建一个monitor模式,用于放置各种监控扩展、表、视图、函数。
pg_default_extensions参数名称: pg_default_extensions, 类型: extension[], 层次:G/C
要在所有数据库中默认创建启用的扩展列表,默认值:
pg_default_extensions : # default extensions to be created
- { name: pg_stat_statements ,schema : monitor }
- { name: pgstattuple ,schema : monitor }
- { name: pg_buffercache ,schema : monitor }
- { name: pageinspect ,schema : monitor }
- { name: pg_prewarm ,schema : monitor }
- { name: pg_visibility ,schema : monitor }
- { name: pg_freespacemap ,schema : monitor }
- { name: postgres_fdw ,schema : public }
- { name: file_fdw ,schema : public }
- { name: btree_gist ,schema : public }
- { name: btree_gin ,schema : public }
- { name: pg_trgm ,schema : public }
- { name: intagg ,schema : public }
- { name: intarray ,schema : public }
- { name : pg_repack }
唯一的三方扩展是 pg_repack,这对于数据库维护很重要,所有其他扩展都是内置的 PostgreSQL Contrib 扩展插件。
监控相关的扩展默认安装在 monitor 模式中,该模式由pg_default_schemas 创建。
pg_reload参数名称: pg_reload, 类型: bool, 层次:A
在hba更改后重新加载 PostgreSQL,默认值为true
当您想在应用HBA更改之前进行检查时,将其设置为false以禁用自动重新加载配置。
pg_default_hba_rules参数名称: pg_default_hba_rules, 类型: hba[], 层次:G/C
PostgreSQL 基于主机的认证规则,全局默认规则定义。默认值为:
pg_default_hba_rules : # postgres default host-based authentication rules
- {user : '${dbsu}' ,db: all ,addr: local ,auth: ident ,title : 'dbsu access via local os user ident' }
- {user : '${dbsu}' ,db: replication ,addr: local ,auth: ident ,title : 'dbsu replication from local os ident' }
- {user : '${repl}' ,db: replication ,addr: localhost ,auth: pwd ,title : 'replicator replication from localhost' }
- {user : '${repl}' ,db: replication ,addr: intra ,auth: pwd ,title : 'replicator replication from intranet' }
- {user : '${repl}' ,db: postgres ,addr: intra ,auth: pwd ,title : 'replicator postgres db from intranet' }
- {user : '${monitor}' ,db: all ,addr: localhost ,auth: pwd ,title : 'monitor from localhost with password' }
- {user : '${monitor}' ,db: all ,addr: infra ,auth: pwd ,title : 'monitor from infra host with password' }
- {user : '${admin}' ,db: all ,addr: infra ,auth: ssl ,title : 'admin @ infra nodes with pwd & ssl' }
- {user : '${admin}' ,db: all ,addr: world ,auth: ssl ,title : 'admin @ everywhere with ssl & pwd' }
- {user: '+dbrole_readonly',db: all ,addr: localhost ,auth: pwd ,title : 'pgbouncer read/write via local socket' }
- {user: '+dbrole_readonly',db: all ,addr: intra ,auth: pwd ,title : 'read/write biz user via password' }
- {user: '+dbrole_offline' ,db: all ,addr: intra ,auth: pwd ,title : 'allow etl offline tasks from intranet' }
默认值为常见场景提供了足够的安全级别,请查看PGSQL身份验证 了解详情。
本参数为 HBA 规则对象组成的数组,在形式上与 pg_hba_rules 完全一致。
建议在全局配置统一的 pg_default_hba_rules ,针对特定集群使用 pg_hba_rules 进行额外定制。两个参数中的规则都会依次应用,后者优先级更高。
pgb_default_hba_rules参数名称: pgb_default_hba_rules, 类型: hba[], 层次:G/C
pgbouncer default host-based authentication rules, array or hba rule object.
default value provides a fair enough security level for common scenarios, check PGSQL Authentication for details.
pgb_default_hba_rules : # pgbouncer default host-based authentication rules
- {user : '${dbsu}' ,db: pgbouncer ,addr: local ,auth: peer ,title : 'dbsu local admin access with os ident' }
- {user: 'all' ,db: all ,addr: localhost ,auth: pwd ,title : 'allow all user local access with pwd' }
- {user : '${monitor}' ,db: pgbouncer ,addr: intra ,auth: pwd ,title : 'monitor access via intranet with pwd' }
- {user : '${monitor}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other monitor access addr' }
- {user : '${admin}' ,db: all ,addr: intra ,auth: pwd ,title : 'admin access via intranet with pwd' }
- {user : '${admin}' ,db: all ,addr: world ,auth: deny ,title : 'reject all other admin access addr' }
- {user: 'all' ,db: all ,addr: intra ,auth: pwd ,title : 'allow all user intra access with pwd' }
默认的Pgbouncer HBA规则很简单:
允许从本地 使用密码登陆 允许从内网网断使用密码登陆 用户可以按照自己的需求进行定制。
本参数在形式上与 pgb_hba_rules 完全一致,建议在全局配置统一的 pgb_default_hba_rules ,针对特定集群使用 pgb_hba_rules 进行额外定制。两个参数中的规则都会依次应用,后者优先级更高。
PG_BACKUP本节定义了用于 pgBackRest 的变量,它被用于 PGSQL 时间点恢复 PITR 。
查看 PGSQL 备份 & PITR 以获取详细信息。
pgbackrest_enabled : true # 在 pgsql 主机上启用 pgBackRest 吗?
pgbackrest_clean : true # 初始化时删除 pg 备份数据?
pgbackrest_log_dir : /pg/log/pgbackrest # pgbackrest 日志目录,默认为 `/pg/log/pgbackrest`
pgbackrest_method : local # pgbackrest 仓库方法:local, minio, [用户定义...]
pgbackrest_init_backup : true # pgbackrest 初始化完成后是否立即执行全量备份?
pgbackrest_repo : # pgbackrest 仓库:https://pgbackrest.org/configuration.html#section-repository
local : # 默认使用本地 posix 文件系统的 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按计数保留完整备份
retention_full : 2 # 使用本地文件系统仓库时,最多保留 3 个完整备份,至少保留 2 个
minio : # pgbackrest 的可选 minio 仓库
type : s3 # minio 是与 s3 兼容的,所以使用 s3
s3_endpoint : sss.pigsty # minio 端点域名,默认为 `sss.pigsty`
s3_region : us-east-1 # minio 区域,默认为 us-east-1,对 minio 无效
s3_bucket : pgsql # minio 桶名称,默认为 `pgsql`
s3_key : pgbackrest # pgbackrest 的 minio 用户访问密钥
s3_key_secret : S3User.Backup # pgbackrest 的 minio 用户秘密密钥
s3_uri_style : path # 对 minio 使用路径风格的 uri,而不是主机风格
path : /pgbackrest # minio 备份路径,默认为 `/pgbackrest`
storage_port : 9000 # minio 端口,默认为 9000
storage_ca_file : /etc/pki/ca.crt # minio ca 文件路径,默认为 `/etc/pki/ca.crt`
block : y # 启用块级增量备份(pgBackRest 2.46+)
bundle : y # 将小文件打包成一个文件
bundle_limit : 20MiB # 对象存储文件打包阈值,默认 20MiB
bundle_size : 128MiB # 对象存储文件打包目标大小,默认 128MiB
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 在 minio 仓库上按时间保留完整备份
retention_full : 14 # 保留过去 14 天的完整备份
pgbackrest_enabled参数名称: pgbackrest_enabled, 类型: bool, 层次:C
是否在 PGSQL 节点上启用 pgBackRest?默认值为: true
在使用本地文件系统备份仓库(local)时,只有集群主库才会真正启用 pgbackrest。其他实例只会初始化一个空仓库。
pgbackrest_clean参数名称: pgbackrest_clean, 类型: bool, 层次:C
初始化时删除 PostgreSQL 备份数据吗?默认值为 true。
pgbackrest_log_dir参数名称: pgbackrest_log_dir, 类型: path, 层次:C
pgBackRest 日志目录,默认为 /pg/log/pgbackrest,Vector 日志代理会引用此参数收集日志。
pgbackrest_method参数名称: pgbackrest_method, 类型: enum, 层次:C
pgBackRest 仓库方法:默认可选项为:local、minio 或其他用户定义的方法,默认为 local。
此参数用于确定用于 pgBackRest 的仓库,所有可用的仓库方法都在 pgbackrest_repo 中定义。
Pigsty 默认使用 local 备份仓库,这将在主实例的 /pg/backup 目录上创建一个备份仓库。底层存储路径由 pg_fs_backup 指定。
pgbackrest_init_backup参数名称: pgbackrest_init_backup, 类型: bool, 层次:C
在 pgBackRest 初始化完成后是否立即执行一次全量备份?默认为 true。
此操作仅在集群主库(primary)且非级联从库(无 pg_upstream 定义)时执行。启用此参数可以确保在集群初始化后立即拥有一个基础备份,以便在需要时进行恢复。
pgbackrest_repo参数名称: pgbackrest_repo, 类型: dict, 层次:G/C
pgBackRest 仓库文档:https://pgbackrest.org/configuration.html#section-repository
默认值包括两种仓库方法:local 和 minio,定义如下:
pgbackrest_repo : # pgbackrest 仓库:https://pgbackrest.org/configuration.html#section-repository
local : # 默认使用本地 posix 文件系统的 pgbackrest 仓库
path : /pg/backup # 本地备份目录,默认为 `/pg/backup`
retention_full_type : count # 按计数保留完整备份
retention_full : 2 # 使用本地文件系统仓库时,最多保留 3 个完整备份,至少保留 2 个
minio : # pgbackrest 的可选 minio 仓库
type : s3 # minio 是与 s3 兼容的,所以使用 s3
s3_endpoint : sss.pigsty # minio 端点域名,默认为 `sss.pigsty`
s3_region : us-east-1 # minio 区域,默认为 us-east-1,对 minio 无效
s3_bucket : pgsql # minio 桶名称,默认为 `pgsql`
s3_key : pgbackrest # pgbackrest 的 minio 用户访问密钥
s3_key_secret : S3User.Backup # pgbackrest 的 minio 用户秘密密钥
s3_uri_style : path # 对 minio 使用路径风格的 uri,而不是主机风格
path : /pgbackrest # minio 备份路径,默认为 `/pgbackrest`
storage_port : 9000 # minio 端口,默认为 9000
storage_ca_file : /etc/pki/ca.crt # minio ca 文件路径,默认为 `/etc/pki/ca.crt`
block : y # 启用块级增量备份(pgBackRest 2.46+)
bundle : y # 将小文件打包成一个文件
bundle_limit : 20MiB # 对象存储文件打包阈值,默认 20MiB
bundle_size : 128MiB # 对象存储文件打包目标大小,默认 128MiB
cipher_type : aes-256-cbc # 为远程备份仓库启用 AES 加密
cipher_pass : pgBackRest # AES 加密密码,默认为 'pgBackRest'
retention_full_type : time # 在 minio 仓库上按时间保留完整备份
retention_full : 14 # 保留过去 14 天的完整备份
您可以定义新的备份仓库,例如使用 AWS S3,GCP 或其他云供应商的 S3 兼容存储服务。
块级增量备份 (Block Incremental Backup) :从 pgBackRest 2.46 版本开始支持 block: y 选项,可以实现块级增量备份。
这意味着在增量备份时,pgBackRest 只会备份发生变化的数据块,而不是整个变化的文件,从而大幅减少备份数据量和备份时间。
此功能对于大型数据库特别有用,建议在对象存储仓库上启用此选项。
PG_ACCESS本节负责数据库访问路径,包括:
在每个 PGSQL 节点上部署 Pgbouncer 连接池并设定默认行为 通过本地或专用 haproxy 节点发布服务端口 绑定可选的 L2 VIP、注册 DNS 记录 pgbouncer_enabled : true # if disabled, pgbouncer will not be launched on pgsql host
pgbouncer_port : 6432 # pgbouncer listen port, 6432 by default
pgbouncer_log_dir : /pg/log/pgbouncer # pgbouncer log dir, `/pg/log/pgbouncer` by default
pgbouncer_auth_query : false # query postgres to retrieve unlisted business users?
pgbouncer_poolmode: transaction # pooling mode : transaction,session,statement, transaction by default
pgbouncer_sslmode : disable # pgbouncer client ssl mode, disable by default
pgbouncer_ignore_param : [ extra_float_digits, application_name, TimeZone, DateStyle, IntervalStyle, search_path ]
pg_weight : 100 #INSTANCE # relative load balance weight in service, 100 by default, 0-255
pg_service_provider : '' # dedicate haproxy node group name, or empty string for local nodes by default
pg_default_service_dest : pgbouncer # default service destination if svc.dest='default'
pg_default_services : # postgres default service definitions
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
pg_vip_enabled : false # enable a l2 vip for pgsql primary? false by default
pg_vip_address : 127.0.0.1 /24 # vip address in `<ipv4>/<mask>` format, require if vip is enabled
pg_vip_interface : eth0 # vip network interface to listen, eth0 by default
pg_dns_suffix : '' # pgsql dns suffix, '' by default
pg_dns_target : auto # auto, primary, vip, none, or ad hoc ip
pgbouncer_enabled参数名称: pgbouncer_enabled, 类型: bool, 层次:C
默认值为 true,如果禁用,将不会在 PGSQL节点上配置连接池 Pgbouncer。
pgbouncer_port参数名称: pgbouncer_port, 类型: port, 层次:C
Pgbouncer 监听端口,默认为 6432。
pgbouncer_log_dir参数名称: pgbouncer_log_dir, 类型: path, 层次:C
Pgbouncer 日志目录,默认为 /pg/log/pgbouncer,Vector 日志代理会根据此参数收集 Pgbouncer 日志。
pgbouncer_auth_query参数名称: pgbouncer_auth_query, 类型: bool, 层次:C
是否允许 Pgbouncer 查询 PostgreSQL,以允许未显式列出的用户通过连接池访问 PostgreSQL?默认值是 false。
如果启用,pgbouncer 用户将使用 SELECT username, password FROM monitor.pgbouncer_auth($1) 对 postgres 数据库进行身份验证,否则,只有带有 pgbouncer: true 的业务用户才被允许连接到 Pgbouncer 连接池。
pgbouncer_poolmode参数名称: pgbouncer_poolmode, 类型: enum, 层次:C
Pgbouncer 连接池池化模式:transaction,session,statement,默认为 transaction。
session:会话级池化,具有最佳的功能兼容性。transaction:事务级池化,具有更好的性能(许多小连接),可能会破坏某些会话级特性,如NOTIFY/LISTEN 等…statements:语句级池化,用于简单的只读查询。如果您的应用出现功能兼容性问题,可以考虑修改此参数为 session。
pgbouncer_sslmode参数名称: pgbouncer_sslmode, 类型: enum, 层次:C
Pgbouncer 客户端 ssl 模式,默认为 disable。
注意,启用 SSL 可能会对你的 pgbouncer 产生巨大的性能影响。
disable:如果客户端请求 TLS 则忽略(默认)allow:如果客户端请求 TLS 则使用。如果没有则使用纯TCP。不验证客户端证书。prefer:与 allow 相同。require:客户端必须使用 TLS。如果没有则拒绝客户端连接。不验证客户端证书。verify-ca:客户端必须使用有效的客户端证书的TLS。verify-full:与 verify-ca 相同。pgbouncer_ignore_param参数名称: pgbouncer_ignore_param, 类型: string[], 层次:C
PgBouncer 忽略的启动参数列表,默认值为:
[ extra_float_digits, application_name, TimeZone, DateStyle, IntervalStyle, search_path ]
这些参数会被配置到 PgBouncer 配置文件中的 ignore_startup_parameters 选项。当客户端连接时设置这些参数时,PgBouncer 不会因为连接池中的连接参数不匹配而创建新的连接。
这允许不同的客户端使用相同的连接池,即使它们设置了不同的这些参数值。此参数在 Pigsty v3.5 中新增。
pg_weight参数名称: pg_weight, 类型: int, 层次:I
服务中的相对负载均衡权重,默认为100,范围0-255。
默认值: 100。您必须在实例变量中定义它,并重载服务 以生效。
pg_service_provider参数名称: pg_service_provider, 类型: string, 层次:G/C
专用的haproxy节点组名,或默认为本地节点的空字符串。
如果指定,PostgreSQL服务将注册到专用的haproxy节点组,而不是当下的 PGSQL 集群节点。
请记住为每个服务在专用的 haproxy 节点上分配唯一 的端口!
例如,如果我们在3节点的 pg-test 集群上定义以下参数:
pg_service_provider : infra # use load balancer on group `infra`
pg_default_services : # alloc port 10001 and 10002 for pg-test primary/replica service
- { name: primary ,port: 10001 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: replica ,port: 10002 ,dest: postgres ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
pg_default_service_dest参数名称: pg_default_service_dest, 类型: enum, 层次:G/C
当定义一个服务 时,如果 svc.dest='default',此参数将用作默认值。
默认值: pgbouncer,意味着5433主服务和5434副本服务将默认将流量路由到 pgbouncer。
如果您不想使用pgbouncer,将其设置为postgres。流量将直接路由到 postgres。
pg_default_services参数名称: pg_default_services, 类型: service[], 层次:G/C
postgres默认服务定义
默认值是四个默认服务定义,如PGSQL Service 所述
pg_default_services : # postgres default service definitions
- { name: primary ,port: 5433 ,dest: default ,check: /primary ,selector : "[]" }
- { name: replica ,port: 5434 ,dest: default ,check: /read-only ,selector : "[]" , backup : "[? pg_role == `primary` || pg_role == `offline` ]" }
- { name: default ,port: 5436 ,dest: postgres ,check: /primary ,selector : "[]" }
- { name: offline ,port: 5438 ,dest: postgres ,check: /replica ,selector : "[? pg_role == `offline` || pg_offline_query ]" , backup : "[? pg_role == `replica` && !pg_offline_query]" }
pg_vip_enabled参数名称: pg_vip_enabled, 类型: bool, 层次:C
为 PGSQL 集群启用 L2 VIP吗?默认值是false,表示不创建 L2 VIP。
启用 L2 VIP 后,会有一个 VIP 绑定在集群主实例节点上,由 vip-manager 管理,根据 etcd 中的数据进行判断。
L2 VIP只能在相同的L2网络中使用,这可能会对您的网络拓扑产生额外的限制。
pg_vip_address参数名称: pg_vip_address, 类型: cidr4, 层次:C
如果启用vip,则需要<ipv4>/<mask>格式的vip地址。
默认值: 127.0.0.1/24。这个值由两部分组成:ipv4和mask,用/分隔。
pg_vip_interface参数名称: pg_vip_interface, 类型: string, 层次:C/I
vip network interface to listen, eth0 by default.
L2 VIP 监听的网卡接口,默认为 eth0。
它应该是您节点的首要网卡名,即您在配置清单中使用的IP地址。
如果您的节点有多块名称不同的网卡,您可以在实例变量上进行覆盖:
pg-test :
hosts :
10.10.10.11 : {pg_seq: 1, pg_role: replica ,pg_vip_interface : eth0 }
10.10.10.12 : {pg_seq: 2, pg_role: primary ,pg_vip_interface : eth1 }
10.10.10.13 : {pg_seq: 3, pg_role: replica ,pg_vip_interface : eth2 }
vars :
pg_vip_enabled : true # 为这个集群启用L2 VIP,默认绑定到主实例
pg_vip_address: 10.10.10.3/24 # L2网络CIDR: 10.10.10.0/24, vip地址 : 10.10.10.3
# pg_vip_interface: eth1 # 如果您的节点有统一的接口,您可以在这里定义它
pg_dns_suffix参数名称: pg_dns_suffix, 类型: string, 层次:C
PostgreSQL DNS 名称后缀,默认为空字符串。
在默认情况下,PostgreQL 集群名会作为 DNS 域名注册到 Infra 节点的 dnsmasq 中对外提供解析。
您可以通过本参数指定一个域名后缀,这样会使用 {{ pg_cluster }}{{ pg_dns_suffix }} 作为集群 DNS 名称。
例如,如果您将 pg_dns_suffix 设置为 .db.vip.company.tld,那么 pg-test 的集群 DNS 名称将是 pg-test.db.vip.company.tld
pg_dns_target参数名称: pg_dns_target, 类型: enum, 层次:C
Could be: auto, primary, vip, none, or an ad hoc ip address, which will be the target IP address of cluster DNS record.
default values: auto , which will bind to pg_vip_address if pg_vip_enabled, or fallback to cluster primary instance ip address.
vip: bind to pg_vip_addressprimary: resolve to cluster primary instance ip addressauto: resolve to pg_vip_address if pg_vip_enabled, or fallback to cluster primary instance ip address.none: do not bind to any ip address<ipv4>: bind to the given IP address可以是:auto、primary、vip、none或一个特定的IP地址,它将是集群DNS记录的解析目标IP地址。
默认值: auto,如果pg_vip_enabled,将绑定到pg_vip_address,否则会回退到集群主实例的 IP 地址。
PG_MONITORPG_MONITOR 组的参数用于监控 PostgreSQL 数据库、Pgbouncer 连接池与 pgBackRest 备份系统的状态。
此参数组定义了三个 Exporter 的配置:pg_exporter 用于监控 PostgreSQL,pgbouncer_exporter 用于监控连接池,pgbackrest_exporter 用于监控备份状态。
pg_exporter_enabled : true # 在 pgsql 主机上启用 pg_exporter 吗?
pg_exporter_config : pg_exporter.yml # pg_exporter 配置文件名
pg_exporter_cache_ttls : '1,10,60,300' # pg_exporter 收集器 ttl 阶段(秒),默认为 '1,10,60,300'
pg_exporter_port : 9630 # pg_exporter 监听端口,默认为 9630
pg_exporter_params : 'sslmode=disable' # pg_exporter dsn 的额外 url 参数
pg_exporter_url : '' # 如果指定,将覆盖自动生成的 pg dsn
pg_exporter_auto_discovery : true # 启用自动数据库发现?默认启用
pg_exporter_exclude_database : 'template0,template1,postgres' # 在自动发现过程中不会被监控的数据库的 csv 列表
pg_exporter_include_database : '' # 在自动发现过程中将被监控的数据库的 csv 列表
pg_exporter_connect_timeout : 200 # pg_exporter 连接超时(毫秒),默认为 200
pg_exporter_options : '' # 覆盖 pg_exporter 的额外选项
pgbouncer_exporter_enabled : true # 在 pgsql 主机上启用 pgbouncer_exporter 吗?
pgbouncer_exporter_port : 9631 # pgbouncer_exporter 监听端口,默认为 9631
pgbouncer_exporter_url : '' # 如果指定,将覆盖自动生成的 pgbouncer dsn
pgbouncer_exporter_options : '' # 覆盖 pgbouncer_exporter 的额外选项
pgbackrest_exporter_enabled : true # 在 pgsql 主机上启用 pgbackrest_exporter 吗?
pgbackrest_exporter_port : 9854 # pgbackrest_exporter 监听端口,默认为 9854
pgbackrest_exporter_options : '' # 覆盖 pgbackrest_exporter 的额外选项
pg_exporter_enabled参数名称: pg_exporter_enabled, 类型: bool, 层次:C
是否在 PGSQL 节点上启用 pg_exporter?默认值为:true。
PG Exporter 用于监控 PostgreSQL 数据库实例,如果不想安装 pg_exporter 可以设置为 false。
pg_exporter_config参数名称: pg_exporter_config, 类型: string, 层次:C
pg_exporter 配置文件名,PG Exporter 和 PGBouncer Exporter 都会使用这个配置文件。默认值:pg_exporter.yml。
如果你想使用自定义配置文件,你可以在这里定义它。你的自定义配置文件应当放置于 files/<name>.yml。
例如,当您希望监控一个远程的 PolarDB 数据库实例时,可以使用样例配置:files/polar_exporter.yml。
pg_exporter_cache_ttls参数名称: pg_exporter_cache_ttls, 类型: string, 层次:C
pg_exporter 收集器 TTL 阶梯(秒),默认为 ‘1,10,60,300’
默认值:1,10,60,300,它将为不同的度量收集器使用不同的TTL值: 1s, 10s, 60s, 300s。
PG Exporter 内置了缓存机制,避免多个 Prometheus 重复抓取对数据库产生不当影响,所有指标收集器按 TTL 分为四类:
ttl_fast : "{{ pg_exporter_cache_ttls.split(',')[0]|int }}" # critical queries
ttl_norm : "{{ pg_exporter_cache_ttls.split(',')[1]|int }}" # common queries
ttl_slow : "{{ pg_exporter_cache_ttls.split(',')[2]|int }}" # slow queries (e.g table size)
ttl_slowest : "{{ pg_exporter_cache_ttls.split(',')[3]|int }}" # ver slow queries (e.g bloat)
例如,在默认配置下,存活类指标默认最多缓存 1s,大部分普通指标会缓存 10s(应当与监控抓取间隔 victoria_scrape_interval 相同)。
少量变化缓慢的查询会有 60s 的TTL,极个别大开销监控查询会有 300s 的TTL。
pg_exporter_port参数名称: pg_exporter_port, 类型: port, 层次:C
pg_exporter 监听端口号,默认值为:9630
pg_exporter_params参数名称: pg_exporter_params, 类型: string, 层次:C
pg_exporter 所使用 DSN 中额外的 URL PATH 参数。
默认值:sslmode=disable,它将禁用用于监控连接的 SSL(因为默认使用本地 unix 套接字)。
pg_exporter_url参数名称: pg_exporter_url, 类型: pgurl, 层次:C
如果指定了本参数,将会覆盖自动生成的 PostgreSQL DSN,使用指定的 DSN 连接 PostgreSQL 。默认值为空字符串。
如果没有指定此参数,PG Exporter 默认会使用以下的连接串访问 PostgreSQL :
postgres://{{ pg_monitor_username }}:{{ pg_monitor_password }}@{{ pg_host }}:{{ pg_port }}/postgres{% if pg_exporter_params != '' %}?{{ pg_exporter_params }}{% endif %}
当您想监控一个远程的 PostgreSQL 实例时,或者需要使用不同的监控用户/密码,配置选项时,可以使用这个参数。
pg_exporter_auto_discovery参数名称: pg_exporter_auto_discovery, 类型: bool, 层次:C
启用自动数据库发现吗? 默认启用:true。
PG Exporter 默认会连接到 DSN 中指定的数据库 (默认为管理数据库 postgres) 收集全局指标,如果您希望收集所有业务数据库的指标,可以开启此选项。
PG Exporter 会自动发现目标 PostgreSQL 实例中的所有数据库,并在这些数据库中收集 库级监控指标 。
pg_exporter_exclude_database参数名称: pg_exporter_exclude_database, 类型: string, 层次:C
如果启用了数据库自动发现(默认启用),在这个参数指定的列表中的数据库将不会被监控。
默认值为: template0,template1,postgres,即管理数据库 postgres 与模板数据库会被排除在自动监控的数据库之外。
作为例外,DSN 中指定的数据库不受此参数影响,例如,PG Exporter 如果连接的是 postgres 数据库,那么即使 postgres 在此列表中,也会被监控。
pg_exporter_include_database参数名称: pg_exporter_include_database, 类型: string, 层次:C
如果启用了数据库自动发现(默认启用),在这个参数指定的列表中的数据库才会被监控。默认值为空字符串,即不启用此功能。
参数的形式是由逗号分隔的数据库名称列表,例如:db1,db2,db3。
此参数相对于 [pg_exporter_exclude_database] 有更高的优先级,相当于白名单模式。如果您只希望监控特定的数据库,可以使用此参数。
pg_exporter_connect_timeout参数名称: pg_exporter_connect_timeout, 类型: int, 层次:C
pg_exporter 连接超时(毫秒),默认为 200 (单位毫秒)
当 PG Exporter 尝试连接到 PostgreSQL 数据库时,最多会等待多长时间?超过这个时间,PG Exporter 将会放弃连接并报错。
默认值 200毫秒 对于绝大多数场景(例如:同可用区监控)都是足够的,但是如果您监控的远程 PostgreSQL 位于另一个大洲,您可能需要增加此值以避免连接超时。
pg_exporter_options参数名称: pg_exporter_options, 类型: arg, 层次:C
传给 PG Exporter 的命令行参数,默认值为:"" 空字符串。
当使用空字符串时,会使用默认的命令参数:
{ % if pg_exporter_port != '' %}
PG_EXPORTER_OPTS = '--web.listen-address=:{{ pg_exporter_port }} {{ pg_exporter_options }}'
{ % else %}
PG_EXPORTER_OPTS = '--web.listen-address=:{{ pg_exporter_port }} --log.level=info'
{ % endif %}
注意,请不要在本参数中覆盖 pg_exporter_port 的端口配置。
pgbouncer_exporter_enabled参数名称: pgbouncer_exporter_enabled, 类型: bool, 层次:C
在 PGSQL 节点上,是否启用 pgbouncer_exporter ?默认值为:true。
pgbouncer_exporter_port参数名称: pgbouncer_exporter_port, 类型: port, 层次:C
pgbouncer_exporter 监听端口号,默认值为:9631
pgbouncer_exporter_url参数名称: pgbouncer_exporter_url, 类型: pgurl, 层次:C
如果指定了本参数,将会覆盖自动生成的 pgbouncer DSN,使用指定的 DSN 连接 pgbouncer。默认值为空字符串。
如果没有指定此参数,Pgbouncer Exporter 默认会使用以下的连接串访问 Pgbouncer:
postgres://{{ pg_monitor_username }}:{{ pg_monitor_password }}@:{{ pgbouncer_port }}/pgbouncer?host={{ pg_localhost }}&sslmode=disable
当您想监控一个远程的 Pgbouncer 实例时,或者需要使用不同的监控用户/密码,配置选项时,可以使用这个参数。
pgbouncer_exporter_options参数名称: pgbouncer_exporter_options, 类型: arg, 层次:C
传给 Pgbouncer Exporter 的命令行参数,默认值为:"" 空字符串。
当使用空字符串时,会使用默认的命令参数:
{ % if pgbouncer_exporter_options != '' %}
PG_EXPORTER_OPTS = '--web.listen-address=:{{ pgbouncer_exporter_port }} {{ pgbouncer_exporter_options }}'
{ % else %}
PG_EXPORTER_OPTS = '--web.listen-address=:{{ pgbouncer_exporter_port }} --log.level=info'
{ % endif %}
注意,请不要在本参数中覆盖 pgbouncer_exporter_port 的端口配置。
pgbackrest_exporter_enabled参数名称: pgbackrest_exporter_enabled, 类型: bool, 层次:C
是否在 PGSQL 节点上启用 pgbackrest_exporter?默认值为:true。
pgbackrest_exporter 用于监控 pgBackRest 备份系统的状态,包括备份的大小、时间、类型、持续时长等关键指标。
pgbackrest_exporter_port参数名称: pgbackrest_exporter_port, 类型: port, 层次:C
pgbackrest_exporter 监听端口号,默认值为:9854。
此端口需要在 Prometheus 服务发现配置中引用,用于抓取备份相关的监控指标。
pgbackrest_exporter_options参数名称: pgbackrest_exporter_options, 类型: arg, 层次:C
传给 pgbackrest_exporter 的命令行参数,默认值为:"" 空字符串。
当使用空字符串时,会使用默认的命令参数配置。您可以在此指定额外的参数选项来调整 exporter 的行为。
PG_REMOVEpgsql-rm.yml 会调用 pg_remove 角色来安全地移除 PostgreSQL 实例。本节参数用于控制清理行为,避免误删。
pg_rm_data : true # remove postgres data during remove? true by default
pg_rm_backup : true # remove pgbackrest backup during primary remove? true by default
pg_rm_pkg : true # uninstall postgres packages during remove? true by default
pg_safeguard : false # stop pg_remove running if pg_safeguard is enabled, false by default
pg_rm_data参数名称: pg_rm_data, 类型: bool, 层次:G/C/A
删除 PGSQL 实例时是否清理 pg_data 以及软链,默认值 true。
该开关既影响 pgsql-rm.yml,也影响其他触发 pg_remove 的场景。设为 false 可以保留数据目录,便于手动检查或重新挂载。
pg_rm_backup参数名称: pg_rm_backup, 类型: bool, 层次:G/C/A
删除主库时是否一并清理 pgBackRest 仓库与配置,默认值 true。
该参数仅对 pg_role=primary 的主实例生效:pg_remove 会先停止 pgBackRest、删除当前集群的 stanza,并在 pgbackrest_method == 'local' 时移除 pg_fs_backup 中的数据。备用集群或上游备份不会受到影响。
pg_rm_pkg参数名称: pg_rm_pkg, 类型: bool, 层次:G/C/A
在清理 PGSQL 实例时是否卸载 pg_packages 安装的所有软件包,默认值 true。
如果只想暂时停机并保留二进制文件,可将其设为 false,否则 pg_remove 会调用系统包管理器彻底卸载 PostgreSQL 相关组件。
pg_safeguard参数名称: pg_safeguard, 类型: bool, 层次:G/C/A
防误删保险,默认值为 false。当显式设置为 true 时,pg_remove 会立即终止并提示,必须使用 -e pg_safeguard=false 或在变量中关闭后才会继续。
建议在生产环境批量清理前先开启此开关,确认命令与目标节点无误后再解除,以避免误操作导致实例被删除。
11.16 - 预置剧本 如何使用 ansible 剧本来管理 PostgreSQL 集群
Pigsty提供了一系列剧本,用于集群上下线扩缩容,用户/数据库管理,监控、备份恢复或迁移已有实例。
保护机制 使用 PGSQL 剧本时需要特别注意 ,剧本 pgsql.yml 与 pgsql-rm.yml 使用不当会有误删数据库的风险!
在执行时添加 -l 参数,限制命令执行的对象范围,并确保自己在正确的目标上执行正确的任务。 限制范围通常以一个数据库集群为宜,使用不带参数的 pgsql.yml 在生产环境中是一个高危操作,务必三思而后行。 出于防止误删的目的,Pigsty 的 PGSQL 模块提供了防误删保险,由 pg_safeguard 参数控制。
当 pg_safeguard 设置为 true 时,pgsql-rm.yml 剧本会立即中止执行,防止误删数据库集群。
# 将会中止执行,保护数据安全
./pgsql-rm.yml -l pg-test
# 通过命令行参数强制覆盖保护开关
./pgsql-rm.yml -l pg-test -e pg_safeguard = false
除了 pg_safeguard 外,pgsql-rm.yml 还提供了更细粒度的控制参数:
参数 默认值 说明 pg_safeguardfalse防误删保险,设为 true 时剧本会中止执行 pg_rm_datatrue是否移除 PostgreSQL 数据目录 pg_rm_backuptrue是否移除 pgBackRest 备份数据(仅主库移除时生效) pg_rm_pkgfalse是否卸载 PostgreSQL 软件包
这些参数允许你根据实际需求精确控制移除行为:
# 移除集群但保留数据目录(仅停止服务)
./pgsql-rm.yml -l pg-test -e pg_rm_data = false
# 移除集群但保留备份数据
./pgsql-rm.yml -l pg-test -e pg_rm_backup = false
# 移除集群并卸载软件包
./pgsql-rm.yml -l pg-test -e pg_rm_pkg = true
pgsql.yml剧本 pgsql.yml 用于初始化 PostgreSQL 集群或添加新的从库。
下面是使用此剧本初始化沙箱环境中 PostgreSQL 集群的过程:
基本用法
./pgsql.yml -l pg-meta # 初始化集群 pg-meta
./pgsql.yml -l 10.10.10.13 # 初始化/添加实例 10.10.10.13
./pgsql.yml -l pg-test -t pg_service # 刷新集群 pg-test 的服务
./pgsql.yml -l pg-test -t pg_hba,pgbouncer_hba,pgbouncer_reload -e pg_reload = true # 重载HBA规则
包装脚本
Pigsty 提供了便捷的包装脚本简化常见操作:
bin/pgsql-add pg-meta # 初始化 pgsql 集群 pg-meta
bin/pgsql-add 10.10.10.10 # 初始化 pgsql 实例 10.10.10.10
bin/pgsql-add pg-test 10.10.10.13 # 添加 10.10.10.13 到集群 pg-test(自动刷新服务)
bin/pgsql-svc pg-test # 刷新 pg-test 的 haproxy 服务(成员变更时使用)
bin/pgsql-hba pg-test # 重载 pg-test 的 pg/pgb HBA 规则
任务列表
本剧本包含以下子任务:
# pg_install : 安装 postgres 软件包与扩展
# - pg_dbsu : 设置 postgres 超级用户
# - pg_dbsu_create : 创建 dbsu 用户
# - pg_dbsu_sudo : 配置 dbsu sudo 权限
# - pg_ssh : 交换 dbsu SSH 密钥
# - pg_pkg : 安装 postgres 软件包
# - pg_pre : 安装前置任务
# - pg_ext : 安装 postgres 扩展包
# - pg_post : 安装后置任务
# - pg_link : 将 pgsql 版本 bin 链接到 /usr/pgsql
# - pg_path : 将 pgsql bin 添加到系统路径
# - pg_dir : 创建 postgres 目录并设置 FHS
# - pg_bin : 同步 /pg/bin 脚本
# - pg_alias : 配置 pgsql/psql 别名
# - pg_dummy : 创建 dummy 占位文件
#
# pg_bootstrap : 引导 postgres 集群
# - pg_config : 生成 postgres 配置
# - pg_conf : 生成 patroni 配置
# - pg_key : 生成 pgsodium 密钥
# - pg_cert : 为 postgres 签发证书
# - pg_cert_private : 检查 pg 私钥是否存在
# - pg_cert_issue : 签发 pg 服务端证书
# - pg_cert_copy : 复制密钥与证书到 pg 节点
# - pg_launch : 启动 patroni 主库与从库
# - pg_watchdog : 授予 postgres watchdog 权限
# - pg_primary : 启动 patroni/postgres 主库
# - pg_init : 使用角色/模板初始化 pg 集群
# - pg_pass : 将 .pgpass 文件写入 pg 主目录
# - pg_replica : 启动 patroni/postgres 从库
# - pg_hba : 生成 pg HBA 规则
# - patroni_reload : 重新加载 patroni 配置
# - pg_patroni : 必要时暂停或移除 patroni
#
# pg_provision : 创建 postgres 业务用户与数据库
# - pg_user : 创建 postgres 业务用户
# - pg_user_config : 渲染创建用户的 sql
# - pg_user_create : 在 postgres 上创建用户
# - pg_db : 创建 postgres 业务数据库
# - pg_db_config : 渲染创建数据库的 sql
# - pg_db_create : 在 postgres 上创建数据库
#
# pg_backup : 初始化 postgres PITR 备份
# - pgbackrest : 配置 pgbackrest 备份
# - pgbackrest_config : 生成 pgbackrest 配置
# - pgbackrest_init : 初始化 pgbackrest 仓库
# - pgbackrest_backup : 引导后进行初始备份
#
# pg_access : 初始化 postgres 服务访问层
# - pgbouncer : 部署 pgbouncer 连接池
# - pgbouncer_dir : 创建 pgbouncer 目录
# - pgbouncer_config : 生成 pgbouncer 配置
# - pgbouncer_hba : 生成 pgbouncer hba 配置
# - pgbouncer_user : 生成 pgbouncer 用户列表
# - pgbouncer_launch : 启动 pgbouncer 服务
# - pgbouncer_reload : 重载 pgbouncer 配置
# - pg_vip : 使用 vip-manager 绑定 VIP 到主库
# - pg_vip_config : 生成 vip-manager 配置
# - pg_vip_launch : 启动 vip-manager 绑定 vip
# - pg_dns : 将 DNS 名称注册到基础设施 dnsmasq
# - pg_dns_ins : 注册 pg 实例名称
# - pg_dns_cls : 注册 pg 集群名称
# - pg_service : 使用 haproxy 暴露 pgsql 服务
# - pg_service_config : 为 pg 服务生成本地 haproxy 配置
# - pg_service_reload : 使用 haproxy 暴露 postgres 服务
#
# pg_monitor : 设置 pgsql 监控并注册到基础设施
# - pg_exporter : 配置并启动 pg_exporter
# - pgbouncer_exporter : 配置并启动 pgbouncer_exporter
# - pgbackrest_exporter : 配置并启动 pgbackrest_exporter
# - pg_register : 将 pgsql 注册到监控/日志/数据源
# - add_metrics : 将 pg 注册为 victoria 监控目标
# - add_logs : 将 pg 注册为 vector 日志来源
# - add_ds : 将 pg 数据库注册为 grafana 数据源
以下管理任务使用到了此剧本
注意事项
单独针对某一集群从库执行此剧本时,用户应当确保 集群主库已经完成初始化! 扩容完成后,您需要重载服务 与重载HBA ,包装脚本 bin/pgsql-add 会自动完成这些任务。 集群扩容时,如果 Patroni 拉起从库的时间过长,Ansible 剧本可能会因为超时而中止:
典型错误信息为:wait for postgres/patroni replica 任务执行很长时间后中止 但制作从库的进程会继续,例如制作从库需超过1天的场景,后续处理请参考 FAQ :制作从库失败。 pgsql-rm.yml剧本 pgsql-rm.yml 用于移除 PostgreSQL 集群,或移除某个实例。
下面是使用此剧本移除沙箱环境中 PostgreSQL 集群的过程:
基本用法
./pgsql-rm.yml -l pg-test # 移除集群 pg-test
./pgsql-rm.yml -l 10.10.10.13 # 移除实例 10.10.10.13
命令行参数
本剧本可以使用以下命令行参数控制其行为:
./pgsql-rm.yml -l pg-test # 移除集群 pg-test
-e pg_safeguard = false # 防误删保险,默认关闭,开启时需强制覆盖
-e pg_rm_data = true # 是否一并移除 PostgreSQL 数据目录,默认移除
-e pg_rm_backup = true # 是否一并移除 pgBackRest 备份(仅主库),默认移除
-e pg_rm_pkg = false # 是否卸载 PostgreSQL 软件包,默认不卸载
包装脚本
bin/pgsql-rm pg-meta # 移除 pgsql 集群 pg-meta
bin/pgsql-rm pg-test 10.10.10.13 # 从集群 pg-test 移除实例 10.10.10.13
任务列表
本剧本包含以下子任务:
# pg_safeguard : 如果 pg_safeguard 启用则中止执行
#
# pg_monitor : 从监控系统移除注册
# - pg_deregister : 从基础设施移除 pg 监控目标
# - rm_metrics : 从 prometheus 移除监控目标
# - rm_ds : 从 grafana 移除数据源
# - rm_logs : 从 vector 移除日志目标
# - pg_exporter : 移除 pg_exporter
# - pgbouncer_exporter : 移除 pgbouncer_exporter
# - pgbackrest_exporter: 移除 pgbackrest_exporter
#
# pg_access : 移除 pg 服务访问层
# - dns : 移除 pg DNS 记录
# - vip : 移除 vip-manager
# - pg_service : 从 haproxy 移除 pg 服务
# - pgbouncer : 移除 pgbouncer 连接中间件
#
# postgres : 移除 postgres 实例
# - pg_replica : 移除所有从库
# - pg_primary : 移除主库
# - pg_meta : 从 etcd 移除元数据
#
# pg_backup : 移除备份仓库(使用 pg_rm_backup=false 禁用)
# pg_data : 移除 postgres 数据(使用 pg_rm_data=false 禁用)
# pg_pkg : 卸载 pg 软件包(使用 pg_rm_pkg=true 启用)
# - pg_ext : 单独卸载 postgres 扩展
以下管理任务使用到了此剧本
注意事项
请不要直接对还有从库的集群主库单独执行此剧本 ,否则抹除主库后,其余从库会自动触发高可用自动故障切换。总是先下线所有从库后,再下线主库,当一次性下线整个集群时不需要操心此问题。实例下线后请刷新集群服务 ,当您从集群中下线掉某一个从库实例时,它仍然存留于在负载均衡器的配置文件中。因为健康检查无法通过,所以下线后的实例不会对集群产生影响。但您应当在恰当的时间点 重载服务 ,确保生产环境与配置清单的一致性。pgsql-user.yml剧本 pgsql-user.yml 用于在现有的 PostgreSQL 集群中添加新的业务用户。
基本用法
./pgsql-user.yml -l pg-meta -e username = dbuser_meta
包装脚本
bin/pgsql-user pg-meta dbuser_meta # 在集群 pg-meta 上创建用户 dbuser_meta
工作流程
在配置清单中定义用户: all.children.<pg_cluster>.vars.pg_users[i] 执行剧本时指定集群和用户名: pgsql-user.yml -l <pg_cluster> -e username=<name> 剧本会:
在 /pg/tmp/pg-user-{{ user.name }}.sql 生成用户创建 SQL 在集群主库上执行用户创建/更新 SQL 更新 /etc/pgbouncer/userlist.txt 与 useropts.txt 重载 pgbouncer 使配置生效 用户定义示例
pg_users :
- name : dbuser_meta # 必填,用户名是唯一必须的字段
password : DBUser.Meta # 可选,密码可以是 scram-sha-256 哈希或明文
login : true # 可选,是否可登录,默认 true
superuser : false # 可选,是否超级用户,默认 false
createdb : false # 可选,是否可创建数据库,默认 false
createrole : false # 可选,是否可创建角色,默认 false
inherit : true # 可选,是否继承权限,默认 true
replication : false # 可选,是否可复制,默认 false
bypassrls : false # 可选,是否绕过 RLS,默认 false
pgbouncer : true # 可选,是否添加到 pgbouncer 用户列表,默认 false
connlimit : -1 # 可选,连接数限制,-1 表示无限制
expire_in : 3650 # 可选,N 天后过期(覆盖 expire_at)
expire_at : '2030-12-31' # 可选,指定过期日期
comment : pigsty admin user # 可选,用户注释
roles : [ dbrole_admin] # 可选,所属角色
parameters : {} # 可选,角色级参数
pool_mode : transaction # 可选,pgbouncer 用户级连接池模式
pool_connlimit : -1 # 可选,用户级最大连接数
详情请参考:管理SOP:创建用户
pgsql-db.yml剧本 pgsql-db.yml 用于在现有的 PostgreSQL 集群中添加新的业务数据库。
基本用法
./pgsql-db.yml -l pg-meta -e dbname = meta
包装脚本
bin/pgsql-db pg-meta meta # 在集群 pg-meta 上创建数据库 meta
工作流程
在配置清单中定义数据库: all.children.<pg_cluster>.vars.pg_databases[i] 执行剧本时指定集群和数据库名: pgsql-db.yml -l <pg_cluster> -e dbname=<name> 剧本会:
在 /pg/tmp/pg-db-{{ database.name }}.sql 生成数据库创建 SQL 在集群主库上执行数据库创建/更新 SQL 如果 db.register_datasource 为 true,将数据库注册为 grafana 数据源 更新 /etc/pgbouncer/database.txt 并重载 pgbouncer 数据库定义示例
pg_databases :
- name : meta # 必填,数据库名是唯一必须的字段
baseline : cmdb.sql # 可选,数据库初始化 SQL 文件路径
pgbouncer : true # 可选,是否添加到 pgbouncer,默认 true
schemas : [ pigsty] # 可选,额外创建的 schema
extensions : # 可选,要安装的扩展
- { name: postgis, schema : public }
- { name : timescaledb }
comment : pigsty meta database # 可选,数据库注释
owner : postgres # 可选,数据库所有者
template : template1 # 可选,模板数据库
encoding : UTF8 # 可选,字符编码
locale : C # 可选,区域设置
tablespace : pg_default # 可选,默认表空间
allowconn : true # 可选,是否允许连接
revokeconn : false # 可选,是否回收 public 连接权限
register_datasource : true # 可选,是否注册到 grafana 数据源
connlimit : -1 # 可选,连接数限制
pool_mode : transaction # 可选,pgbouncer 连接池模式
pool_size : 64 # 可选,pgbouncer 连接池大小
pool_size_reserve : 32 # 可选,pgbouncer 保留连接池大小
详情请参考:管理SOP:创建数据库
pgsql-monitor.yml剧本 pgsql-monitor.yml 用于将远程 PostgreSQL 实例纳入 Pigsty 监控体系。
基本用法
./pgsql-monitor.yml -e clsname = pg-foo # 监控远程集群 pg-foo
包装脚本
bin/pgmon-add pg-foo # 监控一个远程 pgsql 集群 pg-foo
bin/pgmon-add pg-foo pg-bar # 同时监控多个集群
配置方式
首先需要在 infra 组变量中定义 pg_exporters:
infra :
hosts :
10.10.10.10 :
pg_exporters : # 列出所有远程实例,分配唯一的未使用本地端口
20001 : { pg_cluster: pg-foo, pg_seq: 1, pg_host : 10.10.10.10 }
20002 : { pg_cluster: pg-foo, pg_seq: 2, pg_host : 10.10.10.11 }
架构示意
------ infra ------
| |
| prometheus | v---- pg-foo-1 ----v
| ^ | metrics | ^ |
| pg_exporter <-|------------|---- postgres |
| (port: 20001) | | 10.10.10.10:5432 |
| ^ | ^------------------^
| ^ | ^
| ^ | v---- pg-foo-2 ----v
| ^ | metrics | ^ |
| pg_exporter <-|------------|---- postgres |
| (port: 20002) | | 10.10.10.11:5433 |
------------------- ^------------------^
可配置参数
pg_exporter_config : pg_exporter.yml # pg_exporter 配置文件名
pg_exporter_cache_ttls : '1,10,60,300' # pg_exporter 采集器 TTL 阶段
pg_exporter_port : 9630 # pg_exporter 监听端口
pg_exporter_params : 'sslmode=disable' # DSN 额外 URL 参数
pg_exporter_url : '' # 直接覆盖自动生成的 DSN
pg_exporter_auto_discovery : true # 是否启用自动数据库发现
pg_exporter_exclude_database : 'template0,template1,postgres' # 排除的数据库
pg_exporter_include_database : '' # 仅包含的数据库
pg_exporter_connect_timeout : 200 # 连接超时(毫秒)
pg_monitor_username : dbuser_monitor # 监控用户名
pg_monitor_password : DBUser.Monitor # 监控密码
远程数据库配置
远程 PostgreSQL 实例需要创建监控用户:
CREATE USER dbuser_monitor ;
COMMENT ON ROLE dbuser_monitor IS 'system monitor user' ;
ALTER USER dbuser_monitor PASSWORD 'DBUser.Monitor' ;
GRANT pg_monitor TO dbuser_monitor ;
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements" WITH SCHEMA "monitor" ;
限制
仅 postgres 指标可用 node、pgbouncer、patroni、haproxy 指标不可用 详情请参考:管理SOP:监控现有PG
pgsql-migration.yml剧本 pgsql-migration.yml 用于为现有的 PostgreSQL 集群生成基于逻辑复制的零停机迁移手册和脚本。
基本用法
./pgsql-migration.yml -e@files/migration/pg-meta.yml
工作流程
定义迁移任务配置文件(如 files/migration/pg-meta.yml) 执行剧本生成迁移手册与脚本 按照手册逐步执行脚本完成迁移 迁移任务定义示例
# files/migration/pg-meta.yml
context_dir : ~/migration # 迁移手册与脚本输出目录
src_cls : pg-meta # 源集群名称(必填)
src_db : meta # 源数据库名称(必填)
src_ip : 10.10.10.10 # 源集群主库 IP(必填)
dst_cls : pg-test # 目标集群名称(必填)
dst_db : test # 目标数据库名称(必填)
dst_ip : 10.10.10.11 # 目标集群主库 IP(必填)
# 可选参数
pg_dbsu : postgres
pg_replication_username : replicator
pg_replication_password : DBUser.Replicator
pg_admin_username : dbuser_dba
pg_admin_password : DBUser.DBA
pg_monitor_username : dbuser_monitor
pg_monitor_password : DBUser.Monitor
详情请参考:管理SOP:迁移数据库集群
pgsql-pitr.yml剧本 pgsql-pitr.yml 用于执行 PostgreSQL 时间点恢复 (Point-In-Time Recovery)。
基本用法
# 恢复到最新状态(WAL 归档流末端)
./pgsql-pitr.yml -l pg-meta -e '{"pg_pitr": {}}'
# 恢复到指定时间点
./pgsql-pitr.yml -l pg-meta -e '{"pg_pitr": {"time": "2025-07-13 10:00:00+00"}}'
# 恢复到指定 LSN
./pgsql-pitr.yml -l pg-meta -e '{"pg_pitr": {"lsn": "0/4001C80"}}'
# 恢复到指定事务 ID
./pgsql-pitr.yml -l pg-meta -e '{"pg_pitr": {"xid": "250000"}}'
# 恢复到命名还原点
./pgsql-pitr.yml -l pg-meta -e '{"pg_pitr": {"name": "some_restore_point"}}'
# 从其他集群备份恢复
./pgsql-pitr.yml -l pg-test -e '{"pg_pitr": {"cluster": "pg-meta"}}'
PITR 任务参数
pg_pitr : # 定义 PITR 任务
cluster : "pg-meta" # 源集群名称(恢复其他集群的备份时使用)
type: latest # 恢复目标类型 : time, xid, name, lsn, immediate, latest
time : "2025-01-01 10:00:00+00" # 恢复目标:时间点
name : "some_restore_point" # 恢复目标:命名还原点
xid : "100000" # 恢复目标:事务 ID
lsn : "0/3000000" # 恢复目标:日志序列号
timeline : latest # 目标时间线,可以是整数,默认 latest
exclusive : false # 是否排除目标点,默认 false
action: pause # 恢复后动作 : pause, promote, shutdown
archive : false # 是否保留归档设置,默认 false
db_include : [] # 仅包含这些数据库
db_exclude : [] # 排除这些数据库
link_map : {} # 表空间链接映射
process : 4 # 并行恢复进程数
repo : {} # 恢复源仓库配置
data : /pg/data # 恢复数据目录
port : 5432 # 恢复实例监听端口
任务列表
本剧本包含以下子任务:
# down : 停止 HA 并关闭 patroni 和 postgres
# - pause : 暂停 patroni 自动故障转移
# - stop : 停止 patroni 和 postgres 服务
# - stop_patroni : 停止 patroni 服务
# - stop_postgres : 停止 postgres 服务
#
# pitr : 执行 PITR 恢复过程
# - config : 生成 pgbackrest 配置和恢复脚本
# - restore : 运行 pgbackrest restore 命令
# - recovery : 启动 postgres 并完成恢复
# - verify : 验证恢复的集群控制数据
#
# up : 启动 postgres/patroni 并恢复 HA
# - etcd : 启动前清理 etcd 元数据
# - start : 启动 patroni 和 postgres 服务
# - start_postgres : 启动 postgres 服务
# - start_patroni : 启动 patroni 服务
# - resume : 恢复 patroni 自动故障转移
恢复目标类型说明
类型 说明 示例 latest恢复到 WAL 归档流末端(最新状态) {"pg_pitr": {}}time恢复到指定时间点 {"pg_pitr": {"time": "2025-07-13 10:00:00"}}xid恢复到指定事务 ID {"pg_pitr": {"xid": "250000"}}name恢复到命名还原点 {"pg_pitr": {"name": "before_ddl"}}lsn恢复到指定 LSN {"pg_pitr": {"lsn": "0/4001C80"}}immediate恢复到一致性状态后立即停止 {"pg_pitr": {"type": "immediate"}}
详情请参考:备份恢复教程
11.17 - 常见问题 PostgreSQL 常见问题答疑
我当前执行安装的用户为何不能使用 pg 管理别名? 从 Pigsty v4.0 开始,使用 pg 管理别名管理全局的 Patroni / PostgreSQL 集群的权限被收紧到了管理节点上的管理员分组(admin)。
node.yml 剧本创建的管理员(dba)默认具有此权限,而当前用户如果想要获得这个权限,需要你显式地将该用户加入到 admin 组中。
sudo usermod -aG admin <username>
PGSQL初始化失败:Fail to wait for postgres/patroni primary 这种错误信息存在多种可能,需要你 检查 Ansible,Systemd / Patroni / PostgreSQL 日志,找出真正的原因。
可能性1:集群配置错误,找出错误的配置项修改并应用。 可能性2:在部署中存在同名集群,或者之前的同名集群主节点被不正确地移除 可能性3:在DCS中有同名集群残留的垃圾元数据:没有正确完成下线,你可以使用 etcdctl del --prefix /pg/<cls> 来手工删除残留数据(请小心) 可能性4:你的 PostgreSQL 或节点相关 RPM 包没有被成功安装 可能性5:你的 Watchdog 内核模块没有正确启用加载 可能性6:你在初始化数据库时指定的语言 Locale 不存在(例如,使用了 en_US.UTF8,但没有安装英文语言包或 Locale 支持) 如果你遇到了其他的原因,欢迎提交 Issue 或向社区求助。 PGSQL初始化失败:Fail to wait for postgres/patroni replica 存在几种可能的原因:
立即失败 :通常是由于配置错误、网络问题、损坏的DCS元数据等原因。你必须检查 /pg/log 找出实际原因。
过了一会儿失败 :这可能是由于源实例数据损坏。查看 PGSQL FAQ:如何在数据损坏时创建副本?
过了很长时间再超时 :如果 wait for postgres replica 任务耗时 30 分钟或更长时间并由于超时而失败,这对于大型集群(例如,1TB+,可能需要几小时创建一个副本)是很常见的。
在这种情况下,底层创建副本的过程仍在进行。你可以使用 pg list <cls> 检查集群状态并等待副本赶上主节点。然后使用以下命令继续以下任务,完成完整的从库初始化:
./pgsql.yml -t pg_hba,pg_reload,pg_backup,pgbouncer,pg_vip,pg_dns,pg_service,pg_exporter,pg_register -l <problematic_replica>
PGSQL初始化失败:ABORT due to pg_safeguard enabled 这意味着正准备清理的 PostgreSQL 实例打开了防误删保险, 禁用 pg_safeguard 以移除 Postgres 实例。
如果防误删保险 pg_safeguard 打开,那么你就不能使用 bin/pgsql-rm 和 pgsql-rm.yml 剧本移除正在运行的 PGSQL 实例了。
要禁用 pg_safeguard,你可以在配置清单中将 pg_safeguard 设置为 false,或者在执行剧本时使用命令参数 -e pg_safeguard=false。
./pgsql-rm.yml -e pg_safeguard = false -l <cls_to_remove> # 强制覆盖 pg_safeguard
如何为 PostgreSQL 启用大页/HugePage? 使用 node_hugepage_count 和 node_hugepage_ratio 或 /pg/bin/pg-tune-hugepage
如果你计划启用大页(HugePage),请考虑使用 node_hugepage_count 和 node_hugepage_ratio ,并配合 ./node.yml -t node_tune 进行应用。
大页对于数据库来说有利有弊,利是内存是专门管理的,不用担心被挪用,降低数据库 OOM 风险。缺点是某些场景下可能对性能由负面影响。
在 PostgreSQL 启动前,您需要分配 足够多的 大页,浪费的部分可以使用 pg-tune-hugepage 脚本对其进行回收,不过此脚本仅 PostgreSQL 15+ 可用。
如果你的 PostgreSQL 已经在运行,你可以使用下面的办法启动大页(仅 PG15+ 可用):
sync; echo 3 > /proc/sys/vm/drop_caches # 刷盘,释放系统缓存(请做好数据库性能受到冲击的准备)
sudo /pg/bin/pg-tune-hugepage # 将 nr_hugepages 写入 /etc/sysctl.d/hugepage.conf
pg restart <cls> # 重启 postgres 以使用 hugepage
如何确保故障转移中数据不丢失? 使用 crit.yml 参数模板,设置 pg_rpo 为 0,或配置集群 为同步提交模式。
考虑使用 同步备库 和 法定多数提交 来确保故障转移过程中的零数据丢失。
更多细节,可以参考 安全考量 - 可用性 的相关介绍。
磁盘写满了如何抢救? 如果磁盘写满了,连 Shell 命令都无法执行,rm -rf /pg/dummy 可以释放一些救命空间。
默认情况下,pg_dummy_filesize 设置为 64MB。在生产环境中,建议将其增加到 8GB 或更大。
它将被放置在 PGSQL 主数据磁盘上的 /pg/dummy 路径下。你可以删除该文件以释放一些紧急空间:至少可以让你在该节点上运行一些 shell 脚本来进一步回收其他空间。
当集群数据已经损坏时如何创建副本? Pigsty 在所有实例的 patroni 配置中设置了 cloneform: true 标签,标记该实例可用于创建副本。
如果某个实例有损坏的数据文件,导致创建新副本的时候出错中断,那么你可以设置 clonefrom: false 来避免从损坏的实例中拉取数据。具体操作如下
$ vi /pg/bin/patroni.yml
tags:
nofailover: false
clonefrom: true # ----------> change to false
noloadbalance: false
nosync: false
version: '15'
spec: '4C.8G.50G'
conf: 'oltp.yml'
$ systemctl reload patroni # 重新加载 Patroni 配置
PostgreSQL 监控的性能损耗如何? 一个常规 PostgreSQL 实例抓取耗时大约 200ms。抓取间隔默认为 10 秒,对于一个生产多核数据库实例来说几乎微不足道。
请注意,Pigsty 默认开启了库内对象监控,所以如果您的数据库内有数以十万计的表/索引对象,抓取可能耗时会增加到几秒。
您可以修改 Prometheus 的抓取频率,请确保一点:抓取周期应当显著高于一次抓取的时长。
如何监控一个现存的 PostgreSQL 实例? 在 PGSQL Monitor 中提供了详细的监控配置说明。
如何手工从监控中移除 PostgreSQL 监控目标? ./pgsql-rm.yml -t rm_metrics -l <cls> # 将集群 'cls' 的所有实例从 victoria 中移除
bin/pgmon-rm <ins> # 用于从 Victoria 中移除单个实例 'ins' 的监控对象,特别适合移除添加的外部实例
12 - 模块:INFRA 可独立使用且可选的基础设施,为 PostgreSQL 提供 NTP,DNS,可观测性等基础服务。
配置 | 管理 | 剧本 | 监控 | 参数
概览 每一套 Pigsty 部署都会提供一套基础架构组件,为纳管的节点与数据库集群提供服务,组件包括:
在 Pigsty 中,PGSQL 模块会使用到INFRA节点 上的一些服务,具体来说包括:
数据库集群/主机节点的域名,依赖 INFRA 节点的 DNSMASQ 解析 。 在数据库节点软件上安装 ,需要用到 INFRA 节点上的 Nginx 托管的本地 yum/apt 软件源。 数据库集群/节点的监控指标 ,会被 INFRA 节点上的 VictoriaMetrics 拉取并存储,可通过 VMUI / PromQL 访问。 数据库与节点运行日志由 Vector 收集,统一推送到 INFRA 上的 VictoriaLogs,支持在 Grafana 中检索。 VMAlert 根据 VictoriaMetrics 中的指标评估 告警规则,并将事件转发到 Alertmanager。 用户会从 Infra/Admin 节点上使用 Ansible 或其他工具发起对数据库节点的管理 :执行集群创建,扩缩容,实例/集群回收 创建业务用户、业务数据库、修改服务、HBA修改; 执行日志采集、垃圾清理,备份,巡检等 数据库节点默认会从 INFRA/ADMIN 节点上的 NTP 服务器同步时间 如果没有专用集群,高可用组件 Patroni 会使用 INFRA 节点上的 etcd 作为高可用DCS。 如果没有专用集群,备份组件 pgbackrest 会使用 INFRA 节点上的 minio 作为可选的集中备份仓库。 Nginx Nginx是Pigsty所有WebUI类服务的访问入口,默认使用管理节点80端口。
有许多带有 WebUI 的基础设施组件通过 Nginx 对外暴露服务,例如 Grafana、VictoriaMetrics(VMUI)、AlertManager,以及 HAProxy 流量管理页等,此外 yum/apt 仓库等静态文件资源也通过 Nginx 对外提供服务。
Nginx会根据 infra_portal 的内容,通过域名 进行区分,将访问请求转发至对应的上游组件处理。如果您使用了其他的域名,或者公网域名,可以在这里进行相应修改:
infra_portal : # domain names and upstream servers
home : { domain : i.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:8428" } # VMUI
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
vmalert : { endpoint : "${admin_ip}:8880" }
#logs : { domain: logs.pigsty ,endpoint: "${admin_ip}:9428" }
#minio : { domain: sss.pigsty ,endpoint: "${admin_ip}:9001" ,scheme: https ,websocket: true }
Pigsty强烈建议使用域名访问Pigsty UI系统,而不是直接通过IP+端口的方式访问,基于以下几个理由:
使用域名便于启用 HTTPS 流量加密,可以将访问收拢至Nginx,审计一切请求,并方便地集成认证机制。 一些组件默认只监听 127.0.0.1 ,因此只能通过Nginx代理访问。 域名更容易记忆,并提供了额外的配置灵活性。 如果您没有可用的互联网域名或本地DNS解析,您可以在 /etc/hosts (MacOS/Linux)或C:\Windows\System32\drivers\etc\hosts (Windows)中添加本地静态解析记录。
Nginx相关配置参数位于:配置:INFRA - NGINX
本地软件仓库 Pigsty会在安装时首先建立一个本地软件源,以加速后续软件安装。
该软件源由Nginx提供服务,默认位于为 /www/pigsty,可以访问 http://i.pigsty/pigsty 使用。
Pigsty的离线软件包即是将已经建立好的软件源目录(yum/apt)整个打成压缩包,当Pigsty尝试构建本地源时,如果发现本地源目录 /www/pigsty 已经存在,
且带有 /www/pigsty/repo_complete 标记文件,则会认为本地源已经构建完成,从而跳过从原始上游下载软件的步骤,消除了对互联网访问的依赖。
Repo定义文件位于 /www/pigsty.repo,默认可以通过 http://${admin_ip}/pigsty.repo 获取
curl -L http://i.pigsty/pigsty.repo -o /etc/yum.repos.d/pigsty.repo
您也可以在没有Nginx的情况下直接使用文件本地源:
[pigsty-local]
name = Pigsty local $releasever - $basearch
baseurl = file:///www/pigsty/
enabled = 1
gpgcheck = 0
本地软件仓库相关配置参数位于:配置:INFRA - REPO
Victoria 可观测性套件 Pigsty v4.0 使用 VictoriaMetrics 家族替代 Prometheus/Loki,提供统一的监控、日志与链路追踪能力:
VictoriaMetrics 默认监听 8428 端口,可通过 http://p.pigsty 或 https://i.pigsty/vmetrics/ 访问 VMUI,兼容 Prometheus API。VMAlert 负责评估 /infra/rules/*.yml 中的告警规则,监听 8880 端口,并将告警事件发送到 Alertmanager。VictoriaLogs 监听 9428 端口,支持 https://i.pigsty/vlogs/ 查询界面。所有节点默认运行 Vector,将系统日志、PostgreSQL 日志等结构化后推送至 VictoriaLogs。VictoriaTraces 监听 10428 端口,用于慢 SQL / Trace 采集,Grafana 以 Jaeger 数据源方式访问。Alertmanager 监听 9059 端口,可通过 http://a.pigsty 或 https://i.pigsty/alertmgr/ 管理告警通知。完成 SMTP、Webhook 等配置后即可推送消息。Blackbox Exporter 默认监听 9115 端口,用于 Ping/TCP/HTTP 探测,可通过 https://i.pigsty/blackbox/ 访问。更多信息请参阅:配置:INFRA - VICTORIA 与 配置:INFRA - PROMETHEUS 。
Grafana Grafana 是 Pigsty 的 WebUI 核心,默认监听 3000 端口,可以直接通过 IP:3000 或域名 http://g.pigsty 访问。
Pigsty 预置了针对 VictoriaMetrics / Logs / Traces 的数据源(vmetrics-*、vlogs-*、vtraces-*),以及大量 Dashboard,可通过 URL 进行联动跳转,快速定位问题。
Grafana 也可作为通用低代码可视化平台使用,因此 Pigsty 默认安装了 ECharts、victoriametrics-datasource 等插件,方便构建监控大屏或巡检报表。
Grafana 相关配置参数位于:配置:INFRA - GRAFANA 。
Ansible Pigsty默认会在元节点上安装Ansible,Ansible是一个流行的运维工具,采用声明式的配置风格与幂等的剧本设计,可以极大降低系统维护的复杂度。
DNSMASQ DNSMASQ 提供环境内的DNS解析 服务,其他模块的域名将会注册到 INFRA节点上的 DNSMASQ 服务中。
DNS记录默认放置于所有INFRA节点的 /etc/hosts.d/ 目录中。
DNSMASQ相关配置参数位于:配置:INFRA - DNS
Chronyd NTP服务用于同步环境内所有节点的时间(可选)
NTP相关配置参数位于:配置:NODES - NTP
配置 要在节点上安装 INFRA 模块,首先需要在配置清单中的 infra 分组中将其加入,并分配实例号 infra_seq
# 配置单个 INFRA 节点
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } }}
# 配置两个 INFRA 节点
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
10.10.10.11 : { infra_seq : 2 }
然后,使用 infra.yml 剧本在节点上初始化 INFRA 模块即可。
管理 下面是与 INFRA 模块相关的一些管理任务:
安装卸载Infra模块 ./infra.yml # 在 infra 分组上安装 INFRA 模块
./infra-rm.yml # 从 infra 分组上卸载 INFRA 模块
管理本地软件仓库 您可以使用以下剧本子任务,管理 Infra节点 上的本地yun源:
./infra.yml -t repo #从互联网或离线包中创建本地软件源
./infra.yml -t repo_dir # 创建本地软件源
./infra.yml -t repo_check # 检查本地软件源是否已经存在?
./infra.yml -t repo_prepare # 如果存在,直接使用已有的本地软件源
./infra.yml -t repo_build # 如果不存在,从上游构建本地软件源
./infra.yml -t repo_upstream # 处理 /etc/yum.repos.d 中的上游仓库文件
./infra.yml -t repo_remove # 如果 repo_remove == true,则删除现有的仓库文件
./infra.yml -t repo_add # 将上游仓库文件添加到 /etc/yum.repos.d (或 /etc/apt/sources.list.d)
./infra.yml -t repo_url_pkg # 从由 repo_url_packages 定义的互联网下载包
./infra.yml -t repo_cache # 使用 yum makecache / apt update 创建上游软件源元数据缓存
./infra.yml -t repo_boot_pkg # 安装如 createrepo_c、yum-utils 等的引导包...(或 dpkg-)
./infra.yml -t repo_pkg # 从上游仓库下载包 & 依赖项
./infra.yml -t repo_create # 使用 createrepo_c & modifyrepo_c 创建本地软件源
./infra.yml -t repo_use # 将新建的仓库添加到 /etc/yum.repos.d | /etc/apt/sources.list.d 用起来
./infra.yml -t repo_nginx # 如果没有 nginx 在服务,启动一个 nginx 作为 Web Server
其中最常用的命令为:
./infra.yml -t repo_upstream # 向 INFRA 节点添加 repo_upstream 中定义的上游软件源
./infra.yml -t repo_pkg # 从上游仓库下载包及其依赖项。
./infra.yml -t repo_create # 使用 createrepo_c & modifyrepo_c 创建/更新本地 yum 仓库
管理基础设施组件 您可以使用以下剧本子任务,管理 Infra节点 上的各个基础设施组件
./infra.yml -t infra # 配置基础设施
./infra.yml -t infra_env # 配置管理节点上的环境变量:env_dir, env_pg, env_var
./infra.yml -t infra_pkg # 安装INFRA所需的软件包:infra_pkg_yum, infra_pkg_pip
./infra.yml -t infra_user # 设置 infra 操作系统用户组
./infra.yml -t infra_cert # 为 infra 组件颁发证书
./infra.yml -t dns # 配置 DNSMasq:dns_config, dns_record, dns_launch
./infra.yml -t nginx # 配置 Nginx:nginx_config, nginx_cert, nginx_static, nginx_launch, nginx_exporter
./infra.yml -t victoria # 配置 VictoriaMetrics/Logs/Traces:vmetrics|vlogs|vtraces|vmalert
./infra.yml -t alertmanager # 配置 AlertManager:alertmanager_config, alertmanager_launch
./infra.yml -t blackbox # 配置 Blackbox Exporter: blackbox_launch
./infra.yml -t grafana # 配置 Grafana:grafana_clean, grafana_config, grafana_plugin, grafana_launch, grafana_provision
./infra.yml -t infra_register # 将 infra 组件注册到 VictoriaMetrics / Grafana
其他常用的任务包括:
./infra.yml -t nginx_index # 重新渲染 Nginx 首页内容
./infra.yml -t nginx_config,nginx_reload # 重新渲染 Nginx 网站门户配置,对外暴露新的上游服务。
./infra.yml -t vmetrics_config,vmetrics_launch # 重新生成 VictoriaMetrics 主配置文件,并重启服务
./infra.yml -t vlogs_config,vlogs_launch # 重新渲染 VictoriaLogs 配置
./infra.yml -t vmetrics_clean # 清理 VictoriaMetrics 存储数据目录
./infra.yml -t grafana_plugin # 从互联网上下载 Grafana 插件,通常需要科学上网
剧本 Pigsty 提供了三个与 INFRA 模块相关的剧本:
infra.ymlINFRA模块剧本 infra.yml 用于在 Infra节点 上初始化 pigsty 基础设施
执行该剧本将完成以下任务
配置元节点的目录与环境变量 下载并建立一个本地软件源,加速后续安装。(若使用离线软件包,则跳过下载阶段) 将当前元节点作为一个普通节点纳入 Pigsty 管理 部署基础设施 组件,包括 VictoriaMetrics/Logs/Traces、VMAlert、Grafana、Alertmanager、Blackbox Exporter 等 该剧本默认在 INFRA节点 上执行
Pigsty默认将使用当前执行此剧本的节点 作为Pigsty的Infra节点与Admin节点。 Pigsty在配置过程 中默认会将当前节点标记为Infra/Admin节点,并使用当前节点首要IP地址 替换配置模板中的占位IP地址10.10.10.10。 该节点除了可以发起管理,部署有基础设施,与一个部署普通托管节点并无区别。 单机安装时,ETCD 也会安装在此节点上,提供 DCS 服务 本剧本的一些注意事项
本剧本为幂等剧本,重复执行会抹除元节点上的基础设施组件。 如需保留历史监控数据,请先将 vmetrics_clean、vlogs_clean、vtraces_clean 设置为 false。 当离线软件源 /www/pigsty/repo_complete 存在时,本剧本会跳过从互联网下载软件的任务。完整执行该剧本耗时约5-8分钟,视机器配置而异。 不使用离线软件包而直接从互联网原始上游下载软件时,可能耗时10-20分钟,根据您的网络条件而异。
infra-rm.ymlINFRA模块剧本 infra-rm.yml 用于从 Infra节点 上移除 pigsty 基础设施
常用子任务包括:
./infra-rm.yml # 移除 INFRA 模块
./infra-rm.yml -t service # 停止 INFRA 上的基础设施服务
./infra-rm.yml -t data # 移除 INFRA 上的存留数据
./infra-rm.yml -t package # 卸载 INFRA 上安装的软件包
install.ymlINFRA模块剧本 install.yml 用于在所有节点 上一次性完整安装 Pigsty
该剧本在 剧本:一次性安装 中有更详细的介绍。
监控 Pigsty Home : Pigsty 监控系统主页
Pigsty Home Dashboard
INFRA Overview : Pigsty 基础设施自监控概览
INFRA Overview Dashboard
Nginx Instance : Nginx 监控指标与日志
Nginx Overview Dashboard
Grafana Instance : Grafana 监控指标与日志
Grafana Overview Dashboard
VictoriaMetrics Instance : VictoriaMetrics 抓取、查询与存储指标
VMAlert Instance : 告警规则评估与队列状态
Alertmanager Instance : 告警聚合、通知管道与 Silences
VictoriaLogs Instance : 日志写入速率、查询负载与索引命中
VictoriaTraces Instance : Trace/KV 存储与 Jaeger 接口
Logs Instance : 基于 Vector + VictoriaLogs 的节点日志检索
Logs Instance Dashboard
CMDB Overview : CMDB 可视化
CMDB Overview Dashboard
ETCD Overview : etcd 监控指标与日志
ETCD Overview Dashboard
参数 INFRA 模块有下列10个参数组。
参数速览 为保持与 Pigsty 版本一致,请参阅 《参数列表》 获取最新的默认值、类型与层级说明。
12.1 - 系统架构 介绍 Pigsty 中 INFRA 模块的整体架构,功能组件与责任分工。
架构总览 一套标准的 Pigsty 部署会带有一个 INFRA 模块,为纳管的节点与数据库集群提供服务:
Nginx :作为 Web 服务器,提供本地软件仓库服务;作为反向代理,统一收拢 Grafana、VMUI、Alertmanager 等 WebUI 的访问入口。Grafana :可视化平台,呈现监控指标、日志与链路追踪,承载监控大屏、巡检报表以及自定义数据应用。VictoriaMetrics 套件 :提供统一的可观测性平台。VictoriaMetrics :拉取全部监控指标,兼容 Prometheus API,并通过 VMUI 提供查询界面。VMAlert :评估告警规则,将事件推送至 Alertmanager。VictoriaLogs :集中收集存储日志,所有节点默认运行 Vector,将系统日志与数据库日志推送到此。VictoriaTraces :收集慢 SQL、服务链路等追踪数据。AlertManager :聚合告警事件,分发告警通知,支持邮件、Webhook 等渠道。BlackboxExporter :探测各个 IP/VIP/URL 的可达性。DNSMASQ :提供 DNS 解析服务,解析 Pigsty 内部使用到的域名。Chronyd :提供 NTP 时间同步服务,确保所有节点时间一致。
INFRA 模块对于高可用 PostgreSQL 并非必选项,例如在 精简安装 模式下,就不会安装 Infra 模块。
但 INFRA 模块提供了运行生产级高可用 PostgreSQL 集群所需要的支持性服务,通常强烈建议安装启用以获得完整的 Pigsty DBaaS 体验。
如果您已经有自己的基础设施(Nginx,本地仓库,监控系统,DNS,NTP),您也可以停用 INFRA 模块,并通过修改配置来使用现有的基础设施。
组件 端口 默认域名 描述 Nginx 80/443i.pigstyWeb 服务门户、本地仓库 Grafana 3000g.pigsty可视化平台 VictoriaMetrics 8428p.pigsty时序数据库(VMUI,兼容 Prometheus) VictoriaLogs 9428- 日志数据库(接收 Vector 推送) VictoriaTraces 10428- 链路追踪 / 慢 SQL 存储 VMAlert 8880- 计算指标、评估告警规则 AlertManager 9059a.pigsty告警聚合分发 BlackboxExporter 9115- 黑盒监控探测 DNSMasq 53- DNS 服务器 Chronyd 123- NTP 时间服务器
Nginx Nginx 是 Pigsty 所有 WebUI 类服务的访问入口,默认使用 80 / 443 端口对外提供 HTTP / HTTPS 服务。
带有 WebUI 的基础设施组件可以通过 Nginx 统一对外暴露服务,例如 Grafana、VictoriaMetrics(VMUI)、AlertManager,
以及 HAProxy 控制台,此外,本地 yum/apt 仓库等静态文件资源也通过 Nginx 对内提供服务。
Nginx 会根据 infra_portal 的定义配置本地 Web 服务器或反向代理服务器。
默认情况下将对外暴露 Pigsty 的管理首页:i.pigsty
infra_portal :
home : { domain : i.pigsty }
Pigsty 允许对 Nginx 进行丰富的定制,将其作为本地文件服务器,或者反向代理服务器,配置自签名或者真正的 HTTPS 证书。
以下是 Pigsty 公开演示站点 demo.pigsty.cc 使用的 Nginx 配置:
您可以在 Nginx 上监听不同的域名,通过反向代理的方式,使用统一入口对外暴露不同的 Web 服务:
infra_portal : # domain names and upstream servers
home : { domain: home.pigsty.cc ,certbot : pigsty.demo }
grafana : { domain: demo.pigsty.cc ,endpoint : "${admin_ip}:3000" , websocket: true ,certbot : pigsty.demo }
prometheus : { domain: p.pigsty.cc ,endpoint : "${admin_ip}:8428" ,certbot : pigsty.demo }
alertmanager : { domain: a.pigsty.cc ,endpoint : "${admin_ip}:9059" ,certbot : pigsty.demo }
blackbox : { endpoint : "${admin_ip}:9115" }
vmalert : { endpoint : "${admin_ip}:8880" }
postgrest : { domain: api.pigsty.cc ,endpoint : "127.0.0.1:8884" }
pgadmin : { domain: adm.pigsty.cc ,endpoint : "127.0.0.1:8885" }
pgweb : { domain: cli.pigsty.cc ,endpoint : "127.0.0.1:8886" }
bytebase : { domain: ddl.pigsty.cc ,endpoint : "127.0.0.1:8887" }
jupyter : { domain: lab.pigsty.cc ,endpoint : "127.0.0.1:8888" ,websocket : true }
gitea : { domain: git.pigsty.cc ,endpoint : "127.0.0.1:8889" ,certbot : pigsty.cc }
wiki : { domain: wiki.pigsty.cc ,endpoint : "127.0.0.1:9002" ,certbot : pigsty.cc }
noco : { domain: noco.pigsty.cc ,endpoint : "127.0.0.1:9003" ,certbot : pigsty.cc }
supa : { domain: supa.pigsty.cc ,endpoint : "10.2.82.163:8000" ,websocket: true ,certbot : pigsty.cc }
dify : { domain: dify.pigsty.cc ,endpoint : "10.2.82.163:8001" ,websocket: true ,certbot : pigsty.cc }
odoo : { domain: odoo.pigsty.cc ,endpoint : "127.0.0.1:8069" ,websocket: true ,certbot : pigsty.cc }
mm : { domain: mm.pigsty.cc ,endpoint : "10.2.82.163:8065" ,websocket : true }
web.io :
domain : en.pigsty.cc
path : "/www/web.io"
certbot : pigsty.doc
enforce_https : true
config : |
# rewrite /zh/ to /
location /zh/ {
rewrite ^/zh/(.*)$ /$1 permanent;
}
web.cc :
domain : pigsty.cc
path : "/www/web.cc"
domains : [ zh.pigsty.cc ]
certbot : pigsty.doc
config : |
# rewrite /zh/ to /
location /zh/ {
rewrite ^/zh/(.*)$ /$1 permanent;
}
repo :
domain : pro.pigsty.cc
path : "/www/repo"
index : true
certbot : pigsty.doc
更多信息,请参阅:教程:Nginx:向外代理暴露Web服务 与 教程:Certbot:申请与更新HTTPS证书
本地软件仓库 Pigsty 会在安装时,默认在 Infra 节点上创建一个本地软件仓库,以加速后续软件安装。
该软件仓库默认位于 /www/pigsty 目录,由 Nginx 提供服务,可以访问 http://i.pigsty/pigsty 使用。
Pigsty 的离线软件包是将已经建立好的软件源目录整个打成压缩包:当 Pigsty 尝试构建本地源时,如果发现本地源目录 /www/pigsty 已经存在,且带有 /www/pigsty/repo_complete 标记文件,则会认为本地源已经构建完成,从而跳过从原始上游下载软件的步骤,消除了对互联网访问的依赖。
Repo 定义文件位于 /www/pigsty.repo,默认可以通过 http://${admin_ip}/pigsty.repo 获取。
curl -L http://i.pigsty/pigsty.repo -o /etc/yum.repos.d/pigsty.repo
您也可以在没有 Nginx 的情况下直接使用文件本地源:
[pigsty-local]
name = Pigsty local $releasever - $basearch
baseurl = file:///www/pigsty/
enabled = 1
gpgcheck = 0
更多信息,请参阅:配置:INFRA - REPO
Victoria 可观测性套件 Pigsty v4.0 使用 VictoriaMetrics 系列组件取代 Prometheus/Loki,提供统一的可观测性平台:
VictoriaMetrics :默认监听 8428 端口,可通过 http://p.pigsty 或 https://i.pigsty/vmetrics/ 访问 VMUI,兼容 PromQL、远程读写协议以及 Alertmanager API。VMAlert :在 8880 端口上运行告警规则,将事件发送至 Alertmanager。VictoriaLogs :默认监听 9428 端口,支持通过 https://i.pigsty/vlogs/ 检索日志。节点侧 Vector 会将系统日志、PostgreSQL 日志等结构化后推送至此。VictoriaTraces :监听 10428 端口,提供 Jaeger 兼容接口,便于分析慢 SQL 与链路追踪。Alertmanager :监听 9059 端口,可通过 http://a.pigsty 或 https://i.pigsty/alertmgr/ 管理告警路由与通知。Blackbox Exporter :默认监听 9115 端口,负责 ICMP/TCP/HTTP 黑盒探测。更多信息请参阅:配置:INFRA - VICTORIA 与 配置:INFRA - PROMETHEUS 。
Grafana Grafana 是 Pigsty WebUI 的核心,默认监听 3000 端口,可通过 IP:3000 或 http://g.pigsty 访问。
Pigsty 预置了基于 VictoriaMetrics / Logs / Traces 的 Dashboard,并通过 URL 跳转实现一键下钻上卷,帮助快速定位故障。
Grafana 亦可作为低代码可视化平台使用,因此默认安装 ECharts、victoriametrics-datasource、victorialogs-datasource 等插件,同时将 Vector / Victoria 数据源统一注册为 vmetrics-*、vlogs-*、vtraces-*,方便扩展自定义仪表板。
更多信息请参阅:配置:INFRA - GRAFANA 。
Ansible Pigsty 默认会在元节点上安装 Ansible,Ansible 是一个流行的运维工具,采用声明式的配置风格与幂等的剧本设计,可以极大降低系统维护的复杂度。
DNSMASQ DNSMASQ 提供环境内的 DNS 解析服务,其他模块的域名将会注册到 INFRA 节点上的 DNSMASQ 服务中。
DNS 记录默认放置于所有 INFRA 节点的 /etc/hosts.d/ 目录中。
更多信息,请参阅:配置:INFRA - DNS 与 教程:DNS:配置域名解析
Chronyd NTP 服务用于同步环境内所有节点的时间(可选)。
更多信息,请参阅:配置:NODES - NTP
12.2 - 集群配置 如何配置 Infra 节点?定制 Nginx 服务器的配置与本地软件仓库的内容?配置 DNS,NTP 与监控组件的方法。
配置说明 INFRA 主要用于提供监控 基础设施,对于 PostgreSQL 数据库是可选项 。
除非手工配置了对 INFRA 节点上 DNS/NTP 服务的依赖,否则 INFRA 模块故障通常不影响 PostgreSQL 数据库集群运行。
单个 INFRA 节点足以应对绝大部分场景。生产环境建议使用 2~3 个 INFRA 节点实现高可用。
通常出于提高资源利用率的考虑,PostgreSQL 高可用依赖的 ETCD 模块可以与 INFRA 模块共用节点。
使用 3 个以上的 INFRA 节点意义不大,但可以使用更多 ETCD 节点(如 5 个)提高 DCS 服务可用性。
配置样例 在配置清单中的 infra 分组加入节点 IP,并分配 Infra 实例号 infra_seq。
默认单个 INFRA 节点配置:
all :
children :
infra : { hosts : { 10.10.10.10 : { infra_seq : 1 } }}
默认情况下,10.10.10.10 占位符在配置过程中被替换为当前节点首要 IP 地址。
使用 infra.yml 剧本在节点上初始化 INFRA 模块。
更多节点 两个 INFRA 节点配置:
all :
children :
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
10.10.10.11 : { infra_seq : 2 }
三个 INFRA 节点配置(含参数):
all :
children :
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
10.10.10.11 : { infra_seq: 2, repo_enabled : false }
10.10.10.12 : { infra_seq: 3, repo_enabled : false }
vars :
grafana_clean : false
vmetrics_clean : false
vlogs_clean : false
vtraces_clean : false
Infra 高可用 Infra 模块中的大部分组件都属于"无状态/相同状态",对于这类组件,高可用只需要操心"负载均衡"问题。
高可用可通过 Keepalived L2 VIP 或 HAProxy 四层负载均衡实现。二层互通网络推荐使用 Keepalived L2 VIP。
配置示例:
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
10.10.10.11 : { infra_seq : 2 }
10.10.10.12 : { infra_seq : 3 }
vars :
vip_enabled : true
vip_vrid : 128
vip_address : 10.10.10.8
vip_interface : eth1
infra_portal :
home : { domain : i.pigsty }
grafana : { domain: g.pigsty ,endpoint : "10.10.10.8:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "10.10.10.8:8428" }
alertmanager : { domain: a.pigsty ,endpoint : "10.10.10.8:9059" }
blackbox : { endpoint : "10.10.10.8:9115" }
vmalert : { endpoint : "10.10.10.8:8880" }
需要设置 VIP 相关参数并在 infra_portal 中修改各 Infra 服务端点。
Nginx配置 请参阅 Nginx 参数配置 与 教程:Nginx 。
本地仓库配置 请参阅 Repo 参数配置 。
DNS配置 请参阅 DNS 参数配置 与 教程:DNS 。
NTP配置 请参阅 NTP 参数配置 。
12.3 - 参数列表 INFRA 模块提供了 10 组共 70+ 个配置参数
INFRA 模块负责配置 Pigsty 的基础设施组件:本地软件源、Nginx、DNSMasq、VictoriaMetrics、VictoriaLogs、Grafana、Alertmanager、Blackbox Exporter 等监控告警基础设施。
Pigsty v4.0 使用 VictoriaMetrics 替代 Prometheus,使用 VictoriaLogs 替代 Loki,实现了更优秀的可观测性方案。
参数概览 META 参数组用于定义 Pigsty 的元信息,包括版本号、管理节点 IP、软件源区域、默认语言以及代理设置。
CA 参数组用于配置 Pigsty 自签名 CA 证书管理,包括是否创建 CA、CA 名称以及证书有效期。
INFRA_ID 参数组用于定义基础设施节点的身份标识,包括节点序号、服务门户配置以及数据目录。
REPO 参数组用于配置本地软件仓库,包括仓库启用开关、目录路径、上游源定义以及要下载的软件包列表。
INFRA_PACKAGE 参数组用于定义在基础设施节点上安装的软件包,包括 RPM/DEB 包和 PIP 包。
NGINX 参数组用于配置 Nginx Web 服务器与反向代理,包括启用开关、端口、SSL 模式、证书以及基础认证。
DNS 参数组用于配置 DNSMasq 域名解析服务,包括启用开关、监听端口以及动态 DNS 记录。
VICTORIA 参数组用于配置 VictoriaMetrics/Logs/Traces 可观测性套件,包括启用开关、端口、数据保留策略等。
PROMETHEUS 参数组用于配置 Alertmanager 与 Blackbox Exporter,提供告警管理和网络探测功能。
GRAFANA 参数组用于配置 Grafana 可视化平台,包括启用开关、端口、管理员凭据以及数据源配置。
这一小节指定了一套 Pigsty 部署的元数据:包括版本号,管理员节点 IP 地址,软件源镜像上游区域 ,默认语言,以及下载软件包时使用的 http(s) 代理。
version : v4.0.0 # pigsty 版本号
admin_ip : 10.10.10.10 # 管理节点IP地址
region : default # 上游镜像区域:default,china,europe
language: en # 默认语言 : en 或 zh
proxy_env : # 全局HTTPS代理,用于下载、安装软件包。
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.*,*.myqcloud.com,*.tsinghua.edu.cn"
# http_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# https_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
# all_proxy: # set your proxy here: e.g http://user:pass@proxy.xxx.com
version参数名称: version, 类型: string, 层次:G
Pigsty 版本号字符串,默认值为当前版本:v4.0.0。
Pigsty 内部会使用版本号进行功能控制与内容渲染,请勿随意修改此参数。
Pigsty 使用语义化版本号,版本号字符串通常以字符 v 开头,例如 v4.0.0。
admin_ip参数名称: admin_ip, 类型: ip, 层次:G
管理节点的 IP 地址,默认为占位符 IP 地址:10.10.10.10
由该参数指定的节点将被视为管理节点,通常指向安装 Pigsty 时的第一个节点,即中控节点。
默认值 10.10.10.10 是一个占位符,会在 configure 过程中被替换为实际的管理节点 IP 地址。
许多参数都会引用此参数,例如:
在这些参数中,字符串 ${admin_ip} 会被替换为 admin_ip 的真实取值。使用这种机制,您可以为不同的节点指定不同的中控管理节点。
region参数名称: region, 类型: enum, 层次:G
上游镜像的区域,默认可选值为:default、 china、 europe,默认为: default
如果一个不同于 default 的区域被设置,且在 repo_upstream 中有对应的条目,将会使用该条目对应 baseurl 代替 default 中的 baseurl。
例如,如果您的区域被设置为 china,那么 Pigsty 会尝试使用中国地区的上游软件镜像站点以加速下载,如果某个上游软件仓库没有对应的中国地区镜像,那么会使用默认的上游镜像站点替代。
同时,在 repo_url_packages 中定义的 URL 地址,也会进行从 repo.pigsty.io 到 repo.pigsty.cc 的替换,以使用国内的镜像源。
language参数名称: language, 类型: enum, 层次:G
默认语言设置,可选值为 en(英文) 或 zh(中文),默认为 en。
此参数会影响 Pigsty 生成的部分配置与内容的语言偏好,例如 Grafana 面板的初始语言设置等。
如果您是中国用户,建议将此参数设置为 zh,以获得更好的中文支持体验。
proxy_env参数名称: proxy_env, 类型: dict, 层次:G
下载包时使用的全局代理环境变量,默认值指定了 no_proxy,即不使用代理的地址列表:
proxy_env :
no_proxy : "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.aliyuncs.com,mirrors.tuna.tsinghua.edu.cn,mirrors.zju.edu.cn"
#http_proxy: 'http://username:password@proxy.address.com'
#https_proxy: 'http://username:password@proxy.address.com'
#all_proxy: 'http://username:password@proxy.address.com'
当您在中国大陆地区从互联网上游安装时,特定的软件包可能会被墙,您可以使用代理来解决这个问题。
请注意,如果使用了 Docker 模块,那么这里的代理服务器配置也会写入 Docker Daemon 配置文件中。
请注意,如果在 ./configure 过程中指定了 -x 参数,那么当前环境中的代理配置信息将会被自动填入到生成的 pigsty.yaml 文件中。
CAPigsty 使用自签名 CA 证书,用于支持高级安全特性,例如 HTTPS 访问、PostgreSQL SSL 连接等。
ca_create : true # 如果 CA 不存在,是否创建?默认为 true
ca_cn : pigsty-ca # CA CN名称,固定为 pigsty-ca
cert_validity : 7300d # 证书有效期,默认为 20 年
ca_create参数名称: ca_create, 类型: bool, 层次:G
如果 CA 不存在,是否创建?默认值为 true。
当设置为 true 时,如果 files/pki/ca 目录中不存在 CA 公私钥对,Pigsty 将会自动创建一个新的 CA。
如果您已经有了一对 CA 公私钥对,可以将其复制到 files/pki/ca 目录下:
files/pki/ca/ca.crt:CA 公钥证书files/pki/ca/ca.key:CA 私钥文件Pigsty 将会使用现有的 CA 公私钥对,而不是新建一个。如果 CA 不存在且此参数设置为 false,则会报错终止。
请务必保留并备份好部署过程中新生成的 CA 私钥文件,这对于后续签发新证书至关重要。
注意:Pigsty v3.x 使用的是 ca_method 参数(取值为 create/recreate/copy),v4.0 简化为布尔类型的 ca_create。
ca_cn参数名称: ca_cn, 类型: string, 层次:G
CA CN(Common Name)名称,固定为 pigsty-ca,不建议修改。
你可以使用以下命令来查看节点上的 Pigsty CA 证书详情:
openssl x509 -text -in /etc/pki/ca.crt
cert_validity参数名称: cert_validity, 类型: interval, 层次:G
签发证书的有效期,默认为 20 年,对绝大多数场景都足够了。默认值为: 7300d
此参数影响由 Pigsty CA 签发的所有证书的有效期,包括:
PostgreSQL 服务器证书 Patroni API 证书 etcd 服务器/客户端证书 其他内部服务证书 注意:Nginx 使用的 HTTPS 证书有效期由 nginx_cert_validity 单独控制,因为现代浏览器对网站证书有效期有更严格的要求(最长 397 天)。
INFRA_ID基础设施身份标识与门户定义。
#infra_seq: 1 # 基础设施节点序号,必选身份参数
infra_portal : # 通过 Nginx 门户暴露的基础设施服务
home : { domain : i.pigsty } # 默认首页服务器定义
infra_data : /data/infra # 基础设施默认数据目录
infra_seq参数名称: infra_seq, 类型: int, 层次:I
基础设施节点序号,必选身份参数,必须在基础设施节点上显式指定,所以不提供默认值。
此参数用于在多个基础设施节点的部署中唯一标识每个节点,通常使用从 1 开始的正整数。
示例配置:
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
10.10.10.11 : { infra_seq : 2 }
infra_portal参数名称: infra_portal, 类型: dict, 层次:G
通过 Nginx 门户暴露的基础设施服务列表。v4.0 的默认值非常简洁:
infra_portal :
home : { domain : i.pigsty } # 默认首页服务器定义
Pigsty 会根据实际启用的组件自动配置相应的反向代理,用户通常只需要定义首页域名即可。
每条记录由一个 Key 与一个 Value 字典组成,name 作为键,代表组件名称,value 是一个可以配置以下参数的对象:
name: 必填 ,指定 Nginx 服务器的名称默认记录:home 是固定名称,请不要修改。 作为 Nginx 配置文件名称的一部分,对应配置文件:/etc/nginx/conf.d/<name>.conf 没有 domain 字段的 Nginx 服务器不会生成配置文件,但会被用作引用。 domain: 可选 ,当服务需要通过 Nginx 对外暴露时为必填 字段,指定使用的域名在 Pigsty 自签名 Nginx HTTPS 证书中,域名将被添加到 Nginx SSL 证书的 SAN 字段 Pigsty 网页交叉引用将使用这里的默认域名 endpoint: 通常作为 path 的替代,指定上游服务器地址。设置 endpoint 表示这是一个反向代理服务器配置中可以使用 ${admin_ip} 作为占位符,在部署时会被动态替换为 admin_ip 默认反向代理服务器使用 endpoint.conf 作为配置模板 反向代理服务器还可以配置 websocket 和 schema 参数 path: 通常作为 endpoint 的替代,指定本地文件服务器路径。设置 path 表示这是一个本地 Web 服务器本地 Web 服务器使用 path.conf 作为配置模板 本地 Web 服务器还可以配置 index 参数,是否启用文件索引页 certbot: Certbot 证书名称,如果配置,将使用 Certbot 申请证书如果多个服务器指定相同的 certbot,Pigsty 会合并证书申请,最终证书名称为此 certbot 的值 cert: 证书文件路径,如果配置,将覆盖默认证书路径key: 证书密钥文件路径,如果配置,将覆盖默认证书密钥路径websocket: 是否启用 WebSocket 支持只有反向代理服务器可以配置此参数,如果启用将允许上游使用 WebSocket 连接 schema: 上游服务器使用的协议,如果配置,将覆盖默认协议默认为 http,如果配置为 https 将强制使用 HTTPS 连接到上游服务器 index: 是否启用文件索引页只有本地 Web 服务器可以配置此参数,如果启用将启用 autoindex 配置自动生成目录索引页 log: Nginx 日志文件路径如果指定,访问日志将写入此文件,否则根据服务器类型使用默认日志文件 反向代理服务器使用 /var/log/nginx/<name>.log 作为默认日志文件路径 本地 Web 服务器使用默认 Access 日志 conf: Nginx 配置文件路径config: Nginx 配置代码块直接注入到 Nginx Server 配置块中的配置文本 enforce_https: 将 HTTP 重定向到 HTTPS可以通过 nginx_sslmode: enforce 指定全局配置 此配置不影响默认的 home 服务器,它将始终同时监听 80 和 443 端口以确保兼容性 infra_data参数名称: infra_data, 类型: path, 层次:G
基础设施数据目录,默认值为 /data/infra。
此目录用于存放基础设施组件的数据文件,包括:
VictoriaMetrics 时序数据库数据 VictoriaLogs 日志数据 VictoriaTraces 追踪数据 其他基础设施组件的持久化数据 建议将此目录放置在独立的数据盘上,以便于管理和扩展。
REPO本节配置是关于本地软件仓库的。 Pigsty 默认会在基础设施节点上启用一个本地软件仓库(APT / YUM)。
在初始化过程中,Pigsty 会从互联网上游仓库(由 repo_upstream 指定)下载所有软件包及其依赖项(由 repo_packages 指定)到 {{ nginx_home }} / {{ repo_name }} (默认为 /www/pigsty),所有软件及其依赖的总大小约为 1GB 左右。
创建本地软件仓库时,如果仓库已存在(判断方式:仓库目录中有一个名为 repo_complete 的标记文件)Pigsty 将认为仓库已经创建完成,跳过软件下载阶段,直接使用构建好的仓库。
如果某些软件包的下载速度太慢,您可以通过使用 proxy_env 配置项来设置下载代理来完成首次下载,或直接下载预打包的 离线软件包 ,离线软件包本质上就是在同样操作系统上构建好的本地软件源。
repo_enabled : true # 在此 Infra 节点上创建本地软件仓库?
repo_home : /www # 软件仓库主目录,默认为 /www
repo_name : pigsty # 软件仓库名称,默认为 pigsty
repo_endpoint : http://${admin_ip}:80 # 仓库访问端点
repo_remove : true # 移除现有上游仓库定义
repo_modules : infra,node,pgsql # 启用的上游仓库模块
#repo_upstream: [] # 上游仓库定义(从操作系统变量继承)
#repo_packages: [] # 要下载的软件包(从操作系统变量继承)
#repo_extra_packages: [] # 额外要下载的软件包
repo_url_packages : [] # 通过 URL 下载的额外软件包
repo_enabled参数名称: repo_enabled, 类型: bool, 层次:G/I
是否在当前的基础设施节点上启用本地软件源?默认为: true,即所有 Infra 节点都会设置一个本地软件仓库。
如果您有多个基础设施节点,可以只保留 1~2 个节点作为软件仓库,其他节点可以通过设置此参数为 false 来避免重复软件下载构建。
repo_home参数名称: repo_home, 类型: path, 层次:G
本地软件仓库的家目录,默认为 Nginx 的根目录,也就是: /www。
这个目录实际上是指向 nginx_data 的软链接,不建议修改此目录。如果修改,需要和 nginx_home 保持一致。
repo_name参数名称: repo_name, 类型: string, 层次:G
本地仓库名称,默认为 pigsty,更改此仓库的名称是不明智的行为。
最终的仓库路径为 {{ repo_home }}/{{ repo_name }},默认为 /www/pigsty。
repo_endpoint参数名称: repo_endpoint, 类型: url, 层次:G
其他节点访问此仓库时使用的端点,默认值为:http://${admin_ip}:80。
Pigsty 默认会在基础设施节点 80/443 端口启动 Nginx,对外提供本地软件源(静态文件)服务。
如果您修改了 nginx_port 与 nginx_ssl_port ,或者使用了不同于中控节点的基础设施节点,请相应调整此参数。
如果您使用了域名,可以在 node_default_etc_hosts 、node_etc_hosts 、或者 dns_records 中添加解析。
repo_remove参数名称: repo_remove, 类型: bool, 层次:G/A
在构建本地软件源时,是否移除现有的上游仓库定义?默认值: true。
当启用此参数时,/etc/yum.repos.d 中所有已有仓库文件会被移动备份至 /etc/yum.repos.d/backup,在 Debian 系上是移除 /etc/apt/sources.list 和 /etc/apt/sources.list.d,将文件备份至 /etc/apt/backup 中。
因为操作系统已有的源内容不可控,使用 Pigsty 验证过的上游软件源可以提高从互联网下载软件包的成功率与速度。
但在一些特定情况下(例如您的操作系统是某种 EL/Deb 兼容版,许多软件包使用了自己的私有源),您可能需要保留现有的上游仓库定义,此时可以将此参数设置为 false。
repo_modules参数名称: repo_modules, 类型: string, 层次:G/A
哪些上游仓库模块会被添加到本地软件源中,默认值: infra,node,pgsql
当 Pigsty 尝试添加上游仓库时,会根据此参数的值来过滤 repo_upstream 中的条目,只有 module 字段与此参数值匹配的条目才会被添加到本地软件源中。
模块以逗号分隔,可用的模块列表请参考 repo_upstream 中的定义,常见模块包括:
local: 本地 Pigsty 仓库infra: 基础设施软件包(Nginx、Docker 等)node: 操作系统基础软件包pgsql: PostgreSQL 相关软件包extra: 额外的 PostgreSQL 扩展docker: Docker 相关redis: Redis 相关mongo: MongoDB 相关mysql: MySQL 相关等等… repo_upstream参数名称: repo_upstream, 类型: upstream[], 层次:G
构建本地软件源时,从哪里下载上游软件包?本参数没有默认值,如果用户不在配置文件中显式指定,则会从根据当前节点的操作系统族,从定义于 roles/node_id/vars 中的 repo_upstream_default 变量中加载获取。
Pigsty 为不同的操作系统版本(EL8/9/10, Debian 11/12/13, Ubuntu 22/24)预置了完整的上游仓库定义,包括:
操作系统基础仓库(BaseOS、AppStream、EPEL 等) PostgreSQL 官方 PGDG 仓库 Pigsty 扩展仓库 各种第三方软件仓库(Docker、Nginx、Grafana 等) 每个上游仓库定义包含以下字段:
- name : pigsty-pgsql # 仓库名称
description : 'Pigsty PGSQL' # 仓库描述
module : pgsql # 所属模块
releases : [ 8 , 9 , 10 ] # 支持的操作系统版本
arch : [ x86_64, aarch64] # 支持的 CPU 架构
baseurl : # 仓库 URL,按区域配置
default : 'https://repo.pigsty.io/yum/pgsql/el$releasever.$basearch'
china : 'https://repo.pigsty.cc/yum/pgsql/el$releasever.$basearch'
用户通常不需要修改此参数,除非有特殊的仓库需求。详细的仓库定义请参考 roles/node_id/vars/ 目录下对应操作系统的配置文件。
repo_packages参数名称: repo_packages, 类型: string[], 层次:G
字符串数组类型,每一行都是 由空格分隔 的软件包列表字符串,指定将要使用 repotrack 或 apt download 下载到本地的软件包(及其依赖)。
本参数没有默认值,即默认值为未定义状态。如果该参数没有被显式定义,那么 Pigsty 会从 roles/node_id/vars 中定义的 repo_packages_default 变量中加载获取默认值,默认值为:
[ node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-utility, extra-modules ]
该参数中的每个元素,都会在上述文件中定义的 package_map 中,根据特定的操作系统发行版大版本进行翻译。例如在 EL 系统上会翻译为:
node-bootstrap : "ansible python3 python3-pip python3-virtualenv python3-requests python3-jmespath python3-cryptography dnf-utils modulemd-tools createrepo_c sshpass"
infra-package : "nginx dnsmasq etcd haproxy vip-manager node_exporter keepalived_exporter pg_exporter pgbackrest_exporter redis_exporter redis minio mcli pig"
infra-addons : "grafana grafana-plugins grafana-victoriametrics-ds grafana-victorialogs-ds victoria-metrics victoria-logs victoria-traces vlogscli vmutils vector alertmanager"
作为一个使用约定,repo_packages 中通常包括了那些与 PostgreSQL 大版本号无关的软件包(例如 Infra,Node 和 PGDG Common 等部分),而 PostgreSQL 大版本相关的软件包(内核,扩展),通常在 repo_extra_packages 中指定,方便用户切换 PG 大版本。
参数名称: repo_extra_packages, 类型: string[], 层次:G/C/I
用于在不修改 repo_packages 的基础上,指定额外需要下载的软件包(通常是 PG 大版本相关的软件包),默认值为空列表。
如果该参数没有被显式定义,那么 Pigsty 会从 roles/node_id/vars 中定义的 repo_extra_packages_default 变量中加载获取默认值,默认值为:
该参数中的元素会进行包名翻译,其中 $v 会被替换为 pg_version ,即当前 PG 大版本号(默认为 18)。
这里的 pgsql-main 在 EL 系统上会翻译为:
postgresql$v postgresql$v-server postgresql$v-libs postgresql$v-contrib postgresql$v-plperl postgresql$v-plpython3 postgresql$v-pltcl postgresql$v-llvmjit pg_repack_$v* wal2json_$v* pgvector_$v*
通常用户可以在这里指定 PostgreSQL 大版本相关的软件包,而不影响 repo_packages 中定义的其他 PG 大版本无关的软件包。
repo_url_packages参数名称: repo_url_packages, 类型: object[] | string[], 层次:G
直接使用 URL 从互联网上下载的软件包,默认为空数组: []
您可以直接在本参数中使用 URL 字符串作为数组元素,也可以使用对象结构,显式指定 URL 与文件名称。
请注意,本参数会受到 region 变量的影响,如果您在中国大陆地区,Pigsty 会自动将 URL 替换为国内镜像站点,即将 URL 里的 repo.pigsty.io 替换为 repo.pigsty.cc。
INFRA_PACKAGE这些软件包只会在 INFRA 节点上安装,包括普通的 RPM/DEB 软件包,以及 PIP 软件包。
infra_packages参数名称: infra_packages, 类型: string[], 层次:G
字符串数组类型,每一行都是 由空格分隔 的软件包列表字符串,指定将要在 Infra 节点上安装的软件包列表。
本参数没有默认值,即默认值为未定义状态。如果用户不在配置文件中显式指定本参数,则 Pigsty 会从根据当前节点的操作系统族,从定义于 roles/node_id/vars 中的 infra_packages_default 变量中加载获取默认值。
v4.0 默认值(EL系操作系统):
infra_packages_default :
- grafana,grafana-plugins,grafana-victorialogs-ds,grafana-victoriametrics-ds,victoria-metrics,victoria-logs,victoria-traces,vmutils,vlogscli,alertmanager
- node_exporter,blackbox_exporter,nginx_exporter,pg_exporter,pev2,nginx,dnsmasq,ansible,etcd,python3-requests,redis,mcli,restic,certbot,python3-certbot-nginx
默认值(Debian/Ubuntu):
infra_packages_default :
- grafana,grafana-plugins,grafana-victorialogs-ds,grafana-victoriametrics-ds,victoria-metrics,victoria-logs,victoria-traces,vmutils,vlogscli,alertmanager
- node-exporter,blackbox-exporter,nginx-exporter,pg-exporter,pev2,nginx,dnsmasq,ansible,etcd,python3-requests,redis,mcli,restic,certbot,python3-certbot-nginx
注意:v4.0 使用 VictoriaMetrics 套件替代了 Prometheus 和 Loki,因此软件包列表与 v3.x 有显著差异。
infra_packages_pip参数名称: infra_packages_pip, 类型: string, 层次:G
Infra 节点上要使用 pip 额外安装的软件包,包名使用逗号分隔,默认值是空字符串,即不安装任何额外的 python 包。
示例:
infra_packages_pip : 'requests,boto3,awscli'
NGINXPigsty 会通过 Nginx 代理所有的 Web 服务访问:Home Page、Grafana、VictoriaMetrics 等等。
以及其他可选的工具,如 PGWeb、Jupyter Lab、Pgadmin、Bytebase 等等,还有一些静态资源和报告,如 pev、schemaspy 和 pgbadger。
最重要的是,Nginx 还作为本地软件仓库(Yum/Apt)的 Web 服务器,用于存储和分发 Pigsty 的软件包。
nginx_enabled : true # 在此 Infra 节点上启用 Nginx?
nginx_clean : false # 初始化时清理现有 Nginx 配置?
nginx_exporter_enabled : true # 启用 nginx_exporter?
nginx_exporter_port : 9113 # nginx_exporter 监听端口
nginx_sslmode : enable # SSL 模式:disable,enable,enforce
nginx_cert_validity : 397d # 自签名证书有效期
nginx_home : /www # Nginx 内容目录(软链接)
nginx_data : /data/nginx # Nginx 实际数据目录
nginx_users : {} # 基础认证用户字典
nginx_port : 80 # HTTP 端口
nginx_ssl_port : 443 # HTTPS 端口
certbot_sign : false # 使用 certbot 签署证书?
certbot_email : your@email.com # certbot 邮箱
certbot_options : '' # certbot 额外选项
nginx_enabled参数名称: nginx_enabled, 类型: bool, 层次:G/I
是否在当前的 Infra 节点上启用 Nginx?默认值为: true。
Nginx 是 Pigsty 基础设施的核心组件,负责:
提供本地软件仓库服务 反向代理 Grafana、VictoriaMetrics 等 Web 服务 托管静态文件和报告 nginx_clean参数名称: nginx_clean, 类型: bool, 层次:G/A
初始化时是否清理现有的 Nginx 配置?默认值为: false。
当设置为 true 时,在 Nginx 初始化过程中会删除 /etc/nginx/conf.d/ 下的所有现有配置文件,确保一个干净的起点。
如果您是首次部署或希望完全重建 Nginx 配置,可以将此参数设置为 true。
nginx_exporter_enabled参数名称: nginx_exporter_enabled, 类型: bool, 层次:G/I
在此基础设施节点上启用 nginx_exporter ?默认值为: true。
如果禁用此选项,还会一并禁用 /nginx 健康检查 stub,当您安装使用的 Nginx 版本不支持此功能时可以考虑关闭此开关。
nginx_exporter_port参数名称: nginx_exporter_port, 类型: port, 层次:G
nginx_exporter 监听端口,默认值为 9113。
nginx_exporter 用于收集 Nginx 的运行指标,供 VictoriaMetrics 抓取监控。
nginx_sslmode参数名称: nginx_sslmode, 类型: enum, 层次:G
Nginx 的 SSL 工作模式?有三种选择:disable , enable , enforce, 默认值为 enable,即启用 SSL,但不强制使用。
nginx_cert_validity参数名称: nginx_cert_validity, 类型: duration, 层次:G
Nginx 自签名证书的有效期,默认值为 397d(约13个月)。
现代浏览器要求网站证书的有效期最多为 397 天,因此这是默认值。不建议设置更长的有效期,否则浏览器可能会拒绝信任该证书。
nginx_home参数名称: nginx_home, 类型: path, 层次:G
Nginx 服务器静态文件目录,默认为: /www
这是一个软链接,实际指向 nginx_data 目录。此目录包含静态资源和软件仓库文件。
最好不要随意修改此参数,修改时需要与 repo_home 参数保持一致。
nginx_data参数名称: nginx_data, 类型: path, 层次:G
Nginx 实际数据目录,默认为 /data/nginx。
这是 Nginx 静态文件的实际存储位置,nginx_home 是指向此目录的软链接。
建议将此目录放置在数据盘上,以便于管理大量的软件包文件。
nginx_users参数名称: nginx_users, 类型: dict, 层次:G
Nginx 基础认证(Basic Auth)用户字典,默认为空字典 {}。
格式为 { username: password } 的键值对,例如:
nginx_users :
admin : pigsty
viewer : readonly
这些用户可用于保护某些需要认证的 Nginx 端点。
nginx_port参数名称: nginx_port, 类型: port, 层次:G
Nginx 默认监听的端口(提供 HTTP 服务),默认为 80 端口,最好不要修改这个参数。
当您的服务器 80 端口被占用时,可以考虑修改此参数,但是需要同时修改 repo_endpoint ,以及 node_repo_local_urls 所使用的端口并与这里保持一致。
nginx_ssl_port参数名称: nginx_ssl_port, 类型: port, 层次:G
Nginx SSL 默认监听的端口,默认为 443,最好不要修改这个参数。
certbot_sign参数名称: certbot_sign, 类型: bool, 层次:G/A
是否在安装过程中使用 certbot 签署 Nginx 证书?默认值为 false。
当设置为 true 时,Pigsty 会在执行 infra.yml 和 install.yml 剧本(nginx 角色)期间使用 certbot 自动从 Let’s Encrypt 申请免费 SSL 证书。
在 infra_portal 定义的域名中,如果定义了 certbot 参数,Pigsty 将使用 certbot 为 domain 域名申请证书,证书名称将是 certbot 参数的值。如果多个服务器/域名指定了相同的 certbot 参数,Pigsty 会合并并为这些域名申请一个证书,使用 certbot 参数的值作为证书名称。
启用此选项需要:
当前节点可以通过公共域名访问,并且 DNS 解析已正确指向当前节点的公网 IP 当前节点可以访问 Let’s Encrypt API 接口 此选项默认禁用,您可以在安装后手动执行 make cert 命令来手动执行,它实际上调用渲染好的 /etc/nginx/sign-cert 脚本,使用 certbot 更新或申请证书。
certbot_email参数名称: certbot_email, 类型: string, 层次:G/A
用于接收证书过期提醒邮件的电子邮件地址,默认值为 your@email.com。
当 certbot_sign 设置为 true 时,建议提供此参数。Let’s Encrypt 会在证书即将过期时向此邮箱发送提醒邮件。
certbot_options参数名称: certbot_options, 类型: string, 层次:G/A
传递给 certbot 的额外配置参数,默认值为空字符串。
您可以通过此参数向 certbot 传递额外的命令行选项,例如 --dry-run,则 certbot 不会实际申请证书,而是进行预览和测试。
DNSPigsty 默认会在 Infra 节点上启用 DNSMASQ 服务,用于解析一些辅助域名,例如 i.pigsty、m.pigsty、api.pigsty 等等,以及可选 MinIO 的 sss.pigsty。
解析记录会记录在 Infra 节点的 /etc/hosts.d/default 文件中。 要使用这个 DNS 服务器,您必须将 nameserver <ip> 添加到 /etc/resolv.conf 中,node_dns_servers 参数可以解决这个问题。
dns_enabled : true # 在此 Infra 节点上设置 dnsmasq?
dns_port : 53 # DNS 服务器监听端口
dns_records : # 动态 DNS 记录
- "${admin_ip} i.pigsty"
- "${admin_ip} m.pigsty supa.pigsty api.pigsty adm.pigsty cli.pigsty ddl.pigsty"
dns_enabled参数名称: dns_enabled, 类型: bool, 层次:G/I
是否在这个 Infra 节点上启用 DNSMASQ 服务?默认值为: true。
如果你不想使用默认的 DNS 服务器(比如你已经有了外部的 DNS 服务器,或者您的供应商不允许您使用 DNS 服务器)可以将此值设置为 false 来禁用它。
并使用 node_default_etc_hosts 和 node_etc_hosts 静态解析记录代替。
dns_port参数名称: dns_port, 类型: port, 层次:G
DNSMASQ 的默认监听端口,默认是 53,不建议修改 DNS 服务默认端口。
dns_records参数名称: dns_records, 类型: string[], 层次:G
由 dnsmasq 负责解析的动态 DNS 记录,一般用于将一些辅助域名解析到管理节点。这些记录会被写入到基础设施节点的 /etc/hosts.d/default 文件中。
v4.0 默认值:
dns_records :
- "${admin_ip} i.pigsty"
- "${admin_ip} m.pigsty supa.pigsty api.pigsty adm.pigsty cli.pigsty ddl.pigsty"
这里使用 ${admin_ip} 占位符,在部署时会被替换为实际的 admin_ip 值。
常见的域名用途:
i.pigsty:Pigsty 首页m.pigsty:VictoriaMetrics Web UIapi.pigsty:API 服务adm.pigsty:管理服务其他根据实际部署需求自定义 VICTORIAPigsty v4.0 使用 VictoriaMetrics 套件替代 Prometheus 和 Loki,提供更优秀的可观测性解决方案:
VictoriaMetrics :替代 Prometheus,作为时序数据库存储监控指标VictoriaLogs :替代 Loki,作为日志聚合存储VictoriaTraces :分布式追踪存储VMAlert :替代 Prometheus Alerting,进行告警规则评估vmetrics_enabled : true # 启用 VictoriaMetrics?
vmetrics_clean : false # 初始化时清理数据?
vmetrics_port : 8428 # 监听端口
vmetrics_scrape_interval : 10s # 全局抓取间隔
vmetrics_scrape_timeout : 8s # 全局抓取超时
vmetrics_options : >-
-retentionPeriod=15d
-promscrape.fileSDCheckInterval=5s
vlogs_enabled : true # 启用 VictoriaLogs?
vlogs_clean : false # 初始化时清理数据?
vlogs_port : 9428 # 监听端口
vlogs_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
-insert.maxLineSizeBytes=1MB
-search.maxQueryDuration=120s
vtraces_enabled : true # 启用 VictoriaTraces?
vtraces_clean : false # 初始化时清理数据?
vtraces_port : 10428 # 监听端口
vtraces_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
vmalert_enabled : true # 启用 VMAlert?
vmalert_port : 8880 # 监听端口
vmalert_options : '' # 额外命令行参数
vmetrics_enabled参数名称: vmetrics_enabled, 类型: bool, 层次:G/I
是否在当前 Infra 节点上启用 VictoriaMetrics?默认值为 true。
VictoriaMetrics 是 Pigsty v4.0 的核心监控组件,替代 Prometheus 作为时序数据库,负责:
从各个 Exporter 抓取监控指标 存储时序数据 提供 PromQL 兼容的查询接口 支持 Grafana 数据源 vmetrics_clean参数名称: vmetrics_clean, 类型: bool, 层次:G/A
初始化 VictoriaMetrics 时是否清理现有数据?默认值为 false。
当设置为 true 时,在初始化过程中会删除已有的时序数据。谨慎使用此选项,除非您确定要重建监控数据。
vmetrics_port参数名称: vmetrics_port, 类型: port, 层次:G
VictoriaMetrics 监听端口,默认值为 8428。
此端口用于:
HTTP API 访问 Web UI 访问 Prometheus 兼容的远程写入/读取 Grafana 数据源连接 vmetrics_scrape_interval参数名称: vmetrics_scrape_interval, 类型: interval, 层次:G
VictoriaMetrics 全局指标抓取周期,默认值为 10s。
在生产环境,10秒 - 30秒是一个较为合适的抓取周期。如果您需要更精细的监控数据粒度,可以调整此参数,但会增加存储和 CPU 开销。
vmetrics_scrape_timeout参数名称: vmetrics_scrape_timeout, 类型: interval, 层次:G
VictoriaMetrics 全局抓取超时,默认为 8s。
设置抓取超时可以有效避免监控系统查询导致的雪崩,设置原则是本参数必须小于并接近 vmetrics_scrape_interval ,确保每次抓取时长不超过抓取周期。
vmetrics_options参数名称: vmetrics_options, 类型: arg, 层次:G
VictoriaMetrics 的额外命令行参数,默认值:
vmetrics_options : >-
-retentionPeriod=15d
-promscrape.fileSDCheckInterval=5s
常用参数说明:
-retentionPeriod=15d:数据保留期限,默认 15 天-promscrape.fileSDCheckInterval=5s:文件服务发现刷新间隔您可以根据需要添加其他 VictoriaMetrics 支持的参数。
vlogs_enabled参数名称: vlogs_enabled, 类型: bool, 层次:G/I
是否在当前 Infra 节点上启用 VictoriaLogs?默认值为 true。
VictoriaLogs 替代 Loki 作为日志聚合存储,负责:
接收来自 Vector 的日志数据 存储和索引日志 提供日志查询接口 支持 Grafana VictoriaLogs 数据源 vlogs_clean参数名称: vlogs_clean, 类型: bool, 层次:G/A
初始化 VictoriaLogs 时是否清理现有数据?默认值为 false。
vlogs_port参数名称: vlogs_port, 类型: port, 层次:G
VictoriaLogs 监听端口,默认值为 9428。
vlogs_options参数名称: vlogs_options, 类型: arg, 层次:G
VictoriaLogs 的额外命令行参数,默认值:
vlogs_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
-insert.maxLineSizeBytes=1MB
-search.maxQueryDuration=120s
常用参数说明:
-retentionPeriod=15d:日志保留期限,默认 15 天-retention.maxDiskSpaceUsageBytes=50GiB:最大磁盘使用量-insert.maxLineSizeBytes=1MB:单行日志最大大小-search.maxQueryDuration=120s:查询最大执行时间vtraces_enabled参数名称: vtraces_enabled, 类型: bool, 层次:G/I
是否在当前 Infra 节点上启用 VictoriaTraces?默认值为 true。
VictoriaTraces 用于分布式追踪数据的存储和查询,支持 Jaeger、Zipkin 等追踪协议。
vtraces_clean参数名称: vtraces_clean, 类型: bool, 层次:G/A
初始化 VictoriaTraces 时是否清理现有数据?默认值为 false。
vtraces_port参数名称: vtraces_port, 类型: port, 层次:G
VictoriaTraces 监听端口,默认值为 10428。
vtraces_options参数名称: vtraces_options, 类型: arg, 层次:G
VictoriaTraces 的额外命令行参数,默认值:
vtraces_options : >-
-retentionPeriod=15d
-retention.maxDiskSpaceUsageBytes=50GiB
vmalert_enabled参数名称: vmalert_enabled, 类型: bool, 层次:G/I
是否在当前 Infra 节点上启用 VMAlert?默认值为 true。
VMAlert 负责告警规则评估,替代 Prometheus Alerting 功能,与 Alertmanager 配合使用。
vmalert_port参数名称: vmalert_port, 类型: port, 层次:G
VMAlert 监听端口,默认值为 8880。
vmalert_options参数名称: vmalert_options, 类型: arg, 层次:G
VMAlert 的额外命令行参数,默认值为空字符串。
PROMETHEUS此部分现在主要包含 Blackbox Exporter 和 Alertmanager 的配置。
注意:Pigsty v4.0 使用 VictoriaMetrics 替代 Prometheus,原有的 prometheus_* 和 pushgateway_* 参数已移至 VICTORIA 部分。
blackbox_enabled : true # 启用 blackbox_exporter?
blackbox_port : 9115 # blackbox_exporter 监听端口
blackbox_options : '' # 额外命令行参数
alertmanager_enabled : true # 启用 alertmanager?
alertmanager_port : 9059 # alertmanager 监听端口
alertmanager_options : '' # 额外命令行参数
exporter_metrics_path : /metrics # exporter 指标路径
blackbox_enabled参数名称: blackbox_enabled, 类型: bool, 层次:G/I
是否在当前 Infra 节点上启用 BlackboxExporter?默认值为 true。
BlackboxExporter 会向节点 IP 地址、VIP 地址、PostgreSQL VIP 地址发送 ICMP 报文测试网络连通性,还可以进行 HTTP、TCP、DNS 等探测。
blackbox_port参数名称: blackbox_port, 类型: port, 层次:G
Blackbox Exporter 监听端口,默认值为 9115。
blackbox_options参数名称: blackbox_options, 类型: arg, 层次:G
BlackboxExporter 的额外命令行参数,默认值:空字符串。
alertmanager_enabled参数名称: alertmanager_enabled, 类型: bool, 层次:G/I
是否在当前 Infra 节点上启用 AlertManager?默认值为 true。
AlertManager 负责接收来自 VMAlert 的告警通知,并进行告警分组、抑制、静默、路由等处理。
alertmanager_port参数名称: alertmanager_port, 类型: port, 层次:G
AlertManager 监听端口,默认值为 9059。
如果您修改了此端口,请确保相应更新 infra_portal 中 alertmanager 条目的 endpoint 配置(如果有定义的话)。
alertmanager_options参数名称: alertmanager_options, 类型: arg, 层次:G
AlertManager 的额外命令行参数,默认值:空字符串。
exporter_metrics_path参数名称: exporter_metrics_path, 类型: path, 层次:G
监控 exporter 暴露指标的 HTTP 端点路径,默认为: /metrics,不建议修改此参数。
此参数定义了所有 Exporter 暴露监控指标的标准路径。
GRAFANAPigsty 使用 Grafana 作为监控系统前端。它也可以作为数据分析与可视化平台,或者用于低代码数据应用开发,制作数据应用原型等目的。
grafana_enabled : true # 启用 Grafana?
grafana_port : 3000 # Grafana 监听端口
grafana_clean : true # 初始化时清理数据?
grafana_admin_username : admin # 管理员用户名
grafana_admin_password : pigsty # 管理员密码
grafana_auth_proxy : false # 启用身份代理?
grafana_pgurl : '' # 外部 PostgreSQL URL
grafana_view_password : DBUser.Viewer # PG 数据源密码
grafana_enabled参数名称: grafana_enabled, 类型: bool, 层次:G/I
是否在 Infra 节点上启用 Grafana?默认值为: true,即所有基础设施节点默认都会安装启用 Grafana。
grafana_port参数名称: grafana_port, 类型: port, 层次:G
Grafana 监听端口,默认值为 3000。
如果您需要直接访问 Grafana(不通过 Nginx 反向代理),可以使用此端口。
grafana_clean参数名称: grafana_clean, 类型: bool, 层次:G/A
是否在初始化 Grafana 时一并清理其数据文件?默认为:true。
该操作会移除 /var/lib/grafana/grafana.db,确保 Grafana 全新安装。
如果您希望保留现有的 Grafana 配置(如仪表盘、用户、数据源等),请将此参数设置为 false。
grafana_admin_username参数名称: grafana_admin_username, 类型: username, 层次:G
Grafana 管理员用户名,默认为 admin。
grafana_admin_password参数名称: grafana_admin_password, 类型: password, 层次:G
Grafana 管理员密码,默认为 pigsty。
重要提示:请务必在生产部署中修改此密码参数!
grafana_auth_proxy参数名称: grafana_auth_proxy, 类型: bool, 层次:G
是否启用 Grafana 身份代理?默认为 false。
当启用时,Grafana 会信任反向代理(Nginx)传递的用户身份信息,实现单点登录(SSO)功能。
这通常用于与外部身份认证系统集成的场景。
grafana_pgurl参数名称: grafana_pgurl, 类型: url, 层次:G
外部 PostgreSQL 数据库 URL,用于 Grafana 持久化存储。默认为空字符串。
如果指定,Grafana 将使用此 PostgreSQL 数据库替代默认的 SQLite 数据库存储其配置数据。
格式示例:postgres://grafana:password@pg-meta:5432/grafana?sslmode=disable
这对于需要 Grafana 高可用部署或数据持久化的场景非常有用。
grafana_view_password参数名称: grafana_view_password, 类型: password, 层次:G
Grafana 元数据库 PG 数据源使用的只读用户密码,默认为 DBUser.Viewer。
此密码用于 Grafana 连接 PostgreSQL CMDB 数据源,以只读方式查询元数据。
12.4 - 预置剧本 如何使用预置的 ansible 剧本来管理 INFRA 集群,常用管理命令速查。
Pigsty 提供了三个与 INFRA 模块相关的剧本:
infra.yml在配置文件的 infra 分组所定义的 Infra节点 上初始化基础设施模块。
执行该剧本将完成以下任务:
配置 Infra节点 的目录与环境变量 下载并创建本地软件仓库,加速后续安装 将当前 Infra节点 作为普通节点纳入 Pigsty 管理 部署基础设施组件(VictoriaMetrics/Logs/Traces、VMAlert、Grafana、Alertmanager、Blackbox Exporter 等) 剧本注意事项 :
本剧本为幂等剧本,重复执行会抹除 Infra 节点上的基础设施组件 如需保留历史监控数据,请先将 vmetrics_clean、vlogs_clean、vtraces_clean 设置为 false 除非设置 grafana_clean 为 false,否则 Grafana 监控面板与配置修改会丢失 当本地软件仓库 /www/pigsty/repo_complete 存在时,本剧本会跳过从互联网下载软件的任务 完整执行该剧本耗时约1~3分钟,视机器配置与网络条件而异 可用任务列表 # ca: create self-signed CA on localhost files/pki
# - ca_dir : create CA directory
# - ca_private : generate ca private key: files/pki/ca/ca.key
# - ca_cert : signing ca cert: files/pki/ca/ca.crt
#
# id: generate node identity
#
# repo: bootstrap a local yum repo from internet or offline packages
# - repo_dir : create repo directory
# - repo_check : check repo exists
# - repo_prepare : use existing repo if exists
# - repo_build : build repo from upstream if not exists
# - repo_upstream : handle upstream repo files in /etc/yum.repos.d
# - repo_remove : remove existing repo file if repo_remove == true
# - repo_add : add upstream repo files to /etc/yum.repos.d
# - repo_url_pkg : download packages from internet defined by repo_url_packages
# - repo_cache : make upstream yum cache with yum makecache
# - repo_boot_pkg : install bootstrap pkg such as createrepo_c,yum-utils,...
# - repo_pkg : download packages & dependencies from upstream repo
# - repo_create : create a local yum repo with createrepo_c & modifyrepo_c
# - repo_use : add newly built repo into /etc/yum.repos.d
# - repo_nginx : launch a nginx for repo if no nginx is serving
#
# node/haproxy/docker/monitor: setup infra node as a common node
# - node_name, node_hosts, node_resolv, node_firewall, node_ca, node_repo, node_pkg
# - node_feature, node_kernel, node_tune, node_sysctl, node_profile, node_ulimit
# - node_data, node_admin, node_timezone, node_ntp, node_crontab, node_vip
# - haproxy_install, haproxy_config, haproxy_launch, haproxy_reload
# - docker_install, docker_admin, docker_config, docker_launch, docker_image
# - haproxy_register, node_exporter, node_register, vector
#
# infra: setup infra components
# - infra_env : env_dir, env_pg, env_pgadmin, env_var
# - infra_pkg : infra_pkg_yum, infra_pkg_pip
# - infra_user : setup infra os user group
# - infra_cert : issue cert for infra components
# - dns : dns_config, dns_record, dns_launch
# - nginx : nginx_config, nginx_cert, nginx_static, nginx_launch, nginx_certbot, nginx_reload, nginx_exporter
# - victoria : vmetrics_config, vmetrics_launch, vlogs_config, vlogs_launch, vtraces_config, vtraces_launch, vmalert_config, vmalert_launch
# - alertmanager : alertmanager_config, alertmanager_launch
# - blackbox : blackbox_config, blackbox_launch
# - grafana : grafana_clean, grafana_config, grafana_launch, grafana_provision
# - infra_register : register infra components to victoria
infra-rm.yml从配置文件 infra 分组定义的 Infra节点 上移除 Pigsty 基础设施。
常用子任务包括:
./infra-rm.yml # 移除 INFRA 模块
./infra-rm.yml -t service # 停止 INFRA 上的基础设施服务
./infra-rm.yml -t data # 移除 INFRA 上的存留数据
./infra-rm.yml -t package # 卸载 INFRA 上安装的软件包
install.yml在所有节点上一次性完整安装 Pigsty。
该剧本在 剧本:一次性安装 中有更详细的介绍。
12.5 - 管理预案 基础设施组件与 Infra 集群管理 SOP:创建,销毁,扩容,缩容,证书,仓库……
本章节介绍 Pigsty 部署的日常管理和运维操作。
12.5.1 - Ansible 使用 Ansible 运行管理命令
所有 INFRA 节点上都默认安装了 Ansible,可以用于管理整套部署。
Pigsty 基于 Ansible 实现自动化管理,它遵循 基础设施即代码(Infrastructure-as-Code) 的理念。
对于管理数据库与基础设施而言,Ansible 的知识很有用,但并非必需 。您只需知道如何执行 剧本(Playbook) —— 那些定义了一系列自动化任务的 YAML 文件即可。
安装 Pigsty 在 引导过程 中会尽力自动安装 ansible 及其依赖项。
如需手动安装,请使用以下命令:
# Debian / Ubuntu
sudo apt install -y ansible python3-jmespath
# EL 10
sudo dnf install -y ansible python-jmespath
# EL 8/9
sudo dnf install -y ansible python3.12-jmespath
# EL 7
sudo yum install -y ansible python-jmespath
macOS macOS 用户可使用 Homebrew 安装:
brew install ansible
pip3 install jmespath
基础用法 运行剧本只需执行 ./path/to/playbook.yml 即可。以下是最常用的 Ansible 命令行参数:
用途 参数 说明 在哪里 -l / --limit <pattern>限定目标主机/分组/匹配模式 做什么 -t / --tags <tags>仅运行带有指定标签的任务 怎么做 -e / --extra-vars <vars>传递额外的命令行变量 用什么配置 -i / --inventory <path>指定配置清单文件路径
限定主机 使用 -l|--limit <pattern> 参数可将执行范围限定到特定的分组、主机或匹配模式:
./node.yml # 在所有节点上执行
./pgsql.yml -l pg-test # 仅在 pg-test 集群上执行
./pgsql.yml -l pg-* # 在所有以 pg- 开头的集群上执行
./pgsql.yml -l 10.10.10.10 # 仅在特定 IP 的主机上执行
不指定主机限制直接运行剧本可能非常危险 !缺省情况下,大多数剧本会在 所有(all) 主机上执行。务必谨慎使用!
限定任务 使用 -t|--tags <tags> 参数可仅执行带有指定标签的任务子集:
./infra.yml -t repo # 仅执行创建本地仓库的任务
./infra.yml -t repo_upstream # 仅执行添加上游仓库的任务
./node.yml -t node_pkg # 仅执行安装节点软件包的任务
./pgsql.yml -t pg_hba # 仅执行渲染 pg_hba.conf 的任务
传递变量 使用 -e|--extra-vars <key=value> 参数可在运行时覆盖变量:
./pgsql.yml -e pg_clean = true # 强制清理现有的 PG 实例
./pgsql-rm.yml -e pg_rm_pkg = false # 卸载时保留软件包
./node.yml -e '{"node_tune":"tiny"}' # 使用 JSON 格式传递变量
./pgsql.yml -e @/path/to/config.yml # 从 YAML 文件加载变量
指定配置清单 默认情况下,Ansible 会使用当前目录下的 pigsty.yml 作为配置清单。
使用 -i|--inventory <path> 参数可指定其他配置文件:
./pgsql.yml -i files/pigsty/full.yml -l pg-test
[!NOTE]
若要永久更改默认配置文件的路径,可修改 ansible.cfg 中的 inventory 参数。
12.5.2 - 剧本 Pigsty 内置的 Ansible 剧本
Pigsty 使用幂等的 Ansible 剧本实现管理控制。执行剧本需要将 ansible-playbook 添加到系统 PATH 中,用户需要先 安装 Ansible 才能执行剧本。
可用剧本 模块 剧本 功能 INFRA install.yml一键式安装 Pigsty INFRA infra.yml在基础设施节点上初始化 Pigsty 基础设施 INFRA infra-rm.yml从基础设施节点移除基础设施组件 INFRA cache.yml从目标节点制作离线安装包 INFRA cert.yml使用 Pigsty 自签名 CA 签发证书 NODE node.yml初始化节点,将节点配置到预期状态 NODE node-rm.yml从 Pigsty 中移除节点 PGSQL pgsql.yml初始化高可用 PostgreSQL 集群,或添加新从库 PGSQL pgsql-rm.yml移除 PostgreSQL 集群,或移除从库 PGSQL pgsql-db.yml向现有 PostgreSQL 集群添加新业务数据库 PGSQL pgsql-user.yml向现有 PostgreSQL 集群添加新业务用户 PGSQL pgsql-pitr.yml在现有 PostgreSQL 集群上执行时间点恢复(PITR) PGSQL pgsql-monitor.yml使用本地导出器监控远程 PostgreSQL 实例 PGSQL pgsql-migration.yml为现有 PostgreSQL 生成迁移手册和脚本 PGSQL slim.yml以最小化组件安装 Pigsty REDIS redis.yml初始化 Redis 集群/节点/实例 REDIS redis-rm.yml移除 Redis 集群/节点/实例 ETCD etcd.yml初始化 ETCD 集群,或添加新成员 ETCD etcd-rm.yml移除 ETCD 集群,或移除现有成员 MINIO minio.yml初始化 MinIO 集群 MINIO minio-rm.yml移除 MinIO 集群 DOCKER docker.yml在节点上安装 Docker DOCKER app.yml使用 Docker Compose 安装应用 FERRET mongo.yml在节点上安装 Mongo/FerretDB
部署策略 install.yml 剧本会按照以下分组顺序协调各个专用剧本,完成完整部署:
infra :infra.yml(-l infra)nodes :node.ymletcd :etcd.yml(-l etcd)minio :minio.yml(-l minio)pgsql :pgsql.yml循环依赖说明 :NODE 和 INFRA 之间存在弱循环依赖:要将 NODE 注册到 INFRA,INFRA 必须已经存在;而 INFRA 模块又依赖 NODE 才能工作。
解决方法是先初始化 infra 节点,然后再添加其他节点。如果希望一次性完成所有部署,使用 install.yml 即可。
安全须知 大多数剧本都是幂等 的,这意味着某些部署剧本在未开启保护选项的情况下,可能会擦除现有数据库并创建新数据库 。
使用 pgsql、minio 和 infra 剧本时请特别小心。请仔细阅读文档,谨慎操作。
最佳实践 执行前仔细阅读剧本文档 发现异常时立即按 Ctrl-C 停止 先在非生产环境 中进行测试 使用 -l 参数限定执行主机 ,避免影响非目标主机 使用 -t 参数指定特定标签 ,仅执行部分任务 预演模式 使用 --check --diff 选项可以预览将要进行的更改,而不实际执行:
# 预览将要进行的更改,但不实际执行
./pgsql.yml -l pg-test --check --diff
# 结合标签检查特定任务
./pgsql.yml -l pg-test -t pg_config --check --diff
12.5.3 - Nginx 管理 Nginx 管理,Web 门户配置,Web Server,暴露上游服务
Pigsty 在 INFRA 节点上安装 Nginx 作为所有 Web 服务的入口,默认监听在 80/443 标准端口上。
在 Pigsty 中,你可以通过修改配置清单,让 nginx 对外提供多种服务:
对外暴露 Grafana、VictoriaMetrics(VMUI)、Alertmanager、VictoriaLogs 等监控组件的 Web 界面 提供静态文件服务(如软件仓库、文档站,网站等) 代理自定义的应用服务(如内部应用、数据库管理界面,Docker 应用的界面等) 自动签发自签名的 HTTPS 证书,或者使用 certbot 申请免费的 Let’s Encrypt 证书 通过不同的子域名,使用单一端口对外暴露服务 基础配置 您可以通过 infra_portal 参数定制 Nginx 的行为,
infra_portal :
home : { domain : i.pigsty }
服务器参数 基本参数 参数 说明 domain可选的代理域名 endpoint上游服务地址(IP:PORT 或 socket) path静态内容的本地目录 scheme协议类型(http/https/tcp/udp)
SSL/TLS 选项 参数 说明 certbot启用 Let’s Encrypt 证书管理 cert自定义证书文件路径 key自定义私钥文件路径
高级设置 参数 说明 conf自定义 Nginx 配置模板 domains额外的域名列表 index启用目录列表 log自定义日志文件配置 websocket启用 WebSocket 支持
配置示例 静态文件与目录列表 repo : { domain: repo.pigsty.cc, path : "/www/repo" , index : true }
自定义 SSL 证书 secure_app : {
domain : secure.pigsty.cc,
endpoint : "${admin_ip}:8443" ,
cert : "/etc/ssl/certs/custom.crt" ,
key : "/etc/ssl/private/custom.key"
}
TCP 流代理 pg_primary : { domain: pg.pigsty.cc, endpoint : "10.10.10.11:5432" , scheme : tcp }
管理命令 ./infra.yml -t nginx # 完整重新配置 Nginx
./infra.yml -t nginx_config # 重新生成配置文件
./infra.yml -t nginx_launch # 重启 Nginx 服务
./infra.yml -t nginx_cert # 重新生成 SSL 证书
域名解析 有三种方式将域名解析到 Pigsty 服务器:
公网域名 :通过 DNS 服务商配置内网 DNS 服务器 :配置内部 DNS 解析本地 hosts 文件 :修改 /etc/hosts本地开发时,在 /etc/hosts 中添加:
<your_public_ip_address> i.pigsty g.pigsty p.pigsty a.pigsty
HTTPS 配置 通过 nginx_sslmode 参数配置 HTTPS:
模式 说明 disable仅监听 HTTP(nginx_port) enable同时监听 HTTPS(nginx_ssl_port),默认签发自签名证书 enforce强制跳转到 HTTPS,所有 80 端口请求都会 301 重定向
对于自签名证书,有以下几种访问方式:
在浏览器中信任自签名 CA 使用浏览器安全绕过(Chrome 中输入 “thisisunsafe”) 为生产环境配置正规 CA 签发的证书 最佳实践 使用域名而非 IP:PORT 访问 正确配置 DNS 解析或 hosts 文件 为实时服务启用 WebSocket 生产环境部署 HTTPS 使用有意义的子域名组织服务 监控证书过期时间 集中化代理管理 利用静态文件服务托管文档 12.5.4 - 软件仓库 管理本地 APT/YUM 软件仓库
Pigsty 支持创建和管理本地 APT/YUM 软件仓库,用于在离线环境中部署或加速软件包安装。
快速开始 向本地仓库添加软件包:
将软件包添加到 repo_packages (默认软件包) 将软件包添加到 repo_extra_packages (额外软件包) 执行构建命令: ./infra.yml -t repo_build # 从上游构建本地仓库
./node.yml -t node_repo # 刷新节点仓库缓存
软件包别名 Pigsty 预定义了常用的软件包组合,方便批量安装:
EL 系统(RHEL/CentOS/Rocky) 别名 说明 node-bootstrapAnsible、Python3 工具、SSH 相关 infra-packageNginx、etcd、HAProxy、监控导出器、MinIO 等 pgsql-utilityPatroni、pgBouncer、pgBackRest、PG 工具 pgsql完整 PostgreSQL(服务端、客户端、扩展) pgsql-mini最小化 PostgreSQL 安装
Debian/Ubuntu 系统 别名 说明 node-bootstrapAnsible、开发工具 infra-package基础设施组件(使用 Debian 命名规范) pgsql-clientPostgreSQL 客户端 pgsql-serverPostgreSQL 服务端及相关包
剧本任务 主要任务 任务 说明 repo从互联网或离线包创建本地仓库 repo_build如不存在则从上游构建 repo_upstream添加上游仓库文件 repo_pkg下载软件包及依赖 repo_create创建/更新 YUM 或 APT 仓库 repo_nginx启动 Nginx 文件服务器
完整任务列表 ./infra.yml -t repo_dir # 创建本地软件仓库目录
./infra.yml -t repo_check # 检查本地仓库是否存在
./infra.yml -t repo_prepare # 直接使用已有仓库
./infra.yml -t repo_build # 从上游构建仓库
./infra.yml -t repo_upstream # 添加上游仓库
./infra.yml -t repo_remove # 删除现有仓库文件
./infra.yml -t repo_add # 添加仓库到系统目录
./infra.yml -t repo_url_pkg # 从互联网下载包
./infra.yml -t repo_cache # 创建元数据缓存
./infra.yml -t repo_boot_pkg # 安装引导包
./infra.yml -t repo_pkg # 下载包及依赖
./infra.yml -t repo_create # 创建本地仓库
./infra.yml -t repo_use # 添加新建仓库到系统
./infra.yml -t repo_nginx # 启动 Nginx 文件服务器
常用操作 添加新软件包 # 1. 配置上游仓库
./infra.yml -t repo_upstream
# 2. 下载软件包及依赖
./infra.yml -t repo_pkg
# 3. 构建本地仓库元数据
./infra.yml -t repo_create
刷新节点仓库 ./node.yml -t node_repo # 刷新所有节点的仓库缓存
完整重建仓库 ./infra.yml -t repo # 从互联网或离线包创建仓库
12.5.5 - 域名管理 配置本地或公网域名访问 Pigsty 服务
使用域名代替 IP 地址访问 Pigsty 的各项 Web 服务。
快速开始 将以下静态解析记录添加到 /etc/hosts:
10.10.10.10 i.pigsty g.pigsty p.pigsty a.pigsty
将 IP 地址替换为实际 Pigsty 节点的 IP。
为什么使用域名 比 IP 地址更易于记忆 灵活指向不同 IP 通过 Nginx 统一管理服务 支持 HTTPS 加密 防止某些地区的 ISP 劫持 允许通过代理访问内部绑定的服务 DNS 机制 DNS 协议 :将域名解析为 IP 地址。多个域名可以指向同一个 IP。
HTTP 协议 :使用 Host 头将请求路由到同一端口(80/443)上的不同站点。
默认域名 Pigsty 预定义了以下默认域名:
域名 服务 端口 用途 i.pigstyNginx 80/443 默认首页、本地仓库与统一入口 g.pigstyGrafana 3000 监控与可视化 p.pigstyVictoriaMetrics 8428 VMUI/PromQL 入口 a.pigstyAlertManager 9059 告警路由
解析方式 本地静态解析 在客户端机器的 /etc/hosts 中添加条目:
# Linux/macOS
sudo vim /etc/hosts
# Windows
notepad C:\W indows\S ystem32\d rivers\e tc\h osts
添加内容:
10.10.10.10 i.pigsty g.pigsty p.pigsty a.pigsty
内网动态解析 在内部 DNS 服务器上配置这些域名记录。
公网域名 购买域名并添加 DNS A 记录指向公网 IP。
HTTPS 证书 Pigsty 默认使用自签名证书。可选方案包括:
忽略警告,使用 HTTP 信任自签名 CA 证书 使用真实 CA 或通过 Certbot 获取免费公网域名证书 详见 CA 与证书 文档。
扩展域名 Pigsty 扩展预留了以下域名:
域名 用途 adm.pigsty管理界面 ddl.pigstyDDL 管理 cli.pigsty命令行界面 api.pigstyAPI 服务 lab.pigsty实验环境 git.pigstyGit 服务 wiki.pigstyWiki 文档 noco.pigstyNocoDB supa.pigstySupabase dify.pigstyDify AI odoo.pigstyOdoo ERP mm.pigstyMattermost
12.5.6 - 模块管理 Infra 模块本身的管理 SOP:定义,创建,销毁,扩容,缩容
本文介绍 INFRA 模块的日常管理操作,包括安装、卸载、扩容、以及各组件的管理维护。
安装 Infra 模块 使用 infra.yml 剧本在 infra 分组上安装 INFRA 模块:
./infra.yml # 在 infra 分组上安装 INFRA 模块
卸载 Infra 模块 使用 infra-rm.yml 剧本从 infra 分组上卸载 INFRA 模块:
./infra-rm.yml # 从 infra 分组上卸载 INFRA 模块
扩容 Infra 模块 在配置清单中为新节点分配 infra_seq 并加入 infra 分组:
all :
children :
infra :
hosts :
10.10.10.10 : { infra_seq : 1 } # 原有节点
10.10.10.11 : { infra_seq : 2 } # 新节点
使用限制选项 -l 仅在新节点上执行剧本:
./infra.yml -l 10.10.10.11 # 在新节点上安装 INFRA 模块
管理本地软件仓库 本地软件仓库相关的管理任务:
./infra.yml -t repo # 从互联网或离线包创建仓库
./infra.yml -t repo_upstream # 添加上游仓库
./infra.yml -t repo_pkg # 下载包及依赖
./infra.yml -t repo_create # 创建本地 yum/apt 仓库
完整子任务列表:
./infra.yml -t repo_dir # 创建本地软件仓库
./infra.yml -t repo_check # 检查本地软件仓库是否存在
./infra.yml -t repo_prepare # 直接使用已有仓库
./infra.yml -t repo_build # 从上游构建仓库
./infra.yml -t repo_upstream # 添加上游仓库
./infra.yml -t repo_remove # 删除现有仓库文件
./infra.yml -t repo_add # 添加仓库到系统目录
./infra.yml -t repo_url_pkg # 从互联网下载包
./infra.yml -t repo_cache # 创建元数据缓存
./infra.yml -t repo_boot_pkg # 安装引导包
./infra.yml -t repo_pkg # 下载包及依赖
./infra.yml -t repo_create # 创建本地仓库
./infra.yml -t repo_use # 添加新建仓库到系统
./infra.yml -t repo_nginx # 启动 nginx 文件服务器
管理 Nginx Nginx 相关的管理任务:
./infra.yml -t nginx # 重置 Nginx 组件
./infra.yml -t nginx_index # 重新渲染首页
./infra.yml -t nginx_config,nginx_reload # 重新渲染配置并重载
申请 HTTPS 证书:
./infra.yml -t nginx_certbot,nginx_reload -e certbot_sign = true
管理基础设施组件 基础设施各组件的管理命令:
./infra.yml -t infra # 配置基础设施
./infra.yml -t infra_env # 配置环境变量
./infra.yml -t infra_pkg # 安装软件包
./infra.yml -t infra_user # 设置操作系统用户
./infra.yml -t infra_cert # 颁发证书
./infra.yml -t dns # 配置 DNSMasq
./infra.yml -t nginx # 配置 Nginx
./infra.yml -t victoria # 配置 VictoriaMetrics/Logs/Traces
./infra.yml -t alertmanager # 配置 AlertManager
./infra.yml -t blackbox # 配置 Blackbox Exporter
./infra.yml -t grafana # 配置 Grafana
./infra.yml -t infra_register # 注册到 VictoriaMetrics/Grafana
常用维护命令:
./infra.yml -t nginx_index # 重新渲染首页
./infra.yml -t nginx_config,nginx_reload # 重新配置并重载
./infra.yml -t vmetrics_config,vmetrics_launch # 重新生成 VictoriaMetrics 配置并重启
./infra.yml -t vlogs_config,vlogs_launch # 更新 VictoriaLogs 配置
./infra.yml -t grafana_plugin # 下载 Grafana 插件
12.5.7 - CA 与证书 使用自签名或真实 HTTPS 证书
本文介绍如何使用 Certbot 和 Let’s Encrypt 为 Pigsty 获取和管理 HTTPS 证书。
前置条件 拥有公网域名 DNS 记录指向服务器的公网 IP Nginx 已正确配置 配置步骤 第一步:域名配置 在 infra_portal 中配置需要证书的服务域名(Grafana、VictoriaMetrics、AlertManager、MinIO 等):
infra_portal :
home : { domain : pigsty.cc }
grafana : { domain: g.pigsty.cc, endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty.cc, endpoint : "${admin_ip}:8428" }
alertmanager : { domain: a.pigsty.cc, endpoint : "${admin_ip}:9059" }
第二步:DNS 配置 通过 A 记录将所有域名指向服务器的公网 IP。使用 nslookup 或 dig 验证:
nslookup g.pigsty.cc
dig +short g.pigsty.cc
第三步:申请证书 交互式方式:
certbot --nginx -d pigsty.cc -d g.pigsty.cc -d p.pigsty.cc -d a.pigsty.cc
非交互式方式:
certbot --nginx --agree-tos --email admin@pigsty.cc -n \
-d pigsty.cc -d g.pigsty.cc -d p.pigsty.cc -d a.pigsty.cc
第四步:Nginx 配置 在 portal 条目中添加 certbot: true 参数,然后重新生成配置:
./infra.yml -t nginx_config,nginx_launch
第五步:自动续期 测试续期(预演模式):
设置 cron 定时任务(每月 1 日凌晨 2 点):
0 2 1 * * certbot renew --quiet
或启用 systemd 定时器:
systemctl enable certbot.timer
管理命令 命令 说明 certbot certificates列出所有证书 certbot renew --cert-name domain.com续期指定证书 certbot delete --cert-name domain.com删除证书 certbot revoke --cert-path /path/to/cert.pem吊销证书
故障排查 问题 解决方案 域名无法访问 验证 DNS 传播是否完成 端口 80 被阻止 确保验证时端口 80 开放 请求频率限制 避免短时间内多次申请证书 防火墙问题 开放 80 和 443 端口
最佳实践 使用通配符证书管理子域名 设置证书过期告警监控 定期测试续期流程 备份证书文件 记录域名配置文档 12.6 - 监控告警 如何在 Pigsty 中对基础设施进行自监控?
本文介绍 Pigsty 中 INFRA 模块的监控面板与告警规则。
监控面板 Pigsty 针对 Infra 模块提供了以下监控面板:
告警规则 Pigsty 针对 INFRA 模块提供了以下两条告警规则:
告警规则 描述 InfraDown基础设施组件出现宕机 AgentDown监控 Agent 代理出现宕机
可在 files/victoria/rules/infra.yml 中修改或添加新的基础设施告警规则。
告警规则配置 ################################################################
# Infrastructure Alert Rules #
################################################################
- name : infra-alert
rules :
#==============================================================#
# Infra Aliveness #
#==============================================================#
# infra components (victoria,grafana) down for 1m triggers a P1 alert
- alert : InfraDown
expr : infra_up < 1
for : 1m
labels : { level: 0, severity: CRIT, category : infra }
annotations :
summary : "CRIT InfraDown {{ $labels.type }}@{{ $labels.instance }}"
description : |
infra_up[type={{ $labels.type }}, instance={{ $labels.instance }}] = {{ $value | printf "%.2f" }} < 1
#==============================================================#
# Agent Aliveness #
#==============================================================#
# agent aliveness are determined directly by exporter aliveness
# including: node_exporter, pg_exporter, pgbouncer_exporter, haproxy_exporter
- alert : AgentDown
expr : agent_up < 1
for : 1m
labels : { level: 0, severity: CRIT, category : infra }
annotations :
summary : 'CRIT AgentDown {{ $labels.ins }}@{{ $labels.instance }}'
description : |
agent_up[ins={{ $labels.ins }}, instance={{ $labels.instance }}] = {{ $value | printf "%.2f" }} < 1
12.7 - 指标列表 Pigsty INFRA 模块提供的完整监控指标列表与释义
注意 :Pigsty v4.0 已将 Prometheus/Loki 替换为 VictoriaMetrics/Logs/Traces。以下指标清单仍基于 v3.x 生成,仅供排查旧版本问题参考。若需获取最新指标,请在 https://p.pigsty (VMUI) 或 Grafana 中直接查询,后续版本会重新生成与 Victoria 套件一致的指标速查表。
INFRA 指标 INFRA 模块包含有 964 类可用监控指标。
Metric Name Type Labels Description alertmanager_alerts gauge ins, instance, ip, job, cls, stateHow many alerts by state. alertmanager_alerts_invalid_total counter version, ins, instance, ip, job, clsThe total number of received alerts that were invalid. alertmanager_alerts_received_total counter version, ins, instance, ip, status, job, clsThe total number of received alerts. alertmanager_build_info gauge revision, version, ins, instance, ip, tags, goarch, goversion, job, cls, branch, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which alertmanager was built, and the goos and goarch for the build. alertmanager_cluster_alive_messages_total counter ins, instance, ip, peer, job, clsTotal number of received alive messages. alertmanager_cluster_enabled gauge ins, instance, ip, job, clsIndicates whether the clustering is enabled or not. alertmanager_cluster_failed_peers gauge ins, instance, ip, job, clsNumber indicating the current number of failed peers in the cluster. alertmanager_cluster_health_score gauge ins, instance, ip, job, clsHealth score of the cluster. Lower values are better and zero means ’totally healthy’. alertmanager_cluster_members gauge ins, instance, ip, job, clsNumber indicating current number of members in cluster. alertmanager_cluster_messages_pruned_total counter ins, instance, ip, job, clsTotal number of cluster messages pruned. alertmanager_cluster_messages_queued gauge ins, instance, ip, job, clsNumber of cluster messages which are queued. alertmanager_cluster_messages_received_size_total counter ins, instance, ip, msg_type, job, clsTotal size of cluster messages received. alertmanager_cluster_messages_received_total counter ins, instance, ip, msg_type, job, clsTotal number of cluster messages received. alertmanager_cluster_messages_sent_size_total counter ins, instance, ip, msg_type, job, clsTotal size of cluster messages sent. alertmanager_cluster_messages_sent_total counter ins, instance, ip, msg_type, job, clsTotal number of cluster messages sent. alertmanager_cluster_peer_info gauge ins, instance, ip, peer, job, clsA metric with a constant ‘1’ value labeled by peer name. alertmanager_cluster_peers_joined_total counter ins, instance, ip, job, clsA counter of the number of peers that have joined. alertmanager_cluster_peers_left_total counter ins, instance, ip, job, clsA counter of the number of peers that have left. alertmanager_cluster_peers_update_total counter ins, instance, ip, job, clsA counter of the number of peers that have updated metadata. alertmanager_cluster_reconnections_failed_total counter ins, instance, ip, job, clsA counter of the number of failed cluster peer reconnection attempts. alertmanager_cluster_reconnections_total counter ins, instance, ip, job, clsA counter of the number of cluster peer reconnections. alertmanager_cluster_refresh_join_failed_total counter ins, instance, ip, job, clsA counter of the number of failed cluster peer joined attempts via refresh. alertmanager_cluster_refresh_join_total counter ins, instance, ip, job, clsA counter of the number of cluster peer joined via refresh. alertmanager_config_hash gauge ins, instance, ip, job, clsHash of the currently loaded alertmanager configuration. alertmanager_config_last_reload_success_timestamp_seconds gauge ins, instance, ip, job, clsTimestamp of the last successful configuration reload. alertmanager_config_last_reload_successful gauge ins, instance, ip, job, clsWhether the last configuration reload attempt was successful. alertmanager_dispatcher_aggregation_groups gauge ins, instance, ip, job, clsNumber of active aggregation groups alertmanager_dispatcher_alert_processing_duration_seconds_count Unknown ins, instance, ip, job, clsN/A alertmanager_dispatcher_alert_processing_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A alertmanager_http_concurrency_limit_exceeded_total counter ins, instance, method, ip, job, clsTotal number of times an HTTP request failed because the concurrency limit was reached. alertmanager_http_request_duration_seconds_bucket Unknown ins, instance, method, ip, le, job, cls, handlerN/A alertmanager_http_request_duration_seconds_count Unknown ins, instance, method, ip, job, cls, handlerN/A alertmanager_http_request_duration_seconds_sum Unknown ins, instance, method, ip, job, cls, handlerN/A alertmanager_http_requests_in_flight gauge ins, instance, method, ip, job, clsCurrent number of HTTP requests being processed. alertmanager_http_response_size_bytes_bucket Unknown ins, instance, method, ip, le, job, cls, handlerN/A alertmanager_http_response_size_bytes_count Unknown ins, instance, method, ip, job, cls, handlerN/A alertmanager_http_response_size_bytes_sum Unknown ins, instance, method, ip, job, cls, handlerN/A alertmanager_integrations gauge ins, instance, ip, job, clsNumber of configured integrations. alertmanager_marked_alerts gauge ins, instance, ip, job, cls, stateHow many alerts by state are currently marked in the Alertmanager regardless of their expiry. alertmanager_nflog_gc_duration_seconds_count Unknown ins, instance, ip, job, clsN/A alertmanager_nflog_gc_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A alertmanager_nflog_gossip_messages_propagated_total counter ins, instance, ip, job, clsNumber of received gossip messages that have been further gossiped. alertmanager_nflog_maintenance_errors_total counter ins, instance, ip, job, clsHow many maintenances were executed for the notification log that failed. alertmanager_nflog_maintenance_total counter ins, instance, ip, job, clsHow many maintenances were executed for the notification log. alertmanager_nflog_queries_total counter ins, instance, ip, job, clsNumber of notification log queries were received. alertmanager_nflog_query_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A alertmanager_nflog_query_duration_seconds_count Unknown ins, instance, ip, job, clsN/A alertmanager_nflog_query_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A alertmanager_nflog_query_errors_total counter ins, instance, ip, job, clsNumber notification log received queries that failed. alertmanager_nflog_snapshot_duration_seconds_count Unknown ins, instance, ip, job, clsN/A alertmanager_nflog_snapshot_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A alertmanager_nflog_snapshot_size_bytes gauge ins, instance, ip, job, clsSize of the last notification log snapshot in bytes. alertmanager_notification_latency_seconds_bucket Unknown integration, ins, instance, ip, le, job, clsN/A alertmanager_notification_latency_seconds_count Unknown integration, ins, instance, ip, job, clsN/A alertmanager_notification_latency_seconds_sum Unknown integration, ins, instance, ip, job, clsN/A alertmanager_notification_requests_failed_total counter integration, ins, instance, ip, job, clsThe total number of failed notification requests. alertmanager_notification_requests_total counter integration, ins, instance, ip, job, clsThe total number of attempted notification requests. alertmanager_notifications_failed_total counter integration, ins, instance, ip, reason, job, clsThe total number of failed notifications. alertmanager_notifications_total counter integration, ins, instance, ip, job, clsThe total number of attempted notifications. alertmanager_oversize_gossip_message_duration_seconds_bucket Unknown ins, instance, ip, le, key, job, clsN/A alertmanager_oversize_gossip_message_duration_seconds_count Unknown ins, instance, ip, key, job, clsN/A alertmanager_oversize_gossip_message_duration_seconds_sum Unknown ins, instance, ip, key, job, clsN/A alertmanager_oversized_gossip_message_dropped_total counter ins, instance, ip, key, job, clsNumber of oversized gossip messages that were dropped due to a full message queue. alertmanager_oversized_gossip_message_failure_total counter ins, instance, ip, key, job, clsNumber of oversized gossip message sends that failed. alertmanager_oversized_gossip_message_sent_total counter ins, instance, ip, key, job, clsNumber of oversized gossip message sent. alertmanager_peer_position gauge ins, instance, ip, job, clsPosition the Alertmanager instance believes it’s in. The position determines a peer’s behavior in the cluster. alertmanager_receivers gauge ins, instance, ip, job, clsNumber of configured receivers. alertmanager_silences gauge ins, instance, ip, job, cls, stateHow many silences by state. alertmanager_silences_gc_duration_seconds_count Unknown ins, instance, ip, job, clsN/A alertmanager_silences_gc_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A alertmanager_silences_gossip_messages_propagated_total counter ins, instance, ip, job, clsNumber of received gossip messages that have been further gossiped. alertmanager_silences_maintenance_errors_total counter ins, instance, ip, job, clsHow many maintenances were executed for silences that failed. alertmanager_silences_maintenance_total counter ins, instance, ip, job, clsHow many maintenances were executed for silences. alertmanager_silences_queries_total counter ins, instance, ip, job, clsHow many silence queries were received. alertmanager_silences_query_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A alertmanager_silences_query_duration_seconds_count Unknown ins, instance, ip, job, clsN/A alertmanager_silences_query_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A alertmanager_silences_query_errors_total counter ins, instance, ip, job, clsHow many silence received queries did not succeed. alertmanager_silences_snapshot_duration_seconds_count Unknown ins, instance, ip, job, clsN/A alertmanager_silences_snapshot_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A alertmanager_silences_snapshot_size_bytes gauge ins, instance, ip, job, clsSize of the last silence snapshot in bytes. blackbox_exporter_build_info gauge revision, version, ins, instance, ip, tags, goarch, goversion, job, cls, branch, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which blackbox_exporter was built, and the goos and goarch for the build. blackbox_exporter_config_last_reload_success_timestamp_seconds gauge ins, instance, ip, job, clsTimestamp of the last successful configuration reload. blackbox_exporter_config_last_reload_successful gauge ins, instance, ip, job, clsBlackbox exporter config loaded successfully. blackbox_module_unknown_total counter ins, instance, ip, job, clsCount of unknown modules requested by probes cortex_distributor_ingester_clients gauge ins, instance, ip, job, clsThe current number of ingester clients. cortex_dns_failures_total Unknown ins, instance, ip, job, clsN/A cortex_dns_lookups_total Unknown ins, instance, ip, job, clsN/A cortex_frontend_query_range_duration_seconds_bucket Unknown ins, instance, method, ip, le, job, cls, status_codeN/A cortex_frontend_query_range_duration_seconds_count Unknown ins, instance, method, ip, job, cls, status_codeN/A cortex_frontend_query_range_duration_seconds_sum Unknown ins, instance, method, ip, job, cls, status_codeN/A cortex_ingester_flush_queue_length gauge ins, instance, ip, job, clsThe total number of series pending in the flush queue. cortex_kv_request_duration_seconds_bucket Unknown ins, instance, role, ip, le, kv_name, type, operation, job, cls, status_codeN/A cortex_kv_request_duration_seconds_count Unknown ins, instance, role, ip, kv_name, type, operation, job, cls, status_codeN/A cortex_kv_request_duration_seconds_sum Unknown ins, instance, role, ip, kv_name, type, operation, job, cls, status_codeN/A cortex_member_consul_heartbeats_total Unknown ins, instance, ip, job, clsN/A cortex_prometheus_notifications_alertmanagers_discovered gauge ins, instance, ip, user, job, clsThe number of alertmanagers discovered and active. cortex_prometheus_notifications_dropped_total Unknown ins, instance, ip, user, job, clsN/A cortex_prometheus_notifications_queue_capacity gauge ins, instance, ip, user, job, clsThe capacity of the alert notifications queue. cortex_prometheus_notifications_queue_length gauge ins, instance, ip, user, job, clsThe number of alert notifications in the queue. cortex_prometheus_rule_evaluation_duration_seconds summary ins, instance, ip, user, job, cls, quantileThe duration for a rule to execute. cortex_prometheus_rule_evaluation_duration_seconds_count Unknown ins, instance, ip, user, job, clsN/A cortex_prometheus_rule_evaluation_duration_seconds_sum Unknown ins, instance, ip, user, job, clsN/A cortex_prometheus_rule_group_duration_seconds summary ins, instance, ip, user, job, cls, quantileThe duration of rule group evaluations. cortex_prometheus_rule_group_duration_seconds_count Unknown ins, instance, ip, user, job, clsN/A cortex_prometheus_rule_group_duration_seconds_sum Unknown ins, instance, ip, user, job, clsN/A cortex_query_frontend_connected_schedulers gauge ins, instance, ip, job, clsNumber of schedulers this frontend is connected to. cortex_query_frontend_queries_in_progress gauge ins, instance, ip, job, clsNumber of queries in progress handled by this frontend. cortex_query_frontend_retries_bucket Unknown ins, instance, ip, le, job, clsN/A cortex_query_frontend_retries_count Unknown ins, instance, ip, job, clsN/A cortex_query_frontend_retries_sum Unknown ins, instance, ip, job, clsN/A cortex_query_scheduler_connected_frontend_clients gauge ins, instance, ip, job, clsNumber of query-frontend worker clients currently connected to the query-scheduler. cortex_query_scheduler_connected_querier_clients gauge ins, instance, ip, job, clsNumber of querier worker clients currently connected to the query-scheduler. cortex_query_scheduler_inflight_requests summary ins, instance, ip, job, cls, quantileNumber of inflight requests (either queued or processing) sampled at a regular interval. Quantile buckets keep track of inflight requests over the last 60s. cortex_query_scheduler_inflight_requests_count Unknown ins, instance, ip, job, clsN/A cortex_query_scheduler_inflight_requests_sum Unknown ins, instance, ip, job, clsN/A cortex_query_scheduler_queue_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A cortex_query_scheduler_queue_duration_seconds_count Unknown ins, instance, ip, job, clsN/A cortex_query_scheduler_queue_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A cortex_query_scheduler_queue_length Unknown ins, instance, ip, user, job, clsN/A cortex_query_scheduler_running gauge ins, instance, ip, job, clsValue will be 1 if the scheduler is in the ReplicationSet and actively receiving/processing requests cortex_ring_member_heartbeats_total Unknown ins, instance, ip, job, clsN/A cortex_ring_member_tokens_owned gauge ins, instance, ip, job, clsThe number of tokens owned in the ring. cortex_ring_member_tokens_to_own gauge ins, instance, ip, job, clsThe number of tokens to own in the ring. cortex_ring_members gauge ins, instance, ip, job, cls, stateNumber of members in the ring cortex_ring_oldest_member_timestamp gauge ins, instance, ip, job, cls, stateTimestamp of the oldest member in the ring. cortex_ring_tokens_total gauge ins, instance, ip, job, clsNumber of tokens in the ring cortex_ruler_clients gauge ins, instance, ip, job, clsThe current number of ruler clients in the pool. cortex_ruler_config_last_reload_successful gauge ins, instance, ip, user, job, clsBoolean set to 1 whenever the last configuration reload attempt was successful. cortex_ruler_config_last_reload_successful_seconds gauge ins, instance, ip, user, job, clsTimestamp of the last successful configuration reload. cortex_ruler_config_updates_total Unknown ins, instance, ip, user, job, clsN/A cortex_ruler_managers_total gauge ins, instance, ip, job, clsTotal number of managers registered and running in the ruler cortex_ruler_ring_check_errors_total Unknown ins, instance, ip, job, clsN/A cortex_ruler_sync_rules_total Unknown ins, instance, ip, reason, job, clsN/A deprecated_flags_inuse_total Unknown ins, instance, ip, job, clsN/A go_cgo_go_to_c_calls_calls_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_gc_mark_assist_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_gc_mark_dedicated_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_gc_mark_idle_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_gc_pause_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_gc_total_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_idle_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_scavenge_assist_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_scavenge_background_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_scavenge_total_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_total_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_cpu_classes_user_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A go_gc_cycles_automatic_gc_cycles_total Unknown ins, instance, ip, job, clsN/A go_gc_cycles_forced_gc_cycles_total Unknown ins, instance, ip, job, clsN/A go_gc_cycles_total_gc_cycles_total Unknown ins, instance, ip, job, clsN/A go_gc_duration_seconds summary ins, instance, ip, job, cls, quantileA summary of the pause duration of garbage collection cycles. go_gc_duration_seconds_count Unknown ins, instance, ip, job, clsN/A go_gc_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A go_gc_gogc_percent gauge ins, instance, ip, job, clsHeap size target percentage configured by the user, otherwise 100. This value is set by the GOGC environment variable, and the runtime/debug.SetGCPercent function. go_gc_gomemlimit_bytes gauge ins, instance, ip, job, clsGo runtime memory limit configured by the user, otherwise math.MaxInt64. This value is set by the GOMEMLIMIT environment variable, and the runtime/debug.SetMemoryLimit function. go_gc_heap_allocs_by_size_bytes_bucket Unknown ins, instance, ip, le, job, clsN/A go_gc_heap_allocs_by_size_bytes_count Unknown ins, instance, ip, job, clsN/A go_gc_heap_allocs_by_size_bytes_sum Unknown ins, instance, ip, job, clsN/A go_gc_heap_allocs_bytes_total Unknown ins, instance, ip, job, clsN/A go_gc_heap_allocs_objects_total Unknown ins, instance, ip, job, clsN/A go_gc_heap_frees_by_size_bytes_bucket Unknown ins, instance, ip, le, job, clsN/A go_gc_heap_frees_by_size_bytes_count Unknown ins, instance, ip, job, clsN/A go_gc_heap_frees_by_size_bytes_sum Unknown ins, instance, ip, job, clsN/A go_gc_heap_frees_bytes_total Unknown ins, instance, ip, job, clsN/A go_gc_heap_frees_objects_total Unknown ins, instance, ip, job, clsN/A go_gc_heap_goal_bytes gauge ins, instance, ip, job, clsHeap size target for the end of the GC cycle. go_gc_heap_live_bytes gauge ins, instance, ip, job, clsHeap memory occupied by live objects that were marked by the previous GC. go_gc_heap_objects_objects gauge ins, instance, ip, job, clsNumber of objects, live or unswept, occupying heap memory. go_gc_heap_tiny_allocs_objects_total Unknown ins, instance, ip, job, clsN/A go_gc_limiter_last_enabled_gc_cycle gauge ins, instance, ip, job, clsGC cycle the last time the GC CPU limiter was enabled. This metric is useful for diagnosing the root cause of an out-of-memory error, because the limiter trades memory for CPU time when the GC’s CPU time gets too high. This is most likely to occur with use of SetMemoryLimit. The first GC cycle is cycle 1, so a value of 0 indicates that it was never enabled. go_gc_pauses_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A go_gc_pauses_seconds_count Unknown ins, instance, ip, job, clsN/A go_gc_pauses_seconds_sum Unknown ins, instance, ip, job, clsN/A go_gc_scan_globals_bytes gauge ins, instance, ip, job, clsThe total amount of global variable space that is scannable. go_gc_scan_heap_bytes gauge ins, instance, ip, job, clsThe total amount of heap space that is scannable. go_gc_scan_stack_bytes gauge ins, instance, ip, job, clsThe number of bytes of stack that were scanned last GC cycle. go_gc_scan_total_bytes gauge ins, instance, ip, job, clsThe total amount space that is scannable. Sum of all metrics in /gc/scan. go_gc_stack_starting_size_bytes gauge ins, instance, ip, job, clsThe stack size of new goroutines. go_godebug_non_default_behavior_execerrdot_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_gocachehash_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_gocachetest_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_gocacheverify_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_http2client_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_http2server_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_installgoroot_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_jstmpllitinterp_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_multipartmaxheaders_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_multipartmaxparts_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_multipathtcp_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_panicnil_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_randautoseed_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_tarinsecurepath_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_tlsmaxrsasize_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_x509sha1_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_x509usefallbackroots_events_total Unknown ins, instance, ip, job, clsN/A go_godebug_non_default_behavior_zipinsecurepath_events_total Unknown ins, instance, ip, job, clsN/A go_goroutines gauge ins, instance, ip, job, clsNumber of goroutines that currently exist. go_info gauge version, ins, instance, ip, job, clsInformation about the Go environment. go_memory_classes_heap_free_bytes gauge ins, instance, ip, job, clsMemory that is completely free and eligible to be returned to the underlying system, but has not been. This metric is the runtime’s estimate of free address space that is backed by physical memory. go_memory_classes_heap_objects_bytes gauge ins, instance, ip, job, clsMemory occupied by live objects and dead objects that have not yet been marked free by the garbage collector. go_memory_classes_heap_released_bytes gauge ins, instance, ip, job, clsMemory that is completely free and has been returned to the underlying system. This metric is the runtime’s estimate of free address space that is still mapped into the process, but is not backed by physical memory. go_memory_classes_heap_stacks_bytes gauge ins, instance, ip, job, clsMemory allocated from the heap that is reserved for stack space, whether or not it is currently in-use. Currently, this represents all stack memory for goroutines. It also includes all OS thread stacks in non-cgo programs. Note that stacks may be allocated differently in the future, and this may change. go_memory_classes_heap_unused_bytes gauge ins, instance, ip, job, clsMemory that is reserved for heap objects but is not currently used to hold heap objects. go_memory_classes_metadata_mcache_free_bytes gauge ins, instance, ip, job, clsMemory that is reserved for runtime mcache structures, but not in-use. go_memory_classes_metadata_mcache_inuse_bytes gauge ins, instance, ip, job, clsMemory that is occupied by runtime mcache structures that are currently being used. go_memory_classes_metadata_mspan_free_bytes gauge ins, instance, ip, job, clsMemory that is reserved for runtime mspan structures, but not in-use. go_memory_classes_metadata_mspan_inuse_bytes gauge ins, instance, ip, job, clsMemory that is occupied by runtime mspan structures that are currently being used. go_memory_classes_metadata_other_bytes gauge ins, instance, ip, job, clsMemory that is reserved for or used to hold runtime metadata. go_memory_classes_os_stacks_bytes gauge ins, instance, ip, job, clsStack memory allocated by the underlying operating system. In non-cgo programs this metric is currently zero. This may change in the future.In cgo programs this metric includes OS thread stacks allocated directly from the OS. Currently, this only accounts for one stack in c-shared and c-archive build modes, and other sources of stacks from the OS are not measured. This too may change in the future. go_memory_classes_other_bytes gauge ins, instance, ip, job, clsMemory used by execution trace buffers, structures for debugging the runtime, finalizer and profiler specials, and more. go_memory_classes_profiling_buckets_bytes gauge ins, instance, ip, job, clsMemory that is used by the stack trace hash map used for profiling. go_memory_classes_total_bytes gauge ins, instance, ip, job, clsAll memory mapped by the Go runtime into the current process as read-write. Note that this does not include memory mapped by code called via cgo or via the syscall package. Sum of all metrics in /memory/classes. go_memstats_alloc_bytes counter ins, instance, ip, job, clsTotal number of bytes allocated, even if freed. go_memstats_alloc_bytes_total counter ins, instance, ip, job, clsTotal number of bytes allocated, even if freed. go_memstats_buck_hash_sys_bytes gauge ins, instance, ip, job, clsNumber of bytes used by the profiling bucket hash table. go_memstats_frees_total counter ins, instance, ip, job, clsTotal number of frees. go_memstats_gc_sys_bytes gauge ins, instance, ip, job, clsNumber of bytes used for garbage collection system metadata. go_memstats_heap_alloc_bytes gauge ins, instance, ip, job, clsNumber of heap bytes allocated and still in use. go_memstats_heap_idle_bytes gauge ins, instance, ip, job, clsNumber of heap bytes waiting to be used. go_memstats_heap_inuse_bytes gauge ins, instance, ip, job, clsNumber of heap bytes that are in use. go_memstats_heap_objects gauge ins, instance, ip, job, clsNumber of allocated objects. go_memstats_heap_released_bytes gauge ins, instance, ip, job, clsNumber of heap bytes released to OS. go_memstats_heap_sys_bytes gauge ins, instance, ip, job, clsNumber of heap bytes obtained from system. go_memstats_last_gc_time_seconds gauge ins, instance, ip, job, clsNumber of seconds since 1970 of last garbage collection. go_memstats_lookups_total counter ins, instance, ip, job, clsTotal number of pointer lookups. go_memstats_mallocs_total counter ins, instance, ip, job, clsTotal number of mallocs. go_memstats_mcache_inuse_bytes gauge ins, instance, ip, job, clsNumber of bytes in use by mcache structures. go_memstats_mcache_sys_bytes gauge ins, instance, ip, job, clsNumber of bytes used for mcache structures obtained from system. go_memstats_mspan_inuse_bytes gauge ins, instance, ip, job, clsNumber of bytes in use by mspan structures. go_memstats_mspan_sys_bytes gauge ins, instance, ip, job, clsNumber of bytes used for mspan structures obtained from system. go_memstats_next_gc_bytes gauge ins, instance, ip, job, clsNumber of heap bytes when next garbage collection will take place. go_memstats_other_sys_bytes gauge ins, instance, ip, job, clsNumber of bytes used for other system allocations. go_memstats_stack_inuse_bytes gauge ins, instance, ip, job, clsNumber of bytes in use by the stack allocator. go_memstats_stack_sys_bytes gauge ins, instance, ip, job, clsNumber of bytes obtained from system for stack allocator. go_memstats_sys_bytes gauge ins, instance, ip, job, clsNumber of bytes obtained from system. go_sched_gomaxprocs_threads gauge ins, instance, ip, job, clsThe current runtime.GOMAXPROCS setting, or the number of operating system threads that can execute user-level Go code simultaneously. go_sched_goroutines_goroutines gauge ins, instance, ip, job, clsCount of live goroutines. go_sched_latencies_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A go_sched_latencies_seconds_count Unknown ins, instance, ip, job, clsN/A go_sched_latencies_seconds_sum Unknown ins, instance, ip, job, clsN/A go_sql_stats_connections_blocked_seconds unknown ins, instance, db_name, ip, job, clsThe total time blocked waiting for a new connection. go_sql_stats_connections_closed_max_idle unknown ins, instance, db_name, ip, job, clsThe total number of connections closed due to SetMaxIdleConns. go_sql_stats_connections_closed_max_idle_time unknown ins, instance, db_name, ip, job, clsThe total number of connections closed due to SetConnMaxIdleTime. go_sql_stats_connections_closed_max_lifetime unknown ins, instance, db_name, ip, job, clsThe total number of connections closed due to SetConnMaxLifetime. go_sql_stats_connections_idle gauge ins, instance, db_name, ip, job, clsThe number of idle connections. go_sql_stats_connections_in_use gauge ins, instance, db_name, ip, job, clsThe number of connections currently in use. go_sql_stats_connections_max_open gauge ins, instance, db_name, ip, job, clsMaximum number of open connections to the database. go_sql_stats_connections_open gauge ins, instance, db_name, ip, job, clsThe number of established connections both in use and idle. go_sql_stats_connections_waited_for unknown ins, instance, db_name, ip, job, clsThe total number of connections waited for. go_sync_mutex_wait_total_seconds_total Unknown ins, instance, ip, job, clsN/A go_threads gauge ins, instance, ip, job, clsNumber of OS threads created. grafana_access_evaluation_count unknown ins, instance, ip, job, clsnumber of evaluation calls grafana_access_evaluation_duration_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_access_evaluation_duration_count Unknown ins, instance, ip, job, clsN/A grafana_access_evaluation_duration_sum Unknown ins, instance, ip, job, clsN/A grafana_access_permissions_duration_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_access_permissions_duration_count Unknown ins, instance, ip, job, clsN/A grafana_access_permissions_duration_sum Unknown ins, instance, ip, job, clsN/A grafana_aggregator_discovery_aggregation_count_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_active_alerts gauge ins, instance, ip, job, clsamount of active alerts grafana_alerting_active_configurations gauge ins, instance, ip, job, clsThe number of active Alertmanager configurations. grafana_alerting_alertmanager_config_match gauge ins, instance, ip, job, clsThe total number of match grafana_alerting_alertmanager_config_match_re gauge ins, instance, ip, job, clsThe total number of matchRE grafana_alerting_alertmanager_config_matchers gauge ins, instance, ip, job, clsThe total number of matchers grafana_alerting_alertmanager_config_object_matchers gauge ins, instance, ip, job, clsThe total number of object_matchers grafana_alerting_discovered_configurations gauge ins, instance, ip, job, clsThe number of organizations we’ve discovered that require an Alertmanager configuration. grafana_alerting_dispatcher_aggregation_groups gauge ins, instance, ip, job, clsNumber of active aggregation groups grafana_alerting_dispatcher_alert_processing_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_dispatcher_alert_processing_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_execution_time_milliseconds summary ins, instance, ip, job, cls, quantilesummary of alert execution duration grafana_alerting_execution_time_milliseconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_execution_time_milliseconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_gc_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_gc_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_gossip_messages_propagated_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_queries_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_query_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_alerting_nflog_query_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_query_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_query_errors_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_snapshot_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_snapshot_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_nflog_snapshot_size_bytes gauge ins, instance, ip, job, clsSize of the last notification log snapshot in bytes. grafana_alerting_notification_latency_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_alerting_notification_latency_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_notification_latency_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_schedule_alert_rules gauge ins, instance, ip, job, clsThe number of alert rules that could be considered for evaluation at the next tick. grafana_alerting_schedule_alert_rules_hash gauge ins, instance, ip, job, clsA hash of the alert rules that could be considered for evaluation at the next tick. grafana_alerting_schedule_periodic_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_alerting_schedule_periodic_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_schedule_periodic_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_schedule_query_alert_rules_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_alerting_schedule_query_alert_rules_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_schedule_query_alert_rules_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_scheduler_behind_seconds gauge ins, instance, ip, job, clsThe total number of seconds the scheduler is behind. grafana_alerting_silences_gc_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_gc_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_gossip_messages_propagated_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_queries_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_query_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_alerting_silences_query_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_query_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_query_errors_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_snapshot_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_snapshot_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_silences_snapshot_size_bytes gauge ins, instance, ip, job, clsSize of the last silence snapshot in bytes. grafana_alerting_state_calculation_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_alerting_state_calculation_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_alerting_state_calculation_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_alerting_state_history_writes_bytes_total Unknown ins, instance, ip, job, clsN/A grafana_alerting_ticker_interval_seconds gauge ins, instance, ip, job, clsInterval at which the ticker is meant to tick. grafana_alerting_ticker_last_consumed_tick_timestamp_seconds gauge ins, instance, ip, job, clsTimestamp of the last consumed tick in seconds. grafana_alerting_ticker_next_tick_timestamp_seconds gauge ins, instance, ip, job, clsTimestamp of the next tick in seconds before it is consumed. grafana_api_admin_user_created_total Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_get_milliseconds summary ins, instance, ip, job, cls, quantilesummary for dashboard get duration grafana_api_dashboard_get_milliseconds_count Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_get_milliseconds_sum Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_save_milliseconds summary ins, instance, ip, job, cls, quantilesummary for dashboard save duration grafana_api_dashboard_save_milliseconds_count Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_save_milliseconds_sum Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_search_milliseconds summary ins, instance, ip, job, cls, quantilesummary for dashboard search duration grafana_api_dashboard_search_milliseconds_count Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_search_milliseconds_sum Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_snapshot_create_total Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_snapshot_external_total Unknown ins, instance, ip, job, clsN/A grafana_api_dashboard_snapshot_get_total Unknown ins, instance, ip, job, clsN/A grafana_api_dataproxy_request_all_milliseconds summary ins, instance, ip, job, cls, quantilesummary for dataproxy request duration grafana_api_dataproxy_request_all_milliseconds_count Unknown ins, instance, ip, job, clsN/A grafana_api_dataproxy_request_all_milliseconds_sum Unknown ins, instance, ip, job, clsN/A grafana_api_login_oauth_total Unknown ins, instance, ip, job, clsN/A grafana_api_login_post_total Unknown ins, instance, ip, job, clsN/A grafana_api_login_saml_total Unknown ins, instance, ip, job, clsN/A grafana_api_models_dashboard_insert_total Unknown ins, instance, ip, job, clsN/A grafana_api_org_create_total Unknown ins, instance, ip, job, clsN/A grafana_api_response_status_total Unknown ins, instance, ip, job, cls, codeN/A grafana_api_user_signup_completed_total Unknown ins, instance, ip, job, clsN/A grafana_api_user_signup_invite_total Unknown ins, instance, ip, job, clsN/A grafana_api_user_signup_started_total Unknown ins, instance, ip, job, clsN/A grafana_apiserver_audit_event_total Unknown ins, instance, ip, job, clsN/A grafana_apiserver_audit_requests_rejected_total Unknown ins, instance, ip, job, clsN/A grafana_apiserver_client_certificate_expiration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_apiserver_client_certificate_expiration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_apiserver_client_certificate_expiration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_apiserver_envelope_encryption_dek_cache_fill_percent gauge ins, instance, ip, job, cls[ALPHA] Percent of the cache slots currently occupied by cached DEKs. grafana_apiserver_flowcontrol_seat_fair_frac gauge ins, instance, ip, job, cls[ALPHA] Fair fraction of server’s concurrency to allocate to each priority level that can use it grafana_apiserver_storage_data_key_generation_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_apiserver_storage_data_key_generation_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_apiserver_storage_data_key_generation_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_apiserver_storage_data_key_generation_failures_total Unknown ins, instance, ip, job, clsN/A grafana_apiserver_storage_envelope_transformation_cache_misses_total Unknown ins, instance, ip, job, clsN/A grafana_apiserver_tls_handshake_errors_total Unknown ins, instance, ip, job, clsN/A grafana_apiserver_webhooks_x509_insecure_sha1_total Unknown ins, instance, ip, job, clsN/A grafana_apiserver_webhooks_x509_missing_san_total Unknown ins, instance, ip, job, clsN/A grafana_authn_authn_failed_authentication_total Unknown ins, instance, ip, job, clsN/A grafana_authn_authn_successful_authentication_total Unknown ins, instance, ip, client, job, clsN/A grafana_authn_authn_successful_login_total Unknown ins, instance, ip, client, job, clsN/A grafana_aws_cloudwatch_get_metric_data_total Unknown ins, instance, ip, job, clsN/A grafana_aws_cloudwatch_get_metric_statistics_total Unknown ins, instance, ip, job, clsN/A grafana_aws_cloudwatch_list_metrics_total Unknown ins, instance, ip, job, clsN/A grafana_build_info gauge revision, version, ins, instance, edition, ip, goversion, job, cls, branchA metric with a constant ‘1’ value labeled by version, revision, branch, and goversion from which Grafana was built grafana_build_timestamp gauge revision, version, ins, instance, edition, ip, goversion, job, cls, branchA metric exposing when the binary was built in epoch grafana_cardinality_enforcement_unexpected_categorizations_total Unknown ins, instance, ip, job, clsN/A grafana_database_conn_idle gauge ins, instance, ip, job, clsThe number of idle connections grafana_database_conn_in_use gauge ins, instance, ip, job, clsThe number of connections currently in use grafana_database_conn_max_idle_closed_seconds unknown ins, instance, ip, job, clsThe total number of connections closed due to SetConnMaxIdleTime grafana_database_conn_max_idle_closed_total Unknown ins, instance, ip, job, clsN/A grafana_database_conn_max_lifetime_closed_total Unknown ins, instance, ip, job, clsN/A grafana_database_conn_max_open gauge ins, instance, ip, job, clsMaximum number of open connections to the database grafana_database_conn_open gauge ins, instance, ip, job, clsThe number of established connections both in use and idle grafana_database_conn_wait_count_total Unknown ins, instance, ip, job, clsN/A grafana_database_conn_wait_duration_seconds unknown ins, instance, ip, job, clsThe total time blocked waiting for a new connection grafana_datasource_request_duration_seconds_bucket Unknown datasource, ins, instance, method, ip, le, datasource_type, job, cls, codeN/A grafana_datasource_request_duration_seconds_count Unknown datasource, ins, instance, method, ip, datasource_type, job, cls, codeN/A grafana_datasource_request_duration_seconds_sum Unknown datasource, ins, instance, method, ip, datasource_type, job, cls, codeN/A grafana_datasource_request_in_flight gauge datasource, ins, instance, ip, datasource_type, job, clsA gauge of outgoing data source requests currently being sent by Grafana grafana_datasource_request_total Unknown datasource, ins, instance, method, ip, datasource_type, job, cls, codeN/A grafana_datasource_response_size_bytes_bucket Unknown datasource, ins, instance, ip, le, datasource_type, job, clsN/A grafana_datasource_response_size_bytes_count Unknown datasource, ins, instance, ip, datasource_type, job, clsN/A grafana_datasource_response_size_bytes_sum Unknown datasource, ins, instance, ip, datasource_type, job, clsN/A grafana_db_datasource_query_by_id_total Unknown ins, instance, ip, job, clsN/A grafana_disabled_metrics_total Unknown ins, instance, ip, job, clsN/A grafana_emails_sent_failed unknown ins, instance, ip, job, clsNumber of emails Grafana failed to send grafana_emails_sent_total Unknown ins, instance, ip, job, clsN/A grafana_encryption_cache_reads_total Unknown ins, instance, method, ip, hit, job, clsN/A grafana_encryption_ops_total Unknown ins, instance, ip, success, operation, job, clsN/A grafana_environment_info gauge version, ins, instance, ip, job, cls, commitA metric with a constant ‘1’ value labeled by environment information about the running instance. grafana_feature_toggles_info gauge ins, instance, ip, job, clsinfo metric that exposes what feature toggles are enabled or not grafana_frontend_boot_css_time_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_frontend_boot_css_time_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_css_time_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_first_contentful_paint_time_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_frontend_boot_first_contentful_paint_time_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_first_contentful_paint_time_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_first_paint_time_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_frontend_boot_first_paint_time_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_first_paint_time_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_js_done_time_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_frontend_boot_js_done_time_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_js_done_time_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_load_time_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_frontend_boot_load_time_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_frontend_boot_load_time_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_frontend_plugins_preload_ms_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_frontend_plugins_preload_ms_count Unknown ins, instance, ip, job, clsN/A grafana_frontend_plugins_preload_ms_sum Unknown ins, instance, ip, job, clsN/A grafana_hidden_metrics_total Unknown ins, instance, ip, job, clsN/A grafana_http_request_duration_seconds_bucket Unknown ins, instance, method, ip, le, job, cls, status_code, handlerN/A grafana_http_request_duration_seconds_count Unknown ins, instance, method, ip, job, cls, status_code, handlerN/A grafana_http_request_duration_seconds_sum Unknown ins, instance, method, ip, job, cls, status_code, handlerN/A grafana_http_request_in_flight gauge ins, instance, ip, job, clsA gauge of requests currently being served by Grafana. grafana_idforwarding_idforwarding_failed_token_signing_total Unknown ins, instance, ip, job, clsN/A grafana_idforwarding_idforwarding_token_signing_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_idforwarding_idforwarding_token_signing_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_idforwarding_idforwarding_token_signing_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_idforwarding_idforwarding_token_signing_from_cache_total Unknown ins, instance, ip, job, clsN/A grafana_idforwarding_idforwarding_token_signing_total Unknown ins, instance, ip, job, clsN/A grafana_instance_start_total Unknown ins, instance, ip, job, clsN/A grafana_ldap_users_sync_execution_time summary ins, instance, ip, job, cls, quantilesummary for LDAP users sync execution duration grafana_ldap_users_sync_execution_time_count Unknown ins, instance, ip, job, clsN/A grafana_ldap_users_sync_execution_time_sum Unknown ins, instance, ip, job, clsN/A grafana_live_client_command_duration_seconds summary ins, instance, method, ip, job, cls, quantileClient command duration summary. grafana_live_client_command_duration_seconds_count Unknown ins, instance, method, ip, job, clsN/A grafana_live_client_command_duration_seconds_sum Unknown ins, instance, method, ip, job, clsN/A grafana_live_client_num_reply_errors unknown ins, instance, method, ip, job, cls, codeNumber of errors in replies sent to clients. grafana_live_client_num_server_disconnects unknown ins, instance, ip, job, cls, codeNumber of server initiated disconnects. grafana_live_client_recover unknown ins, instance, ip, recovered, job, clsCount of recover operations. grafana_live_node_action_count unknown action, ins, instance, ip, job, clsNumber of node actions called. grafana_live_node_build gauge version, ins, instance, ip, job, clsNode build info. grafana_live_node_messages_received_count unknown ins, instance, ip, type, job, clsNumber of messages received. grafana_live_node_messages_sent_count unknown ins, instance, ip, type, job, clsNumber of messages sent. grafana_live_node_num_channels gauge ins, instance, ip, job, clsNumber of channels with one or more subscribers. grafana_live_node_num_clients gauge ins, instance, ip, job, clsNumber of clients connected. grafana_live_node_num_nodes gauge ins, instance, ip, job, clsNumber of nodes in cluster. grafana_live_node_num_subscriptions gauge ins, instance, ip, job, clsNumber of subscriptions. grafana_live_node_num_users gauge ins, instance, ip, job, clsNumber of unique users connected. grafana_live_transport_connect_count unknown ins, instance, ip, transport, job, clsNumber of connections to specific transport. grafana_live_transport_messages_sent unknown ins, instance, ip, transport, job, clsNumber of messages sent over specific transport. grafana_loki_plugin_parse_response_duration_seconds_bucket Unknown endpoint, ins, instance, ip, le, status, job, clsN/A grafana_loki_plugin_parse_response_duration_seconds_count Unknown endpoint, ins, instance, ip, status, job, clsN/A grafana_loki_plugin_parse_response_duration_seconds_sum Unknown endpoint, ins, instance, ip, status, job, clsN/A grafana_page_response_status_total Unknown ins, instance, ip, job, cls, codeN/A grafana_plugin_build_info gauge version, signature_status, ins, instance, plugin_type, ip, plugin_id, job, clsA metric with a constant ‘1’ value labeled by pluginId, pluginType and version from which Grafana plugin was built grafana_plugin_request_duration_milliseconds_bucket Unknown endpoint, ins, instance, target, ip, le, plugin_id, job, clsN/A grafana_plugin_request_duration_milliseconds_count Unknown endpoint, ins, instance, target, ip, plugin_id, job, clsN/A grafana_plugin_request_duration_milliseconds_sum Unknown endpoint, ins, instance, target, ip, plugin_id, job, clsN/A grafana_plugin_request_duration_seconds_bucket Unknown endpoint, ins, instance, target, ip, le, status, plugin_id, source, job, clsN/A grafana_plugin_request_duration_seconds_count Unknown endpoint, ins, instance, target, ip, status, plugin_id, source, job, clsN/A grafana_plugin_request_duration_seconds_sum Unknown endpoint, ins, instance, target, ip, status, plugin_id, source, job, clsN/A grafana_plugin_request_size_bytes_bucket Unknown endpoint, ins, instance, target, ip, le, plugin_id, source, job, clsN/A grafana_plugin_request_size_bytes_count Unknown endpoint, ins, instance, target, ip, plugin_id, source, job, clsN/A grafana_plugin_request_size_bytes_sum Unknown endpoint, ins, instance, target, ip, plugin_id, source, job, clsN/A grafana_plugin_request_total Unknown endpoint, ins, instance, target, ip, status, plugin_id, job, clsN/A grafana_process_cpu_seconds_total Unknown ins, instance, ip, job, clsN/A grafana_process_max_fds gauge ins, instance, ip, job, clsMaximum number of open file descriptors. grafana_process_open_fds gauge ins, instance, ip, job, clsNumber of open file descriptors. grafana_process_resident_memory_bytes gauge ins, instance, ip, job, clsResident memory size in bytes. grafana_process_start_time_seconds gauge ins, instance, ip, job, clsStart time of the process since unix epoch in seconds. grafana_process_virtual_memory_bytes gauge ins, instance, ip, job, clsVirtual memory size in bytes. grafana_process_virtual_memory_max_bytes gauge ins, instance, ip, job, clsMaximum amount of virtual memory available in bytes. grafana_prometheus_plugin_backend_request_count unknown endpoint, ins, instance, ip, status, errorSource, job, clsThe total amount of prometheus backend plugin requests grafana_proxy_response_status_total Unknown ins, instance, ip, job, cls, codeN/A grafana_public_dashboard_request_count unknown ins, instance, ip, job, clscounter for public dashboards requests grafana_registered_metrics_total Unknown ins, instance, ip, stability_level, deprecated_version, job, clsN/A grafana_rendering_queue_size gauge ins, instance, ip, job, clssize of rendering queue grafana_search_dashboard_search_failures_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_search_dashboard_search_failures_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_search_dashboard_search_failures_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_search_dashboard_search_successes_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A grafana_search_dashboard_search_successes_duration_seconds_count Unknown ins, instance, ip, job, clsN/A grafana_search_dashboard_search_successes_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A grafana_stat_active_users gauge ins, instance, ip, job, clsnumber of active users grafana_stat_total_orgs gauge ins, instance, ip, job, clstotal amount of orgs grafana_stat_total_playlists gauge ins, instance, ip, job, clstotal amount of playlists grafana_stat_total_service_account_tokens gauge ins, instance, ip, job, clstotal amount of service account tokens grafana_stat_total_service_accounts gauge ins, instance, ip, job, clstotal amount of service accounts grafana_stat_total_service_accounts_role_none gauge ins, instance, ip, job, clstotal amount of service accounts with no role grafana_stat_total_teams gauge ins, instance, ip, job, clstotal amount of teams grafana_stat_total_users gauge ins, instance, ip, job, clstotal amount of users grafana_stat_totals_active_admins gauge ins, instance, ip, job, clstotal amount of active admins grafana_stat_totals_active_editors gauge ins, instance, ip, job, clstotal amount of active editors grafana_stat_totals_active_viewers gauge ins, instance, ip, job, clstotal amount of active viewers grafana_stat_totals_admins gauge ins, instance, ip, job, clstotal amount of admins grafana_stat_totals_alert_rules gauge ins, instance, ip, job, clstotal amount of alert rules in the database grafana_stat_totals_annotations gauge ins, instance, ip, job, clstotal amount of annotations in the database grafana_stat_totals_correlations gauge ins, instance, ip, job, clstotal amount of correlations grafana_stat_totals_dashboard gauge ins, instance, ip, job, clstotal amount of dashboards grafana_stat_totals_dashboard_versions gauge ins, instance, ip, job, clstotal amount of dashboard versions in the database grafana_stat_totals_data_keys gauge ins, instance, ip, job, cls, activetotal amount of data keys in the database grafana_stat_totals_datasource gauge ins, instance, ip, plugin_id, job, clstotal number of defined datasources, labeled by pluginId grafana_stat_totals_editors gauge ins, instance, ip, job, clstotal amount of editors grafana_stat_totals_folder gauge ins, instance, ip, job, clstotal amount of folders grafana_stat_totals_library_panels gauge ins, instance, ip, job, clstotal amount of library panels in the database grafana_stat_totals_library_variables gauge ins, instance, ip, job, clstotal amount of library variables in the database grafana_stat_totals_public_dashboard gauge ins, instance, ip, job, clstotal amount of public dashboards grafana_stat_totals_rule_groups gauge ins, instance, ip, job, clstotal amount of alert rule groups in the database grafana_stat_totals_viewers gauge ins, instance, ip, job, clstotal amount of viewers infra_up Unknown ins, instance, ip, job, clsN/A jaeger_tracer_baggage_restrictions_updates_total Unknown result, ins, instance, ip, job, clsN/A jaeger_tracer_baggage_truncations_total Unknown ins, instance, ip, job, clsN/A jaeger_tracer_baggage_updates_total Unknown result, ins, instance, ip, job, clsN/A jaeger_tracer_finished_spans_total Unknown ins, instance, ip, sampled, job, clsN/A jaeger_tracer_reporter_queue_length gauge ins, instance, ip, job, clsCurrent number of spans in the reporter queue jaeger_tracer_reporter_spans_total Unknown result, ins, instance, ip, job, clsN/A jaeger_tracer_sampler_queries_total Unknown result, ins, instance, ip, job, clsN/A jaeger_tracer_sampler_updates_total Unknown result, ins, instance, ip, job, clsN/A jaeger_tracer_span_context_decoding_errors_total Unknown ins, instance, ip, job, clsN/A jaeger_tracer_started_spans_total Unknown ins, instance, ip, sampled, job, clsN/A jaeger_tracer_throttled_debug_spans_total Unknown ins, instance, ip, job, clsN/A jaeger_tracer_throttler_updates_total Unknown result, ins, instance, ip, job, clsN/A jaeger_tracer_traces_total Unknown ins, instance, ip, sampled, job, cls, stateN/A kv_request_duration_seconds_bucket Unknown ins, instance, role, ip, le, kv_name, type, operation, job, cls, status_codeN/A kv_request_duration_seconds_count Unknown ins, instance, role, ip, kv_name, type, operation, job, cls, status_codeN/A kv_request_duration_seconds_sum Unknown ins, instance, role, ip, kv_name, type, operation, job, cls, status_codeN/A legacy_grafana_alerting_ticker_interval_seconds gauge ins, instance, ip, job, clsInterval at which the ticker is meant to tick. legacy_grafana_alerting_ticker_last_consumed_tick_timestamp_seconds gauge ins, instance, ip, job, clsTimestamp of the last consumed tick in seconds. legacy_grafana_alerting_ticker_next_tick_timestamp_seconds gauge ins, instance, ip, job, clsTimestamp of the next tick in seconds before it is consumed. logql_query_duration_seconds_bucket Unknown ins, instance, query_type, ip, le, job, clsN/A logql_query_duration_seconds_count Unknown ins, instance, query_type, ip, job, clsN/A logql_query_duration_seconds_sum Unknown ins, instance, query_type, ip, job, clsN/A loki_azure_blob_egress_bytes_total Unknown ins, instance, ip, job, clsN/A loki_boltdb_shipper_apply_retention_last_successful_run_timestamp_seconds gauge ins, instance, ip, job, clsUnix timestamp of the last successful retention run loki_boltdb_shipper_compact_tables_operation_duration_seconds gauge ins, instance, ip, job, clsTime (in seconds) spent in compacting all the tables loki_boltdb_shipper_compact_tables_operation_last_successful_run_timestamp_seconds gauge ins, instance, ip, job, clsUnix timestamp of the last successful compaction run loki_boltdb_shipper_compact_tables_operation_total Unknown ins, instance, ip, status, job, clsN/A loki_boltdb_shipper_compactor_running gauge ins, instance, ip, job, clsValue will be 1 if compactor is currently running on this instance loki_boltdb_shipper_open_existing_file_failures_total Unknown ins, instance, ip, component, job, clsN/A loki_boltdb_shipper_query_time_table_download_duration_seconds unknown ins, instance, ip, component, job, cls, tableTime (in seconds) spent in downloading of files per table at query time loki_boltdb_shipper_request_duration_seconds_bucket Unknown ins, instance, ip, le, component, operation, job, cls, status_codeN/A loki_boltdb_shipper_request_duration_seconds_count Unknown ins, instance, ip, component, operation, job, cls, status_codeN/A loki_boltdb_shipper_request_duration_seconds_sum Unknown ins, instance, ip, component, operation, job, cls, status_codeN/A loki_boltdb_shipper_tables_download_operation_duration_seconds gauge ins, instance, ip, component, job, clsTime (in seconds) spent in downloading updated files for all the tables loki_boltdb_shipper_tables_sync_operation_total Unknown ins, instance, ip, status, component, job, clsN/A loki_boltdb_shipper_tables_upload_operation_total Unknown ins, instance, ip, status, component, job, clsN/A loki_build_info gauge revision, version, ins, instance, ip, tags, goarch, goversion, job, cls, branch, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which loki was built, and the goos and goarch for the build. loki_bytes_per_line_bucket Unknown ins, instance, ip, le, job, clsN/A loki_bytes_per_line_count Unknown ins, instance, ip, job, clsN/A loki_bytes_per_line_sum Unknown ins, instance, ip, job, clsN/A loki_cache_corrupt_chunks_total Unknown ins, instance, ip, job, clsN/A loki_cache_fetched_keys unknown ins, instance, ip, job, clsTotal count of keys requested from cache. loki_cache_hits unknown ins, instance, ip, job, clsTotal count of keys found in cache. loki_cache_request_duration_seconds_bucket Unknown ins, instance, method, ip, le, job, cls, status_codeN/A loki_cache_request_duration_seconds_count Unknown ins, instance, method, ip, job, cls, status_codeN/A loki_cache_request_duration_seconds_sum Unknown ins, instance, method, ip, job, cls, status_codeN/A loki_cache_value_size_bytes_bucket Unknown ins, instance, method, ip, le, job, clsN/A loki_cache_value_size_bytes_count Unknown ins, instance, method, ip, job, clsN/A loki_cache_value_size_bytes_sum Unknown ins, instance, method, ip, job, clsN/A loki_chunk_fetcher_cache_dequeued_total Unknown ins, instance, ip, job, clsN/A loki_chunk_fetcher_cache_enqueued_total Unknown ins, instance, ip, job, clsN/A loki_chunk_fetcher_cache_skipped_buffer_full_total Unknown ins, instance, ip, job, clsN/A loki_chunk_fetcher_fetched_size_bytes_bucket Unknown ins, instance, ip, le, source, job, clsN/A loki_chunk_fetcher_fetched_size_bytes_count Unknown ins, instance, ip, source, job, clsN/A loki_chunk_fetcher_fetched_size_bytes_sum Unknown ins, instance, ip, source, job, clsN/A loki_chunk_store_chunks_per_query_bucket Unknown ins, instance, ip, le, job, clsN/A loki_chunk_store_chunks_per_query_count Unknown ins, instance, ip, job, clsN/A loki_chunk_store_chunks_per_query_sum Unknown ins, instance, ip, job, clsN/A loki_chunk_store_deduped_bytes_total Unknown ins, instance, ip, job, clsN/A loki_chunk_store_deduped_chunks_total Unknown ins, instance, ip, job, clsN/A loki_chunk_store_fetched_chunk_bytes_total Unknown ins, instance, ip, user, job, clsN/A loki_chunk_store_fetched_chunks_total Unknown ins, instance, ip, user, job, clsN/A loki_chunk_store_index_entries_per_chunk_bucket Unknown ins, instance, ip, le, job, clsN/A loki_chunk_store_index_entries_per_chunk_count Unknown ins, instance, ip, job, clsN/A loki_chunk_store_index_entries_per_chunk_sum Unknown ins, instance, ip, job, clsN/A loki_chunk_store_index_lookups_per_query_bucket Unknown ins, instance, ip, le, job, clsN/A loki_chunk_store_index_lookups_per_query_count Unknown ins, instance, ip, job, clsN/A loki_chunk_store_index_lookups_per_query_sum Unknown ins, instance, ip, job, clsN/A loki_chunk_store_series_post_intersection_per_query_bucket Unknown ins, instance, ip, le, job, clsN/A loki_chunk_store_series_post_intersection_per_query_count Unknown ins, instance, ip, job, clsN/A loki_chunk_store_series_post_intersection_per_query_sum Unknown ins, instance, ip, job, clsN/A loki_chunk_store_series_pre_intersection_per_query_bucket Unknown ins, instance, ip, le, job, clsN/A loki_chunk_store_series_pre_intersection_per_query_count Unknown ins, instance, ip, job, clsN/A loki_chunk_store_series_pre_intersection_per_query_sum Unknown ins, instance, ip, job, clsN/A loki_chunk_store_stored_chunk_bytes_total Unknown ins, instance, ip, user, job, clsN/A loki_chunk_store_stored_chunks_total Unknown ins, instance, ip, user, job, clsN/A loki_consul_request_duration_seconds_bucket Unknown ins, instance, ip, le, kv_name, operation, job, cls, status_codeN/A loki_consul_request_duration_seconds_count Unknown ins, instance, ip, kv_name, operation, job, cls, status_codeN/A loki_consul_request_duration_seconds_sum Unknown ins, instance, ip, kv_name, operation, job, cls, status_codeN/A loki_delete_request_lookups_failed_total Unknown ins, instance, ip, job, clsN/A loki_delete_request_lookups_total Unknown ins, instance, ip, job, clsN/A loki_discarded_bytes_total Unknown ins, instance, ip, reason, job, cls, tenantN/A loki_discarded_samples_total Unknown ins, instance, ip, reason, job, cls, tenantN/A loki_distributor_bytes_received_total Unknown ins, instance, retention_hours, ip, job, cls, tenantN/A loki_distributor_ingester_appends_total Unknown ins, instance, ip, ingester, job, clsN/A loki_distributor_lines_received_total Unknown ins, instance, ip, job, cls, tenantN/A loki_distributor_replication_factor gauge ins, instance, ip, job, clsThe configured replication factor. loki_distributor_structured_metadata_bytes_received_total Unknown ins, instance, retention_hours, ip, job, cls, tenantN/A loki_experimental_features_in_use_total Unknown ins, instance, ip, job, clsN/A loki_index_chunk_refs_total Unknown ins, instance, ip, status, job, clsN/A loki_index_request_duration_seconds_bucket Unknown ins, instance, ip, le, component, operation, job, cls, status_codeN/A loki_index_request_duration_seconds_count Unknown ins, instance, ip, component, operation, job, cls, status_codeN/A loki_index_request_duration_seconds_sum Unknown ins, instance, ip, component, operation, job, cls, status_codeN/A loki_inflight_requests gauge ins, instance, method, ip, route, job, clsCurrent number of inflight requests. loki_ingester_autoforget_unhealthy_ingesters_total Unknown ins, instance, ip, job, clsN/A loki_ingester_blocks_per_chunk_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_blocks_per_chunk_count Unknown ins, instance, ip, job, clsN/A loki_ingester_blocks_per_chunk_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_checkpoint_creations_failed_total Unknown ins, instance, ip, job, clsN/A loki_ingester_checkpoint_creations_total Unknown ins, instance, ip, job, clsN/A loki_ingester_checkpoint_deletions_failed_total Unknown ins, instance, ip, job, clsN/A loki_ingester_checkpoint_deletions_total Unknown ins, instance, ip, job, clsN/A loki_ingester_checkpoint_duration_seconds summary ins, instance, ip, job, cls, quantileTime taken to create a checkpoint. loki_ingester_checkpoint_duration_seconds_count Unknown ins, instance, ip, job, clsN/A loki_ingester_checkpoint_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_checkpoint_logged_bytes_total Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_age_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_chunk_age_seconds_count Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_age_seconds_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_bounds_hours_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_chunk_bounds_hours_count Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_bounds_hours_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_compression_ratio_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_chunk_compression_ratio_count Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_compression_ratio_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_encode_time_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_chunk_encode_time_seconds_count Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_encode_time_seconds_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_entries_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_chunk_entries_count Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_entries_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_size_bytes_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_chunk_size_bytes_count Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_size_bytes_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_stored_bytes_total Unknown ins, instance, ip, job, cls, tenantN/A loki_ingester_chunk_utilization_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_chunk_utilization_count Unknown ins, instance, ip, job, clsN/A loki_ingester_chunk_utilization_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_chunks_created_total Unknown ins, instance, ip, job, clsN/A loki_ingester_chunks_flushed_total Unknown ins, instance, ip, reason, job, clsN/A loki_ingester_chunks_stored_total Unknown ins, instance, ip, job, cls, tenantN/A loki_ingester_client_request_duration_seconds_bucket Unknown ins, instance, ip, le, operation, job, cls, status_codeN/A loki_ingester_client_request_duration_seconds_count Unknown ins, instance, ip, operation, job, cls, status_codeN/A loki_ingester_client_request_duration_seconds_sum Unknown ins, instance, ip, operation, job, cls, status_codeN/A loki_ingester_limiter_enabled gauge ins, instance, ip, job, clsWhether the ingester’s limiter is enabled loki_ingester_memory_chunks gauge ins, instance, ip, job, clsThe total number of chunks in memory. loki_ingester_memory_streams gauge ins, instance, ip, job, cls, tenantThe total number of streams in memory per tenant. loki_ingester_memory_streams_labels_bytes gauge ins, instance, ip, job, clsTotal bytes of labels of the streams in memory. loki_ingester_received_chunks unknown ins, instance, ip, job, clsThe total number of chunks received by this ingester whilst joining. loki_ingester_samples_per_chunk_bucket Unknown ins, instance, ip, le, job, clsN/A loki_ingester_samples_per_chunk_count Unknown ins, instance, ip, job, clsN/A loki_ingester_samples_per_chunk_sum Unknown ins, instance, ip, job, clsN/A loki_ingester_sent_chunks unknown ins, instance, ip, job, clsThe total number of chunks sent by this ingester whilst leaving. loki_ingester_shutdown_marker gauge ins, instance, ip, job, cls1 if prepare shutdown has been called, 0 otherwise loki_ingester_streams_created_total Unknown ins, instance, ip, job, cls, tenantN/A loki_ingester_streams_removed_total Unknown ins, instance, ip, job, cls, tenantN/A loki_ingester_wal_bytes_in_use gauge ins, instance, ip, job, clsTotal number of bytes in use by the WAL recovery process. loki_ingester_wal_disk_full_failures_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_duplicate_entries_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_logged_bytes_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_records_logged_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_recovered_bytes_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_recovered_chunks_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_recovered_entries_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_recovered_streams_total Unknown ins, instance, ip, job, clsN/A loki_ingester_wal_replay_active gauge ins, instance, ip, job, clsWhether the WAL is replaying loki_ingester_wal_replay_duration_seconds gauge ins, instance, ip, job, clsTime taken to replay the checkpoint and the WAL. loki_ingester_wal_replay_flushing gauge ins, instance, ip, job, clsWhether the wal replay is in a flushing phase due to backpressure loki_internal_log_messages_total Unknown ins, instance, ip, level, job, clsN/A loki_kv_request_duration_seconds_bucket Unknown ins, instance, role, ip, le, kv_name, type, operation, job, cls, status_codeN/A loki_kv_request_duration_seconds_count Unknown ins, instance, role, ip, kv_name, type, operation, job, cls, status_codeN/A loki_kv_request_duration_seconds_sum Unknown ins, instance, role, ip, kv_name, type, operation, job, cls, status_codeN/A loki_log_flushes_bucket Unknown ins, instance, ip, le, job, clsN/A loki_log_flushes_count Unknown ins, instance, ip, job, clsN/A loki_log_flushes_sum Unknown ins, instance, ip, job, clsN/A loki_log_messages_total Unknown ins, instance, ip, level, job, clsN/A loki_logql_querystats_bytes_processed_per_seconds_bucket Unknown ins, instance, range, ip, le, sharded, type, job, cls, status_code, latency_typeN/A loki_logql_querystats_bytes_processed_per_seconds_count Unknown ins, instance, range, ip, sharded, type, job, cls, status_code, latency_typeN/A loki_logql_querystats_bytes_processed_per_seconds_sum Unknown ins, instance, range, ip, sharded, type, job, cls, status_code, latency_typeN/A loki_logql_querystats_chunk_download_latency_seconds_bucket Unknown ins, instance, range, ip, le, type, job, cls, status_codeN/A loki_logql_querystats_chunk_download_latency_seconds_count Unknown ins, instance, range, ip, type, job, cls, status_codeN/A loki_logql_querystats_chunk_download_latency_seconds_sum Unknown ins, instance, range, ip, type, job, cls, status_codeN/A loki_logql_querystats_downloaded_chunk_total Unknown ins, instance, range, ip, type, job, cls, status_codeN/A loki_logql_querystats_duplicates_total Unknown ins, instance, ip, job, clsN/A loki_logql_querystats_ingester_sent_lines_total Unknown ins, instance, ip, job, clsN/A loki_logql_querystats_latency_seconds_bucket Unknown ins, instance, range, ip, le, type, job, cls, status_codeN/A loki_logql_querystats_latency_seconds_count Unknown ins, instance, range, ip, type, job, cls, status_codeN/A loki_logql_querystats_latency_seconds_sum Unknown ins, instance, range, ip, type, job, cls, status_codeN/A loki_panic_total Unknown ins, instance, ip, job, clsN/A loki_querier_index_cache_corruptions_total Unknown ins, instance, ip, job, clsN/A loki_querier_index_cache_encode_errors_total Unknown ins, instance, ip, job, clsN/A loki_querier_index_cache_gets_total Unknown ins, instance, ip, job, clsN/A loki_querier_index_cache_hits_total Unknown ins, instance, ip, job, clsN/A loki_querier_index_cache_puts_total Unknown ins, instance, ip, job, clsN/A loki_querier_query_frontend_clients gauge ins, instance, ip, job, clsThe current number of clients connected to query-frontend. loki_querier_query_frontend_request_duration_seconds_bucket Unknown ins, instance, ip, le, operation, job, cls, status_codeN/A loki_querier_query_frontend_request_duration_seconds_count Unknown ins, instance, ip, operation, job, cls, status_codeN/A loki_querier_query_frontend_request_duration_seconds_sum Unknown ins, instance, ip, operation, job, cls, status_codeN/A loki_querier_tail_active gauge ins, instance, ip, job, clsNumber of active tailers loki_querier_tail_active_streams gauge ins, instance, ip, job, clsNumber of active streams being tailed loki_querier_tail_bytes_total Unknown ins, instance, ip, job, clsN/A loki_querier_worker_concurrency gauge ins, instance, ip, job, clsNumber of concurrent querier workers loki_querier_worker_inflight_queries gauge ins, instance, ip, job, clsNumber of queries being processed by the querier workers loki_query_frontend_log_result_cache_hit_total Unknown ins, instance, ip, job, clsN/A loki_query_frontend_log_result_cache_miss_total Unknown ins, instance, ip, job, clsN/A loki_query_frontend_partitions_bucket Unknown ins, instance, ip, le, job, clsN/A loki_query_frontend_partitions_count Unknown ins, instance, ip, job, clsN/A loki_query_frontend_partitions_sum Unknown ins, instance, ip, job, clsN/A loki_query_frontend_shard_factor_bucket Unknown ins, instance, ip, le, mapper, job, clsN/A loki_query_frontend_shard_factor_count Unknown ins, instance, ip, mapper, job, clsN/A loki_query_frontend_shard_factor_sum Unknown ins, instance, ip, mapper, job, clsN/A loki_query_scheduler_enqueue_count Unknown ins, instance, ip, level, user, job, clsN/A loki_rate_store_expired_streams_total Unknown ins, instance, ip, job, clsN/A loki_rate_store_max_stream_rate_bytes gauge ins, instance, ip, job, clsThe maximum stream rate for any stream reported by ingesters during a sync operation. Sharded Streams are combined. loki_rate_store_max_stream_shards gauge ins, instance, ip, job, clsThe number of shards for a single stream reported by ingesters during a sync operation. loki_rate_store_max_unique_stream_rate_bytes gauge ins, instance, ip, job, clsThe maximum stream rate for any stream reported by ingesters during a sync operation. Sharded Streams are considered separate. loki_rate_store_stream_rate_bytes_bucket Unknown ins, instance, ip, le, job, clsN/A loki_rate_store_stream_rate_bytes_count Unknown ins, instance, ip, job, clsN/A loki_rate_store_stream_rate_bytes_sum Unknown ins, instance, ip, job, clsN/A loki_rate_store_stream_shards_bucket Unknown ins, instance, ip, le, job, clsN/A loki_rate_store_stream_shards_count Unknown ins, instance, ip, job, clsN/A loki_rate_store_stream_shards_sum Unknown ins, instance, ip, job, clsN/A loki_rate_store_streams gauge ins, instance, ip, job, clsThe number of unique streams reported by all ingesters. Sharded streams are combined loki_request_duration_seconds_bucket Unknown ins, instance, method, ip, le, ws, route, job, cls, status_codeN/A loki_request_duration_seconds_count Unknown ins, instance, method, ip, ws, route, job, cls, status_codeN/A loki_request_duration_seconds_sum Unknown ins, instance, method, ip, ws, route, job, cls, status_codeN/A loki_request_message_bytes_bucket Unknown ins, instance, method, ip, le, route, job, clsN/A loki_request_message_bytes_count Unknown ins, instance, method, ip, route, job, clsN/A loki_request_message_bytes_sum Unknown ins, instance, method, ip, route, job, clsN/A loki_response_message_bytes_bucket Unknown ins, instance, method, ip, le, route, job, clsN/A loki_response_message_bytes_count Unknown ins, instance, method, ip, route, job, clsN/A loki_response_message_bytes_sum Unknown ins, instance, method, ip, route, job, clsN/A loki_results_cache_version_comparisons_total Unknown ins, instance, ip, job, clsN/A loki_store_chunks_downloaded_total Unknown ins, instance, ip, status, job, clsN/A loki_store_chunks_per_batch_bucket Unknown ins, instance, ip, le, status, job, clsN/A loki_store_chunks_per_batch_count Unknown ins, instance, ip, status, job, clsN/A loki_store_chunks_per_batch_sum Unknown ins, instance, ip, status, job, clsN/A loki_store_series_total Unknown ins, instance, ip, status, job, clsN/A loki_stream_sharding_count unknown ins, instance, ip, job, clsTotal number of times the distributor has sharded streams loki_tcp_connections gauge ins, instance, ip, protocol, job, clsCurrent number of accepted TCP connections. loki_tcp_connections_limit gauge ins, instance, ip, protocol, job, clsThe max number of TCP connections that can be accepted (0 means no limit). net_conntrack_dialer_conn_attempted_total counter ins, instance, ip, dialer_name, job, clsTotal number of connections attempted by the given dialer a given name. net_conntrack_dialer_conn_closed_total counter ins, instance, ip, dialer_name, job, clsTotal number of connections closed which originated from the dialer of a given name. net_conntrack_dialer_conn_established_total counter ins, instance, ip, dialer_name, job, clsTotal number of connections successfully established by the given dialer a given name. net_conntrack_dialer_conn_failed_total counter ins, instance, ip, dialer_name, reason, job, clsTotal number of connections failed to dial by the dialer a given name. net_conntrack_listener_conn_accepted_total counter ins, instance, ip, listener_name, job, clsTotal number of connections opened to the listener of a given name. net_conntrack_listener_conn_closed_total counter ins, instance, ip, listener_name, job, clsTotal number of connections closed that were made to the listener of a given name. nginx_connections_accepted counter ins, instance, ip, job, clsAccepted client connections nginx_connections_active gauge ins, instance, ip, job, clsActive client connections nginx_connections_handled counter ins, instance, ip, job, clsHandled client connections nginx_connections_reading gauge ins, instance, ip, job, clsConnections where NGINX is reading the request header nginx_connections_waiting gauge ins, instance, ip, job, clsIdle client connections nginx_connections_writing gauge ins, instance, ip, job, clsConnections where NGINX is writing the response back to the client nginx_exporter_build_info gauge revision, version, ins, instance, ip, tags, goarch, goversion, job, cls, branch, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which nginx_exporter was built, and the goos and goarch for the build. nginx_http_requests_total counter ins, instance, ip, job, clsTotal http requests nginx_up gauge ins, instance, ip, job, clsStatus of the last metric scrape plugins_active_instances gauge ins, instance, ip, job, clsThe number of active plugin instances plugins_datasource_instances_total Unknown ins, instance, ip, job, clsN/A process_cpu_seconds_total counter ins, instance, ip, job, clsTotal user and system CPU time spent in seconds. process_max_fds gauge ins, instance, ip, job, clsMaximum number of open file descriptors. process_open_fds gauge ins, instance, ip, job, clsNumber of open file descriptors. process_resident_memory_bytes gauge ins, instance, ip, job, clsResident memory size in bytes. process_start_time_seconds gauge ins, instance, ip, job, clsStart time of the process since unix epoch in seconds. process_virtual_memory_bytes gauge ins, instance, ip, job, clsVirtual memory size in bytes. process_virtual_memory_max_bytes gauge ins, instance, ip, job, clsMaximum amount of virtual memory available in bytes. prometheus_api_remote_read_queries gauge ins, instance, ip, job, clsThe current number of remote read queries being executed or waiting. prometheus_build_info gauge revision, version, ins, instance, ip, tags, goarch, goversion, job, cls, branch, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which prometheus was built, and the goos and goarch for the build. prometheus_config_last_reload_success_timestamp_seconds gauge ins, instance, ip, job, clsTimestamp of the last successful configuration reload. prometheus_config_last_reload_successful gauge ins, instance, ip, job, clsWhether the last configuration reload attempt was successful. prometheus_engine_queries gauge ins, instance, ip, job, clsThe current number of queries being executed or waiting. prometheus_engine_queries_concurrent_max gauge ins, instance, ip, job, clsThe max number of concurrent queries. prometheus_engine_query_duration_seconds summary ins, instance, ip, job, cls, quantile, sliceQuery timings prometheus_engine_query_duration_seconds_count Unknown ins, instance, ip, job, cls, sliceN/A prometheus_engine_query_duration_seconds_sum Unknown ins, instance, ip, job, cls, sliceN/A prometheus_engine_query_log_enabled gauge ins, instance, ip, job, clsState of the query log. prometheus_engine_query_log_failures_total counter ins, instance, ip, job, clsThe number of query log failures. prometheus_engine_query_samples_total counter ins, instance, ip, job, clsThe total number of samples loaded by all queries. prometheus_http_request_duration_seconds_bucket Unknown ins, instance, ip, le, job, cls, handlerN/A prometheus_http_request_duration_seconds_count Unknown ins, instance, ip, job, cls, handlerN/A prometheus_http_request_duration_seconds_sum Unknown ins, instance, ip, job, cls, handlerN/A prometheus_http_requests_total counter ins, instance, ip, job, cls, code, handlerCounter of HTTP requests. prometheus_http_response_size_bytes_bucket Unknown ins, instance, ip, le, job, cls, handlerN/A prometheus_http_response_size_bytes_count Unknown ins, instance, ip, job, cls, handlerN/A prometheus_http_response_size_bytes_sum Unknown ins, instance, ip, job, cls, handlerN/A prometheus_notifications_alertmanagers_discovered gauge ins, instance, ip, job, clsThe number of alertmanagers discovered and active. prometheus_notifications_dropped_total counter ins, instance, ip, job, clsTotal number of alerts dropped due to errors when sending to Alertmanager. prometheus_notifications_errors_total counter ins, instance, ip, alertmanager, job, clsTotal number of errors sending alert notifications. prometheus_notifications_latency_seconds summary ins, instance, ip, alertmanager, job, cls, quantileLatency quantiles for sending alert notifications. prometheus_notifications_latency_seconds_count Unknown ins, instance, ip, alertmanager, job, clsN/A prometheus_notifications_latency_seconds_sum Unknown ins, instance, ip, alertmanager, job, clsN/A prometheus_notifications_queue_capacity gauge ins, instance, ip, job, clsThe capacity of the alert notifications queue. prometheus_notifications_queue_length gauge ins, instance, ip, job, clsThe number of alert notifications in the queue. prometheus_notifications_sent_total counter ins, instance, ip, alertmanager, job, clsTotal number of alerts sent. prometheus_ready gauge ins, instance, ip, job, clsWhether Prometheus startup was fully completed and the server is ready for normal operation. prometheus_remote_storage_exemplars_in_total counter ins, instance, ip, job, clsExemplars in to remote storage, compare to exemplars out for queue managers. prometheus_remote_storage_highest_timestamp_in_seconds gauge ins, instance, ip, job, clsHighest timestamp that has come into the remote storage via the Appender interface, in seconds since epoch. prometheus_remote_storage_histograms_in_total counter ins, instance, ip, job, clsHistogramSamples in to remote storage, compare to histograms out for queue managers. prometheus_remote_storage_samples_in_total counter ins, instance, ip, job, clsSamples in to remote storage, compare to samples out for queue managers. prometheus_remote_storage_string_interner_zero_reference_releases_total counter ins, instance, ip, job, clsThe number of times release has been called for strings that are not interned. prometheus_rule_evaluation_duration_seconds summary ins, instance, ip, job, cls, quantileThe duration for a rule to execute. prometheus_rule_evaluation_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_rule_evaluation_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_rule_evaluation_failures_total counter ins, instance, ip, job, cls, rule_groupThe total number of rule evaluation failures. prometheus_rule_evaluations_total counter ins, instance, ip, job, cls, rule_groupThe total number of rule evaluations. prometheus_rule_group_duration_seconds summary ins, instance, ip, job, cls, quantileThe duration of rule group evaluations. prometheus_rule_group_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_rule_group_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_rule_group_interval_seconds gauge ins, instance, ip, job, cls, rule_groupThe interval of a rule group. prometheus_rule_group_iterations_missed_total counter ins, instance, ip, job, cls, rule_groupThe total number of rule group evaluations missed due to slow rule group evaluation. prometheus_rule_group_iterations_total counter ins, instance, ip, job, cls, rule_groupThe total number of scheduled rule group evaluations, whether executed or missed. prometheus_rule_group_last_duration_seconds gauge ins, instance, ip, job, cls, rule_groupThe duration of the last rule group evaluation. prometheus_rule_group_last_evaluation_samples gauge ins, instance, ip, job, cls, rule_groupThe number of samples returned during the last rule group evaluation. prometheus_rule_group_last_evaluation_timestamp_seconds gauge ins, instance, ip, job, cls, rule_groupThe timestamp of the last rule group evaluation in seconds. prometheus_rule_group_rules gauge ins, instance, ip, job, cls, rule_groupThe number of rules. prometheus_sd_azure_cache_hit_total counter ins, instance, ip, job, clsNumber of cache hit during refresh. prometheus_sd_azure_failures_total counter ins, instance, ip, job, clsNumber of Azure service discovery refresh failures. prometheus_sd_consul_rpc_duration_seconds summary endpoint, ins, instance, ip, job, cls, call, quantileThe duration of a Consul RPC call in seconds. prometheus_sd_consul_rpc_duration_seconds_count Unknown endpoint, ins, instance, ip, job, cls, callN/A prometheus_sd_consul_rpc_duration_seconds_sum Unknown endpoint, ins, instance, ip, job, cls, callN/A prometheus_sd_consul_rpc_failures_total counter ins, instance, ip, job, clsThe number of Consul RPC call failures. prometheus_sd_discovered_targets gauge ins, instance, ip, config, job, clsCurrent number of discovered targets. prometheus_sd_dns_lookup_failures_total counter ins, instance, ip, job, clsThe number of DNS-SD lookup failures. prometheus_sd_dns_lookups_total counter ins, instance, ip, job, clsThe number of DNS-SD lookups. prometheus_sd_failed_configs gauge ins, instance, ip, job, clsCurrent number of service discovery configurations that failed to load. prometheus_sd_file_mtime_seconds gauge ins, instance, ip, filename, job, clsTimestamp (mtime) of files read by FileSD. Timestamp is set at read time. prometheus_sd_file_read_errors_total counter ins, instance, ip, job, clsThe number of File-SD read errors. prometheus_sd_file_scan_duration_seconds summary ins, instance, ip, job, cls, quantileThe duration of the File-SD scan in seconds. prometheus_sd_file_scan_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_sd_file_scan_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_sd_file_watcher_errors_total counter ins, instance, ip, job, clsThe number of File-SD errors caused by filesystem watch failures. prometheus_sd_http_failures_total counter ins, instance, ip, job, clsNumber of HTTP service discovery refresh failures. prometheus_sd_kubernetes_events_total counter event, ins, instance, role, ip, job, clsThe number of Kubernetes events handled. prometheus_sd_kuma_fetch_duration_seconds summary ins, instance, ip, job, cls, quantileThe duration of a Kuma MADS fetch call. prometheus_sd_kuma_fetch_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_sd_kuma_fetch_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_sd_kuma_fetch_failures_total counter ins, instance, ip, job, clsThe number of Kuma MADS fetch call failures. prometheus_sd_kuma_fetch_skipped_updates_total counter ins, instance, ip, job, clsThe number of Kuma MADS fetch calls that result in no updates to the targets. prometheus_sd_linode_failures_total counter ins, instance, ip, job, clsNumber of Linode service discovery refresh failures. prometheus_sd_nomad_failures_total counter ins, instance, ip, job, clsNumber of nomad service discovery refresh failures. prometheus_sd_received_updates_total counter ins, instance, ip, job, clsTotal number of update events received from the SD providers. prometheus_sd_updates_total counter ins, instance, ip, job, clsTotal number of update events sent to the SD consumers. prometheus_target_interval_length_seconds summary ins, instance, interval, ip, job, cls, quantileActual intervals between scrapes. prometheus_target_interval_length_seconds_count Unknown ins, instance, interval, ip, job, clsN/A prometheus_target_interval_length_seconds_sum Unknown ins, instance, interval, ip, job, clsN/A prometheus_target_metadata_cache_bytes gauge ins, instance, ip, scrape_job, job, clsThe number of bytes that are currently used for storing metric metadata in the cache prometheus_target_metadata_cache_entries gauge ins, instance, ip, scrape_job, job, clsTotal number of metric metadata entries in the cache prometheus_target_scrape_pool_exceeded_label_limits_total counter ins, instance, ip, job, clsTotal number of times scrape pools hit the label limits, during sync or config reload. prometheus_target_scrape_pool_exceeded_target_limit_total counter ins, instance, ip, job, clsTotal number of times scrape pools hit the target limit, during sync or config reload. prometheus_target_scrape_pool_reloads_failed_total counter ins, instance, ip, job, clsTotal number of failed scrape pool reloads. prometheus_target_scrape_pool_reloads_total counter ins, instance, ip, job, clsTotal number of scrape pool reloads. prometheus_target_scrape_pool_sync_total counter ins, instance, ip, scrape_job, job, clsTotal number of syncs that were executed on a scrape pool. prometheus_target_scrape_pool_target_limit gauge ins, instance, ip, scrape_job, job, clsMaximum number of targets allowed in this scrape pool. prometheus_target_scrape_pool_targets gauge ins, instance, ip, scrape_job, job, clsCurrent number of targets in this scrape pool. prometheus_target_scrape_pools_failed_total counter ins, instance, ip, job, clsTotal number of scrape pool creations that failed. prometheus_target_scrape_pools_total counter ins, instance, ip, job, clsTotal number of scrape pool creation attempts. prometheus_target_scrapes_cache_flush_forced_total counter ins, instance, ip, job, clsHow many times a scrape cache was flushed due to getting big while scrapes are failing. prometheus_target_scrapes_exceeded_body_size_limit_total counter ins, instance, ip, job, clsTotal number of scrapes that hit the body size limit prometheus_target_scrapes_exceeded_native_histogram_bucket_limit_total counter ins, instance, ip, job, clsTotal number of scrapes that hit the native histogram bucket limit and were rejected. prometheus_target_scrapes_exceeded_sample_limit_total counter ins, instance, ip, job, clsTotal number of scrapes that hit the sample limit and were rejected. prometheus_target_scrapes_exemplar_out_of_order_total counter ins, instance, ip, job, clsTotal number of exemplar rejected due to not being out of the expected order. prometheus_target_scrapes_sample_duplicate_timestamp_total counter ins, instance, ip, job, clsTotal number of samples rejected due to duplicate timestamps but different values. prometheus_target_scrapes_sample_out_of_bounds_total counter ins, instance, ip, job, clsTotal number of samples rejected due to timestamp falling outside of the time bounds. prometheus_target_scrapes_sample_out_of_order_total counter ins, instance, ip, job, clsTotal number of samples rejected due to not being out of the expected order. prometheus_target_sync_failed_total counter ins, instance, ip, scrape_job, job, clsTotal number of target sync failures. prometheus_target_sync_length_seconds summary ins, instance, ip, scrape_job, job, cls, quantileActual interval to sync the scrape pool. prometheus_target_sync_length_seconds_count Unknown ins, instance, ip, scrape_job, job, clsN/A prometheus_target_sync_length_seconds_sum Unknown ins, instance, ip, scrape_job, job, clsN/A prometheus_template_text_expansion_failures_total counter ins, instance, ip, job, clsThe total number of template text expansion failures. prometheus_template_text_expansions_total counter ins, instance, ip, job, clsThe total number of template text expansions. prometheus_treecache_watcher_goroutines gauge ins, instance, ip, job, clsThe current number of watcher goroutines. prometheus_treecache_zookeeper_failures_total counter ins, instance, ip, job, clsThe total number of ZooKeeper failures. prometheus_tsdb_blocks_loaded gauge ins, instance, ip, job, clsNumber of currently loaded data blocks prometheus_tsdb_checkpoint_creations_failed_total counter ins, instance, ip, job, clsTotal number of checkpoint creations that failed. prometheus_tsdb_checkpoint_creations_total counter ins, instance, ip, job, clsTotal number of checkpoint creations attempted. prometheus_tsdb_checkpoint_deletions_failed_total counter ins, instance, ip, job, clsTotal number of checkpoint deletions that failed. prometheus_tsdb_checkpoint_deletions_total counter ins, instance, ip, job, clsTotal number of checkpoint deletions attempted. prometheus_tsdb_clean_start gauge ins, instance, ip, job, cls-1: lockfile is disabled. 0: a lockfile from a previous execution was replaced. 1: lockfile creation was clean prometheus_tsdb_compaction_chunk_range_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A prometheus_tsdb_compaction_chunk_range_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_chunk_range_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_chunk_samples_bucket Unknown ins, instance, ip, le, job, clsN/A prometheus_tsdb_compaction_chunk_samples_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_chunk_samples_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_chunk_size_bytes_bucket Unknown ins, instance, ip, le, job, clsN/A prometheus_tsdb_compaction_chunk_size_bytes_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_chunk_size_bytes_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_duration_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A prometheus_tsdb_compaction_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_compaction_populating_block gauge ins, instance, ip, job, clsSet to 1 when a block is currently being written to the disk. prometheus_tsdb_compactions_failed_total counter ins, instance, ip, job, clsTotal number of compactions that failed for the partition. prometheus_tsdb_compactions_skipped_total counter ins, instance, ip, job, clsTotal number of skipped compactions due to disabled auto compaction. prometheus_tsdb_compactions_total counter ins, instance, ip, job, clsTotal number of compactions that were executed for the partition. prometheus_tsdb_compactions_triggered_total counter ins, instance, ip, job, clsTotal number of triggered compactions for the partition. prometheus_tsdb_data_replay_duration_seconds gauge ins, instance, ip, job, clsTime taken to replay the data on disk. prometheus_tsdb_exemplar_exemplars_appended_total counter ins, instance, ip, job, clsTotal number of appended exemplars. prometheus_tsdb_exemplar_exemplars_in_storage gauge ins, instance, ip, job, clsNumber of exemplars currently in circular storage. prometheus_tsdb_exemplar_last_exemplars_timestamp_seconds gauge ins, instance, ip, job, clsThe timestamp of the oldest exemplar stored in circular storage. Useful to check for what timerange the current exemplar buffer limit allows. This usually means the last timestampfor all exemplars for a typical setup. This is not true though if one of the series timestamp is in future compared to rest series. prometheus_tsdb_exemplar_max_exemplars gauge ins, instance, ip, job, clsTotal number of exemplars the exemplar storage can store, resizeable. prometheus_tsdb_exemplar_out_of_order_exemplars_total counter ins, instance, ip, job, clsTotal number of out of order exemplar ingestion failed attempts. prometheus_tsdb_exemplar_series_with_exemplars_in_storage gauge ins, instance, ip, job, clsNumber of series with exemplars currently in circular storage. prometheus_tsdb_head_active_appenders gauge ins, instance, ip, job, clsNumber of currently active appender transactions prometheus_tsdb_head_chunks gauge ins, instance, ip, job, clsTotal number of chunks in the head block. prometheus_tsdb_head_chunks_created_total counter ins, instance, ip, job, clsTotal number of chunks created in the head prometheus_tsdb_head_chunks_removed_total counter ins, instance, ip, job, clsTotal number of chunks removed in the head prometheus_tsdb_head_chunks_storage_size_bytes gauge ins, instance, ip, job, clsSize of the chunks_head directory. prometheus_tsdb_head_gc_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_head_gc_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_head_max_time gauge ins, instance, ip, job, clsMaximum timestamp of the head block. The unit is decided by the library consumer. prometheus_tsdb_head_max_time_seconds gauge ins, instance, ip, job, clsMaximum timestamp of the head block. prometheus_tsdb_head_min_time gauge ins, instance, ip, job, clsMinimum time bound of the head block. The unit is decided by the library consumer. prometheus_tsdb_head_min_time_seconds gauge ins, instance, ip, job, clsMinimum time bound of the head block. prometheus_tsdb_head_out_of_order_samples_appended_total counter ins, instance, ip, job, clsTotal number of appended out of order samples. prometheus_tsdb_head_samples_appended_total counter ins, instance, ip, type, job, clsTotal number of appended samples. prometheus_tsdb_head_series gauge ins, instance, ip, job, clsTotal number of series in the head block. prometheus_tsdb_head_series_created_total counter ins, instance, ip, job, clsTotal number of series created in the head prometheus_tsdb_head_series_not_found_total counter ins, instance, ip, job, clsTotal number of requests for series that were not found. prometheus_tsdb_head_series_removed_total counter ins, instance, ip, job, clsTotal number of series removed in the head prometheus_tsdb_head_truncations_failed_total counter ins, instance, ip, job, clsTotal number of head truncations that failed. prometheus_tsdb_head_truncations_total counter ins, instance, ip, job, clsTotal number of head truncations attempted. prometheus_tsdb_isolation_high_watermark gauge ins, instance, ip, job, clsThe highest TSDB append ID that has been given out. prometheus_tsdb_isolation_low_watermark gauge ins, instance, ip, job, clsThe lowest TSDB append ID that is still referenced. prometheus_tsdb_lowest_timestamp gauge ins, instance, ip, job, clsLowest timestamp value stored in the database. The unit is decided by the library consumer. prometheus_tsdb_lowest_timestamp_seconds gauge ins, instance, ip, job, clsLowest timestamp value stored in the database. prometheus_tsdb_mmap_chunk_corruptions_total counter ins, instance, ip, job, clsTotal number of memory-mapped chunk corruptions. prometheus_tsdb_mmap_chunks_total counter ins, instance, ip, job, clsTotal number of chunks that were memory-mapped. prometheus_tsdb_out_of_bound_samples_total counter ins, instance, ip, type, job, clsTotal number of out of bound samples ingestion failed attempts with out of order support disabled. prometheus_tsdb_out_of_order_samples_total counter ins, instance, ip, type, job, clsTotal number of out of order samples ingestion failed attempts due to out of order being disabled. prometheus_tsdb_reloads_failures_total counter ins, instance, ip, job, clsNumber of times the database failed to reloadBlocks block data from disk. prometheus_tsdb_reloads_total counter ins, instance, ip, job, clsNumber of times the database reloaded block data from disk. prometheus_tsdb_retention_limit_bytes gauge ins, instance, ip, job, clsMax number of bytes to be retained in the tsdb blocks, configured 0 means disabled prometheus_tsdb_retention_limit_seconds gauge ins, instance, ip, job, clsHow long to retain samples in storage. prometheus_tsdb_size_retentions_total counter ins, instance, ip, job, clsThe number of times that blocks were deleted because the maximum number of bytes was exceeded. prometheus_tsdb_snapshot_replay_error_total counter ins, instance, ip, job, clsTotal number snapshot replays that failed. prometheus_tsdb_storage_blocks_bytes gauge ins, instance, ip, job, clsThe number of bytes that are currently used for local storage by all blocks. prometheus_tsdb_symbol_table_size_bytes gauge ins, instance, ip, job, clsSize of symbol table in memory for loaded blocks prometheus_tsdb_time_retentions_total counter ins, instance, ip, job, clsThe number of times that blocks were deleted because the maximum time limit was exceeded. prometheus_tsdb_tombstone_cleanup_seconds_bucket Unknown ins, instance, ip, le, job, clsN/A prometheus_tsdb_tombstone_cleanup_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_tombstone_cleanup_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_too_old_samples_total counter ins, instance, ip, type, job, clsTotal number of out of order samples ingestion failed attempts with out of support enabled, but sample outside of time window. prometheus_tsdb_vertical_compactions_total counter ins, instance, ip, job, clsTotal number of compactions done on overlapping blocks. prometheus_tsdb_wal_completed_pages_total counter ins, instance, ip, job, clsTotal number of completed pages. prometheus_tsdb_wal_corruptions_total counter ins, instance, ip, job, clsTotal number of WAL corruptions. prometheus_tsdb_wal_fsync_duration_seconds summary ins, instance, ip, job, cls, quantileDuration of write log fsync. prometheus_tsdb_wal_fsync_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_wal_fsync_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_wal_page_flushes_total counter ins, instance, ip, job, clsTotal number of page flushes. prometheus_tsdb_wal_segment_current gauge ins, instance, ip, job, clsWrite log segment index that TSDB is currently writing to. prometheus_tsdb_wal_storage_size_bytes gauge ins, instance, ip, job, clsSize of the write log directory. prometheus_tsdb_wal_truncate_duration_seconds_count Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_wal_truncate_duration_seconds_sum Unknown ins, instance, ip, job, clsN/A prometheus_tsdb_wal_truncations_failed_total counter ins, instance, ip, job, clsTotal number of write log truncations that failed. prometheus_tsdb_wal_truncations_total counter ins, instance, ip, job, clsTotal number of write log truncations attempted. prometheus_tsdb_wal_writes_failed_total counter ins, instance, ip, job, clsTotal number of write log writes that failed. prometheus_web_federation_errors_total counter ins, instance, ip, job, clsTotal number of errors that occurred while sending federation responses. prometheus_web_federation_warnings_total counter ins, instance, ip, job, clsTotal number of warnings that occurred while sending federation responses. promhttp_metric_handler_requests_in_flight gauge ins, instance, ip, job, clsCurrent number of scrapes being served. promhttp_metric_handler_requests_total counter ins, instance, ip, job, cls, codeTotal number of scrapes by HTTP status code. pushgateway_build_info gauge revision, version, ins, instance, ip, tags, goarch, goversion, job, cls, branch, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which pushgateway was built, and the goos and goarch for the build. pushgateway_http_requests_total counter ins, instance, method, ip, job, cls, code, handlerTotal HTTP requests processed by the Pushgateway, excluding scrapes. querier_cache_added_new_total Unknown ins, instance, ip, job, cache, clsN/A querier_cache_added_total Unknown ins, instance, ip, job, cache, clsN/A querier_cache_entries gauge ins, instance, ip, job, cache, clsThe total number of entries querier_cache_evicted_total Unknown ins, instance, ip, job, reason, cache, clsN/A querier_cache_gets_total Unknown ins, instance, ip, job, cache, clsN/A querier_cache_memory_bytes gauge ins, instance, ip, job, cache, clsThe current cache size in bytes querier_cache_misses_total Unknown ins, instance, ip, job, cache, clsN/A querier_cache_stale_gets_total Unknown ins, instance, ip, job, cache, clsN/A ring_member_heartbeats_total Unknown ins, instance, ip, job, clsN/A ring_member_tokens_owned gauge ins, instance, ip, job, clsThe number of tokens owned in the ring. ring_member_tokens_to_own gauge ins, instance, ip, job, clsThe number of tokens to own in the ring. scrape_duration_seconds Unknown ins, instance, ip, job, clsN/A scrape_samples_post_metric_relabeling Unknown ins, instance, ip, job, clsN/A scrape_samples_scraped Unknown ins, instance, ip, job, clsN/A scrape_series_added Unknown ins, instance, ip, job, clsN/A up Unknown ins, instance, ip, job, clsN/A
PING 指标 PING 任务包含有 54 类可用监控指标,由 blackbox_epxorter 提供。
Metric Name Type Labels Description agent_up Unknown ins, ip, job, instance, clsN/A probe_dns_lookup_time_seconds gauge ins, ip, job, instance, clsReturns the time taken for probe dns lookup in seconds probe_duration_seconds gauge ins, ip, job, instance, clsReturns how long the probe took to complete in seconds probe_icmp_duration_seconds gauge ins, ip, job, phase, instance, clsDuration of icmp request by phase probe_icmp_reply_hop_limit gauge ins, ip, job, instance, clsReplied packet hop limit (TTL for ipv4) probe_ip_addr_hash gauge ins, ip, job, instance, clsSpecifies the hash of IP address. It’s useful to detect if the IP address changes. probe_ip_protocol gauge ins, ip, job, instance, clsSpecifies whether probe ip protocol is IP4 or IP6 probe_success gauge ins, ip, job, instance, clsDisplays whether or not the probe was a success scrape_duration_seconds Unknown ins, ip, job, instance, clsN/A scrape_samples_post_metric_relabeling Unknown ins, ip, job, instance, clsN/A scrape_samples_scraped Unknown ins, ip, job, instance, clsN/A scrape_series_added Unknown ins, ip, job, instance, clsN/A up Unknown ins, ip, job, instance, clsN/A
PUSH 指标 PushGateway 提供 44 类监控指标。
Metric Name Type Labels Description agent_up Unknown job, cls, instance, ins, ipN/A go_gc_duration_seconds summary job, cls, instance, ins, quantile, ipA summary of the pause duration of garbage collection cycles. go_gc_duration_seconds_count Unknown job, cls, instance, ins, ipN/A go_gc_duration_seconds_sum Unknown job, cls, instance, ins, ipN/A go_goroutines gauge job, cls, instance, ins, ipNumber of goroutines that currently exist. go_info gauge job, cls, instance, ins, ip, versionInformation about the Go environment. go_memstats_alloc_bytes counter job, cls, instance, ins, ipTotal number of bytes allocated, even if freed. go_memstats_alloc_bytes_total counter job, cls, instance, ins, ipTotal number of bytes allocated, even if freed. go_memstats_buck_hash_sys_bytes gauge job, cls, instance, ins, ipNumber of bytes used by the profiling bucket hash table. go_memstats_frees_total counter job, cls, instance, ins, ipTotal number of frees. go_memstats_gc_sys_bytes gauge job, cls, instance, ins, ipNumber of bytes used for garbage collection system metadata. go_memstats_heap_alloc_bytes gauge job, cls, instance, ins, ipNumber of heap bytes allocated and still in use. go_memstats_heap_idle_bytes gauge job, cls, instance, ins, ipNumber of heap bytes waiting to be used. go_memstats_heap_inuse_bytes gauge job, cls, instance, ins, ipNumber of heap bytes that are in use. go_memstats_heap_objects gauge job, cls, instance, ins, ipNumber of allocated objects. go_memstats_heap_released_bytes gauge job, cls, instance, ins, ipNumber of heap bytes released to OS. go_memstats_heap_sys_bytes gauge job, cls, instance, ins, ipNumber of heap bytes obtained from system. go_memstats_last_gc_time_seconds gauge job, cls, instance, ins, ipNumber of seconds since 1970 of last garbage collection. go_memstats_lookups_total counter job, cls, instance, ins, ipTotal number of pointer lookups. go_memstats_mallocs_total counter job, cls, instance, ins, ipTotal number of mallocs. go_memstats_mcache_inuse_bytes gauge job, cls, instance, ins, ipNumber of bytes in use by mcache structures. go_memstats_mcache_sys_bytes gauge job, cls, instance, ins, ipNumber of bytes used for mcache structures obtained from system. go_memstats_mspan_inuse_bytes gauge job, cls, instance, ins, ipNumber of bytes in use by mspan structures. go_memstats_mspan_sys_bytes gauge job, cls, instance, ins, ipNumber of bytes used for mspan structures obtained from system. go_memstats_next_gc_bytes gauge job, cls, instance, ins, ipNumber of heap bytes when next garbage collection will take place. go_memstats_other_sys_bytes gauge job, cls, instance, ins, ipNumber of bytes used for other system allocations. go_memstats_stack_inuse_bytes gauge job, cls, instance, ins, ipNumber of bytes in use by the stack allocator. go_memstats_stack_sys_bytes gauge job, cls, instance, ins, ipNumber of bytes obtained from system for stack allocator. go_memstats_sys_bytes gauge job, cls, instance, ins, ipNumber of bytes obtained from system. go_threads gauge job, cls, instance, ins, ipNumber of OS threads created. process_cpu_seconds_total counter job, cls, instance, ins, ipTotal user and system CPU time spent in seconds. process_max_fds gauge job, cls, instance, ins, ipMaximum number of open file descriptors. process_open_fds gauge job, cls, instance, ins, ipNumber of open file descriptors. process_resident_memory_bytes gauge job, cls, instance, ins, ipResident memory size in bytes. process_start_time_seconds gauge job, cls, instance, ins, ipStart time of the process since unix epoch in seconds. process_virtual_memory_bytes gauge job, cls, instance, ins, ipVirtual memory size in bytes. process_virtual_memory_max_bytes gauge job, cls, instance, ins, ipMaximum amount of virtual memory available in bytes. pushgateway_build_info gauge job, goversion, cls, branch, instance, tags, revision, goarch, ins, ip, version, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which pushgateway was built, and the goos and goarch for the build. pushgateway_http_requests_total counter job, cls, method, code, handler, instance, ins, ipTotal HTTP requests processed by the Pushgateway, excluding scrapes. scrape_duration_seconds Unknown job, cls, instance, ins, ipN/A scrape_samples_post_metric_relabeling Unknown job, cls, instance, ins, ipN/A scrape_samples_scraped Unknown job, cls, instance, ins, ipN/A scrape_series_added Unknown job, cls, instance, ins, ipN/A up Unknown job, cls, instance, ins, ipN/A
12.8 - 常见问题 Pigsty INFRA 基础设施模块常见问题答疑
INFRA 模块中包含了哪些组件? Ansible :用于自动化配置、部署和日常运维。Nginx :对外暴露 Grafana、VictoriaMetrics(VMUI)、Alertmanager 等 WebUI,并托管本地 YUM/APT 仓库。自签名 CA :为 Nginx、Patroni、pgBackRest 等组件签发 SSL/TLS 证书。VictoriaMetrics 套件 :替代 Prometheus/Loki,包含 VictoriaMetrics(TSDB)、VMAlert(告警评估)、VictoriaLogs(集中日志)、VictoriaTraces(链路追踪)。Vector :节点侧日志采集器,负责将系统/数据库日志推送至 VictoriaLogs。AlertManager :聚合并分发告警通知。Grafana :监控/可视化平台,预置大量仪表板和数据源。Chronyd :提供 NTP 时间同步。DNSMasq :提供 DNS 注册与解析。ETCD :作为 PostgreSQL 高可用 DCS(亦可在专用集群部署)。PostgreSQL :在管理节点上充当 CMDB(可选)。Docker :在节点上运行无状态工具或应用(可选)。如何重新向 VictoriaMetrics 注册监控目标? VictoriaMetrics 通过 /infra/targets/<job>/*.yml 目录进行静态服务发现。如果目标文件被误删,可使用如下命令重新注册:
./infra.yml -t infra_register # 重新渲染 infra 自监控目标
./node.yml -t node_register # 重新渲染节点 / HAProxy / Vector 目标
./etcd.yml -t etcd_register # 重新渲染 etcd 目标
./minio.yml -t minio_register # 重新渲染 MinIO 目标
./pgsql.yml -t pg_register # 重新渲染 PGSQL/Patroni 目标
./redis.yml -t redis_register # 重新渲染 Redis 目标
其他模块(如 pg_monitor.yml、mongo.yml、mysql.yml)也提供了对应的 *_register 标签,可按需执行。
如何重新向 Grafana 注册 PostgreSQL 数据源? 在 pg_databases 中定义的 PGSQL 数据库默认会被注册为 Grafana 数据源(以供 PGCAT 应用使用)。
如果你不小心删除了在 Grafana 中注册的 postgres 数据源,你可以使用以下命令再次注册它们:
# 将所有(在 pg_databases 中定义的) pgsql 数据库注册为 grafana 数据源
./pgsql.yml -t register_grafana
如何重新向 Nginx 注册节点的 Haproxy 管控界面? 如果你不小心删除了 /etc/nginx/conf.d/haproxy 中的已注册 haproxy 代理设置,你可以使用以下命令再次恢复它们:
./node.yml -t register_nginx # 在 infra 节点上向 nginx 注册所有 haproxy 管理页面的代理设置
如何恢复 DNSMASQ 中的域名注册记录? PGSQL 集群/实例域名默认注册到 infra 节点的 /etc/hosts.d/<name>。你可以使用以下命令再次恢复它们:
./pgsql.yml -t pg_dns # 在 infra 节点上向 dnsmasq 注册 pg 的 DNS 名称
如何使用Nginx对外暴露新的上游服务? 尽管您可以直接通过 IP:Port 的方式访问服务,但我们依然建议收敛访问入口,使用域名并统一从 Nginx 代理访问各类带有 Web 界面的服务。
这样有利于统一收口访问,减少暴露的端口,便于进行访问控制与审计。
如果你希望通过 Nginx 门户公开新的 WebUI 服务,你可以将服务定义添加到 infra_portal 参数中。
例如,下面是 Pigsty 官方 Demo 使用的 Infra 门户配置,对外暴露了几种额外的服务:
infra_portal :
home : { domain : home.pigsty.cc }
grafana : { domain: demo.pigsty.cc ,endpoint : "${admin_ip}:3000" ,websocket : true }
prometheus : { domain: p.pigsty.cc ,endpoint : "${admin_ip}:8428" }
alertmanager : { domain: a.pigsty.cc ,endpoint : "${admin_ip}:9059" }
blackbox : { endpoint : "${admin_ip}:9115" }
vmalert : { endpoint : "${admin_ip}:8880" }
# 新增的 Web 门户
minio : { domain: sss.pigsty ,endpoint : "${admin_ip}:9001" ,scheme: https ,websocket : true }
postgrest : { domain: api.pigsty.cc ,endpoint : "127.0.0.1:8884" }
pgadmin : { domain: adm.pigsty.cc ,endpoint : "127.0.0.1:8885" }
pgweb : { domain: cli.pigsty.cc ,endpoint : "127.0.0.1:8886" }
bytebase : { domain: ddl.pigsty.cc ,endpoint : "127.0.0.1:8887" }
gitea : { domain: git.pigsty.cc ,endpoint : "127.0.0.1:8889" }
wiki : { domain: wiki.pigsty.cc ,endpoint : "127.0.0.1:9002" }
noco : { domain: noco.pigsty.cc ,endpoint : "127.0.0.1:9003" }
supa : { domain: supa.pigsty.cc ,endpoint : "127.0.0.1:8000" , websocket : true }
完成 Nginx 上游服务定义后,使用以下配置与命令,向 Nginx 注册新的服务。
./infra.yml -t nginx_config # 重新生成 Nginx 配置文件
./infra.yml -t nginx_launch # 更新并应用 Nginx 配置。
# 您也可以使用 Ansible 手工重载 Nginx 配置
ansible infra -b -a 'nginx -s reload' # 重载Nginx配置
如果你希望通过 HTTPS 访问,你必须删除 files/pki/csr/pigsty.csr 和 files/pki/nginx/pigsty.{key,crt} 以强制重新生成 Nginx SSL/TLS 证书以包括新上游的域名。
如果您希望使用权威机构签发的 SSL 证书,而不是 Pigsty 自签名 CA 颁发的证书,可以将其放置于 /etc/nginx/conf.d/cert/ 目录中并修改相应配置:/etc/nginx/conf.d/<name>.conf。
如何手动向节点添加上游仓库的Repo文件? Pigsty 有一个内置的包装脚本 bin/repo-add,它将调用 ansible 剧本 node.yml 来将 repo 文件添加到相应的节点。
bin/repo-add <selector> [ modules]
bin/repo-add 10.10.10.10 # 为节点 10.10.10.10 添加 node 源
bin/repo-add infra node,infra # 为 infra 分组添加 node 和 infra 源
bin/repo-add infra node,local # 为 infra 分组添加节点仓库和本地pigsty源
bin/repo-add pg-test node,pgsql # 为 pg-test 分组添加 node 和 pgsql 源
13 - 模块:NODE 配置目标服务器,纳管主机节点,并将其调整至描述的状态。也包括节点上的 VIP,HAProxy 以及监控组件。
配置目标服务器,纳管主机节点,并将其调整至描述的状态。也包括节点上的 VIP,HAProxy 以及监控组件。
13.1 - 核心概念 介绍 Node 集群中涉及到的重要概念
节点是硬件资源的抽象,可以是物理机,裸金属、虚拟机、容器或 K8s pods。
只要装着 Linux 操作系统(以及 systemd 守护进程),能使用 CPU/内存/磁盘/网络 等标准资源即可。
Pigsty 中存在不同类型节点,区别在于安装了不同的 模块 :
在 单机安装 Pigsty 时,四者合一,当前节点将同时作为普通节点,管理节点、基础设施节点,以及数据库节点。
普通节点 使用 Pigsty 管理节点,可在其上安装模块。node.yml 剧本将调整节点至所需状态。以下服务默认会被添加到所有节点:
组件 端口 描述 状态 Node Exporter 9100 节点监控指标导出器 默认启用 HAProxy Admin 9101 HAProxy 管理页面 默认启用 Vector 9598 日志收集代理 默认启用 Docker Daemon 9323 启用容器支持 按需启用 Keepalived — 管理主机集群 L2 VIP 按需启用 Keepalived Exporter 9650 监控 Keepalived 状态 按需启用
可为节点选装 Docker 与 Keepalived 及其监控组件,这两个默认不启用。
ADMIN节点 一套 Pigsty 部署中有且只有一个管理节点,由 admin_ip 指定。在单机安装配置过程中,设置为该机器的首要 IP 地址。
该节点拥有对所有其他节点的 ssh/sudo 访问权限。管理节点的安全至关重要,请确保它的访问受到严格控制。
通常管理节点与基础设施节点(INFRA 节点)重合。若有多个 INFRA 节点,管理节点通常是其中第一个,其他作为备份。
INFRA节点 一套 Pigsty 部署可能有 1 个或多个 INFRA 节点,大型生产环境可能有 2-3 个。
配置清单中的 infra 分组指定哪些节点是 INFRA 节点,这些节点安装 INFRA 模块(DNS、Nginx、Prometheus、Grafana 等)。
管理节点通常是 INFRA 节点分组中的第一个,其他 INFRA 节点可被用作备用管理节点。
组件 端口 域名 描述 Nginx 80 i.pigstyWeb 服务门户(软件仓库) Grafana 3000 - 可视化平台 VictoriaMetrics 9090 - 时序数据库(收存监控指标) VictoriaLogs 9428 — 日志收集服务器 VictoriaTraces 10428 — 日志收集服务器 vmalert 8880 — 日志收集服务器 AlertManager 9093 - 告警聚合分发 BlackboxExporter 9115 — 黑盒监控探测 DNSMASQ 53 — DNS 服务器 Chronyd 123 — NTP 时间服务器 Ansible — — 运行剧本
PGSQL节点 安装了 PGSQL 模块的节点被称为 PGSQL 节点。节点与 PostgreSQL 实例为 1:1 部署。
PGSQL 节点可从相应 PostgreSQL 实例借用身份,由 node_id_from_pg 参数控制。
组件 端口 描述 状态 Postgres 5432 PostgreSQL 数据库 默认启用 Pgbouncer 6432 Pgbouncer 连接池 默认启用 Patroni 8008 Patroni 高可用组件 默认启用 HAProxy Primary 5433 主连接池:读/写服务 默认启用 HAProxy Replica 5434 副本连接池:只读服务 默认启用 HAProxy Default 5436 主直连服务 默认启用 HAProxy Offline 5438 离线直连:离线读服务 默认启用 HAProxy service 543x PostgreSQL 定制服务 按需定制 HAProxy Admin 9101 监控指标和流量管理 默认启用 PG Exporter 9630 PG 监控指标导出器 默认启用 PGBouncer Exporter 9631 PGBouncer 监控指标导出器 默认启用 Node Exporter 9100 节点监控指标导出器 默认启用 Vector 9598 收集数据库组件与主机日志 默认启用 vip-manager — 将 VIP 绑定到主节点 按需启用 Docker Daemon 9323 Docker 守护进程 按需启用 keepalived — 为整个集群绑定 L2 VIP 按需启用 Keepalived Exporter 9650 Keepalived 指标导出器 按需启用
13.2 - 集群配置 根据需求场景选择合适的 Node 部署类型,并对外提供可靠的接入。
Pigsty 使用 IP地址 作为 节点 的唯一身份标识,该IP地址应当是数据库实例监听并对外提供服务的内网IP地址 。
node-test :
hosts :
10.10.10.11 : { nodename : node-test-1 }
10.10.10.12 : { nodename : node-test-2 }
10.10.10.13 : { nodename : node-test-3 }
vars :
node_cluster : node-test
该IP地址必须是数据库实例监听并对外提供服务的IP地址,但不宜使用公网IP地址。尽管如此,用户并不一定非要通过该IP地址连接至该数据库。例如,通过SSH隧道或跳板机中转的方式间接操作管理目标节点也是可行的。但在标识数据库节点时,首要IPv4地址依然是节点的核心标识符。这一点非常重要,用户应当在配置时保证这一点 。
IP地址即配置清单中主机的 inventory_hostname,体现为 <cluster>.hosts 对象中的 key。除此之外,每个节点还有两个额外的身份参数:
nodename 与 node_cluster 两个参数是可选的,如果不提供,会使用节点现有的主机名,和固定值 nodes 作为默认值。在 Pigsty 的监控系统中,这两者将会被用作节点的 集群标识 (cls)与 实例标识 (ins)。
对于 PGSQL节点 来说,因为Pigsty默认采用PG:节点独占1:1部署,因此可以通过 node_id_from_pg 参数,将 PostgreSQL 实例的身份参数(pg_cluster 与 pg_seq )借用至节点的 ins 与 cls 标签上,从而让数据库与节点的监控指标拥有相同的标签,便于交叉分析。
#nodename: # [实例] # 节点实例标识,如缺失则使用现有主机名,可选,无默认值
node_cluster : nodes # [集群] # 节点集群标识,如缺失则使用默认值'nodes',可选
nodename_overwrite : true # 用 nodename 覆盖节点的主机名吗?
nodename_exchange : false # 在剧本主机之间交换 nodename 吗?
node_id_from_pg : true # 如果可行,是否借用 postgres 身份作为节点身份?
您还可以为主机集群配置丰富的功能参数,例如,使用节点集群上的 HAProxy 对外提供负载均衡,暴露服务,或者为集群绑定一个 L2 VIP。
13.3 - 参数列表 NODE 模块提供了 11 组共 60+ 个配置参数
NODE 模块负责将主机节点调整到期待的目标状态,并将其纳入 Pigsty 的监控系统中。
参数概览 NODE_ID 参数组用于定义节点的身份标识参数,包括节点名称、集群名称,以及是否从 PostgreSQL 借用身份。
NODE_DNS 参数组用于配置节点的 DNS 解析,包括静态 hosts 记录与动态 DNS 服务器。
NODE_PACKAGE 参数组用于配置节点的软件源与软件包安装。
NODE_TUNE 参数组用于配置节点的内核参数、特性开关与性能调优模板。
NODE_SEC 参数组用于配置节点的安全相关选项,包括 SELinux、防火墙等。
NODE_ADMIN 参数组用于配置节点的管理员用户、数据目录与命令别名。
NODE_TIME 参数组用于配置节点的时区、NTP 时间同步与定时任务。
NODE_VIP 参数组用于配置节点集群的 L2 VIP,由 keepalived 实现。
HAPROXY 参数组用于配置节点上的 HAProxy 负载均衡器与服务暴露。
NODE_EXPORTER 参数组用于配置节点监控 Exporter。
VECTOR 参数组用于配置 Vector 日志收集器。
NODE_ID每个节点都有身份参数 ,通过在<cluster>.hosts与<cluster>.vars中的相关参数进行配置。
Pigsty使用IP地址 作为数据库节点 的唯一标识,该IP地址必须是数据库实例监听并对外提供服务的IP地址 ,但不宜使用公网IP地址。
尽管如此,用户并不一定非要通过该IP地址连接至该数据库。例如,通过SSH隧道或跳板机中转的方式间接操作管理目标节点也是可行的。
但在标识数据库节点时,首要IPv4地址依然是节点的核心标识符。这一点非常重要,用户应当在配置时保证这一点 。
IP地址即配置清单中主机的inventory_hostname ,体现为<cluster>.hosts对象中的key。
node-test :
hosts :
10.10.10.11 : { nodename : node-test-1 }
10.10.10.12 : { nodename : node-test-2 }
10.10.10.13 : { nodename : node-test-3 }
vars :
node_cluster : node-test
除此之外,在Pigsty监控系统中,节点还有两个重要的身份参数:nodename 与 node_cluster ,这两者将在监控系统中被用作节点的 实例标识 (ins) 与 集群标识 (cls)。
node_load1{cls="pg-meta", ins="pg-meta-1", ip="10.10.10.10", job="nodes"}
node_load1{cls="pg-test", ins="pg-test-1", ip="10.10.10.11", job="nodes"}
node_load1{cls="pg-test", ins="pg-test-2", ip="10.10.10.12", job="nodes"}
node_load1{cls="pg-test", ins="pg-test-3", ip="10.10.10.13", job="nodes"}
在执行默认的PostgreSQL部署时,因为Pigsty默认采用节点独占1:1部署,因此可以通过 node_id_from_pg 参数,将数据库实例的身份参数( pg_cluster 借用至节点的ins与cls标签上。
#nodename: # [实例] # 节点实例标识,如缺失则使用现有主机名,可选,无默认值
node_cluster : nodes # [集群] # 节点集群标识,如缺失则使用默认值'nodes',可选
nodename_overwrite : true # 用 nodename 覆盖节点的主机名吗?
nodename_exchange : false # 在剧本主机之间交换 nodename 吗?
node_id_from_pg : true # 如果可行,是否借用 postgres 身份作为节点身份?
nodename参数名称: nodename, 类型: string, 层次:I
主机节点的身份参数,如果没有显式设置,则会使用现有的主机 Hostname 作为节点名。本参数虽然是身份参数,但因为有合理默认值,所以是可选项。
如果启用了 node_id_from_pg 选项(默认启用),且 nodename 没有被显式指定,
那么 nodename 会尝试使用 ${pg_cluster}-${pg_seq} 作为实例身份参数,如果集群没有定义 PGSQL 模块,那么会回归到默认值,也就是主机节点的 HOSTNAME。
node_cluster参数名称: node_cluster, 类型: string, 层次:C
该选项可为节点显式指定一个集群名称,通常在节点集群层次定义才有意义。使用默认空值将直接使用固定值nodes作为节点集群标识。
如果启用了 node_id_from_pg 选项(默认启用),且 node_cluster 没有被显式指定,那么 node_cluster 会尝试使用 ${pg_cluster}-${pg_seq} 作为集群身份参数,如果集群没有定义 PGSQL 模块,那么会回归到默认值 nodes。
nodename_overwrite参数名称: nodename_overwrite, 类型: bool, 层次:C
是否使用 nodename 覆盖主机名?默认值为 true,在这种情况下,如果你设置了一个非空的 nodename ,那么它会被用作当前主机的 HOSTNAME 。
当 nodename 配置为空时,如果 node_id_from_pg 参数被配置为 true (默认为真),那么 Pigsty 会尝试借用1:1定义在节点上的 PostgreSQL 实例的身份参数作为主机的节点名。
也就是 {{ pg_cluster }}-{{ pg_seq }},如果该节点没有安装 PGSQL 模块,则会回归到默认什么都不做的状态。
因此,如果您将 nodename 留空,并且没有启用 node_id_from_pg 参数时,Pigsty不会对现有主机名进行任何修改。
nodename_exchange参数名称: nodename_exchange, 类型: bool, 层次:C
是否在剧本节点间交换主机名?默认值为:false
启用此参数时,同一批组执行 node.yml 剧本的节点之间会相互交换节点名称,写入/etc/hosts中。
node_id_from_pg参数名称: node_id_from_pg, 类型: bool, 层次:C
从节点上 1:1 部署的 PostgreSQL 实例/集群上借用身份参数? 默认值为 true。
Pigsty 中的 PostgreSQL 实例与节点默认使用 1:1 部署,因此,您可以从数据库实例上“借用” 身份参数。
此参数默认启用,这意味着一套 PostgreSQL 集群如果没有特殊配置,主机节点集群和实例的身份参数默认值是与数据库身份参数保持一致的。对于问题分析,监控数据处理都提供了额外便利。
NODE_DNSPigsty会为节点配置静态DNS解析记录与动态DNS服务器。
如果您的节点供应商已经为您配置了DNS服务器,您可以将 node_dns_method 设置为 none 跳过DNS设置。
node_write_etc_hosts : true # modify `/etc/hosts` on target node?
node_default_etc_hosts : # static dns records in `/etc/hosts`
- "${admin_ip} i.pigsty"
node_etc_hosts : [] # extra static dns records in `/etc/hosts`
node_dns_method: add # how to handle dns servers : add,none,overwrite
node_dns_servers : [ '${admin_ip}' ] # dynamic nameserver in `/etc/resolv.conf`
node_dns_options : # dns resolv options in `/etc/resolv.conf`
- options single-request-reopen timeout:1
node_write_etc_hosts 参数名称: node_write_etc_hosts, 类型: bool, 层次:G|C|I
是否修改目标节点上的 /etc/hosts?例如,在容器环境中通常不允许修改此配置文件。
node_default_etc_hosts参数名称: node_default_etc_hosts, 类型: string[], 层次:G
默认写入所有节点 /etc/hosts 的静态DNS记录,默认值为:
node_default_etc_hosts 是一个数组,每个元素都是一条 DNS 记录,格式为 <ip> <name>,您可以指定多个用空格分隔的域名。
这个参数是用于配置全局静态DNS解析记录的,如果您希望为单个集群与实例配置特定的静态DNS解析,则可以使用 node_etc_hosts 参数。
node_etc_hosts参数名称: node_etc_hosts, 类型: string[], 层次:C
写入节点 /etc/hosts 的额外的静态DNS记录,默认值为:[] 空数组。
本参数与 node_default_etc_hosts ,形式一样,但用途不同:适合在集群/实例层面进行配置。
node_dns_method参数名称: node_dns_method, 类型: enum, 层次:C
如何配置DNS服务器?有三种选项:add、none、overwrite,默认值为 add。
add:将 node_dns_servers 中的记录追加 至/etc/resolv.conf,并保留已有DNS服务器。(默认)overwrite:使用将 node_dns_servers 中的记录覆盖/etc/resolv.confnone:跳过DNS服务器配置,如果您的环境中已经配置有DNS服务器,则可以直接跳过DNS配置。node_dns_servers参数名称: node_dns_servers, 类型: string[], 层次:C
配置 /etc/resolv.conf 中的动态DNS服务器列表:默认值为: ["${admin_ip}"],即将管理节点作为首要DNS服务器。
node_dns_options参数名称: node_dns_options, 类型: string[], 层次:C
/etc/resolv.conf 中的DNS解析选项,默认值为:
- "options single-request-reopen timeout:1"
如果 node_dns_method 配置为add或overwrite,则本配置项中的记录会被首先写入/etc/resolv.conf 中。具体格式请参考Linux文档关于/etc/resolv.conf的说明
NODE_PACKAGEPigsty会为纳入管理的节点配置Yum源,并安装软件包。
node_repo_modules : local # upstream repo to be added on node, local by default.
node_repo_remove : true # remove existing repo on node?
node_packages : [ openssh-server] # packages to be installed current nodes with latest version
#node_default_packages: # default packages to be installed on all nodes
node_repo_modules参数名称: node_repo_modules, 类型: string, 层次:C/A
需要在节点上添加的的软件源模块列表,形式同 repo_modules 。默认值为 local,即使用 repo_upstream 中 local 所指定的本地软件源。
当 Pigsty 纳管节点时,会根据此参数的值来过滤 repo_upstream 中的条目,只有 module 字段与此参数值匹配的条目才会被添加到节点的软件源中。
node_repo_remove参数名称: node_repo_remove, 类型: bool, 层次:C/A
是否移除节点已有的软件仓库定义?默认值为:true。
如果启用,则Pigsty会 移除 节点上/etc/yum.repos.d中原有的配置文件,并备份至/etc/yum.repos.d/backup。
在 Debian/Ubuntu 系统上,则是 /etc/apt/sources.list(.d) 备份至 /etc/apt/backup。
node_packages参数名称: node_packages, 类型: string[], 层次:C
在当前节点上要安装并升级的软件包列表,默认值为:[openssh-server] ,即在安装时会将 sshd 升级到最新版本(避免安全漏洞)。
每一个数组元素都是字符串:由逗号分隔的软件包名称。形式上与 node_packages_default 相同。本参数通常用于在节点/集群层面指定需要额外安装的软件包。
在本参数中指定的软件包,会 升级到可用的最新版本 ,如果您需要保持现有节点软件版本不变(存在即可),请使用 node_default_packages 参数。
node_default_packages参数名称: node_default_packages, 类型: string[], 层次:G
默认在所有节点上安装的软件包,默认值是 EL 7/8/9 通用的 RPM 软件包列表,数组,每个元素为逗号分隔的包名:
字符串数组类型,每一行都是 由空格分隔 的软件包列表字符串,指定默认在所有节点上安装的软件包列表。
在此变量中指定的软件包,只要求 存在 ,而不要求 最新 。如果您需要安装最新版本的软件包,请使用 node_packages 参数。
本参数没有默认值,即默认值为未定义状态。如果用户不在配置文件中显式指定本参数,则 Pigsty 会从根据当前节点的操作系统族,从定义于 roles/node_id/vars 中的 node_packages_default 变量中加载获取默认值。
默认值(EL系操作系统):
- lz4,unzip,bzip2,pv,jq,git,ncdu,make,patch,bash,lsof,wget,uuid,tuned,nvme-cli,numactl,sysstat,iotop,htop,rsync,tcpdump
- python3,python3-pip,socat,lrzsz,net-tools,ipvsadm,telnet,ca-certificates,openssl,keepalived,etcd,haproxy,chrony,pig
- zlib,yum,audit,bind-utils,readline,vim-minimal,node_exporter,grubby,openssh-server,openssh-clients,chkconfig,vector
默认值(Debian/Ubuntu):
- lz4,unzip,bzip2,pv,jq,git,ncdu,make,patch,bash,lsof,wget,uuid,tuned,nvme-cli,numactl,sysstat,iotop,htop,rsync
- python3,python3-pip,socat,lrzsz,net-tools,ipvsadm,telnet,ca-certificates,openssl,keepalived,etcd,haproxy,chrony,pig
- zlib1g,acl,dnsutils,libreadline-dev,vim-tiny,node-exporter,openssh-server,openssh-client,vector
本参数形式上与 node_packages 相同,但本参数通常用于全局层面指定所有节点都必须安装的默认软件包
NODE_TUNE主机节点特性、内核模块与参数调优模板。
node_disable_numa : false # disable node numa, reboot required
node_disable_swap : false # disable node swap, use with caution
node_static_network : true # preserve dns resolver settings after reboot
node_disk_prefetch : false # setup disk prefetch on HDD to increase performance
node_kernel_modules : [ softdog, ip_vs, ip_vs_rr, ip_vs_wrr, ip_vs_sh ]
node_hugepage_count : 0 # number of 2MB hugepage, take precedence over ratio
node_hugepage_ratio : 0 # node mem hugepage ratio, 0 disable it by default
node_overcommit_ratio : 0 # node mem overcommit ratio, 0 disable it by default
node_tune: oltp # node tuned profile : none,oltp,olap,crit,tiny
node_sysctl_params : { } # sysctl parameters in k:v format in addition to tuned
node_disable_numa参数名称: node_disable_numa, 类型: bool, 层次:C
是否关闭NUMA?默认不关闭NUMA:false。
注意,关闭NUMA需要重启机器后方可生效!如果您不清楚如何绑核,在生产环境使用数据库时建议关闭 NUMA。
node_disable_swap参数名称: node_disable_swap, 类型: bool, 层次:C
是否关闭 SWAP ? 默认不关闭SWAP:false。
通常情况下不建议关闭 SWAP,例外情况是如果您有足够的内存用于独占式 PostgreSQL 部署,则可以关闭 SWAP 提高性能。
例外:当您的节点用于部署 Kubernetes 模块时,应当禁用SWAP。
node_static_network参数名称: node_static_network, 类型: bool, 层次:C
是否使用静态DNS服务器, 类型:bool,层级:C,默认值为:true,默认启用。
启用静态网络,意味着您的DNS Resolv配置不会因为机器重启与网卡变动被覆盖,建议启用,或由网络工程师负责配置。
node_disk_prefetch参数名称: node_disk_prefetch, 类型: bool, 层次:C
是否启用磁盘预读?默认不启用:false。
针对HDD部署的实例可以优化性能,使用机械硬盘时建议启用。
node_kernel_modules参数名称: node_kernel_modules, 类型: string[], 层次:C
启用哪些内核模块?默认启用以下内核模块:
node_kernel_modules : [ softdog, ip_vs, ip_vs_rr, ip_vs_wrr, ip_vs_sh ]
形式上是由内核模块名称组成的数组,声明了需要在节点上安装的内核模块。
node_hugepage_count参数名称: node_hugepage_count, 类型: int, 层次:C
在节点上分配 2MB 大页的数量,默认为 0,另一个相关的参数是 node_hugepage_ratio 。
如果这两个参数 node_hugepage_count 和 node_hugepage_ratio 都为 0(默认),则大页将完全被禁用,本参数的优先级相比 node_hugepage_ratio 更高,因为它更加精确。
如果设定了一个非零值,它将被写入 /etc/sysctl.d/hugepage.conf 中应用生效;负值将不起作用,高于 90% 节点内存的数字将被限制为节点内存的 90%
如果不为零,它应该略大于pg_shared_buffer_ratio 的对应值,这样才能让 PostgreSQL 用上大页。
node_hugepage_ratio参数名称: node_hugepage_ratio, 类型: float, 层次:C
节点内存大页占内存的比例,默认为 0,有效范围:0 ~ 0.40
此内存比例将以大页的形式分配,并为PostgreSQL预留。 node_hugepage_count 是具有更高优先级和精度的参数版本。
默认值:0,这将设置 vm.nr_hugepages=0 并完全不使用大页。
本参数应该等于或略大于pg_shared_buffer_ratio ,如果不为零。
例如,如果您为Postgres共享缓冲区默认分配了25%的内存,您可以将此值设置为 0.27 ~ 0.30,并在初始化后使用 /pg/bin/pg-tune-hugepage 精准回收浪费的大页。
node_overcommit_ratio参数名称: node_overcommit_ratio, 类型: int, 层次:C
节点内存超额分配比率,默认为:0。这是一个从 0 到 100+ 的整数。
默认值:0,这将设置 vm.overcommit_memory=0,否则将使用 vm.overcommit_memory=2, 并使用此值作为 vm.overcommit_ratio。
建议在 pgsql 独占节点上设置 vm.overcommit_ratio,避免内存过度提交。
node_tune参数名称: node_tune, 类型: enum, 层次:C
针对机器进行调优的预制方案,基于tuned 提供服务。有四种预制模式:
tiny:微型虚拟机oltp:常规OLTP模板,优化延迟(默认值)olap:常规OLAP模板,优化吞吐量crit:核心金融业务模板,优化脏页数量通常,数据库的调优模板 pg_conf 应当与机器调优模板配套。
node_sysctl_params参数名称: node_sysctl_params, 类型: dict, 层次:C
使用 K:V 形式的 sysctl 内核参数,会添加到 tuned profile 中,默认值为: {} 空对象。
这是一个 KV 结构的字典参数,Key 是内核 sysctl 参数名,Value 是参数值。你也可以考虑直接在 roles/node/templates 中的 tuned 模板中直接定义额外的 sysctl 参数。
NODE_SEC节点安全相关参数,包括 SELinux 与防火墙配置。
node_selinux_mode: permissive # selinux mode : disabled, permissive, enforcing
node_firewall_mode: zone # firewall mode : disabled, zone, rules
node_firewall_intranet : # which intranet cidr considered as internal network
- 10.0.0.0 /8
- 192.168.0.0 /16
- 172.16.0.0 /12
node_firewall_public_port : # expose these ports to public network in (zone, strict) mode
- 22 # enable ssh access
- 80 # enable http access
- 443 # enable https access
- 5432 # enable postgresql access (think twice before exposing it!)
node_selinux_mode参数名称: node_selinux_mode, 类型: enum, 层次:C
SELinux 运行模式,默认值为:permissive(宽容模式)。
可选值:
disabled:完全禁用 SELinux(等同于旧版本的 node_disable_selinux: true)permissive:宽容模式,记录违规但不阻止(推荐,默认值)enforcing:强制模式,严格执行 SELinux 策略如果您没有专业的操作系统/安全专家,建议使用 permissive 或 disabled 模式。
请注意,SELinux 默认只在 EL 系列系统上启用,如果你想要在 Debian/Ubuntu 系统上启用 SELinux,请自行安装并启用 SELinux 配置。
另外,SELinux 模式的更改可能需要重启系统才能完全生效。
node_firewall_mode参数名称: node_firewall_mode, 类型: enum, 层次:C
防火墙运行模式,默认值为:zone(区域模式)。
可选值:
off:关闭并禁用防火墙(等同于旧版本的 node_disable_firewall: true)none:什么也不管,维持现有防火墙规则不变。zone:使用 firewalld / ufw 配置防火墙规则:内网信任,公网只开放指定端口。在 EL 系统上使用 firewalld 服务,在 Debian/Ubuntu 系统上使用 ufw 服务。
如果您在完全受信任的内网环境中部署,或者通过云厂商安全组等方式进行访问控制,您可以选择 none 模式以保留现有防火墙配置,或者设置为 off 完全禁用防火墙。
生产环境建议使用 zone 模式,配合 node_firewall_intranet 和 node_firewall_public_port 进行精细化访问控制。
请注意,zone 模式不会自动替你启用防火墙。
node_firewall_intranet参数名称: node_firewall_intranet, 类型: cidr[], 层次:C
内网 CIDR 地址列表,空数组,自 v4.0 版本引入,默认值为:
node_firewall_intranet :
- 10.0.0.0 /8
- 172.16.0.0 /12
- 192.168.0.0 /16
此参数定义了被视为"内部网络"的 IP 地址范围。来自这些网络的流量将被允许访问所有服务端口,而无需单独配置开放规则。
这些 CIDR 范围内的主机将被视为可信内网主机,享有更宽松的防火墙规则。同时,在 PG/PGB HBA 规则中,这里定义的内网范围也会被视作 “内网” 对待。
node_firewall_public_port参数名称: node_firewall_public_port, 类型: port[], 层次:C
公网开放端口列表,默认值为:[22, 80, 443, 5432]。
此参数定义了对公网(非内网 CIDR)开放的端口列表。默认开放的端口包括:
22:SSH 服务端口80:HTTP 服务端口443:HTTPS 服务端口5432:PostgreSQL 数据库端口您可以根据实际需求调整此列表。例如,如果不需要对外暴露数据库端口,可以移除 5432:
node_firewall_public_port : [ 22 , 80 , 443 ]
Pigsty 中 PostgreSQL 默认安全策略仅允许管理员通过公网访问数据库端口。
如果您想要让其他用户也能通过公网访问数据库,请确保在 PG/PGB HBA 规则中正确配置相应的访问权限。
如果你想要将其他服务端口对公网开放,也可以将它们添加到此列表中,
如果您想要收紧防火墙规则,可以移除 5432 数据库端口,确保只开放真正需要的服务端口。
请注意,只有当 node_firewall_mode 设置为 zone 时,此参数才会生效。
NODE_ADMIN这一节关于主机节点上的管理员,谁能登陆,怎么登陆。
node_data : /data # node main data directory, `/data` by default
node_admin_enabled : true # create a admin user on target node?
node_admin_uid : 88 # uid and gid for node admin user
node_admin_username : dba # name of node admin user, `dba` by default
node_admin_sudo: nopass # admin user's sudo privilege : limited, nopass, all, none
node_admin_ssh_exchange : true # exchange admin ssh key among node cluster
node_admin_pk_current : true # add current user's ssh pk to admin authorized_keys
node_admin_pk_list : [] # ssh public keys to be added to admin user
node_aliases : {} # alias name -> IP address dict for `/etc/hosts`
node_data参数名称: node_data, 类型: path, 层次:C
节点的主数据目录,默认为 /data。
如果该目录不存在,则该目录会被创建。该目录应当由 root 拥有,并拥有 777 权限。
node_admin_enabled参数名称: node_admin_enabled, 类型: bool, 层次:C
是否在本节点上创建一个专用管理员用户?默认值为:true。
Pigsty默认会在每个节点上创建一个管理员用户(拥有免密sudo与ssh权限),默认的管理员名为dba (uid=88)的管理用户,可以从元节点上通过SSH免密访问环境中的其他节点并执行免密sudo。
node_admin_uid参数名称: node_admin_uid, 类型: int, 层次:C
管理员用户UID,默认值为:88。
请尽可能确保 UID 在所有节点上都相同,可以避免一些无谓的权限问题。
如果默认 UID 88 已经被占用,您可以选择一个其他 UID ,手工分配时请注意UID命名空间冲突。
node_admin_username参数名称: node_admin_username, 类型: username, 层次:C
管理员用户名,默认为 dba 。
node_admin_sudo参数名称: node_admin_sudo, 类型: enum, 层次:C
管理员用户的 sudo 权限级别,默认值为:nopass(免密 sudo)。
可选值:
none:不授予 sudo 权限limited:授予有限的 sudo 权限(仅允许执行特定命令)nopass:授予免密 sudo 权限(默认,允许执行所有命令但无需密码)all:授予完整 sudo 权限(需要密码)Pigsty 默认使用 nopass 模式,管理员用户可以无需密码执行任意 sudo 命令,这对于自动化运维非常方便。
在安全要求较高的生产环境中,您可能需要将此参数调整为 limited 或 all,以限制管理员的权限范围。
node_admin_ssh_exchange参数名称: node_admin_ssh_exchange, 类型: bool, 层次:C
在节点集群间交换节点管理员SSH密钥, 类型:bool,层级:C,默认值为:true
启用时,Pigsty会在执行剧本时,在成员间交换SSH公钥,允许管理员 node_admin_username 从不同节点上相互访问。
node_admin_pk_current参数名称: node_admin_pk_current, 类型: bool, 层次:C
是否将当前节点 & 用户的公钥加入管理员账户,默认值是: true
启用时,将会把当前节点上执行此剧本的管理用户的SSH公钥(~/.ssh/id_rsa.pub)拷贝至目标节点管理员用户的 authorized_keys 中。
生产环境部署时,请务必注意此参数,此参数会将当前执行命令用户的默认公钥安装至所有机器的管理用户上。
node_admin_pk_list参数名称: node_admin_pk_list, 类型: string[], 层次:C
可登陆管理员的公钥列表,默认值为:[] 空数组。
数组的每一个元素为字符串,内容为写入到管理员用户~/.ssh/authorized_keys中的公钥,持有对应私钥的用户可以以管理员身份登录。
生产环境部署时,请务必注意此参数,仅将信任的密钥加入此列表中。
node_aliases参数名称: node_aliases, 类型: dict, 层次:C
用于写入主机 /etc/profile.d/node.alias.sh 的 shell 别名,默认值为:{} 空字典。
此参数允许您为主机的 shell 环境配置方便使用的 alias,此处定义的 K:V 字典将以 alias k=v 的形式写入到目标节点的 profile.d 文件中生效。
例如,以下命令声明了一个名为 dp 的别名,用于快速执行 docker compose pull 命令:
node_alias :
dp : 'docker compose pull'
NODE_TIME关于主机时间/时区/NTP/定时任务的相关配置。
时间同步对于数据库服务来说非常重要,请确保系统 chronyd 授时服务正常运行。
node_timezone : '' # 设置节点时区,空字符串表示跳过
node_ntp_enabled : true # 启用chronyd时间同步服务?
node_ntp_servers : # `/etc/chrony.conf`中的ntp服务器
- pool pool.ntp.org iburst
node_crontab_overwrite : true # 覆盖还是追加到`/etc/crontab`?
node_crontab : [ ] # `/etc/crontab`中的crontab条目
node_timezone参数名称: node_timezone, 类型: string, 层次:C
设置节点时区,空字符串表示跳过。默认值是空字符串,默认不会修改默认的时区(即使用通常的默认值UTC)
在中国地区使用时,建议设置为 Asia/Hong_Kong / Asia/ShangHai。
node_ntp_enabled参数名称: node_ntp_enabled, 类型: bool, 层次:C
启用chronyd时间同步服务?默认值为:true
此时 Pigsty 将使用 node_ntp_servers 中指定的 NTP服务器列表覆盖节点的 /etc/chrony.conf。
如果您的节点已经配置好了 NTP 服务器,那么可以将此参数设置为 false 跳过时间同步配置。
node_ntp_servers参数名称: node_ntp_servers, 类型: string[], 层次:C
在 /etc/chrony.conf 中使用的 NTP 服务器列表。默认值为:["pool pool.ntp.org iburst"]
本参数是一个数组,每一个数组元素是一个字符串,代表一行 NTP 服务器配置。仅当 node_ntp_enabled 启用时生效。
Pigsty 默认使用全球 NTP 服务器 pool.ntp.org,您可以根据自己的网络环境修改此参数,例如 cn.pool.ntp.org iburst,或内网的时钟服务。
您也可以在配置中使用 ${admin_ip} 占位符,使用管理节点上的时间服务器。
node_ntp_servers : [ 'pool ${admin_ip} iburst' ]
node_crontab_overwrite参数名称: node_crontab_overwrite, 类型: bool, 层次:C
处理 node_crontab 中的定时任务时,是追加还是覆盖?默认值为:true,即覆盖。
如果您希望在节点上追加定时任务,可以将此参数设置为 false,Pigsty 将会在节点的 crontab 上 追加 ,而非 覆盖所有 定时任务。
node_crontab参数名称: node_crontab, 类型: string[], 层次:C
定义在节点 /etc/crontab 中的定时任务:默认值为:[] 空数组。
每一个数组数组元素都是一个字符串,代表一行定时任务。使用标准的 cron 格式定义。
例如,以下配置会以 postgres 用户在每天凌晨1点执行全量备份任务。
node_crontab :
- '00 01 * * * postgres /pg/bin/pg-backup full' ] # make a full backup every 1am
NODE_VIP您可以为节点集群绑定一个可选的 L2 VIP,默认不启用此特性。L2 VIP 只对一组节点集群有意义,该 VIP 会根据配置的优先级在集群中的节点之间进行切换,确保节点服务的高可用。
请注意,L2 VIP 只能 在同一 L2 网段中使用,这可能会对您的网络拓扑产生额外的限制,如果不想受此限制,您可以考虑使用 DNS LB 或者 Haproxy 实现类似的功能。
当启用此功能时,您需要为这个 L2 VIP 显式分配可用的 vip_address 与 vip_vrid ,用户应当确保这两者在同一网段内唯一。
请注意,NODE VIP 与 PG VIP 不同,PG VIP 是为 PostgreSQL 实例服务的 VIP,由 vip-manager 组件管理并绑定在 PG 集群主库上。
而 NODE VIP 由 Keepalived 组件管理,绑定在节点集群上。可以是主备模式,也可以是负载均衡模式,两者可以并存。
vip_enabled : false # enable vip on this node cluster?
# vip_address: [IDENTITY] # node vip address in ipv4 format, required if vip is enabled
# vip_vrid: [IDENTITY] # required, integer, 1-254, should be unique among same VLAN
vip_role : backup # optional, `master/backup`, backup by default, use as init role
vip_preempt : false # optional, `true/false`, false by default, enable vip preemption
vip_interface : eth0 # node vip network interface to listen, `eth0` by default
vip_dns_suffix : '' # node vip dns name suffix, empty string by default
vip_exporter_port : 9650 # keepalived exporter listen port, 9650 by default
vip_enabled参数名称: vip_enabled, 类型: bool, 层次:C
是否在当前这个节点集群中配置一个由 Keepalived 管理的 L2 VIP ? 默认值为: false。
vip_address参数名称: vip_address, 类型: ip, 层次:C
节点 VIP 地址,IPv4 格式(不带 CIDR 网段后缀),当节点启用 vip_enabled 时,这是一个必选参数。
本参数没有默认值,这意味着您必须显式地为节点集群分配一个唯一的 VIP 地址。
vip_vrid参数名称: vip_vrid, 类型: int, 层次:C
VRID 是一个范围从 1 到 254 的正整数,用于标识一个网络中的 VIP,当节点启用 vip_enabled 时,这是一个必选参数。
本参数没有默认值,这意味着您必须显式地为节点集群分配一个网段内唯一的 ID。
vip_role参数名称: vip_role, 类型: enum, 层次:I
节点 VIP 角色,可选值为: master 或 backup,默认值为 backup
该参数的值会被设置为 keepalived 的初始状态。
vip_preempt参数名称: vip_preempt, 类型: bool, 层次:C/I
是否启用 VIP 抢占?可选参数,默认值为 false,即不抢占 VIP。
所谓抢占,是指一个 backup 角色的节点,当其优先级高于当前存活且正常工作的 master 角色的节点时,是否取抢占其 VIP?
vip_interface参数名称: vip_interface, 类型: string, 层次:C/I
节点 VIP 监听使用的网卡,默认为 eth0。
您应当使用与节点主IP地址(即:你填入清单中IP地址)所使用网卡相同的名称。
如果你的节点有着不同的网卡名称,你可以在实例/节点层次对其进行覆盖。
vip_dns_suffix参数名称: vip_dns_suffix, 类型: string, 层次:C/I
节点集群 L2 VIP 使用的DNS名称,默认是空字符串,即直接使用集群名本身作为DNS名。
vip_exporter_port参数名称: vip_exporter_port, 类型: port, 层次:C/I
keepalived exporter 监听端口号,默认为:9650。
HAPROXYHAProxy 默认在所有节点上安装启用,并以类似于 Kubernetes NodePort 的方式对外暴露服务。
PGSQL 模块对外服务 使用到了 Haproxy。
haproxy_enabled : true # 在此节点上启用haproxy?
haproxy_clean : false # 清理所有现有的haproxy配置?
haproxy_reload : true # 配置后重新加载haproxy?
haproxy_auth_enabled : true # 为haproxy管理页面启用身份验证
haproxy_admin_username : admin # haproxy管理用户名,默认为`admin`
haproxy_admin_password : pigsty # haproxy管理密码,默认为`pigsty`
haproxy_exporter_port : 9101 # haproxy管理/导出端口,默认为9101
haproxy_client_timeout : 24h # 客户端连接超时,默认为24小时
haproxy_server_timeout : 24h # 服务器端连接超时,默认为24小时
haproxy_services : [] # 需要在节点上暴露的haproxy服务列表
haproxy_enabled参数名称: haproxy_enabled, 类型: bool, 层次:C
在此节点上启用haproxy?默认值为: true。
haproxy_clean参数名称: haproxy_clean, 类型: bool, 层次:G/C/A
清理所有现有的haproxy配置?默认值为 false。
haproxy_reload参数名称: haproxy_reload, 类型: bool, 层次:A
配置后重新加载 haproxy?默认值为 true,配置更改后会重新加载haproxy。
如果您希望在应用配置前进行手工检查,您可以使用命令参数关闭此选项,并进行检查后再应用。
haproxy_auth_enabled参数名称: haproxy_auth_enabled, 类型: bool, 层次:G
为haproxy管理页面启用身份验证,默认值为 true,它将要求管理页面进行http基本身份验证。
建议不要禁用认证,因为您的流量控制页面将对外暴露,这是比较危险的。
haproxy_admin_username参数名称: haproxy_admin_username, 类型: username, 层次:G
haproxy 管理员用户名,默认为:admin。
haproxy_admin_password参数名称: haproxy_admin_password, 类型: password, 层次:G
haproxy管理密码,默认为 pigsty
在生产环境中请务必修改此密码!
haproxy_exporter_port参数名称: haproxy_exporter_port, 类型: port, 层次:C
haproxy 流量管理/指标对外暴露的端口,默认为:9101
haproxy_client_timeout参数名称: haproxy_client_timeout, 类型: interval, 层次:C
客户端连接超时,默认为 24h。
设置一个超时可以避免难以清理的超长的连接,但如果您真的需要一个长连接,您可以将其设置为更长的时间。
haproxy_server_timeout参数名称: haproxy_server_timeout, 类型: interval, 层次:C
服务端连接超时,默认为 24h。
设置一个超时可以避免难以清理的超长的连接,但如果您真的需要一个长连接,您可以将其设置为更长的时间。
haproxy_services参数名称: haproxy_services, 类型: service[], 层次:C
需要在此节点上通过 Haproxy 对外暴露的服务列表,默认值为: [] 空数组。
每一个数组元素都是一个服务定义,下面是一个服务定义的例子:
haproxy_services : # list of haproxy service
# expose pg-test read only replicas
- name : pg-test-ro # [REQUIRED] service name, unique
port : 5440 # [REQUIRED] service port, unique
ip : "*" # [OPTIONAL] service listen addr, "*" by default
protocol : tcp # [OPTIONAL] service protocol, 'tcp' by default
balance : leastconn # [OPTIONAL] load balance algorithm, roundrobin by default (or leastconn)
maxconn : 20000 # [OPTIONAL] max allowed front-end connection, 20000 by default
default : 'inter 3s fastinter 1s downinter 5s rise 3 fall 3 on-marked-down shutdown-sessions slowstart 30s maxconn 3000 maxqueue 128 weight 100'
options :
- option httpchk
- option http-keep-alive
- http-check send meth OPTIONS uri /read-only
- http-check expect status 200
servers :
- { name: pg-test-1 ,ip: 10.10.10.11 , port: 5432 , options: check port 8008 , backup : true }
- { name: pg-test-2 ,ip: 10.10.10.12 , port: 5432 , options : check port 8008 }
- { name: pg-test-3 ,ip: 10.10.10.13 , port: 5432 , options : check port 8008 }
每个服务定义会被渲染为 /etc/haproxy/<service.name>.cfg 配置文件,并在 Haproxy 重载后生效。
NODE_EXPORTERnode_exporter_enabled : true # setup node_exporter on this node?
node_exporter_port : 9100 # node exporter listen port, 9100 by default
node_exporter_options : '--no-collector.softnet --no-collector.nvme --collector.tcpstat --collector.processes'
node_exporter_enabled参数名称: node_exporter_enabled, 类型: bool, 层次:C
在当前节点上启用节点指标收集器?默认启用:true
node_exporter_port参数名称: node_exporter_port, 类型: port, 层次:C
对外暴露节点指标使用的端口,默认为 9100。
node_exporter_options参数名称: node_exporter_options, 类型: arg, 层次:C
节点指标采集器的命令行参数,默认值为:
--no-collector.softnet --no-collector.nvme --collector.tcpstat --collector.processes
该选项会启用/禁用一些指标收集器,请根据您的需要进行调整。
VECTORVector 是 Pigsty v4.0 使用的日志收集组件,会收集各个模块产生的日志并发送至基础设施节点上的 VictoriaLogs 服务。
INFRA: 基础设施组件的日志只会在 Infra 节点上收集。
nginx-access: /var/log/nginx/access.lognginx-error: /var/log/nginx/error.loggrafana: /var/log/grafana/grafana.logNODES:主机相关的日志,所有节点上都会启用收集。
syslog: /var/log/messages (Debian上为 /var/log/syslog)dmesg: /var/log/dmesgcron: /var/log/cronPGSQL:PostgreSQL 相关的日志,只有节点配置了 PGSQL 模块才会启用收集。
postgres: /pg/log/postgres/*patroni: /pg/log/patroni.logpgbouncer: /pg/log/pgbouncer/pgbouncer.logpgbackrest: /pg/log/pgbackrest/*.logREDIS:Redis 相关日志,只有节点配置了 REDIS 模块才会启用收集。
redis: /var/log/redis/*.log日志目录会根据这些参数的配置自动调整:pg_log_dir , patroni_log_dir , pgbouncer_log_dir , pgbackrest_log_dir
vector_enabled : true # 启用 vector 日志收集器吗?
vector_clean : false # 初始化时清除 vector 数据目录吗?
vector_data : /data/vector # vector 数据目录,默认为 /data/vector
vector_port : 9598 # vector 指标端口,默认为 9598
vector_read_from : beginning # vector 从头还是从尾开始读取日志
vector_log_endpoint : [ infra ] # 日志发送目标端点,默认发送至 infra 组
vector_enabled参数名称: vector_enabled, 类型: bool, 层次:C
是否启用 Vector 日志收集服务?默认值为: true
Vector 是 Pigsty v4.0 使用的日志收集代理,替代了之前版本使用的 Promtail,用于收集节点和服务的日志并发送至 VictoriaLogs。
vector_clean参数名称: vector_clean, 类型: bool, 层次:G/A
是否在安装 Vector 时清除已有数据目录?默认值为: false。
默认不会清理,当您选择清理时,Pigsty 会在部署 Vector 时移除现有数据目录 vector_data ,这意味着 Vector 会重新收集当前节点上的所有日志并发送至 VictoriaLogs。
vector_data参数名称: vector_data, 类型: path, 层次:C
Vector 数据目录路径,默认值为:/data/vector。
Vector 会将日志读取的偏移量和缓冲数据存储在此目录中。
vector_port参数名称: vector_port, 类型: port, 层次:C
Vector 指标监听端口号,默认为:9598
此端口用于暴露 Vector 自身的监控指标,可被 VictoriaMetrics 抓取。
vector_read_from参数名称: vector_read_from, 类型: enum, 层次:C
Vector 日志读取起始位置,默认值为:beginning。
可选值为 beginning(从头开始)或 end(从尾开始)。beginning 会读取现有日志文件的全部内容,end 只读取新产生的日志。
vector_log_endpoint参数名称: vector_log_endpoint, 类型: string[], 层次:C
日志发送目标端点列表,默认值为:[ infra ]。
指定将日志发送至哪个节点组的 VictoriaLogs 服务。默认发送至 infra 组的节点。
13.4 - 预置剧本 如何使用预置的 ansible 剧本来管理 Node 集群,常用管理命令速查。
Pigsty 提供两个与 NODE 模块相关的剧本:
另提供两个包装命令工具:bin/node-add 与 bin/node-rm,用于快速调用剧本。
node.yml向 Pigsty 添加节点的 node.yml 包含以下子任务:
node-id :生成节点身份标识
node_name :设置主机名
node_hosts :配置 /etc/hosts 记录
node_resolv :配置 DNS 解析器 /etc/resolv.conf
node_firewall :设置防火墙 & selinux
node_ca :添加并信任CA证书
node_repo :添加上游软件仓库
node_pkg :安装 rpm/deb 软件包
node_feature :配置 numa、grub、静态网络等特性
node_kernel :配置操作系统内核模块
node_tune :配置 tuned 调优模板
node_sysctl :设置额外的 sysctl 参数
node_profile :写入 /etc/profile.d/node.sh
node_ulimit :配置资源限制
node_data :配置数据目录
node_admin :配置管理员用户和ssh密钥
node_timezone :配置时区
node_ntp :配置 NTP 服务器/客户端
node_crontab :添加/覆盖 crontab 定时任务
node_vip :为节点集群设置可选的 L2 VIP
haproxy :在节点上设置 haproxy 以暴露服务
monitor :配置节点监控:node_exporter & vector
node-rm.yml从 Pigsty 中移除节点的剧本 node-rm.yml 包含以下子任务:
register : 从 prometheus & nginx 中移除节点注册信息
- prometheus : 移除已注册的 prometheus 监控目标
- nginx : 移除用于 haproxy 管理界面的 nginx 代理记录
vip : 移除节点的 keepalived 与 L2 VIP(如果启用 VIP)
haproxy : 移除 haproxy 负载均衡器
node_exporter : 移除节点监控:Node Exporter
vip_exporter : 移除 keepalived_exporter (如果启用 VIP)
vector : 移除日志收集代理 vector
profile : 移除 /etc/profile.d/node.sh 环境配置文件
常用命令速查 # 基础节点管理
./node.yml -l <cls| ip| group> # 向 Pigsty 中添加节点
./node-rm.yml -l <cls| ip| group> # 从 Pigsty 中移除节点
# 节点管理快捷命令
bin/node-add node-test # 初始化节点集群 'node-test'
bin/node-add 10.10.10.10 # 初始化节点 '10.10.10.10'
bin/node-rm node-test # 移除节点集群 'node-test'
bin/node-rm 10.10.10.10 # 移除节点 '10.10.10.10'
# 节点主体初始化
./node.yml -t node # 完成节点主体初始化(haproxy,监控除外)
./node.yml -t haproxy # 在节点上设置 haproxy
./node.yml -t monitor # 配置节点监控:node_exporter & vector
# VIP 管理
./node.yml -t node_vip # 为节点集群设置可选的 L2 VIP
./node.yml -t vip_config,vip_reload # 刷新节点 L2 VIP 配置
# HAProxy 管理
./node.yml -t haproxy_config,haproxy_reload # 刷新节点上的服务定义
# 注册管理
./node.yml -t register_prometheus # 重新将节点注册到 Prometheus 中
./node.yml -t register_nginx # 重新将节点 haproxy 管控界面注册到 Nginx 中
# 具体任务
./node.yml -t node-id # 生成节点身份标识
./node.yml -t node_name # 设置主机名
./node.yml -t node_hosts # 配置节点 /etc/hosts 记录
./node.yml -t node_resolv # 配置节点 DNS 解析器 /etc/resolv.conf
./node.yml -t node_firewall # 配置防火墙 & selinux
./node.yml -t node_ca # 配置节点的CA证书
./node.yml -t node_repo # 配置节点上游软件仓库
./node.yml -t node_pkg # 在节点上安装 yum 软件包
./node.yml -t node_feature # 配置 numa、grub、静态网络等特性
./node.yml -t node_kernel # 配置操作系统内核模块
./node.yml -t node_tune # 配置 tuned 调优模板
./node.yml -t node_sysctl # 设置额外的 sysctl 参数
./node.yml -t node_profile # 配置节点环境变量:/etc/profile.d/node.sh
./node.yml -t node_ulimit # 配置节点资源限制
./node.yml -t node_data # 配置节点首要数据目录
./node.yml -t node_admin # 配置管理员用户和ssh密钥
./node.yml -t node_timezone # 配置节点时区
./node.yml -t node_ntp # 配置节点 NTP 服务器/客户端
./node.yml -t node_crontab # 添加/覆盖 crontab 定时任务
13.5 - 管理预案 Node 集群管理 SOP:创建,销毁,扩容,缩容,节点故障与磁盘故障的处理。
下面是 Node 模块中常用的管理操作:
更多问题请参考 FAQ:NODE
添加节点 要将节点添加到 Pigsty,您需要对该节点具有无密码的 ssh/sudo 访问权限。
您也可以选择一次性添加一个集群,或使用通配符匹配配置清单中要加入 Pigsty 的节点。
# ./node.yml -l <cls|ip|group> # 向 Pigsty 中添加节点的实际剧本
# bin/node-add <selector|ip...> # 向 Pigsty 中添加节点
bin/node-add node-test # 初始化节点集群 'node-test'
bin/node-add 10.10.10.10 # 初始化节点 '10.10.10.10'
移除节点 要从 Pigsty 中移除一个节点,您可以使用以下命令:
# ./node-rm.yml -l <cls|ip|group> # 从 pigsty 中移除节点的实际剧本
# bin/node-rm <cls|ip|selector> ... # 从 pigsty 中移除节点
bin/node-rm node-test # 移除节点集群 'node-test'
bin/node-rm 10.10.10.10 # 移除节点 '10.10.10.10'
您也可以选择一次性移除一个集群,或使用通配符匹配配置清单中要从 Pigsty 移除的节点。
创建管理员 如果当前用户没有对节点的无密码 ssh/sudo 访问权限,您可以使用另一个管理员用户来初始化该节点:
node.yml -t node_admin -k -K -e ansible_user = <另一个管理员> # 为另一个管理员输入 ssh/sudo 密码以完成此任务
绑定VIP 您可以在节点集群上绑定一个可选的 L2 VIP,使用 vip_enabled 参数。
proxy :
hosts :
10.10.10.29 : { nodename : proxy-1 } # 您可以显式指定初始的 VIP 角色:MASTER / BACKUP
10.10.10.30 : { nodename: proxy-2 } # , vip_role : master }
vars :
node_cluster : proxy
vip_enabled : true
vip_vrid : 128
vip_address : 10.10.10.99
vip_interface : eth1
./node.yml -l proxy -t node_vip # 首次启用 VIP
./node.yml -l proxy -t vip_refresh # 刷新 vip 配置(例如指定 master)
添加节点监控 如果您想要在现有节点上添加或重新配置监控,可以使用以下命令:
./node.yml -t node_exporter,node_register # 配置监控并注册
./node.yml -t vector # 配置日志收集
其他常见任务 # Play
./node.yml -t node # 完成节点主体初始化(haproxy,监控除外)
./node.yml -t haproxy # 在节点上设置 haproxy
./node.yml -t monitor # 配置节点监控:node_exporter & vector
./node.yml -t node_vip # 为没启用过 VIP 的集群安装、配置、启用 L2 VIP
./node.yml -t vip_config,vip_reload # 刷新节点 L2 VIP 配置
./node.yml -t haproxy_config,haproxy_reload # 刷新节点上的服务定义
./node.yml -t register_prometheus # 重新将节点注册到 Prometheus 中
./node.yml -t register_nginx # 重新将节点 haproxy 管控界面注册到 Nginx 中
# Task
./node.yml -t node-id # 生成节点身份标识
./node.yml -t node_name # 设置主机名
./node.yml -t node_hosts # 配置节点 /etc/hosts 记录
./node.yml -t node_resolv # 配置节点 DNS 解析器 /etc/resolv.conf
./node.yml -t node_firewall # 配置防火墙 & selinux
./node.yml -t node_ca # 配置节点的CA证书
./node.yml -t node_repo # 配置节点上游软件仓库
./node.yml -t node_pkg # 在节点上安装 yum 软件包
./node.yml -t node_feature # 配置 numa、grub、静态网络等特性
./node.yml -t node_kernel # 配置操作系统内核模块
./node.yml -t node_tune # 配置 tuned 调优模板
./node.yml -t node_sysctl # 设置额外的 sysctl 参数
./node.yml -t node_profile # 配置节点环境变量:/etc/profile.d/node.sh
./node.yml -t node_ulimit # 配置节点资源限制
./node.yml -t node_data # 配置节点首要数据目录
./node.yml -t node_admin # 配置管理员用户和ssh密钥
./node.yml -t node_timezone # 配置节点时区
./node.yml -t node_ntp # 配置节点 NTP 服务器/客户端
./node.yml -t node_crontab # 添加/覆盖 crontab 定时任务
./node.yml -t node_vip # 为节点集群设置可选的 L2 VIP
13.6 - 监控告警 如何在 Pigsty 中监控 Node?如何使用 Node 本身的管控面板?有哪些告警规则值得关注?
Pigsty 中的 NODE 模块提供了 6 个监控面板和完善的告警规则。
监控面板 NODE 模块提供 6 个监控仪表板:
NODE Overview 展示当前环境所有主机节点的总体情况概览。
NODE Cluster 显示特定主机集群的详细监控数据。
Node Instance 呈现单个主机节点的详细监控信息。
NODE Alert 集中展示环境中所有主机的告警信息。
NODE VIP 监控 L2 虚拟 IP 的详细状态。
Node Haproxy 追踪 HAProxy 负载均衡器的运行情况。
告警规则 Pigsty 针对 NODE 实现了以下告警规则:
可用性告警 规则 级别 说明 NodeDownCRIT 节点离线 HaproxyDownCRIT HAProxy 服务离线 PromtailDownWARN 日志收集代理离线(Vector) DockerDownWARN 容器引擎离线 KeepalivedDownWARN Keepalived 守护进程离线
CPU 告警 规则 级别 说明 NodeCpuHighWARN CPU 使用率超过 70%
调度告警 规则 级别 说明 NodeLoadHighWARN 标准化负载超过 100%
内存告警 规则 级别 说明 NodeOutOfMemWARN 可用内存少于 10% NodeMemSwappedWARN Swap 使用率超过 1%
文件系统告警 规则 级别 说明 NodeFsSpaceFullWARN 磁盘使用率超过 90% NodeFsFilesFullWARN Inode 使用率超过 90% NodeFdFullWARN 文件描述符使用率超过 90%
磁盘告警 规则 级别 说明 NodeDiskSlowWARN 读写延迟超过 32ms
网络协议告警 规则 级别 说明 NodeTcpErrHighWARN TCP 错误率超过 1/分钟 NodeTcpRetransHighWARN TCP 重传率超过 1%
时间同步告警 规则 级别 说明 NodeTimeDriftWARN 系统时间未同步
13.7 - 指标列表 Pigsty NODE 模块提供的完整监控指标列表与释义
NODE 模块包含有 747 类可用监控指标。
Metric Name Type Labels Description ALERTS Unknown alertname, ip, level, severity, ins, job, alertstate, category, instance, clsN/A ALERTS_FOR_STATE Unknown alertname, ip, level, severity, ins, job, category, instance, clsN/A deprecated_flags_inuse_total Unknown instance, ins, job, ip, clsN/A go_gc_duration_seconds summary quantile, instance, ins, job, ip, clsA summary of the pause duration of garbage collection cycles. go_gc_duration_seconds_count Unknown instance, ins, job, ip, clsN/A go_gc_duration_seconds_sum Unknown instance, ins, job, ip, clsN/A go_goroutines gauge instance, ins, job, ip, clsNumber of goroutines that currently exist. go_info gauge version, instance, ins, job, ip, clsInformation about the Go environment. go_memstats_alloc_bytes gauge instance, ins, job, ip, clsNumber of bytes allocated and still in use. go_memstats_alloc_bytes_total counter instance, ins, job, ip, clsTotal number of bytes allocated, even if freed. go_memstats_buck_hash_sys_bytes gauge instance, ins, job, ip, clsNumber of bytes used by the profiling bucket hash table. go_memstats_frees_total counter instance, ins, job, ip, clsTotal number of frees. go_memstats_gc_sys_bytes gauge instance, ins, job, ip, clsNumber of bytes used for garbage collection system metadata. go_memstats_heap_alloc_bytes gauge instance, ins, job, ip, clsNumber of heap bytes allocated and still in use. go_memstats_heap_idle_bytes gauge instance, ins, job, ip, clsNumber of heap bytes waiting to be used. go_memstats_heap_inuse_bytes gauge instance, ins, job, ip, clsNumber of heap bytes that are in use. go_memstats_heap_objects gauge instance, ins, job, ip, clsNumber of allocated objects. go_memstats_heap_released_bytes gauge instance, ins, job, ip, clsNumber of heap bytes released to OS. go_memstats_heap_sys_bytes gauge instance, ins, job, ip, clsNumber of heap bytes obtained from system. go_memstats_last_gc_time_seconds gauge instance, ins, job, ip, clsNumber of seconds since 1970 of last garbage collection. go_memstats_lookups_total counter instance, ins, job, ip, clsTotal number of pointer lookups. go_memstats_mallocs_total counter instance, ins, job, ip, clsTotal number of mallocs. go_memstats_mcache_inuse_bytes gauge instance, ins, job, ip, clsNumber of bytes in use by mcache structures. go_memstats_mcache_sys_bytes gauge instance, ins, job, ip, clsNumber of bytes used for mcache structures obtained from system. go_memstats_mspan_inuse_bytes gauge instance, ins, job, ip, clsNumber of bytes in use by mspan structures. go_memstats_mspan_sys_bytes gauge instance, ins, job, ip, clsNumber of bytes used for mspan structures obtained from system. go_memstats_next_gc_bytes gauge instance, ins, job, ip, clsNumber of heap bytes when next garbage collection will take place. go_memstats_other_sys_bytes gauge instance, ins, job, ip, clsNumber of bytes used for other system allocations. go_memstats_stack_inuse_bytes gauge instance, ins, job, ip, clsNumber of bytes in use by the stack allocator. go_memstats_stack_sys_bytes gauge instance, ins, job, ip, clsNumber of bytes obtained from system for stack allocator. go_memstats_sys_bytes gauge instance, ins, job, ip, clsNumber of bytes obtained from system. go_threads gauge instance, ins, job, ip, clsNumber of OS threads created. haproxy:cls:usage Unknown job, clsN/A haproxy:ins:uptime Unknown instance, ins, job, ip, clsN/A haproxy:ins:usage Unknown instance, ins, job, ip, clsN/A haproxy_backend_active_servers gauge proxy, instance, ins, job, ip, clsTotal number of active UP servers with a non-zero weight haproxy_backend_agg_check_status gauge state, proxy, instance, ins, job, ip, clsBackend’s aggregated gauge of servers’ state check status haproxy_backend_agg_server_check_status gauge state, proxy, instance, ins, job, ip, cls[DEPRECATED] Backend’s aggregated gauge of servers’ status haproxy_backend_agg_server_status gauge state, proxy, instance, ins, job, ip, clsBackend’s aggregated gauge of servers’ status haproxy_backend_backup_servers gauge proxy, instance, ins, job, ip, clsTotal number of backup UP servers with a non-zero weight haproxy_backend_bytes_in_total counter proxy, instance, ins, job, ip, clsTotal number of request bytes since process started haproxy_backend_bytes_out_total counter proxy, instance, ins, job, ip, clsTotal number of response bytes since process started haproxy_backend_check_last_change_seconds gauge proxy, instance, ins, job, ip, clsHow long ago the last server state changed, in seconds haproxy_backend_check_up_down_total counter proxy, instance, ins, job, ip, clsTotal number of failed checks causing UP to DOWN server transitions, per server/backend, since the worker process started haproxy_backend_client_aborts_total counter proxy, instance, ins, job, ip, clsTotal number of requests or connections aborted by the client since the worker process started haproxy_backend_connect_time_average_seconds gauge proxy, instance, ins, job, ip, clsAvg. connect time for last 1024 successful connections. haproxy_backend_connection_attempts_total counter proxy, instance, ins, job, ip, clsTotal number of outgoing connection attempts on this backend/server since the worker process started haproxy_backend_connection_errors_total counter proxy, instance, ins, job, ip, clsTotal number of failed connections to server since the worker process started haproxy_backend_connection_reuses_total counter proxy, instance, ins, job, ip, clsTotal number of reused connection on this backend/server since the worker process started haproxy_backend_current_queue gauge proxy, instance, ins, job, ip, clsNumber of current queued connections haproxy_backend_current_sessions gauge proxy, instance, ins, job, ip, clsNumber of current sessions on the frontend, backend or server haproxy_backend_downtime_seconds_total counter proxy, instance, ins, job, ip, clsTotal time spent in DOWN state, for server or backend haproxy_backend_failed_header_rewriting_total counter proxy, instance, ins, job, ip, clsTotal number of failed HTTP header rewrites since the worker process started haproxy_backend_http_cache_hits_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP requests not found in the cache on this frontend/backend since the worker process started haproxy_backend_http_cache_lookups_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP requests looked up in the cache on this frontend/backend since the worker process started haproxy_backend_http_comp_bytes_bypassed_total counter proxy, instance, ins, job, ip, clsTotal number of bytes that bypassed HTTP compression for this object since the worker process started (CPU/memory/bandwidth limitation) haproxy_backend_http_comp_bytes_in_total counter proxy, instance, ins, job, ip, clsTotal number of bytes submitted to the HTTP compressor for this object since the worker process started haproxy_backend_http_comp_bytes_out_total counter proxy, instance, ins, job, ip, clsTotal number of bytes emitted by the HTTP compressor for this object since the worker process started haproxy_backend_http_comp_responses_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP responses that were compressed for this object since the worker process started haproxy_backend_http_requests_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP requests processed by this object since the worker process started haproxy_backend_http_responses_total counter ip, proxy, ins, code, job, instance, clsTotal number of HTTP responses with status 100-199 returned by this object since the worker process started haproxy_backend_internal_errors_total counter proxy, instance, ins, job, ip, clsTotal number of internal errors since process started haproxy_backend_last_session_seconds gauge proxy, instance, ins, job, ip, clsHow long ago some traffic was seen on this object on this worker process, in seconds haproxy_backend_limit_sessions gauge proxy, instance, ins, job, ip, clsFrontend/listener/server’s maxconn, backend’s fullconn haproxy_backend_loadbalanced_total counter proxy, instance, ins, job, ip, clsTotal number of requests routed by load balancing since the worker process started (ignores queue pop and stickiness) haproxy_backend_max_connect_time_seconds gauge proxy, instance, ins, job, ip, clsMaximum observed time spent waiting for a connection to complete haproxy_backend_max_queue gauge proxy, instance, ins, job, ip, clsHighest value of queued connections encountered since process started haproxy_backend_max_queue_time_seconds gauge proxy, instance, ins, job, ip, clsMaximum observed time spent in the queue haproxy_backend_max_response_time_seconds gauge proxy, instance, ins, job, ip, clsMaximum observed time spent waiting for a server response haproxy_backend_max_session_rate gauge proxy, instance, ins, job, ip, clsHighest value of sessions per second observed since the worker process started haproxy_backend_max_sessions gauge proxy, instance, ins, job, ip, clsHighest value of current sessions encountered since process started haproxy_backend_max_total_time_seconds gauge proxy, instance, ins, job, ip, clsMaximum observed total request+response time (request+queue+connect+response+processing) haproxy_backend_queue_time_average_seconds gauge proxy, instance, ins, job, ip, clsAvg. queue time for last 1024 successful connections. haproxy_backend_redispatch_warnings_total counter proxy, instance, ins, job, ip, clsTotal number of server redispatches due to connection failures since the worker process started haproxy_backend_requests_denied_total counter proxy, instance, ins, job, ip, clsTotal number of denied requests since process started haproxy_backend_response_errors_total counter proxy, instance, ins, job, ip, clsTotal number of invalid responses since the worker process started haproxy_backend_response_time_average_seconds gauge proxy, instance, ins, job, ip, clsAvg. response time for last 1024 successful connections. haproxy_backend_responses_denied_total counter proxy, instance, ins, job, ip, clsTotal number of denied responses since process started haproxy_backend_retry_warnings_total counter proxy, instance, ins, job, ip, clsTotal number of server connection retries since the worker process started haproxy_backend_server_aborts_total counter proxy, instance, ins, job, ip, clsTotal number of requests or connections aborted by the server since the worker process started haproxy_backend_sessions_total counter proxy, instance, ins, job, ip, clsTotal number of sessions since process started haproxy_backend_status gauge state, proxy, instance, ins, job, ip, clsCurrent status of the service, per state label value. haproxy_backend_total_time_average_seconds gauge proxy, instance, ins, job, ip, clsAvg. total time for last 1024 successful connections. haproxy_backend_uweight gauge proxy, instance, ins, job, ip, clsServer’s user weight, or sum of active servers’ user weights for a backend haproxy_backend_weight gauge proxy, instance, ins, job, ip, clsServer’s effective weight, or sum of active servers’ effective weights for a backend haproxy_frontend_bytes_in_total counter proxy, instance, ins, job, ip, clsTotal number of request bytes since process started haproxy_frontend_bytes_out_total counter proxy, instance, ins, job, ip, clsTotal number of response bytes since process started haproxy_frontend_connections_rate_max gauge proxy, instance, ins, job, ip, clsHighest value of connections per second observed since the worker process started haproxy_frontend_connections_total counter proxy, instance, ins, job, ip, clsTotal number of new connections accepted on this frontend since the worker process started haproxy_frontend_current_sessions gauge proxy, instance, ins, job, ip, clsNumber of current sessions on the frontend, backend or server haproxy_frontend_denied_connections_total counter proxy, instance, ins, job, ip, clsTotal number of incoming connections blocked on a listener/frontend by a tcp-request connection rule since the worker process started haproxy_frontend_denied_sessions_total counter proxy, instance, ins, job, ip, clsTotal number of incoming sessions blocked on a listener/frontend by a tcp-request connection rule since the worker process started haproxy_frontend_failed_header_rewriting_total counter proxy, instance, ins, job, ip, clsTotal number of failed HTTP header rewrites since the worker process started haproxy_frontend_http_cache_hits_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP requests not found in the cache on this frontend/backend since the worker process started haproxy_frontend_http_cache_lookups_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP requests looked up in the cache on this frontend/backend since the worker process started haproxy_frontend_http_comp_bytes_bypassed_total counter proxy, instance, ins, job, ip, clsTotal number of bytes that bypassed HTTP compression for this object since the worker process started (CPU/memory/bandwidth limitation) haproxy_frontend_http_comp_bytes_in_total counter proxy, instance, ins, job, ip, clsTotal number of bytes submitted to the HTTP compressor for this object since the worker process started haproxy_frontend_http_comp_bytes_out_total counter proxy, instance, ins, job, ip, clsTotal number of bytes emitted by the HTTP compressor for this object since the worker process started haproxy_frontend_http_comp_responses_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP responses that were compressed for this object since the worker process started haproxy_frontend_http_requests_rate_max gauge proxy, instance, ins, job, ip, clsHighest value of http requests observed since the worker process started haproxy_frontend_http_requests_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP requests processed by this object since the worker process started haproxy_frontend_http_responses_total counter ip, proxy, ins, code, job, instance, clsTotal number of HTTP responses with status 100-199 returned by this object since the worker process started haproxy_frontend_intercepted_requests_total counter proxy, instance, ins, job, ip, clsTotal number of HTTP requests intercepted on the frontend (redirects/stats/services) since the worker process started haproxy_frontend_internal_errors_total counter proxy, instance, ins, job, ip, clsTotal number of internal errors since process started haproxy_frontend_limit_session_rate gauge proxy, instance, ins, job, ip, clsLimit on the number of sessions accepted in a second (frontend only, ‘rate-limit sessions’ setting) haproxy_frontend_limit_sessions gauge proxy, instance, ins, job, ip, clsFrontend/listener/server’s maxconn, backend’s fullconn haproxy_frontend_max_session_rate gauge proxy, instance, ins, job, ip, clsHighest value of sessions per second observed since the worker process started haproxy_frontend_max_sessions gauge proxy, instance, ins, job, ip, clsHighest value of current sessions encountered since process started haproxy_frontend_request_errors_total counter proxy, instance, ins, job, ip, clsTotal number of invalid requests since process started haproxy_frontend_requests_denied_total counter proxy, instance, ins, job, ip, clsTotal number of denied requests since process started haproxy_frontend_responses_denied_total counter proxy, instance, ins, job, ip, clsTotal number of denied responses since process started haproxy_frontend_sessions_total counter proxy, instance, ins, job, ip, clsTotal number of sessions since process started haproxy_frontend_status gauge state, proxy, instance, ins, job, ip, clsCurrent status of the service, per state label value. haproxy_process_active_peers gauge instance, ins, job, ip, clsCurrent number of verified active peers connections on the current worker process haproxy_process_build_info gauge version, instance, ins, job, ip, clsBuild info haproxy_process_busy_polling_enabled gauge instance, ins, job, ip, cls1 if busy-polling is currently in use on the worker process, otherwise zero (config.busy-polling) haproxy_process_bytes_out_rate gauge instance, ins, job, ip, clsNumber of bytes emitted by current worker process over the last second haproxy_process_bytes_out_total counter instance, ins, job, ip, clsTotal number of bytes emitted by current worker process since started haproxy_process_connected_peers gauge instance, ins, job, ip, clsCurrent number of peers having passed the connection step on the current worker process haproxy_process_connections_total counter instance, ins, job, ip, clsTotal number of connections on this worker process since started haproxy_process_current_backend_ssl_key_rate gauge instance, ins, job, ip, clsNumber of SSL keys created on backends in this worker process over the last second haproxy_process_current_connection_rate gauge instance, ins, job, ip, clsNumber of front connections created on this worker process over the last second haproxy_process_current_connections gauge instance, ins, job, ip, clsCurrent number of connections on this worker process haproxy_process_current_frontend_ssl_key_rate gauge instance, ins, job, ip, clsNumber of SSL keys created on frontends in this worker process over the last second haproxy_process_current_run_queue gauge instance, ins, job, ip, clsTotal number of active tasks+tasklets in the current worker process haproxy_process_current_session_rate gauge instance, ins, job, ip, clsNumber of sessions created on this worker process over the last second haproxy_process_current_ssl_connections gauge instance, ins, job, ip, clsCurrent number of SSL endpoints on this worker process (front+back) haproxy_process_current_ssl_rate gauge instance, ins, job, ip, clsNumber of SSL connections created on this worker process over the last second haproxy_process_current_tasks gauge instance, ins, job, ip, clsTotal number of tasks in the current worker process (active + sleeping) haproxy_process_current_zlib_memory gauge instance, ins, job, ip, clsAmount of memory currently used by HTTP compression on the current worker process (in bytes) haproxy_process_dropped_logs_total counter instance, ins, job, ip, clsTotal number of dropped logs for current worker process since started haproxy_process_failed_resolutions counter instance, ins, job, ip, clsTotal number of failed DNS resolutions in current worker process since started haproxy_process_frontend_ssl_reuse gauge instance, ins, job, ip, clsPercent of frontend SSL connections which did not require a new key haproxy_process_hard_max_connections gauge instance, ins, job, ip, clsHard limit on the number of per-process connections (imposed by Memmax_MB or Ulimit-n) haproxy_process_http_comp_bytes_in_total counter instance, ins, job, ip, clsNumber of bytes submitted to the HTTP compressor in this worker process over the last second haproxy_process_http_comp_bytes_out_total counter instance, ins, job, ip, clsNumber of bytes emitted by the HTTP compressor in this worker process over the last second haproxy_process_idle_time_percent gauge instance, ins, job, ip, clsPercentage of last second spent waiting in the current worker thread haproxy_process_jobs gauge instance, ins, job, ip, clsCurrent number of active jobs on the current worker process (frontend connections, master connections, listeners) haproxy_process_limit_connection_rate gauge instance, ins, job, ip, clsHard limit for ConnRate (global.maxconnrate) haproxy_process_limit_http_comp gauge instance, ins, job, ip, clsLimit of CompressBpsOut beyond which HTTP compression is automatically disabled haproxy_process_limit_session_rate gauge instance, ins, job, ip, clsHard limit for SessRate (global.maxsessrate) haproxy_process_limit_ssl_rate gauge instance, ins, job, ip, clsHard limit for SslRate (global.maxsslrate) haproxy_process_listeners gauge instance, ins, job, ip, clsCurrent number of active listeners on the current worker process haproxy_process_max_backend_ssl_key_rate gauge instance, ins, job, ip, clsHighest SslBackendKeyRate reached on this worker process since started (in SSL keys per second) haproxy_process_max_connection_rate gauge instance, ins, job, ip, clsHighest ConnRate reached on this worker process since started (in connections per second) haproxy_process_max_connections gauge instance, ins, job, ip, clsHard limit on the number of per-process connections (configured or imposed by Ulimit-n) haproxy_process_max_fds gauge instance, ins, job, ip, clsHard limit on the number of per-process file descriptors haproxy_process_max_frontend_ssl_key_rate gauge instance, ins, job, ip, clsHighest SslFrontendKeyRate reached on this worker process since started (in SSL keys per second) haproxy_process_max_memory_bytes gauge instance, ins, job, ip, clsWorker process’s hard limit on memory usage in byes (-m on command line) haproxy_process_max_pipes gauge instance, ins, job, ip, clsHard limit on the number of pipes for splicing, 0=unlimited haproxy_process_max_session_rate gauge instance, ins, job, ip, clsHighest SessRate reached on this worker process since started (in sessions per second) haproxy_process_max_sockets gauge instance, ins, job, ip, clsHard limit on the number of per-process sockets haproxy_process_max_ssl_connections gauge instance, ins, job, ip, clsHard limit on the number of per-process SSL endpoints (front+back), 0=unlimited haproxy_process_max_ssl_rate gauge instance, ins, job, ip, clsHighest SslRate reached on this worker process since started (in connections per second) haproxy_process_max_zlib_memory gauge instance, ins, job, ip, clsLimit on the amount of memory used by HTTP compression above which it is automatically disabled (in bytes, see global.maxzlibmem) haproxy_process_nbproc gauge instance, ins, job, ip, clsNumber of started worker processes (historical, always 1) haproxy_process_nbthread gauge instance, ins, job, ip, clsNumber of started threads (global.nbthread) haproxy_process_pipes_free_total counter instance, ins, job, ip, clsCurrent number of allocated and available pipes in this worker process haproxy_process_pipes_used_total counter instance, ins, job, ip, clsCurrent number of pipes in use in this worker process haproxy_process_pool_allocated_bytes gauge instance, ins, job, ip, clsAmount of memory allocated in pools (in bytes) haproxy_process_pool_failures_total counter instance, ins, job, ip, clsNumber of failed pool allocations since this worker was started haproxy_process_pool_used_bytes gauge instance, ins, job, ip, clsAmount of pool memory currently used (in bytes) haproxy_process_recv_logs_total counter instance, ins, job, ip, clsTotal number of log messages received by log-forwarding listeners on this worker process since started haproxy_process_relative_process_id gauge instance, ins, job, ip, clsRelative worker process number (1) haproxy_process_requests_total counter instance, ins, job, ip, clsTotal number of requests on this worker process since started haproxy_process_spliced_bytes_out_total counter instance, ins, job, ip, clsTotal number of bytes emitted by current worker process through a kernel pipe since started haproxy_process_ssl_cache_lookups_total counter instance, ins, job, ip, clsTotal number of SSL session ID lookups in the SSL session cache on this worker since started haproxy_process_ssl_cache_misses_total counter instance, ins, job, ip, clsTotal number of SSL session ID lookups that didn’t find a session in the SSL session cache on this worker since started haproxy_process_ssl_connections_total counter instance, ins, job, ip, clsTotal number of SSL endpoints on this worker process since started (front+back) haproxy_process_start_time_seconds gauge instance, ins, job, ip, clsStart time in seconds haproxy_process_stopping gauge instance, ins, job, ip, cls1 if the worker process is currently stopping, otherwise zero haproxy_process_unstoppable_jobs gauge instance, ins, job, ip, clsCurrent number of unstoppable jobs on the current worker process (master connections) haproxy_process_uptime_seconds gauge instance, ins, job, ip, clsHow long ago this worker process was started (seconds) haproxy_server_bytes_in_total counter proxy, instance, ins, job, server, ip, clsTotal number of request bytes since process started haproxy_server_bytes_out_total counter proxy, instance, ins, job, server, ip, clsTotal number of response bytes since process started haproxy_server_check_code gauge proxy, instance, ins, job, server, ip, clslayer5-7 code, if available of the last health check. haproxy_server_check_duration_seconds gauge proxy, instance, ins, job, server, ip, clsTotal duration of the latest server health check, in seconds. haproxy_server_check_failures_total counter proxy, instance, ins, job, server, ip, clsTotal number of failed individual health checks per server/backend, since the worker process started haproxy_server_check_last_change_seconds gauge proxy, instance, ins, job, server, ip, clsHow long ago the last server state changed, in seconds haproxy_server_check_status gauge state, proxy, instance, ins, job, server, ip, clsStatus of last health check, per state label value. haproxy_server_check_up_down_total counter proxy, instance, ins, job, server, ip, clsTotal number of failed checks causing UP to DOWN server transitions, per server/backend, since the worker process started haproxy_server_client_aborts_total counter proxy, instance, ins, job, server, ip, clsTotal number of requests or connections aborted by the client since the worker process started haproxy_server_connect_time_average_seconds gauge proxy, instance, ins, job, server, ip, clsAvg. connect time for last 1024 successful connections. haproxy_server_connection_attempts_total counter proxy, instance, ins, job, server, ip, clsTotal number of outgoing connection attempts on this backend/server since the worker process started haproxy_server_connection_errors_total counter proxy, instance, ins, job, server, ip, clsTotal number of failed connections to server since the worker process started haproxy_server_connection_reuses_total counter proxy, instance, ins, job, server, ip, clsTotal number of reused connection on this backend/server since the worker process started haproxy_server_current_queue gauge proxy, instance, ins, job, server, ip, clsNumber of current queued connections haproxy_server_current_sessions gauge proxy, instance, ins, job, server, ip, clsNumber of current sessions on the frontend, backend or server haproxy_server_current_throttle gauge proxy, instance, ins, job, server, ip, clsThrottling ratio applied to a server’s maxconn and weight during the slowstart period (0 to 100%) haproxy_server_downtime_seconds_total counter proxy, instance, ins, job, server, ip, clsTotal time spent in DOWN state, for server or backend haproxy_server_failed_header_rewriting_total counter proxy, instance, ins, job, server, ip, clsTotal number of failed HTTP header rewrites since the worker process started haproxy_server_idle_connections_current gauge proxy, instance, ins, job, server, ip, clsCurrent number of idle connections available for reuse on this server haproxy_server_idle_connections_limit gauge proxy, instance, ins, job, server, ip, clsLimit on the number of available idle connections on this server (server ‘pool_max_conn’ directive) haproxy_server_internal_errors_total counter proxy, instance, ins, job, server, ip, clsTotal number of internal errors since process started haproxy_server_last_session_seconds gauge proxy, instance, ins, job, server, ip, clsHow long ago some traffic was seen on this object on this worker process, in seconds haproxy_server_limit_sessions gauge proxy, instance, ins, job, server, ip, clsFrontend/listener/server’s maxconn, backend’s fullconn haproxy_server_loadbalanced_total counter proxy, instance, ins, job, server, ip, clsTotal number of requests routed by load balancing since the worker process started (ignores queue pop and stickiness) haproxy_server_max_connect_time_seconds gauge proxy, instance, ins, job, server, ip, clsMaximum observed time spent waiting for a connection to complete haproxy_server_max_queue gauge proxy, instance, ins, job, server, ip, clsHighest value of queued connections encountered since process started haproxy_server_max_queue_time_seconds gauge proxy, instance, ins, job, server, ip, clsMaximum observed time spent in the queue haproxy_server_max_response_time_seconds gauge proxy, instance, ins, job, server, ip, clsMaximum observed time spent waiting for a server response haproxy_server_max_session_rate gauge proxy, instance, ins, job, server, ip, clsHighest value of sessions per second observed since the worker process started haproxy_server_max_sessions gauge proxy, instance, ins, job, server, ip, clsHighest value of current sessions encountered since process started haproxy_server_max_total_time_seconds gauge proxy, instance, ins, job, server, ip, clsMaximum observed total request+response time (request+queue+connect+response+processing) haproxy_server_need_connections_current gauge proxy, instance, ins, job, server, ip, clsEstimated needed number of connections haproxy_server_queue_limit gauge proxy, instance, ins, job, server, ip, clsLimit on the number of connections in queue, for servers only (maxqueue argument) haproxy_server_queue_time_average_seconds gauge proxy, instance, ins, job, server, ip, clsAvg. queue time for last 1024 successful connections. haproxy_server_redispatch_warnings_total counter proxy, instance, ins, job, server, ip, clsTotal number of server redispatches due to connection failures since the worker process started haproxy_server_response_errors_total counter proxy, instance, ins, job, server, ip, clsTotal number of invalid responses since the worker process started haproxy_server_response_time_average_seconds gauge proxy, instance, ins, job, server, ip, clsAvg. response time for last 1024 successful connections. haproxy_server_responses_denied_total counter proxy, instance, ins, job, server, ip, clsTotal number of denied responses since process started haproxy_server_retry_warnings_total counter proxy, instance, ins, job, server, ip, clsTotal number of server connection retries since the worker process started haproxy_server_safe_idle_connections_current gauge proxy, instance, ins, job, server, ip, clsCurrent number of safe idle connections haproxy_server_server_aborts_total counter proxy, instance, ins, job, server, ip, clsTotal number of requests or connections aborted by the server since the worker process started haproxy_server_sessions_total counter proxy, instance, ins, job, server, ip, clsTotal number of sessions since process started haproxy_server_status gauge state, proxy, instance, ins, job, server, ip, clsCurrent status of the service, per state label value. haproxy_server_total_time_average_seconds gauge proxy, instance, ins, job, server, ip, clsAvg. total time for last 1024 successful connections. haproxy_server_unsafe_idle_connections_current gauge proxy, instance, ins, job, server, ip, clsCurrent number of unsafe idle connections haproxy_server_used_connections_current gauge proxy, instance, ins, job, server, ip, clsCurrent number of connections in use haproxy_server_uweight gauge proxy, instance, ins, job, server, ip, clsServer’s user weight, or sum of active servers’ user weights for a backend haproxy_server_weight gauge proxy, instance, ins, job, server, ip, clsServer’s effective weight, or sum of active servers’ effective weights for a backend haproxy_up Unknown instance, ins, job, ip, clsN/A inflight_requests gauge instance, ins, job, route, ip, cls, methodCurrent number of inflight requests. jaeger_tracer_baggage_restrictions_updates_total Unknown instance, ins, job, result, ip, clsN/A jaeger_tracer_baggage_truncations_total Unknown instance, ins, job, ip, clsN/A jaeger_tracer_baggage_updates_total Unknown instance, ins, job, result, ip, clsN/A jaeger_tracer_finished_spans_total Unknown instance, ins, job, sampled, ip, clsN/A jaeger_tracer_reporter_queue_length gauge instance, ins, job, ip, clsCurrent number of spans in the reporter queue jaeger_tracer_reporter_spans_total Unknown instance, ins, job, result, ip, clsN/A jaeger_tracer_sampler_queries_total Unknown instance, ins, job, result, ip, clsN/A jaeger_tracer_sampler_updates_total Unknown instance, ins, job, result, ip, clsN/A jaeger_tracer_span_context_decoding_errors_total Unknown instance, ins, job, ip, clsN/A jaeger_tracer_started_spans_total Unknown instance, ins, job, sampled, ip, clsN/A jaeger_tracer_throttled_debug_spans_total Unknown instance, ins, job, ip, clsN/A jaeger_tracer_throttler_updates_total Unknown instance, ins, job, result, ip, clsN/A jaeger_tracer_traces_total Unknown state, instance, ins, job, sampled, ip, clsN/A loki_experimental_features_in_use_total Unknown instance, ins, job, ip, clsN/A loki_internal_log_messages_total Unknown level, instance, ins, job, ip, clsN/A loki_log_flushes_bucket Unknown instance, ins, job, le, ip, clsN/A loki_log_flushes_count Unknown instance, ins, job, ip, clsN/A loki_log_flushes_sum Unknown instance, ins, job, ip, clsN/A loki_log_messages_total Unknown level, instance, ins, job, ip, clsN/A loki_logql_querystats_duplicates_total Unknown instance, ins, job, ip, clsN/A loki_logql_querystats_ingester_sent_lines_total Unknown instance, ins, job, ip, clsN/A loki_querier_index_cache_corruptions_total Unknown instance, ins, job, ip, clsN/A loki_querier_index_cache_encode_errors_total Unknown instance, ins, job, ip, clsN/A loki_querier_index_cache_gets_total Unknown instance, ins, job, ip, clsN/A loki_querier_index_cache_hits_total Unknown instance, ins, job, ip, clsN/A loki_querier_index_cache_puts_total Unknown instance, ins, job, ip, clsN/A net_conntrack_dialer_conn_attempted_total counter ip, ins, job, instance, cls, dialer_nameTotal number of connections attempted by the given dialer a given name. net_conntrack_dialer_conn_closed_total counter ip, ins, job, instance, cls, dialer_nameTotal number of connections closed which originated from the dialer of a given name. net_conntrack_dialer_conn_established_total counter ip, ins, job, instance, cls, dialer_nameTotal number of connections successfully established by the given dialer a given name. net_conntrack_dialer_conn_failed_total counter ip, ins, job, reason, instance, cls, dialer_nameTotal number of connections failed to dial by the dialer a given name. node:cls:avail_bytes Unknown job, clsN/A node:cls:cpu_count Unknown job, clsN/A node:cls:cpu_usage Unknown job, clsN/A node:cls:cpu_usage_15m Unknown job, clsN/A node:cls:cpu_usage_1m Unknown job, clsN/A node:cls:cpu_usage_5m Unknown job, clsN/A node:cls:disk_io_bytes_rate1m Unknown job, clsN/A node:cls:disk_iops_1m Unknown job, clsN/A node:cls:disk_mreads_rate1m Unknown job, clsN/A node:cls:disk_mreads_ratio1m Unknown job, clsN/A node:cls:disk_mwrites_rate1m Unknown job, clsN/A node:cls:disk_mwrites_ratio1m Unknown job, clsN/A node:cls:disk_read_bytes_rate1m Unknown job, clsN/A node:cls:disk_reads_rate1m Unknown job, clsN/A node:cls:disk_write_bytes_rate1m Unknown job, clsN/A node:cls:disk_writes_rate1m Unknown job, clsN/A node:cls:free_bytes Unknown job, clsN/A node:cls:mem_usage Unknown job, clsN/A node:cls:network_io_bytes_rate1m Unknown job, clsN/A node:cls:network_rx_bytes_rate1m Unknown job, clsN/A node:cls:network_rx_pps1m Unknown job, clsN/A node:cls:network_tx_bytes_rate1m Unknown job, clsN/A node:cls:network_tx_pps1m Unknown job, clsN/A node:cls:size_bytes Unknown job, clsN/A node:cls:space_usage Unknown job, clsN/A node:cls:space_usage_max Unknown job, clsN/A node:cls:stdload1 Unknown job, clsN/A node:cls:stdload15 Unknown job, clsN/A node:cls:stdload5 Unknown job, clsN/A node:cls:time_drift_max Unknown job, clsN/A node:cpu:idle_time_irate1m Unknown ip, ins, job, cpu, instance, clsN/A node:cpu:sched_timeslices_rate1m Unknown ip, ins, job, cpu, instance, clsN/A node:cpu:sched_wait_rate1m Unknown ip, ins, job, cpu, instance, clsN/A node:cpu:time_irate1m Unknown ip, mode, ins, job, cpu, instance, clsN/A node:cpu:total_time_irate1m Unknown ip, ins, job, cpu, instance, clsN/A node:cpu:usage Unknown ip, ins, job, cpu, instance, clsN/A node:cpu:usage_avg15m Unknown ip, ins, job, cpu, instance, clsN/A node:cpu:usage_avg1m Unknown ip, ins, job, cpu, instance, clsN/A node:cpu:usage_avg5m Unknown ip, ins, job, cpu, instance, clsN/A node:dev:disk_avg_queue_size Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_io_batch_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_io_bytes_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_io_rt_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_io_time_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_iops_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_mreads_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_mreads_ratio1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_mwrites_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_mwrites_ratio1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_read_batch_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_read_bytes_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_read_rt_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_read_time_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_reads_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_util_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_write_batch_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_write_bytes_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_write_rt_1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_write_time_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:disk_writes_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:network_io_bytes_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:network_rx_bytes_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:network_rx_pps1m Unknown ip, device, ins, job, instance, clsN/A node:dev:network_tx_bytes_rate1m Unknown ip, device, ins, job, instance, clsN/A node:dev:network_tx_pps1m Unknown ip, device, ins, job, instance, clsN/A node:env:avail_bytes Unknown jobN/A node:env:cpu_count Unknown jobN/A node:env:cpu_usage Unknown jobN/A node:env:cpu_usage_15m Unknown jobN/A node:env:cpu_usage_1m Unknown jobN/A node:env:cpu_usage_5m Unknown jobN/A node:env:device_space_usage_max Unknown device, mountpoint, job, fstypeN/A node:env:free_bytes Unknown jobN/A node:env:mem_avail Unknown jobN/A node:env:mem_total Unknown jobN/A node:env:mem_usage Unknown jobN/A node:env:size_bytes Unknown jobN/A node:env:space_usage Unknown jobN/A node:env:stdload1 Unknown jobN/A node:env:stdload15 Unknown jobN/A node:env:stdload5 Unknown jobN/A node:fs:avail_bytes Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:free_bytes Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:inode_free Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:inode_total Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:inode_usage Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:inode_used Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:size_bytes Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:space_deriv1h Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:space_exhaust Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:space_predict_1d Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:fs:space_usage Unknown ip, device, mountpoint, ins, cls, job, instance, fstypeN/A node:ins Unknown id, ip, ins, job, nodename, instance, clsN/A node:ins:avail_bytes Unknown instance, ins, job, ip, clsN/A node:ins:cpu_count Unknown instance, ins, job, ip, clsN/A node:ins:cpu_usage Unknown instance, ins, job, ip, clsN/A node:ins:cpu_usage_15m Unknown instance, ins, job, ip, clsN/A node:ins:cpu_usage_1m Unknown instance, ins, job, ip, clsN/A node:ins:cpu_usage_5m Unknown instance, ins, job, ip, clsN/A node:ins:ctx_switch_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_io_bytes_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_iops_1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_mreads_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_mreads_ratio1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_mwrites_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_mwrites_ratio1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_read_bytes_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_reads_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_write_bytes_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:disk_writes_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:fd_alloc_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:fd_usage Unknown instance, ins, job, ip, clsN/A node:ins:forks_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:free_bytes Unknown instance, ins, job, ip, clsN/A node:ins:inode_usage Unknown instance, ins, job, ip, clsN/A node:ins:interrupt_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:mem_avail Unknown instance, ins, job, ip, clsN/A node:ins:mem_commit_ratio Unknown instance, ins, job, ip, clsN/A node:ins:mem_kernel Unknown instance, ins, job, ip, clsN/A node:ins:mem_rss Unknown instance, ins, job, ip, clsN/A node:ins:mem_usage Unknown instance, ins, job, ip, clsN/A node:ins:network_io_bytes_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:network_rx_bytes_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:network_rx_pps1m Unknown instance, ins, job, ip, clsN/A node:ins:network_tx_bytes_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:network_tx_pps1m Unknown instance, ins, job, ip, clsN/A node:ins:pagefault_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:pagein_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:pageout_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:pgmajfault_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:sched_wait_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:size_bytes Unknown instance, ins, job, ip, clsN/A node:ins:space_usage_max Unknown instance, ins, job, ip, clsN/A node:ins:stdload1 Unknown instance, ins, job, ip, clsN/A node:ins:stdload15 Unknown instance, ins, job, ip, clsN/A node:ins:stdload5 Unknown instance, ins, job, ip, clsN/A node:ins:swap_usage Unknown instance, ins, job, ip, clsN/A node:ins:swapin_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:swapout_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_active_opens_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_dropped_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_error Unknown instance, ins, job, ip, clsN/A node:ins:tcp_error_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_insegs_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_outsegs_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_overflow_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_passive_opens_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_retrans_ratio1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_retranssegs_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:tcp_segs_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:time_drift Unknown instance, ins, job, ip, clsN/A node:ins:udp_in_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:udp_out_rate1m Unknown instance, ins, job, ip, clsN/A node:ins:uptime Unknown instance, ins, job, ip, clsN/A node_arp_entries gauge ip, device, ins, job, instance, clsARP entries by device node_boot_time_seconds gauge instance, ins, job, ip, clsNode boot time, in unixtime. node_context_switches_total counter instance, ins, job, ip, clsTotal number of context switches. node_cooling_device_cur_state gauge instance, ins, job, type, ip, clsCurrent throttle state of the cooling device node_cooling_device_max_state gauge instance, ins, job, type, ip, clsMaximum throttle state of the cooling device node_cpu_guest_seconds_total counter ip, mode, ins, job, cpu, instance, clsSeconds the CPUs spent in guests (VMs) for each mode. node_cpu_seconds_total counter ip, mode, ins, job, cpu, instance, clsSeconds the CPUs spent in each mode. node_disk_discard_time_seconds_total counter ip, device, ins, job, instance, clsThis is the total number of seconds spent by all discards. node_disk_discarded_sectors_total counter ip, device, ins, job, instance, clsThe total number of sectors discarded successfully. node_disk_discards_completed_total counter ip, device, ins, job, instance, clsThe total number of discards completed successfully. node_disk_discards_merged_total counter ip, device, ins, job, instance, clsThe total number of discards merged. node_disk_filesystem_info gauge ip, usage, version, device, uuid, ins, type, job, instance, clsInfo about disk filesystem. node_disk_info gauge minor, ip, major, revision, device, model, serial, path, ins, job, instance, clsInfo of /sys/block/<block_device>. node_disk_io_now gauge ip, device, ins, job, instance, clsThe number of I/Os currently in progress. node_disk_io_time_seconds_total counter ip, device, ins, job, instance, clsTotal seconds spent doing I/Os. node_disk_io_time_weighted_seconds_total counter ip, device, ins, job, instance, clsThe weighted # of seconds spent doing I/Os. node_disk_read_bytes_total counter ip, device, ins, job, instance, clsThe total number of bytes read successfully. node_disk_read_time_seconds_total counter ip, device, ins, job, instance, clsThe total number of seconds spent by all reads. node_disk_reads_completed_total counter ip, device, ins, job, instance, clsThe total number of reads completed successfully. node_disk_reads_merged_total counter ip, device, ins, job, instance, clsThe total number of reads merged. node_disk_write_time_seconds_total counter ip, device, ins, job, instance, clsThis is the total number of seconds spent by all writes. node_disk_writes_completed_total counter ip, device, ins, job, instance, clsThe total number of writes completed successfully. node_disk_writes_merged_total counter ip, device, ins, job, instance, clsThe number of writes merged. node_disk_written_bytes_total counter ip, device, ins, job, instance, clsThe total number of bytes written successfully. node_dmi_info gauge bios_vendor, ip, product_family, product_version, product_uuid, system_vendor, bios_version, ins, bios_date, cls, job, product_name, instance, chassis_version, chassis_vendor, product_serialA metric with a constant ‘1’ value labeled by bios_date, bios_release, bios_vendor, bios_version, board_asset_tag, board_name, board_serial, board_vendor, board_version, chassis_asset_tag, chassis_serial, chassis_vendor, chassis_version, product_family, product_name, product_serial, product_sku, product_uuid, product_version, system_vendor if provided by DMI. node_entropy_available_bits gauge instance, ins, job, ip, clsBits of available entropy. node_entropy_pool_size_bits gauge instance, ins, job, ip, clsBits of entropy pool. node_exporter_build_info gauge ip, version, revision, goversion, branch, ins, goarch, job, tags, instance, cls, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which node_exporter was built, and the goos and goarch for the build. node_filefd_allocated gauge instance, ins, job, ip, clsFile descriptor statistics: allocated. node_filefd_maximum gauge instance, ins, job, ip, clsFile descriptor statistics: maximum. node_filesystem_avail_bytes gauge ip, device, mountpoint, ins, cls, job, instance, fstypeFilesystem space available to non-root users in bytes. node_filesystem_device_error gauge ip, device, mountpoint, ins, cls, job, instance, fstypeWhether an error occurred while getting statistics for the given device. node_filesystem_files gauge ip, device, mountpoint, ins, cls, job, instance, fstypeFilesystem total file nodes. node_filesystem_files_free gauge ip, device, mountpoint, ins, cls, job, instance, fstypeFilesystem total free file nodes. node_filesystem_free_bytes gauge ip, device, mountpoint, ins, cls, job, instance, fstypeFilesystem free space in bytes. node_filesystem_readonly gauge ip, device, mountpoint, ins, cls, job, instance, fstypeFilesystem read-only status. node_filesystem_size_bytes gauge ip, device, mountpoint, ins, cls, job, instance, fstypeFilesystem size in bytes. node_forks_total counter instance, ins, job, ip, clsTotal number of forks. node_hwmon_chip_names gauge chip_name, ip, ins, chip, job, instance, clsAnnotation metric for human-readable chip names node_hwmon_energy_joule_total counter sensor, ip, ins, chip, job, instance, clsHardware monitor for joules used so far (input) node_hwmon_sensor_label gauge sensor, ip, ins, chip, job, label, instance, clsLabel for given chip and sensor node_intr_total counter instance, ins, job, ip, clsTotal number of interrupts serviced. node_ipvs_connections_total counter instance, ins, job, ip, clsThe total number of connections made. node_ipvs_incoming_bytes_total counter instance, ins, job, ip, clsThe total amount of incoming data. node_ipvs_incoming_packets_total counter instance, ins, job, ip, clsThe total number of incoming packets. node_ipvs_outgoing_bytes_total counter instance, ins, job, ip, clsThe total amount of outgoing data. node_ipvs_outgoing_packets_total counter instance, ins, job, ip, clsThe total number of outgoing packets. node_load1 gauge instance, ins, job, ip, cls1m load average. node_load15 gauge instance, ins, job, ip, cls15m load average. node_load5 gauge instance, ins, job, ip, cls5m load average. node_memory_Active_anon_bytes gauge instance, ins, job, ip, clsMemory information field Active_anon_bytes. node_memory_Active_bytes gauge instance, ins, job, ip, clsMemory information field Active_bytes. node_memory_Active_file_bytes gauge instance, ins, job, ip, clsMemory information field Active_file_bytes. node_memory_AnonHugePages_bytes gauge instance, ins, job, ip, clsMemory information field AnonHugePages_bytes. node_memory_AnonPages_bytes gauge instance, ins, job, ip, clsMemory information field AnonPages_bytes. node_memory_Bounce_bytes gauge instance, ins, job, ip, clsMemory information field Bounce_bytes. node_memory_Buffers_bytes gauge instance, ins, job, ip, clsMemory information field Buffers_bytes. node_memory_Cached_bytes gauge instance, ins, job, ip, clsMemory information field Cached_bytes. node_memory_CommitLimit_bytes gauge instance, ins, job, ip, clsMemory information field CommitLimit_bytes. node_memory_Committed_AS_bytes gauge instance, ins, job, ip, clsMemory information field Committed_AS_bytes. node_memory_DirectMap1G_bytes gauge instance, ins, job, ip, clsMemory information field DirectMap1G_bytes. node_memory_DirectMap2M_bytes gauge instance, ins, job, ip, clsMemory information field DirectMap2M_bytes. node_memory_DirectMap4k_bytes gauge instance, ins, job, ip, clsMemory information field DirectMap4k_bytes. node_memory_Dirty_bytes gauge instance, ins, job, ip, clsMemory information field Dirty_bytes. node_memory_FileHugePages_bytes gauge instance, ins, job, ip, clsMemory information field FileHugePages_bytes. node_memory_FilePmdMapped_bytes gauge instance, ins, job, ip, clsMemory information field FilePmdMapped_bytes. node_memory_HardwareCorrupted_bytes gauge instance, ins, job, ip, clsMemory information field HardwareCorrupted_bytes. node_memory_HugePages_Free gauge instance, ins, job, ip, clsMemory information field HugePages_Free. node_memory_HugePages_Rsvd gauge instance, ins, job, ip, clsMemory information field HugePages_Rsvd. node_memory_HugePages_Surp gauge instance, ins, job, ip, clsMemory information field HugePages_Surp. node_memory_HugePages_Total gauge instance, ins, job, ip, clsMemory information field HugePages_Total. node_memory_Hugepagesize_bytes gauge instance, ins, job, ip, clsMemory information field Hugepagesize_bytes. node_memory_Hugetlb_bytes gauge instance, ins, job, ip, clsMemory information field Hugetlb_bytes. node_memory_Inactive_anon_bytes gauge instance, ins, job, ip, clsMemory information field Inactive_anon_bytes. node_memory_Inactive_bytes gauge instance, ins, job, ip, clsMemory information field Inactive_bytes. node_memory_Inactive_file_bytes gauge instance, ins, job, ip, clsMemory information field Inactive_file_bytes. node_memory_KReclaimable_bytes gauge instance, ins, job, ip, clsMemory information field KReclaimable_bytes. node_memory_KernelStack_bytes gauge instance, ins, job, ip, clsMemory information field KernelStack_bytes. node_memory_Mapped_bytes gauge instance, ins, job, ip, clsMemory information field Mapped_bytes. node_memory_MemAvailable_bytes gauge instance, ins, job, ip, clsMemory information field MemAvailable_bytes. node_memory_MemFree_bytes gauge instance, ins, job, ip, clsMemory information field MemFree_bytes. node_memory_MemTotal_bytes gauge instance, ins, job, ip, clsMemory information field MemTotal_bytes. node_memory_Mlocked_bytes gauge instance, ins, job, ip, clsMemory information field Mlocked_bytes. node_memory_NFS_Unstable_bytes gauge instance, ins, job, ip, clsMemory information field NFS_Unstable_bytes. node_memory_PageTables_bytes gauge instance, ins, job, ip, clsMemory information field PageTables_bytes. node_memory_Percpu_bytes gauge instance, ins, job, ip, clsMemory information field Percpu_bytes. node_memory_SReclaimable_bytes gauge instance, ins, job, ip, clsMemory information field SReclaimable_bytes. node_memory_SUnreclaim_bytes gauge instance, ins, job, ip, clsMemory information field SUnreclaim_bytes. node_memory_ShmemHugePages_bytes gauge instance, ins, job, ip, clsMemory information field ShmemHugePages_bytes. node_memory_ShmemPmdMapped_bytes gauge instance, ins, job, ip, clsMemory information field ShmemPmdMapped_bytes. node_memory_Shmem_bytes gauge instance, ins, job, ip, clsMemory information field Shmem_bytes. node_memory_Slab_bytes gauge instance, ins, job, ip, clsMemory information field Slab_bytes. node_memory_SwapCached_bytes gauge instance, ins, job, ip, clsMemory information field SwapCached_bytes. node_memory_SwapFree_bytes gauge instance, ins, job, ip, clsMemory information field SwapFree_bytes. node_memory_SwapTotal_bytes gauge instance, ins, job, ip, clsMemory information field SwapTotal_bytes. node_memory_Unevictable_bytes gauge instance, ins, job, ip, clsMemory information field Unevictable_bytes. node_memory_VmallocChunk_bytes gauge instance, ins, job, ip, clsMemory information field VmallocChunk_bytes. node_memory_VmallocTotal_bytes gauge instance, ins, job, ip, clsMemory information field VmallocTotal_bytes. node_memory_VmallocUsed_bytes gauge instance, ins, job, ip, clsMemory information field VmallocUsed_bytes. node_memory_WritebackTmp_bytes gauge instance, ins, job, ip, clsMemory information field WritebackTmp_bytes. node_memory_Writeback_bytes gauge instance, ins, job, ip, clsMemory information field Writeback_bytes. node_netstat_Icmp6_InErrors unknown instance, ins, job, ip, clsStatistic Icmp6InErrors. node_netstat_Icmp6_InMsgs unknown instance, ins, job, ip, clsStatistic Icmp6InMsgs. node_netstat_Icmp6_OutMsgs unknown instance, ins, job, ip, clsStatistic Icmp6OutMsgs. node_netstat_Icmp_InErrors unknown instance, ins, job, ip, clsStatistic IcmpInErrors. node_netstat_Icmp_InMsgs unknown instance, ins, job, ip, clsStatistic IcmpInMsgs. node_netstat_Icmp_OutMsgs unknown instance, ins, job, ip, clsStatistic IcmpOutMsgs. node_netstat_Ip6_InOctets unknown instance, ins, job, ip, clsStatistic Ip6InOctets. node_netstat_Ip6_OutOctets unknown instance, ins, job, ip, clsStatistic Ip6OutOctets. node_netstat_IpExt_InOctets unknown instance, ins, job, ip, clsStatistic IpExtInOctets. node_netstat_IpExt_OutOctets unknown instance, ins, job, ip, clsStatistic IpExtOutOctets. node_netstat_Ip_Forwarding unknown instance, ins, job, ip, clsStatistic IpForwarding. node_netstat_TcpExt_ListenDrops unknown instance, ins, job, ip, clsStatistic TcpExtListenDrops. node_netstat_TcpExt_ListenOverflows unknown instance, ins, job, ip, clsStatistic TcpExtListenOverflows. node_netstat_TcpExt_SyncookiesFailed unknown instance, ins, job, ip, clsStatistic TcpExtSyncookiesFailed. node_netstat_TcpExt_SyncookiesRecv unknown instance, ins, job, ip, clsStatistic TcpExtSyncookiesRecv. node_netstat_TcpExt_SyncookiesSent unknown instance, ins, job, ip, clsStatistic TcpExtSyncookiesSent. node_netstat_TcpExt_TCPSynRetrans unknown instance, ins, job, ip, clsStatistic TcpExtTCPSynRetrans. node_netstat_TcpExt_TCPTimeouts unknown instance, ins, job, ip, clsStatistic TcpExtTCPTimeouts. node_netstat_Tcp_ActiveOpens unknown instance, ins, job, ip, clsStatistic TcpActiveOpens. node_netstat_Tcp_CurrEstab unknown instance, ins, job, ip, clsStatistic TcpCurrEstab. node_netstat_Tcp_InErrs unknown instance, ins, job, ip, clsStatistic TcpInErrs. node_netstat_Tcp_InSegs unknown instance, ins, job, ip, clsStatistic TcpInSegs. node_netstat_Tcp_OutRsts unknown instance, ins, job, ip, clsStatistic TcpOutRsts. node_netstat_Tcp_OutSegs unknown instance, ins, job, ip, clsStatistic TcpOutSegs. node_netstat_Tcp_PassiveOpens unknown instance, ins, job, ip, clsStatistic TcpPassiveOpens. node_netstat_Tcp_RetransSegs unknown instance, ins, job, ip, clsStatistic TcpRetransSegs. node_netstat_Udp6_InDatagrams unknown instance, ins, job, ip, clsStatistic Udp6InDatagrams. node_netstat_Udp6_InErrors unknown instance, ins, job, ip, clsStatistic Udp6InErrors. node_netstat_Udp6_NoPorts unknown instance, ins, job, ip, clsStatistic Udp6NoPorts. node_netstat_Udp6_OutDatagrams unknown instance, ins, job, ip, clsStatistic Udp6OutDatagrams. node_netstat_Udp6_RcvbufErrors unknown instance, ins, job, ip, clsStatistic Udp6RcvbufErrors. node_netstat_Udp6_SndbufErrors unknown instance, ins, job, ip, clsStatistic Udp6SndbufErrors. node_netstat_UdpLite6_InErrors unknown instance, ins, job, ip, clsStatistic UdpLite6InErrors. node_netstat_UdpLite_InErrors unknown instance, ins, job, ip, clsStatistic UdpLiteInErrors. node_netstat_Udp_InDatagrams unknown instance, ins, job, ip, clsStatistic UdpInDatagrams. node_netstat_Udp_InErrors unknown instance, ins, job, ip, clsStatistic UdpInErrors. node_netstat_Udp_NoPorts unknown instance, ins, job, ip, clsStatistic UdpNoPorts. node_netstat_Udp_OutDatagrams unknown instance, ins, job, ip, clsStatistic UdpOutDatagrams. node_netstat_Udp_RcvbufErrors unknown instance, ins, job, ip, clsStatistic UdpRcvbufErrors. node_netstat_Udp_SndbufErrors unknown instance, ins, job, ip, clsStatistic UdpSndbufErrors. node_network_address_assign_type gauge ip, device, ins, job, instance, clsNetwork device property: address_assign_type node_network_carrier gauge ip, device, ins, job, instance, clsNetwork device property: carrier node_network_carrier_changes_total counter ip, device, ins, job, instance, clsNetwork device property: carrier_changes_total node_network_carrier_down_changes_total counter ip, device, ins, job, instance, clsNetwork device property: carrier_down_changes_total node_network_carrier_up_changes_total counter ip, device, ins, job, instance, clsNetwork device property: carrier_up_changes_total node_network_device_id gauge ip, device, ins, job, instance, clsNetwork device property: device_id node_network_dormant gauge ip, device, ins, job, instance, clsNetwork device property: dormant node_network_flags gauge ip, device, ins, job, instance, clsNetwork device property: flags node_network_iface_id gauge ip, device, ins, job, instance, clsNetwork device property: iface_id node_network_iface_link gauge ip, device, ins, job, instance, clsNetwork device property: iface_link node_network_iface_link_mode gauge ip, device, ins, job, instance, clsNetwork device property: iface_link_mode node_network_info gauge broadcast, ip, device, operstate, ins, job, adminstate, duplex, address, instance, clsNon-numeric data from /sys/class/net/, value is always 1. node_network_mtu_bytes gauge ip, device, ins, job, instance, clsNetwork device property: mtu_bytes node_network_name_assign_type gauge ip, device, ins, job, instance, clsNetwork device property: name_assign_type node_network_net_dev_group gauge ip, device, ins, job, instance, clsNetwork device property: net_dev_group node_network_protocol_type gauge ip, device, ins, job, instance, clsNetwork device property: protocol_type node_network_receive_bytes_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_bytes. node_network_receive_compressed_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_compressed. node_network_receive_drop_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_drop. node_network_receive_errs_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_errs. node_network_receive_fifo_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_fifo. node_network_receive_frame_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_frame. node_network_receive_multicast_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_multicast. node_network_receive_nohandler_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_nohandler. node_network_receive_packets_total counter ip, device, ins, job, instance, clsNetwork device statistic receive_packets. node_network_speed_bytes gauge ip, device, ins, job, instance, clsNetwork device property: speed_bytes node_network_transmit_bytes_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_bytes. node_network_transmit_carrier_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_carrier. node_network_transmit_colls_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_colls. node_network_transmit_compressed_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_compressed. node_network_transmit_drop_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_drop. node_network_transmit_errs_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_errs. node_network_transmit_fifo_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_fifo. node_network_transmit_packets_total counter ip, device, ins, job, instance, clsNetwork device statistic transmit_packets. node_network_transmit_queue_length gauge ip, device, ins, job, instance, clsNetwork device property: transmit_queue_length node_network_up gauge ip, device, ins, job, instance, clsValue is 1 if operstate is ‘up’, 0 otherwise. node_nf_conntrack_entries gauge instance, ins, job, ip, clsNumber of currently allocated flow entries for connection tracking. node_nf_conntrack_entries_limit gauge instance, ins, job, ip, clsMaximum size of connection tracking table. node_nf_conntrack_stat_drop gauge instance, ins, job, ip, clsNumber of packets dropped due to conntrack failure. node_nf_conntrack_stat_early_drop gauge instance, ins, job, ip, clsNumber of dropped conntrack entries to make room for new ones, if maximum table size was reached. node_nf_conntrack_stat_found gauge instance, ins, job, ip, clsNumber of searched entries which were successful. node_nf_conntrack_stat_ignore gauge instance, ins, job, ip, clsNumber of packets seen which are already connected to a conntrack entry. node_nf_conntrack_stat_insert gauge instance, ins, job, ip, clsNumber of entries inserted into the list. node_nf_conntrack_stat_insert_failed gauge instance, ins, job, ip, clsNumber of entries for which list insertion was attempted but failed. node_nf_conntrack_stat_invalid gauge instance, ins, job, ip, clsNumber of packets seen which can not be tracked. node_nf_conntrack_stat_search_restart gauge instance, ins, job, ip, clsNumber of conntrack table lookups which had to be restarted due to hashtable resizes. node_os_info gauge id, ip, version, version_id, ins, instance, job, pretty_name, id_like, clsA metric with a constant ‘1’ value labeled by build_id, id, id_like, image_id, image_version, name, pretty_name, variant, variant_id, version, version_codename, version_id. node_os_version gauge id, ip, ins, instance, job, id_like, clsMetric containing the major.minor part of the OS version. node_processes_max_processes gauge instance, ins, job, ip, clsNumber of max PIDs limit node_processes_max_threads gauge instance, ins, job, ip, clsLimit of threads in the system node_processes_pids gauge instance, ins, job, ip, clsNumber of PIDs node_processes_state gauge state, instance, ins, job, ip, clsNumber of processes in each state. node_processes_threads gauge instance, ins, job, ip, clsAllocated threads in system node_processes_threads_state gauge instance, ins, job, thread_state, ip, clsNumber of threads in each state. node_procs_blocked gauge instance, ins, job, ip, clsNumber of processes blocked waiting for I/O to complete. node_procs_running gauge instance, ins, job, ip, clsNumber of processes in runnable state. node_schedstat_running_seconds_total counter ip, ins, job, cpu, instance, clsNumber of seconds CPU spent running a process. node_schedstat_timeslices_total counter ip, ins, job, cpu, instance, clsNumber of timeslices executed by CPU. node_schedstat_waiting_seconds_total counter ip, ins, job, cpu, instance, clsNumber of seconds spent by processing waiting for this CPU. node_scrape_collector_duration_seconds gauge ip, collector, ins, job, instance, clsnode_exporter: Duration of a collector scrape. node_scrape_collector_success gauge ip, collector, ins, job, instance, clsnode_exporter: Whether a collector succeeded. node_selinux_enabled gauge instance, ins, job, ip, clsSELinux is enabled, 1 is true, 0 is false node_sockstat_FRAG6_inuse gauge instance, ins, job, ip, clsNumber of FRAG6 sockets in state inuse. node_sockstat_FRAG6_memory gauge instance, ins, job, ip, clsNumber of FRAG6 sockets in state memory. node_sockstat_FRAG_inuse gauge instance, ins, job, ip, clsNumber of FRAG sockets in state inuse. node_sockstat_FRAG_memory gauge instance, ins, job, ip, clsNumber of FRAG sockets in state memory. node_sockstat_RAW6_inuse gauge instance, ins, job, ip, clsNumber of RAW6 sockets in state inuse. node_sockstat_RAW_inuse gauge instance, ins, job, ip, clsNumber of RAW sockets in state inuse. node_sockstat_TCP6_inuse gauge instance, ins, job, ip, clsNumber of TCP6 sockets in state inuse. node_sockstat_TCP_alloc gauge instance, ins, job, ip, clsNumber of TCP sockets in state alloc. node_sockstat_TCP_inuse gauge instance, ins, job, ip, clsNumber of TCP sockets in state inuse. node_sockstat_TCP_mem gauge instance, ins, job, ip, clsNumber of TCP sockets in state mem. node_sockstat_TCP_mem_bytes gauge instance, ins, job, ip, clsNumber of TCP sockets in state mem_bytes. node_sockstat_TCP_orphan gauge instance, ins, job, ip, clsNumber of TCP sockets in state orphan. node_sockstat_TCP_tw gauge instance, ins, job, ip, clsNumber of TCP sockets in state tw. node_sockstat_UDP6_inuse gauge instance, ins, job, ip, clsNumber of UDP6 sockets in state inuse. node_sockstat_UDPLITE6_inuse gauge instance, ins, job, ip, clsNumber of UDPLITE6 sockets in state inuse. node_sockstat_UDPLITE_inuse gauge instance, ins, job, ip, clsNumber of UDPLITE sockets in state inuse. node_sockstat_UDP_inuse gauge instance, ins, job, ip, clsNumber of UDP sockets in state inuse. node_sockstat_UDP_mem gauge instance, ins, job, ip, clsNumber of UDP sockets in state mem. node_sockstat_UDP_mem_bytes gauge instance, ins, job, ip, clsNumber of UDP sockets in state mem_bytes. node_sockstat_sockets_used gauge instance, ins, job, ip, clsNumber of IPv4 sockets in use. node_tcp_connection_states gauge state, instance, ins, job, ip, clsNumber of connection states. node_textfile_scrape_error gauge instance, ins, job, ip, cls1 if there was an error opening or reading a file, 0 otherwise node_time_clocksource_available_info gauge ip, device, ins, clocksource, job, instance, clsAvailable clocksources read from ‘/sys/devices/system/clocksource’. node_time_clocksource_current_info gauge ip, device, ins, clocksource, job, instance, clsCurrent clocksource read from ‘/sys/devices/system/clocksource’. node_time_seconds gauge instance, ins, job, ip, clsSystem time in seconds since epoch (1970). node_time_zone_offset_seconds gauge instance, ins, job, time_zone, ip, clsSystem time zone offset in seconds. node_timex_estimated_error_seconds gauge instance, ins, job, ip, clsEstimated error in seconds. node_timex_frequency_adjustment_ratio gauge instance, ins, job, ip, clsLocal clock frequency adjustment. node_timex_loop_time_constant gauge instance, ins, job, ip, clsPhase-locked loop time constant. node_timex_maxerror_seconds gauge instance, ins, job, ip, clsMaximum error in seconds. node_timex_offset_seconds gauge instance, ins, job, ip, clsTime offset in between local system and reference clock. node_timex_pps_calibration_total counter instance, ins, job, ip, clsPulse per second count of calibration intervals. node_timex_pps_error_total counter instance, ins, job, ip, clsPulse per second count of calibration errors. node_timex_pps_frequency_hertz gauge instance, ins, job, ip, clsPulse per second frequency. node_timex_pps_jitter_seconds gauge instance, ins, job, ip, clsPulse per second jitter. node_timex_pps_jitter_total counter instance, ins, job, ip, clsPulse per second count of jitter limit exceeded events. node_timex_pps_shift_seconds gauge instance, ins, job, ip, clsPulse per second interval duration. node_timex_pps_stability_exceeded_total counter instance, ins, job, ip, clsPulse per second count of stability limit exceeded events. node_timex_pps_stability_hertz gauge instance, ins, job, ip, clsPulse per second stability, average of recent frequency changes. node_timex_status gauge instance, ins, job, ip, clsValue of the status array bits. node_timex_sync_status gauge instance, ins, job, ip, clsIs clock synchronized to a reliable server (1 = yes, 0 = no). node_timex_tai_offset_seconds gauge instance, ins, job, ip, clsInternational Atomic Time (TAI) offset. node_timex_tick_seconds gauge instance, ins, job, ip, clsSeconds between clock ticks. node_udp_queues gauge ip, queue, ins, job, exported_ip, instance, clsNumber of allocated memory in the kernel for UDP datagrams in bytes. node_uname_info gauge ip, sysname, version, domainname, release, ins, job, nodename, instance, cls, machineLabeled system information as provided by the uname system call. node_up Unknown instance, ins, job, ip, clsN/A node_vmstat_oom_kill unknown instance, ins, job, ip, cls/proc/vmstat information field oom_kill. node_vmstat_pgfault unknown instance, ins, job, ip, cls/proc/vmstat information field pgfault. node_vmstat_pgmajfault unknown instance, ins, job, ip, cls/proc/vmstat information field pgmajfault. node_vmstat_pgpgin unknown instance, ins, job, ip, cls/proc/vmstat information field pgpgin. node_vmstat_pgpgout unknown instance, ins, job, ip, cls/proc/vmstat information field pgpgout. node_vmstat_pswpin unknown instance, ins, job, ip, cls/proc/vmstat information field pswpin. node_vmstat_pswpout unknown instance, ins, job, ip, cls/proc/vmstat information field pswpout. process_cpu_seconds_total counter instance, ins, job, ip, clsTotal user and system CPU time spent in seconds. process_max_fds gauge instance, ins, job, ip, clsMaximum number of open file descriptors. process_open_fds gauge instance, ins, job, ip, clsNumber of open file descriptors. process_resident_memory_bytes gauge instance, ins, job, ip, clsResident memory size in bytes. process_start_time_seconds gauge instance, ins, job, ip, clsStart time of the process since unix epoch in seconds. process_virtual_memory_bytes gauge instance, ins, job, ip, clsVirtual memory size in bytes. process_virtual_memory_max_bytes gauge instance, ins, job, ip, clsMaximum amount of virtual memory available in bytes. prometheus_remote_storage_exemplars_in_total counter instance, ins, job, ip, clsExemplars in to remote storage, compare to exemplars out for queue managers. prometheus_remote_storage_histograms_in_total counter instance, ins, job, ip, clsHistogramSamples in to remote storage, compare to histograms out for queue managers. prometheus_remote_storage_samples_in_total counter instance, ins, job, ip, clsSamples in to remote storage, compare to samples out for queue managers. prometheus_remote_storage_string_interner_zero_reference_releases_total counter instance, ins, job, ip, clsThe number of times release has been called for strings that are not interned. prometheus_sd_azure_failures_total counter instance, ins, job, ip, clsNumber of Azure service discovery refresh failures. prometheus_sd_consul_rpc_duration_seconds summary ip, call, quantile, ins, job, instance, cls, endpointThe duration of a Consul RPC call in seconds. prometheus_sd_consul_rpc_duration_seconds_count Unknown ip, call, ins, job, instance, cls, endpointN/A prometheus_sd_consul_rpc_duration_seconds_sum Unknown ip, call, ins, job, instance, cls, endpointN/A prometheus_sd_consul_rpc_failures_total counter instance, ins, job, ip, clsThe number of Consul RPC call failures. prometheus_sd_consulagent_rpc_duration_seconds summary ip, call, quantile, ins, job, instance, cls, endpointThe duration of a Consul Agent RPC call in seconds. prometheus_sd_consulagent_rpc_duration_seconds_count Unknown ip, call, ins, job, instance, cls, endpointN/A prometheus_sd_consulagent_rpc_duration_seconds_sum Unknown ip, call, ins, job, instance, cls, endpointN/A prometheus_sd_consulagent_rpc_failures_total Unknown instance, ins, job, ip, clsN/A prometheus_sd_dns_lookup_failures_total counter instance, ins, job, ip, clsThe number of DNS-SD lookup failures. prometheus_sd_dns_lookups_total counter instance, ins, job, ip, clsThe number of DNS-SD lookups. prometheus_sd_file_read_errors_total counter instance, ins, job, ip, clsThe number of File-SD read errors. prometheus_sd_file_scan_duration_seconds summary quantile, instance, ins, job, ip, clsThe duration of the File-SD scan in seconds. prometheus_sd_file_scan_duration_seconds_count Unknown instance, ins, job, ip, clsN/A prometheus_sd_file_scan_duration_seconds_sum Unknown instance, ins, job, ip, clsN/A prometheus_sd_file_watcher_errors_total counter instance, ins, job, ip, clsThe number of File-SD errors caused by filesystem watch failures. prometheus_sd_kubernetes_events_total counter ip, event, ins, job, role, instance, clsThe number of Kubernetes events handled. prometheus_target_scrape_pool_exceeded_label_limits_total counter instance, ins, job, ip, clsTotal number of times scrape pools hit the label limits, during sync or config reload. prometheus_target_scrape_pool_exceeded_target_limit_total counter instance, ins, job, ip, clsTotal number of times scrape pools hit the target limit, during sync or config reload. prometheus_target_scrape_pool_reloads_failed_total counter instance, ins, job, ip, clsTotal number of failed scrape pool reloads. prometheus_target_scrape_pool_reloads_total counter instance, ins, job, ip, clsTotal number of scrape pool reloads. prometheus_target_scrape_pools_failed_total counter instance, ins, job, ip, clsTotal number of scrape pool creations that failed. prometheus_target_scrape_pools_total counter instance, ins, job, ip, clsTotal number of scrape pool creation attempts. prometheus_target_scrapes_cache_flush_forced_total counter instance, ins, job, ip, clsHow many times a scrape cache was flushed due to getting big while scrapes are failing. prometheus_target_scrapes_exceeded_body_size_limit_total counter instance, ins, job, ip, clsTotal number of scrapes that hit the body size limit prometheus_target_scrapes_exceeded_sample_limit_total counter instance, ins, job, ip, clsTotal number of scrapes that hit the sample limit and were rejected. prometheus_target_scrapes_exemplar_out_of_order_total counter instance, ins, job, ip, clsTotal number of exemplar rejected due to not being out of the expected order. prometheus_target_scrapes_sample_duplicate_timestamp_total counter instance, ins, job, ip, clsTotal number of samples rejected due to duplicate timestamps but different values. prometheus_target_scrapes_sample_out_of_bounds_total counter instance, ins, job, ip, clsTotal number of samples rejected due to timestamp falling outside of the time bounds. prometheus_target_scrapes_sample_out_of_order_total counter instance, ins, job, ip, clsTotal number of samples rejected due to not being out of the expected order. prometheus_template_text_expansion_failures_total counter instance, ins, job, ip, clsThe total number of template text expansion failures. prometheus_template_text_expansions_total counter instance, ins, job, ip, clsThe total number of template text expansions. prometheus_treecache_watcher_goroutines gauge instance, ins, job, ip, clsThe current number of watcher goroutines. prometheus_treecache_zookeeper_failures_total counter instance, ins, job, ip, clsThe total number of ZooKeeper failures. promhttp_metric_handler_errors_total counter ip, cause, ins, job, instance, clsTotal number of internal errors encountered by the promhttp metric handler. promhttp_metric_handler_requests_in_flight gauge instance, ins, job, ip, clsCurrent number of scrapes being served. promhttp_metric_handler_requests_total counter ip, ins, code, job, instance, clsTotal number of scrapes by HTTP status code. promtail_batch_retries_total Unknown host, ip, ins, job, instance, clsN/A promtail_build_info gauge ip, version, revision, goversion, branch, ins, goarch, job, tags, instance, cls, goosA metric with a constant ‘1’ value labeled by version, revision, branch, goversion from which promtail was built, and the goos and goarch for the build. promtail_config_reload_fail_total Unknown instance, ins, job, ip, clsN/A promtail_config_reload_success_total Unknown instance, ins, job, ip, clsN/A promtail_dropped_bytes_total Unknown host, ip, ins, job, reason, instance, clsN/A promtail_dropped_entries_total Unknown host, ip, ins, job, reason, instance, clsN/A promtail_encoded_bytes_total Unknown host, ip, ins, job, instance, clsN/A promtail_file_bytes_total gauge path, instance, ins, job, ip, clsNumber of bytes total. promtail_files_active_total gauge instance, ins, job, ip, clsNumber of active files. promtail_mutated_bytes_total Unknown host, ip, ins, job, reason, instance, clsN/A promtail_mutated_entries_total Unknown host, ip, ins, job, reason, instance, clsN/A promtail_read_bytes_total gauge path, instance, ins, job, ip, clsNumber of bytes read. promtail_read_lines_total Unknown path, instance, ins, job, ip, clsN/A promtail_request_duration_seconds_bucket Unknown host, ip, ins, job, status_code, le, instance, clsN/A promtail_request_duration_seconds_count Unknown host, ip, ins, job, status_code, instance, clsN/A promtail_request_duration_seconds_sum Unknown host, ip, ins, job, status_code, instance, clsN/A promtail_sent_bytes_total Unknown host, ip, ins, job, instance, clsN/A promtail_sent_entries_total Unknown host, ip, ins, job, instance, clsN/A promtail_targets_active_total gauge instance, ins, job, ip, clsNumber of active total. promtail_up Unknown instance, ins, job, ip, clsN/A request_duration_seconds_bucket Unknown instance, ins, job, status_code, route, ws, le, ip, cls, methodN/A request_duration_seconds_count Unknown instance, ins, job, status_code, route, ws, ip, cls, methodN/A request_duration_seconds_sum Unknown instance, ins, job, status_code, route, ws, ip, cls, methodN/A request_message_bytes_bucket Unknown instance, ins, job, route, le, ip, cls, methodN/A request_message_bytes_count Unknown instance, ins, job, route, ip, cls, methodN/A request_message_bytes_sum Unknown instance, ins, job, route, ip, cls, methodN/A response_message_bytes_bucket Unknown instance, ins, job, route, le, ip, cls, methodN/A response_message_bytes_count Unknown instance, ins, job, route, ip, cls, methodN/A response_message_bytes_sum Unknown instance, ins, job, route, ip, cls, methodN/A scrape_duration_seconds Unknown instance, ins, job, ip, clsN/A scrape_samples_post_metric_relabeling Unknown instance, ins, job, ip, clsN/A scrape_samples_scraped Unknown instance, ins, job, ip, clsN/A scrape_series_added Unknown instance, ins, job, ip, clsN/A tcp_connections gauge instance, ins, job, protocol, ip, clsCurrent number of accepted TCP connections. tcp_connections_limit gauge instance, ins, job, protocol, ip, clsThe max number of TCP connections that can be accepted (0 means no limit). up Unknown instance, ins, job, ip, clsN/A
13.8 - 常见问题 Pigsty NODE 主机节点模块常见问题答疑
如何配置主机节点上的NTP服务? NTP对于生产环境各项服务非常重要,如果没有配置 NTP,您可以使用公共 NTP 服务,或管理节点上的 Chronyd 作为标准时间。
如果您的节点已经配置了 NTP,可以通过设置 node_ntp_enabled 为 false 来保留现有配置,不进行任何变更。
否则,如果您有互联网访问权限,可以使用公共 NTP 服务,例如 pool.ntp.org。
如果您没有互联网访问权限,可以使用以下方式,确保所有环境内的节点与管理节点时间是同步的,或者使用其他内网环境的 NTP 授时服务。
node_ntp_servers: # /etc/chrony.conf 中的 ntp 服务器列表
- pool cn.pool.ntp.org iburst
- pool ${ admin_ip } iburst # 假设其他节点都没有互联网访问,那么至少与 Admin 节点保持时间同步。
如何在节点上强制同步时间? 为了使用 chronyc 来同步时间。您首先需要配置 NTP 服务。
ansible all -b -a 'chronyc -a makestep' # 同步时间
您可以用任何组或主机 IP 地址替换 all,以限制执行范围。
远程节点无法通过SSH访问怎么办? 如果目标机器隐藏在SSH跳板机后面, 或者进行了一些无法直接使用ssh ip访问的自定义操作, 可以使用诸如 ansible_port
或 ansible_host 这一类Ansible连接参数 来指定各种 SSH 连接信息,如下所示:
pg-test:
vars: { pg_cluster: pg-test }
hosts:
10.10.10.11: { pg_seq: 1, pg_role: primary, ansible_host: node-1 }
10.10.10.12: { pg_seq: 2, pg_role: replica, ansible_port: 22223, ansible_user: admin }
10.10.10.13: { pg_seq: 3, pg_role: offline, ansible_port: 22224 }
远程节点SSH与SUDO需要密码怎么办? 执行部署和更改时 ,使用的管理员用户必须 对所有节点拥有ssh和sudo权限。无需密码免密登录。
您可以在执行剧本时通过-k|-K
参数传入ssh和sudo密码,甚至可以通过-eansible_host=<another_user>使用另一个用户来运行剧本。
但是,Pigsty强烈建议为管理员用户配置SSH无密码登录 以及无密码的sudo。
如何使用现有管理员创建专用管理员用户? 使用以下命令,使用该节点上现有的管理员用户,创建由node_admin_username
定义的新的标准的管理员用户。
./node.yml -k -K -e ansible_user = <another_admin> -t node_admin
如何使用节点上的HAProxy对外暴露服务? 您可以在配置中中使用haproxy_services
来暴露服务,并使用 node.yml -t haproxy_config,haproxy_reload 来更新配置。
以下是使用它暴露MinIO服务的示例:暴露MinIO服务
为什么我的 /etc/yum.repos.d/* 全没了? Pigsty会在infra节点上构建的本地软件仓库源中包含所有依赖项。而所有普通节点会根据 node_repo_modules 的默认配置 local 来引用并使用 Infra 节点上的本地软件源。
这一设计从而避免了互联网访问,增强了安装过程的稳定性与可靠性。所有原有的源定义文件会被移动到 /etc/yum.repos.d/backup 目录中,您只要按需复制回来即可。
如果您想在普通节点安装过程中保留原有的源定义文件,将 node_repo_remove 设置为false即可。
如果您想在 Infra 节点构建本地源的过程中保留原有的源定义文件,将 repo_remove 设置为false即可。
为什么我的命令行提示符变样了?怎么恢复? Pigsty 使用的 Shell 命令行提示符是由环境变量 PS1 指定,定义在 /etc/profile.d/node.sh 文件中。
如果您不喜欢,想要修改或恢复原样,可以将这个文件移除,重新登陆即可。
为什么我的主机名变了? 在两种情况下,Pigsty 会修改您的节点主机名:
如果您不希望修改主机名,可以在全局/集群/实例层面修改 nodename_overwrite 参数为 false (默认值为 true)。
详情请参考 NODE_ID 一节。
腾讯云的 OpenCloudOS 有什么兼容性问题? OpenCloudOS 上的 softdog 内核模块不可用,需要从 node_kernel_modules 中移除。在配置文件全局变量中添加以下配置项以覆盖:
node_kernel_modules : [ ip_vs, ip_vs_rr, ip_vs_wrr, ip_vs_sh ]
Debian 系统有哪些常见问题? 在 Debian/Ubuntu 系统上使用 Pigsty 时,可能遇到以下问题:
本地语言环境缺失
如果系统提示 locale 相关错误,可以使用以下命令修复:
localedef -i en_US -f UTF-8 en_US.UTF-8
缺少 rsync 工具
Pigsty 依赖 rsync 进行文件同步,如果系统未安装,可以使用以下命令安装:
14 - 模块:ETCD Pigsty 可部署 etcd 模块,作为 DCS 为 PostgreSQL 高可用提供可靠的分布式配置存储支持。
ETCD 是一个分布式的、可靠的键-值存储,用于存放系统中最为关键的配置数据。
Pigsty 使用 etcd 作为 DCS (分布式配置存储),它对于 PostgreSQL 的高可用性与自动故障转移至关重要。
ETCD 模块依赖 NODE 模块,同时被 PGSQL 模块依赖。因此在安装 ETCD 模块之前,您需要安装 NODE 模块将节点纳管。
在部署任何 PGSQL 集群之前,你必须先部署一套 ETCD 集群,因为 PostgreSQL 高可用所需的 patroni 和 vip-manager 会依赖 etcd 实现高可用与 L2 VIP 主库绑定。
flowchart LR
subgraph PGSQL [PGSQL]
patroni[Patroni]
vip[VIP Manager]
end
subgraph ETCD [ETCD]
etcd[DCS 服务]
end
subgraph NODE [NODE]
node[软件仓库]
end
PGSQL -->|依赖| ETCD -->|依赖| NODE
style PGSQL fill:#3E668F,stroke:#2d4a66,color:#fff
style ETCD fill:#5B9CD5,stroke:#4178a8,color:#fff
style NODE fill:#FCDB72,stroke:#d4b85e,color:#333
style patroni fill:#2d4a66,stroke:#1e3347,color:#fff
style vip fill:#2d4a66,stroke:#1e3347,color:#fff
style etcd fill:#4178a8,stroke:#2d5a7a,color:#fff
style node fill:#d4b85e,stroke:#b89a4a,color:#333 在一套 Pigsty 部署中,只需要一套 etcd 集群。同一套 etcd 集群可以为多套 PostgreSQL 集群提供 DCS 服务支持。
Pigsty 中的 etcd 默认启用 RBAC,不同 PostgreSQL 集群使用独立的用户名与密码访问 etcd,从而实现多租户管理隔离。
管理员使用 etcd root 用户,拥有对所有 PostgreSQL 集群的管理权限。
14.1 - 集群配置 根据需求场景选择合适的 Etcd 集群规模,并对外提供可靠的接入。
在部署 Etcd 之前,你需要在 配置清单 中定义一个 Etcd 集群,通常来说,你可以选择:
单节点 :没有高可用性,适用于开发、测试、演示,或者依赖外部 S3 备份进行 PITR 的无高可用单机部署三节点 :具有基本的高可用性,可以容忍一个节点的故障,适用于中小规模的生产环境五节点 :具有更好的高可用性,可以容忍两个节点的故障,适用于大规模生产环境偶数节点的 Etcd 集群没有意义,超过五节点的 Etcd 集群并不常见,因此通常使用的规格就是单节点、三节点、五节点。
集群规模 仲裁数 容忍故障数 适用场景 1 节点 1 0 开发、测试、演示 3 节点 2 1 中小规模生产环境 5 节点 3 2 大规模生产环境 7 节点 4 3 特殊高可用需求
单节点 在 Pigsty 中,定义一个单例 Etcd 实例非常简单,只需要一行配置即可:
etcd : { hosts : { 10.10.10.10 : { etcd_seq: 1 } }, vars : { etcd_cluster : etcd } }
在 Pigsty 提供的所有单机配置模板中,都有这样一项,其中的占位 IP 地址:10.10.10.10 默认会被替换为当前管理节点的 IP。
除了 IP 地址外,这里唯一必要的参数是 etcd_seq 和 etcd_cluster ,它们会唯一标识每一个 Etcd 实例。
三节点 三节点的 Etcd 集群最为常见,它可以容忍一个节点的故障,适用于中小规模的生产环境。
例如,Pigsty 的三节点模板:trio 和 safe 就使用了三节点的 Etcd 集群,如下所示:
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 } # etcd_seq (etcd实例号)是必须指定的身份参数
10.10.10.11 : { etcd_seq : 2 } # 实例号是正整数,一般从 0 或 1 开始依次分配
10.10.10.12 : { etcd_seq : 3 } # 实例号应当终生不可变,一旦分配就不再回收使用。
vars : # 集群层面的参数
etcd_cluster : etcd # 默认情况下,etcd 集群名就叫 etcd, 除非您想要部署多套 etcd 集群,否则不要改这个名字
etcd_safeguard : false # 是否打开 etcd 的防误删安全保险? 在生产环境初始化完成后,可以考虑打开这个选项,避免误删。
etcd_clean : true # 在初始化过程中,是否强制移除现有的 etcd 实例?测试的时候可以打开,这样剧本就是真正幂等的。
五节点 五节点的 Etcd 集群可以容忍两个节点的故障,适用于大规模生产环境。
例如,Pigsty 的生产仿真模板:prod 中就使用了一个五节点的 Etcd 集群:
etcd :
hosts :
10.10.10.21 : { etcd_seq : 1 }
10.10.10.22 : { etcd_seq : 2 }
10.10.10.23 : { etcd_seq : 3 }
10.10.10.24 : { etcd_seq : 4 }
10.10.10.25 : { etcd_seq : 5 }
vars : { etcd_cluster : etcd }
使用 etcd 的服务 目前 Pigsty 中使用 etcd 的服务有:
服务 用途 配置文件 Patroni PostgreSQL 高可用,存储集群状态和配置 /pg/bin/patroni.ymlVIP-Manager 在 PostgreSQL 集群上绑定 L2 VIP /etc/default/vip-manager
当 etcd 集群的成员信息发生永久性变更时,您应当 重载相关服务的配置 ,以确保服务能够正确访问 Etcd 集群。
更新 Patroni 的 etcd 端点引用 :
./pgsql.yml -t pg_conf # 重新生成 patroni 配置
ansible all -f 1 -b -a 'systemctl reload patroni' # 重新加载 patroni 配置
更新 VIP-Manager 的 etcd 端点引用 (仅当使用 PGSQL L2 VIP 时需要):
./pgsql.yml -t pg_vip_config # 重新生成 vip-manager 配置
ansible all -f 1 -b -a 'systemctl restart vip-manager' # 重启 vip-manager
RBAC 认证配置 Pigsty v4.0 默认启用 etcd 的 RBAC 认证机制。相关配置参数:
生产环境建议 :
all :
vars :
etcd_root_password : 'YourSecureEtcdPassword' # 修改默认密码
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
10.10.10.11 : { etcd_seq : 2 }
10.10.10.12 : { etcd_seq : 3 }
vars :
etcd_cluster : etcd
etcd_safeguard : true # 生产环境开启防误删保护
文件系统布局 etcd 模块在目标主机上创建以下目录和文件:
路径 用途 权限 /etc/etcd/配置目录 0750, etcd:etcd /etc/etcd/etcd.conf主配置文件 0644, etcd:etcd /etc/etcd/etcd.passroot 密码文件 0640, root:etcd /etc/etcd/ca.crtCA 证书 0644, etcd:etcd /etc/etcd/server.crt服务器证书 0644, etcd:etcd /etc/etcd/server.key服务器私钥 0600, etcd:etcd /var/lib/etcd/备用数据目录 0770, etcd:etcd /data/etcd/主数据目录(可配置) 0700, etcd:etcd /etc/profile.d/etcdctl.sh客户端环境变量 0755, root:root /etc/systemd/system/etcd.serviceSystemd 服务 0644, root:root
14.2 - 参数列表 ETCD 模块提供了 13 个配置参数,用于精细控制集群的行为表现。
ETCD 模块的参数列表,共有 13 个参数,分为两个部分:
架构变化:Pigsty v3.6+
自 Pigsty v3.6 起,etcd.yml 剧本不再包含移除功能,移除相关参数已迁移至独立的 etcd_remove 角色。v4.0 起默认启用 RBAC 认证,新增 etcd_root_password 参数。
参数概览 ETCD 参数组用于 etcd 集群的部署与配置,包括实例标识、集群名称、数据目录、端口以及认证密码。
ETCD_REMOVE 参数组控制 etcd 集群的移除行为,包括防误删保险、数据清理以及软件包卸载。
ETCD本节包含 etcd 角色的参数,
这些是 etcd.yml 剧本使用的操作标志参数。
相关参数定义于 roles/etcd/defaults/main.yml
#etcd_seq: 1 # etcd 实例标识符,需要显式指定(必填)
etcd_cluster : etcd # etcd 集群和组名称,默认为 etcd
etcd_learner : false # etcd 实例是否以 learner 模式运行?默认为 false
etcd_data : /data/etcd # etcd 数据目录,默认为 /data/etcd
etcd_port : 2379 # etcd 客户端端口,默认为 2379
etcd_peer_port : 2380 # etcd 对等端口,默认为 2380
etcd_init : new # etcd 初始集群状态,new 或 existing
etcd_election_timeout : 1000 # etcd 选举超时,默认为 1000ms
etcd_heartbeat_interval : 100 # etcd 心跳间隔,默认为 100ms
etcd_root_password : Etcd.Root # etcd root 用户密码,用于 RBAC 认证(请修改!)
etcd_seq参数名称: etcd_seq, 类型: int, 层次:I
etcd 实例标号, 这是必选参数,必须为每一个 etcd 实例指定一个唯一的标号。
以下是一个3节点etcd集群的示例,分配了 1 ~ 3 三个标号。
etcd : # dcs service for postgres/patroni ha consensus
hosts : # 1 node for testing, 3 or 5 for production
10.10.10.10 : { etcd_seq : 1 } # etcd_seq required
10.10.10.11 : { etcd_seq : 2 } # assign from 1 ~ n
10.10.10.12 : { etcd_seq : 3 } # use odd numbers
vars : # cluster level parameter override roles/etcd
etcd_cluster : etcd # mark etcd cluster name etcd
etcd_safeguard : false # safeguard against purging
etcd_cluster参数名称: etcd_cluster, 类型: string, 层次:C
etcd 集群 & 分组名称,默认值为硬编码值 etcd。
当您想要部署另外的 etcd 集群备用时,可以修改此参数并使用其他集群名。
etcd_learner参数名称: etcd_learner, 类型: bool, 层次:I/A
是否以 learner 模式初始化 etcd 实例?默认值为 false。
当设置为 true 时,etcd 实例将以 learner(学习者)模式初始化,这意味着该实例不能在 etcd 集群中参与投票选举。
使用场景 :
集群扩容 :向现有集群添加新成员时,使用 learner 模式可以避免在数据同步完成前影响集群的仲裁安全迁移 :在滚动升级或迁移场景中,先以 learner 模式加入,确认数据同步完成后再提升操作流程 :
设置 etcd_learner: true,以 learner 模式初始化新成员 等待数据同步完成(通过 etcdctl endpoint status 检查) 使用 etcdctl member promote <member_id> 将其提升为正式成员 注意
Learner 实例不计入集群仲裁成员数。例如,3 节点集群中有 1 个 learner,实际投票成员数为 2,不能容忍任何节点故障。
etcd_data参数名称: etcd_data, 类型: path, 层次:C
etcd 数据目录,默认为/data/etcd 。
etcd_port参数名称: etcd_port, 类型: port, 层次:C
etcd 客户端端口号,默认为2379。
etcd_peer_port参数名称: etcd_peer_port, 类型: port, 层次:C
etcd peer 端口,默认为 2380 。
etcd_init参数名称: etcd_init, 类型: enum, 层次:C
etcd 初始集群状态,可以是 new 或 existing,默认值:new。
可选值说明 :
值 说明 使用场景 new创建新的 etcd 集群 首次部署、集群重建 existing加入现有 etcd 集群 集群扩容、添加新成员
重要说明 :
扩容时必须使用 existing
向现有 etcd 集群添加新成员时,必须 设置 etcd_init=existing。否则新实例会尝试创建独立的新集群,导致脑裂或初始化失败。
使用示例 :
# 创建新集群(默认行为)
./etcd.yml
# 向现有集群添加新成员
./etcd.yml -l <new_ip> -e etcd_init = existing
# 或使用便捷脚本(自动设置 etcd_init=existing)
bin/etcd-add <new_ip>
etcd_election_timeout参数名称: etcd_election_timeout, 类型: int, 层次:C
etcd 选举超时,默认为 1000 (毫秒),也就是 1 秒。
etcd_heartbeat_interval参数名称: etcd_heartbeat_interval, 类型: int, 层次:C
etcd心跳间隔,默认为 100 (毫秒)。
etcd_root_password参数名称: etcd_root_password, 类型: password, 层次:G
etcd root 用户密码,用于 RBAC 认证,默认值为 Etcd.Root。
Pigsty v4.0 默认启用 etcd 的 RBAC(基于角色的访问控制)认证机制。在集群初始化时,etcd_auth 任务会自动创建 root 用户并启用认证。
密码存储位置 :
密码存储在 /etc/etcd/etcd.pass 文件中 文件权限为 0640(root 所有,etcd 组可读) etcdctl 环境变量脚本 /etc/profile.d/etcdctl.sh 会自动读取此文件 与其他组件的配合 :
Patroni 通过 pg_etcd_password 参数配置连接 etcd 的密码 如果 pg_etcd_password 为空,Patroni 会使用集群名称作为密码(不推荐) VIP-Manager 也需要使用相同的认证信息连接 etcd 安全建议 :
生产环境安全
在生产环境中,强烈建议修改默认密码 Etcd.Root。可以在全局配置或集群配置中设置:
etcd_root_password : 'YourSecurePassword'
使用 configure -g 参数可以自动生成并替换 etcd_root_password
ETCD_REMOVE本节包含 etcd_remove 角色的参数,
这些是 etcd-rm.yml 剧本使用的操作标志参数。
相关参数定义于 roles/etcd_remove/defaults/main.yml
etcd_safeguard : false # 防误删保险,阻止移除正在运行的 etcd 实例?
etcd_rm_data : true # 移除时是否删除 etcd 数据和配置文件?
etcd_rm_pkg : false # 移除时是否卸载 etcd 软件包?
etcd_safeguard参数名称: etcd_safeguard, 类型: bool, 层次:G/C/A
防误删保险参数,防止清除正在运行的 etcd 实例?默认值为 false。
如果启用安全保险,etcd-rm.yml 剧本在检测到正在运行的 etcd 实例时会主动中止,从而避免意外删除正在使用的 etcd 集群。
使用建议 :
环境 建议值 说明 开发/测试 false方便快速重建和测试 生产环境 true防止误操作导致服务中断
紧急情况下,可以使用命令行参数覆盖配置:
./etcd-rm.yml -e etcd_safeguard = false
etcd_rm_data参数名称: etcd_rm_data, 类型: bool, 层次:G/C/A
移除时是否删除 etcd 数据和配置文件?默认值为 true。
启用此选项后,etcd-rm.yml 剧本在移除集群或成员时会同时删除以下内容:
/etc/etcd/ - 配置目录(包括证书和密码文件)/var/lib/etcd/ - 备用数据目录{{ etcd_data }} - 主数据目录(默认 /data/etcd)/etc/profile.d/etcdctl.sh - 客户端环境变量脚本使用场景 :
场景 建议值 说明 彻底移除 true(默认)完全清理,释放磁盘空间 仅停止服务 false保留数据,便于故障排查或恢复
# 仅停止服务,保留数据
./etcd-rm.yml -e etcd_rm_data = false
etcd_rm_pkg参数名称: etcd_rm_pkg, 类型: bool, 层次:G/C/A
移除时是否卸载 etcd 软件包?默认值为 false。
启用此选项后,etcd-rm.yml 剧本在移除集群或成员时会同时卸载 etcd 软件包。
使用场景 :
场景 建议值 说明 常规移除 false(默认)保留软件包,便于快速重建 彻底清理 true完全卸载,节省磁盘空间
# 移除时同时卸载软件包
./etcd-rm.yml -e etcd_rm_pkg = true
提示
通常不需要卸载 etcd 软件包。保留软件包可以加快后续的重新部署速度,因为不需要重新下载和安装。
14.3 - 管理预案 etcd 集群管理 SOP:创建,销毁,扩缩容,更新配置,RBAC 配置的详细说明。
以下是一些常见的 etcd 管理任务 SOP(预案):
创建集群 :如何初始化 etcd 集群?销毁集群 :如何销毁 etcd 集群?环境变量 :如何配置 etcd 客户端,以访问 etcd 服务器集群?RBAC 认证 :如何使用 etcd 的 RBAC 认证?重载配置 :如何更新客户端使用的 etcd 服务器成员列表?添加成员 :如何向现有 etcd 集群添加新成员?移除成员 :如何从 etcd 集群移除老成员?便捷脚本 :使用 bin/etcd-add 和 bin/etcd-rm 简化操作更多问题请参考 FAQ:ETCD 。
创建集群 要创建一个集群,首先需要在 配置清单 中定义 etcd 集群:
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
10.10.10.11 : { etcd_seq : 2 }
10.10.10.12 : { etcd_seq : 3 }
vars : { etcd_cluster : etcd }
执行 etcd.yml 剧本即可。
架构变化:Pigsty v3.6+
自 Pigsty v3.6 起,etcd.yml 剧本专注于集群安装和成员添加,不再包含移除功能。所有移除操作请使用独立的 etcd-rm.yml 剧本。
对于已初始化的生产环境 etcd 集群,可以打开防误删保护 etcd_safeguard ,避免误删现有的 etcd 实例。
销毁集群 要销毁一个 etcd 集群,请使用独立的 etcd-rm.yml 剧本。执行此命令前请务必三思!
./etcd-rm.yml # 移除整个 etcd 集群
./etcd-rm.yml -e etcd_safeguard = false # 强制覆盖防误删保险
或使用便捷脚本:
bin/etcd-rm # 移除整个 etcd 集群
移除剧本会尊重 etcd_safeguard 防误删保险的配置。如果该参数设置为 true,剧本将中止执行以防止误删。
注意
在移除 etcd 集群之前,请确保没有 PostgreSQL 集群正在使用该 etcd 作为 DCS 服务。否则会导致 PostgreSQL 高可用功能失效。
环境变量 Pigsty 默认使用 etcd v3 API(v3.6+ 已移除 v2 API 支持)。Pigsty 会在 etcd 节点上自动配置环境变量脚本 /etc/profile.d/etcdctl.sh,登录后会自动加载。
以下是 etcd 客户端配置环境变量的示例:
alias e = "etcdctl"
alias em = "etcdctl member"
export ETCDCTL_ENDPOINTS = https://10.10.10.10:2379
export ETCDCTL_CACERT = /etc/etcd/ca.crt
export ETCDCTL_CERT = /etc/etcd/server.crt
export ETCDCTL_KEY = /etc/etcd/server.key
Pigsty v4.0 默认启用 RBAC 认证,因此还需要配置用户认证:
export ETCDCTL_USER = "root: $( cat /etc/etcd/etcd.pass) "
配置好客户端环境变量后,你可以使用以下命令进行 etcd CRUD 操作:
e put a 10 ; e get a; e del a # 基本 KV 操作
e member list # 列出集群成员
e endpoint health # 检查端点健康状态
e endpoint status # 查看端点状态
RBAC 认证 Pigsty v4.0 默认启用 etcd 的 RBAC(基于角色的访问控制)认证机制。在集群初始化时,etcd_auth 任务会自动创建 root 用户并启用认证。
root 用户密码 由 etcd_root_password 参数指定,默认值为 Etcd.Root。密码存储在 /etc/etcd/etcd.pass 文件中,权限为 0640(root 所有,etcd 组可读)。
在生产环境中,强烈建议修改默认密码 :
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
10.10.10.11 : { etcd_seq : 2 }
10.10.10.12 : { etcd_seq : 3 }
vars :
etcd_cluster : etcd
etcd_root_password : 'YourSecurePassword' # 修改默认密码
客户端认证方式 :
# 方式一:使用环境变量(推荐,已自动配置在 /etc/profile.d/etcdctl.sh)
export ETCDCTL_USER = "root: $( cat /etc/etcd/etcd.pass) "
# 方式二:在命令行中指定
etcdctl --user root:YourSecurePassword member list
Patroni 与 etcd 认证 :
PostgreSQL 高可用组件 Patroni 通过 pg_etcd_password 参数配置连接 etcd 的密码。如果该参数为空,Patroni 会使用集群名称作为密码(不推荐)。建议在生产环境中为每个 PG 集群配置独立的 etcd 密码。
重载配置 如果 etcd 集群的成员发生变化(添加或移除成员),我们需要刷新对 etcd 服务端点的引用。目前 Pigsty 中有以下几处 etcd 引用需要更新:
配置位置 配置文件 更新方式 etcd 成员配置 /etc/etcd/etcd.conf./etcd.yml -t etcd_confetcdctl 环境变量 /etc/profile.d/etcdctl.sh./etcd.yml -t etcd_configPatroni DCS 配置 /pg/bin/patroni.yml./pgsql.yml -t pg_confVIP-Manager 配置 /etc/default/vip-manager./pgsql.yml -t pg_vip_config
刷新 etcd 成员配置文件 :
./etcd.yml -t etcd_conf # 刷新 /etc/etcd/etcd.conf
ansible etcd -f 1 -b -a 'systemctl restart etcd' # 可选:逐一重启 etcd 实例
刷新 etcdctl 客户端环境变量 :
./etcd.yml -t etcd_config # 刷新 /etc/profile.d/etcdctl.sh
更新 Patroni DCS 端点配置 :
./pgsql.yml -t pg_conf # 重新生成 patroni 配置
ansible all -f 1 -b -a 'systemctl reload patroni' # 重新加载 patroni 配置
更新 VIP-Manager 端点配置 (仅当使用 PGSQL L2 VIP 时需要):
./pgsql.yml -t pg_vip_config # 重新生成 vip-manager 配置
ansible all -f 1 -b -a 'systemctl restart vip-manager' # 重启 vip-manager
提示
使用 bin/etcd-add 和 bin/etcd-rm 便捷脚本时,脚本会在操作完成后提示您需要执行的配置刷新命令。
添加成员 ETCD 参考: 添加成员
推荐方式:使用便捷脚本 使用 bin/etcd-add 脚本是向现有 etcd 集群添加新成员的推荐方式 :
# 首先在配置清单中添加新成员定义,然后执行:
bin/etcd-add <ip> # 添加单个新成员
bin/etcd-add <ip1> <ip2> ... # 添加多个新成员
脚本会自动完成以下操作:
验证 IP 地址有效性 执行 etcd.yml 剧本(自动设置 etcd_init=existing) 提供安全警告和倒计时 操作完成后提示配置刷新命令 手动方式:分步操作 向现有的 etcd 集群添加新成员需要以下步骤:
更新配置清单 :将新实例添加到 etcd 组通知集群 :执行 etcdctl member add 命令(可选,剧本会自动执行)初始化新成员 :使用 etcd_init=existing 参数运行剧本提升成员 :将学习者提升为正式成员(可选,使用 etcd_learner=true 时需要)重载配置 :更新所有客户端的 etcd 端点引用# 配置清单更新后,初始化新成员
./etcd.yml -l <new_ins_ip> -e etcd_init = existing
# 如果使用 learner 模式,需要手动提升
etcdctl member promote <new_ins_server_id>
重要
添加新成员时必须使用 etcd_init=existing 参数,否则新实例会尝试创建新集群而非加入现有集群。
详细步骤:向etcd集群添加成员 下面是具体操作的详细细节,让我们从一个单实例 etcd 集群开始:
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 } # <--- 集群中原本存在的唯一实例
10.10.10.11 : { etcd_seq : 2 } # <--- 将此新成员定义添加到清单中
vars : { etcd_cluster : etcd }
使用便捷脚本添加新成员(推荐):
$ bin/etcd-add 10.10.10.11
或者手动操作。首先使用 etcdctl member add 向现有 etcd 集群宣告新的学习者实例 etcd-2 即将到来:
$ etcdctl member add etcd-2 --learner= true --peer-urls= https://10.10.10.11:2380
Member 33631ba6ced84cf8 added to cluster 6646fbcf5debc68f
ETCD_NAME = "etcd-2"
ETCD_INITIAL_CLUSTER = "etcd-2=https://10.10.10.11:2380,etcd-1=https://10.10.10.10:2380"
ETCD_INITIAL_ADVERTISE_PEER_URLS = "https://10.10.10.11:2380"
ETCD_INITIAL_CLUSTER_STATE = "existing"
使用 etcdctl member list(或 em list)检查成员列表,我们可以看到一个 unstarted 新成员:
33631ba6ced84cf8, unstarted, , https://10.10.10.11:2380, , true # 这里有一个未启动的新成员
429ee12c7fbab5c1, started, etcd-1, https://10.10.10.10:2380, https://10.10.10.10:2379, false
接下来使用 etcd.yml 剧本初始化新的 etcd 实例 etcd-2,完成后,我们可以看到新成员已经启动:
$ ./etcd.yml -l 10.10.10.11 -e etcd_init = existing # 一定要添加 existing 参数
...
33631ba6ced84cf8, started, etcd-2, https://10.10.10.11:2380, https://10.10.10.11:2379, true
429ee12c7fbab5c1, started, etcd-1, https://10.10.10.10:2380, https://10.10.10.10:2379, false
新成员初始化完成并稳定运行后,可以将新成员从学习者提升为追随者:
$ etcdctl member promote 33631ba6ced84cf8 # 将学习者提升为追随者
Member 33631ba6ced84cf8 promoted in cluster 6646fbcf5debc68f
$ em list # 再次检查,新成员已提升为正式成员
33631ba6ced84cf8, started, etcd-2, https://10.10.10.11:2380, https://10.10.10.11:2379, false
429ee12c7fbab5c1, started, etcd-1, https://10.10.10.10:2380, https://10.10.10.10:2379, false
新成员添加完成,请不要忘记 重载配置 ,让所有客户端也知道新成员的存在。
重复以上步骤,可以添加更多成员。记住,生产环境中至少要使用 3 个成员。
移除成员 推荐方式:使用便捷脚本 使用 bin/etcd-rm 脚本是从 etcd 集群移除成员的推荐方式 :
bin/etcd-rm <ip> # 移除指定成员
bin/etcd-rm <ip1> <ip2> ... # 移除多个成员
bin/etcd-rm # 移除整个 etcd 集群
脚本会自动完成以下操作:
从集群中优雅地移除成员 停止并禁用 etcd 服务 清理数据和配置文件 从监控系统中注销 手动方式:分步操作 要从 etcd 集群中删除一个成员实例,通常需要以下步骤:
从配置清单中移除 :注释或删除该实例,并 重载配置 从集群中踢除 :使用 etcdctl member remove 命令清理实例 :使用 etcd-rm.yml 剧本清理实例# 使用专用移除剧本(推荐)
./etcd-rm.yml -l <ip>
# 或者手动操作
etcdctl member remove <server_id> # 从集群中踢除
./etcd-rm.yml -l <ip> # 清理实例
详细步骤:从etcd集群移除成员 让我们以一个 3 节点的 etcd 集群为例,从中移除 3 号实例。
方法一:使用便捷脚本(推荐)
$ bin/etcd-rm 10.10.10.12
脚本会自动完成所有操作,包括从集群中移除成员、停止服务、清理数据。
方法二:手动操作
首先,为了刷新配置,您需要 注释 待删除的成员,然后 重载配置 ,让所有客户端都不要再使用此实例。
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
10.10.10.11 : { etcd_seq : 2 }
# 10.10.10.12: { etcd_seq: 3 } # <---- 注释掉这个成员
vars : { etcd_cluster : etcd }
然后,使用移除剧本:
$ ./etcd-rm.yml -l 10.10.10.12
剧本会自动执行以下操作:
获取成员列表并找到对应的成员 ID 执行 etcdctl member remove 从集群中踢除 停止 etcd 服务 清理数据和配置文件 如果需要手动操作,可以这样做:
$ etcdctl member list
429ee12c7fbab5c1, started, etcd-1, https://10.10.10.10:2380, https://10.10.10.10:2379, false
33631ba6ced84cf8, started, etcd-2, https://10.10.10.11:2380, https://10.10.10.11:2379, false
93fcf23b220473fb, started, etcd-3, https://10.10.10.12:2380, https://10.10.10.12:2379, false # <--- 移除这个
$ etcdctl member remove 93fcf23b220473fb # 从集群中踢除
Member 93fcf23b220473fb removed from cluster 6646fbcf5debc68f
执行完毕后,您可以将其从配置清单中永久删除,移除成员至此完成。
重复以上步骤,可以移除更多成员,与添加成员 配合使用,可以对 etcd 集群进行滚动升级搬迁。
便捷脚本 Pigsty v3.6+ 提供了便捷脚本简化 etcd 集群的扩容和缩容操作:
bin/etcd-add向现有 etcd 集群添加新成员:
bin/etcd-add <ip> # 添加单个新成员
bin/etcd-add <ip1> <ip2> ... # 添加多个新成员
脚本功能:
验证 IP 地址是否在配置清单中定义 自动设置 etcd_init=existing 参数 执行 etcd.yml 剧本完成成员添加 操作完成后提示配置刷新命令 bin/etcd-rm从 etcd 集群移除成员或整个集群:
bin/etcd-rm <ip> # 移除指定成员
bin/etcd-rm <ip1> <ip2> ... # 移除多个成员
bin/etcd-rm # 移除整个 etcd 集群
脚本功能:
提供安全警告和确认倒计时 自动执行 etcd-rm.yml 剧本 优雅地从集群中移除成员 清理数据和配置文件 14.4 - 预置剧本 如何使用预置的 ansible 剧本来管理 Etcd 集群,常用管理命令速查。
Etcd 模块提供了两个核心剧本:etcd.yml 用于安装与配置 Etcd 集群,etcd-rm.yml 用于移除 Etcd 集群或成员。
架构变化:Pigsty v3.6+
自 Pigsty v3.6 起,etcd.yml 剧本专注于集群安装和成员添加,所有移除操作已迁移至独立的 etcd-rm.yml 剧本和 etcd_remove 角色。
etcd.yml剧本原始文件:etcd.yml
执行本剧本,将会在硬编码的固定分组 etcd 上安装配置 Etcd 集群,并启动 etcd 服务。
在 etcd.yml 中,提供了以下是可用的任务子集:
etcd_assert :验证 etcd 身份参数(etcd_seq 必须定义且为非负整数)etcd_install :安装 etcd 软件包etcd_dir :创建 etcd 数据和配置目录etcd_config :生成 etcd 配置etcd_conf :生成 etcd 主配置文件 /etc/etcd/etcd.confetcd_cert :生成 etcd TLS 证书(CA、服务器证书、私钥)etcd_member :将新成员添加到现有集群(仅当 etcd_init=existing 时执行)etcd_launch :启动 etcd 服务etcd_auth :启用 RBAC 认证(创建 root 用户并启用认证)etcd_register :将 etcd 注册到 VictoriaMetrics/Prometheus 监控etcd-rm.yml剧本原始文件:etcd-rm.yml
用于移除 Etcd 集群或单个成员的专用剧本。在 etcd-rm.yml 中,提供了以下可用的任务子集:
etcd_safeguard :检查防误删保险,如果启用则中止执行prometheus :从 Prometheus/VictoriaMetrics 目标中移除 etcd 注册etcd_leave :在清理前尝试优雅地离开 etcd 集群etcd_stop :使用 systemd 停止并禁用 etcd 服务etcd_data :移除 etcd 数据(可通过 etcd_rm_data=false 禁用)etcd_pkg :卸载 etcd 软件包(需通过 etcd_rm_pkg=true 显式启用)移除剧本使用 etcd_remove 角色,支持以下可配置参数:
执行演示
命令速查 Etcd 安装与配置:
./etcd.yml # 初始化 etcd 集群
./etcd.yml -t etcd_launch # 重启整个 etcd 集群
./etcd.yml -t etcd_conf # 使用最新状态刷新 /etc/etcd/etcd.conf
./etcd.yml -t etcd_cert # 重新生成 etcd TLS 证书
./etcd.yml -l 10.10.10.12 -e etcd_init = existing # 扩容节点:添加新成员到现有集群
Etcd 移除与清理:
./etcd-rm.yml # 移除整个 etcd 集群
./etcd-rm.yml -l 10.10.10.12 # 移除单个 etcd 成员
./etcd-rm.yml -e etcd_safeguard = false # 覆盖防误删保险强制移除
./etcd-rm.yml -e etcd_rm_data = false # 仅停止服务,保留数据
./etcd-rm.yml -e etcd_rm_pkg = true # 同时卸载 etcd 软件包
便捷脚本:
bin/etcd-add <ip> # 向现有集群添加新成员(推荐)
bin/etcd-rm <ip> # 从集群中移除指定成员(推荐)
bin/etcd-rm # 移除整个 etcd 集群
保护机制 出于防止误删的目的,Pigsty 的 ETCD 模块提供了防误删保险,由 etcd_safeguard 参数控制,默认为 false,即默认不打开防误删保护。
对于生产环境已经初始化好的 etcd 集群,建议打开防误删保护,避免误删现有的 etcd 实例:
etcd :
hosts :
10.10.10.10 : { etcd_seq : 1 }
10.10.10.11 : { etcd_seq : 2 }
10.10.10.12 : { etcd_seq : 3 }
vars :
etcd_cluster : etcd
etcd_safeguard : true # 打开防误删保护
当 etcd_safeguard 设置为 true 时,etcd-rm.yml 剧本会检测到存活的 etcd 实例并主动中止,避免误删。您可以使用命令行参数来覆盖这一行为:
./etcd-rm.yml -e etcd_safeguard = false # 强制覆盖防误删保险
除非您清楚地知道自己在做什么,我们并不建议用户随意清理 Etcd 集群。
14.5 - 监控告警 etcd 监控面板,指标,以及告警规则。
监控面板 ETCD 模块提供了一个监控面板:Etcd Overview。
ETCD Overview Dashboard ETCD Overview :ETCD 集群概览
这个监控面板提供了 ETCD 状态的关键信息:最值得关注的是 ETCD Aliveness,它显示了 ETCD 集群整体的服务状态。
红色的条带标识着实例不可用的时间段,而底下蓝灰色的条带标识着整个集群处于不可用的时间段。
告警规则 Pigsty 针对 Etcd 提供了以下五条预置告警规则,定义于 files/prometheus/rules/etcd.yml
EtcdServerDown:Etcd 节点宕机,严重警报EtcdNoLeader:Etcd 集群没有领导者,严重警报EtcdQuotaFull:Etcd 配额使用超过 90%,警告EtcdNetworkPeerRTSlow:Etcd 网络时延缓慢,提醒EtcdWalFsyncSlow:Etcd 磁盘刷盘缓慢,提醒#==============================================================#
# Aliveness #
#==============================================================#
# etcd server instance down
- alert : EtcdServerDown
expr : etcd_up < 1
for : 1m
labels : { level: 0, severity: CRIT, category : etcd }
annotations :
summary : "CRIT EtcdServerDown {{ $labels.ins }}@{{ $labels.instance }}"
description : |
etcd_up[ins={{ $labels.ins }}, instance={{ $labels.instance }}] = {{ $value }} < 1
http://g.pigsty/d/etcd-overview
#==============================================================#
# Error #
#==============================================================#
# Etcd no Leader triggers a P0 alert immediately
# if dcs_failsafe mode is not enabled, this may lead to global outage
- alert : EtcdNoLeader
expr : min(etcd_server_has_leader) by (cls) < 1
for : 15s
labels : { level: 0, severity: CRIT, category : etcd }
annotations :
summary : "CRIT EtcdNoLeader: {{ $labels.cls }} {{ $value }}"
description : |
etcd_server_has_leader[cls={{ $labels.cls }}] = {{ $value }} < 1
http://g.pigsty/d/etcd-overview?from=now-5m&to=now&var-cls={{$labels.cls}}
#==============================================================#
# Saturation #
#==============================================================#
- alert : EtcdQuotaFull
expr : etcd:cls:quota_usage > 0.90
for : 1m
labels : { level: 1, severity: WARN, category : etcd }
annotations :
summary : "WARN EtcdQuotaFull: {{ $labels.cls }}"
description : |
etcd:cls:quota_usage[cls={{ $labels.cls }}] = {{ $value | printf "%.3f" }} > 90%
#==============================================================#
# Latency #
#==============================================================#
# etcd network peer rt p95 > 200ms for 1m
- alert : EtcdNetworkPeerRTSlow
expr : etcd:ins:network_peer_rt_p95_5m > 0.200
for : 1m
labels : { level: 2, severity: INFO, category : etcd }
annotations :
summary : "INFO EtcdNetworkPeerRTSlow: {{ $labels.cls }} {{ $labels.ins }}"
description : |
etcd:ins:network_peer_rt_p95_5m[cls={{ $labels.cls }}, ins={{ $labels.ins }}] = {{ $value }} > 200ms
http://g.pigsty/d/etcd-instance?from=now-10m&to=now&var-cls={{ $labels.cls }}
# Etcd wal fsync rt p95 > 50ms
- alert : EtcdWalFsyncSlow
expr : etcd:ins:wal_fsync_rt_p95_5m > 0.050
for : 1m
labels : { level: 2, severity: INFO, category : etcd }
annotations :
summary : "INFO EtcdWalFsyncSlow: {{ $labels.cls }} {{ $labels.ins }}"
description : |
etcd:ins:wal_fsync_rt_p95_5m[cls={{ $labels.cls }}, ins={{ $labels.ins }}] = {{ $value }} > 50ms
http://g.pigsty/d/etcd-instance?from=now-10m&to=now&var-cls={{ $labels.cls }}
14.6 - 指标列表 Pigsty ETCD 模块提供的完整监控指标列表与释义
ETCD 模块包含有 177 类可用监控指标。
Metric Name Type Labels Description etcd:ins:backend_commit_rt_p99_5m Unknown cls, ins, instance, job, ipN/A etcd:ins:disk_fsync_rt_p99_5m Unknown cls, ins, instance, job, ipN/A etcd:ins:network_peer_rt_p99_1m Unknown cls, To, ins, instance, job, ipN/A etcd_cluster_version gauge cls, cluster_version, ins, instance, job, ipWhich version is running. 1 for ‘cluster_version’ label with current cluster version etcd_debugging_auth_revision gauge cls, ins, instance, job, ipThe current revision of auth store. etcd_debugging_disk_backend_commit_rebalance_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_disk_backend_commit_rebalance_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_disk_backend_commit_rebalance_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_disk_backend_commit_spill_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_disk_backend_commit_spill_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_disk_backend_commit_spill_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_disk_backend_commit_write_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_disk_backend_commit_write_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_disk_backend_commit_write_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_lease_granted_total counter cls, ins, instance, job, ipThe total number of granted leases. etcd_debugging_lease_renewed_total counter cls, ins, instance, job, ipThe number of renewed leases seen by the leader. etcd_debugging_lease_revoked_total counter cls, ins, instance, job, ipThe total number of revoked leases. etcd_debugging_lease_ttl_total_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_lease_ttl_total_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_lease_ttl_total_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_mvcc_compact_revision gauge cls, ins, instance, job, ipThe revision of the last compaction in store. etcd_debugging_mvcc_current_revision gauge cls, ins, instance, job, ipThe current revision of store. etcd_debugging_mvcc_db_compaction_keys_total counter cls, ins, instance, job, ipTotal number of db keys compacted. etcd_debugging_mvcc_db_compaction_last gauge cls, ins, instance, job, ipThe unix time of the last db compaction. Resets to 0 on start. etcd_debugging_mvcc_db_compaction_pause_duration_milliseconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_mvcc_db_compaction_pause_duration_milliseconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_mvcc_db_compaction_pause_duration_milliseconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_mvcc_db_compaction_total_duration_milliseconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_mvcc_db_compaction_total_duration_milliseconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_mvcc_db_compaction_total_duration_milliseconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_mvcc_events_total counter cls, ins, instance, job, ipTotal number of events sent by this member. etcd_debugging_mvcc_index_compaction_pause_duration_milliseconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_mvcc_index_compaction_pause_duration_milliseconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_mvcc_index_compaction_pause_duration_milliseconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_mvcc_keys_total gauge cls, ins, instance, job, ipTotal number of keys. etcd_debugging_mvcc_pending_events_total gauge cls, ins, instance, job, ipTotal number of pending events to be sent. etcd_debugging_mvcc_range_total counter cls, ins, instance, job, ipTotal number of ranges seen by this member. etcd_debugging_mvcc_slow_watcher_total gauge cls, ins, instance, job, ipTotal number of unsynced slow watchers. etcd_debugging_mvcc_total_put_size_in_bytes gauge cls, ins, instance, job, ipThe total size of put kv pairs seen by this member. etcd_debugging_mvcc_watch_stream_total gauge cls, ins, instance, job, ipTotal number of watch streams. etcd_debugging_mvcc_watcher_total gauge cls, ins, instance, job, ipTotal number of watchers. etcd_debugging_server_lease_expired_total counter cls, ins, instance, job, ipThe total number of expired leases. etcd_debugging_snap_save_marshalling_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_snap_save_marshalling_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_snap_save_marshalling_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_snap_save_total_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_debugging_snap_save_total_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_debugging_snap_save_total_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_debugging_store_expires_total counter cls, ins, instance, job, ipTotal number of expired keys. etcd_debugging_store_reads_total counter cls, action, ins, instance, job, ipTotal number of reads action by (get/getRecursive), local to this member. etcd_debugging_store_watch_requests_total counter cls, ins, instance, job, ipTotal number of incoming watch requests (new or reestablished). etcd_debugging_store_watchers gauge cls, ins, instance, job, ipCount of currently active watchers. etcd_debugging_store_writes_total counter cls, action, ins, instance, job, ipTotal number of writes (e.g. set/compareAndDelete) seen by this member. etcd_disk_backend_commit_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_disk_backend_commit_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_disk_backend_commit_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_disk_backend_defrag_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_disk_backend_defrag_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_disk_backend_defrag_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_disk_backend_snapshot_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_disk_backend_snapshot_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_disk_backend_snapshot_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_disk_defrag_inflight gauge cls, ins, instance, job, ipWhether or not defrag is active on the member. 1 means active, 0 means not. etcd_disk_wal_fsync_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_disk_wal_fsync_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_disk_wal_fsync_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_disk_wal_write_bytes_total gauge cls, ins, instance, job, ipTotal number of bytes written in WAL. etcd_grpc_proxy_cache_hits_total gauge cls, ins, instance, job, ipTotal number of cache hits etcd_grpc_proxy_cache_keys_total gauge cls, ins, instance, job, ipTotal number of keys/ranges cached etcd_grpc_proxy_cache_misses_total gauge cls, ins, instance, job, ipTotal number of cache misses etcd_grpc_proxy_events_coalescing_total counter cls, ins, instance, job, ipTotal number of events coalescing etcd_grpc_proxy_watchers_coalescing_total gauge cls, ins, instance, job, ipTotal number of current watchers coalescing etcd_mvcc_db_open_read_transactions gauge cls, ins, instance, job, ipThe number of currently open read transactions etcd_mvcc_db_total_size_in_bytes gauge cls, ins, instance, job, ipTotal size of the underlying database physically allocated in bytes. etcd_mvcc_db_total_size_in_use_in_bytes gauge cls, ins, instance, job, ipTotal size of the underlying database logically in use in bytes. etcd_mvcc_delete_total counter cls, ins, instance, job, ipTotal number of deletes seen by this member. etcd_mvcc_hash_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_mvcc_hash_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_mvcc_hash_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_mvcc_hash_rev_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_mvcc_hash_rev_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_mvcc_hash_rev_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_mvcc_put_total counter cls, ins, instance, job, ipTotal number of puts seen by this member. etcd_mvcc_range_total counter cls, ins, instance, job, ipTotal number of ranges seen by this member. etcd_mvcc_txn_total counter cls, ins, instance, job, ipTotal number of txns seen by this member. etcd_network_active_peers gauge cls, ins, Local, instance, job, ip, RemoteThe current number of active peer connections. etcd_network_client_grpc_received_bytes_total counter cls, ins, instance, job, ipThe total number of bytes received from grpc clients. etcd_network_client_grpc_sent_bytes_total counter cls, ins, instance, job, ipThe total number of bytes sent to grpc clients. etcd_network_peer_received_bytes_total counter cls, ins, instance, job, ip, FromThe total number of bytes received from peers. etcd_network_peer_round_trip_time_seconds_bucket Unknown cls, To, ins, instance, job, le, ipN/A etcd_network_peer_round_trip_time_seconds_count Unknown cls, To, ins, instance, job, ipN/A etcd_network_peer_round_trip_time_seconds_sum Unknown cls, To, ins, instance, job, ipN/A etcd_network_peer_sent_bytes_total counter cls, To, ins, instance, job, ipThe total number of bytes sent to peers. etcd_server_apply_duration_seconds_bucket Unknown cls, version, ins, instance, job, le, success, ip, opN/A etcd_server_apply_duration_seconds_count Unknown cls, version, ins, instance, job, success, ip, opN/A etcd_server_apply_duration_seconds_sum Unknown cls, version, ins, instance, job, success, ip, opN/A etcd_server_client_requests_total counter client_api_version, cls, ins, instance, type, job, ipThe total number of client requests per client version. etcd_server_go_version gauge cls, ins, instance, job, server_go_version, ipWhich Go version server is running with. 1 for ‘server_go_version’ label with current version. etcd_server_has_leader gauge cls, ins, instance, job, ipWhether or not a leader exists. 1 is existence, 0 is not. etcd_server_health_failures counter cls, ins, instance, job, ipThe total number of failed health checks etcd_server_health_success counter cls, ins, instance, job, ipThe total number of successful health checks etcd_server_heartbeat_send_failures_total counter cls, ins, instance, job, ipThe total number of leader heartbeat send failures (likely overloaded from slow disk). etcd_server_id gauge cls, ins, instance, job, server_id, ipServer or member ID in hexadecimal format. 1 for ‘server_id’ label with current ID. etcd_server_is_leader gauge cls, ins, instance, job, ipWhether or not this member is a leader. 1 if is, 0 otherwise. etcd_server_is_learner gauge cls, ins, instance, job, ipWhether or not this member is a learner. 1 if is, 0 otherwise. etcd_server_leader_changes_seen_total counter cls, ins, instance, job, ipThe number of leader changes seen. etcd_server_learner_promote_successes counter cls, ins, instance, job, ipThe total number of successful learner promotions while this member is leader. etcd_server_proposals_applied_total gauge cls, ins, instance, job, ipThe total number of consensus proposals applied. etcd_server_proposals_committed_total gauge cls, ins, instance, job, ipThe total number of consensus proposals committed. etcd_server_proposals_failed_total counter cls, ins, instance, job, ipThe total number of failed proposals seen. etcd_server_proposals_pending gauge cls, ins, instance, job, ipThe current number of pending proposals to commit. etcd_server_quota_backend_bytes gauge cls, ins, instance, job, ipCurrent backend storage quota size in bytes. etcd_server_read_indexes_failed_total counter cls, ins, instance, job, ipThe total number of failed read indexes seen. etcd_server_slow_apply_total counter cls, ins, instance, job, ipThe total number of slow apply requests (likely overloaded from slow disk). etcd_server_slow_read_indexes_total counter cls, ins, instance, job, ipThe total number of pending read indexes not in sync with leader’s or timed out read index requests. etcd_server_snapshot_apply_in_progress_total gauge cls, ins, instance, job, ip1 if the server is applying the incoming snapshot. 0 if none. etcd_server_version gauge cls, server_version, ins, instance, job, ipWhich version is running. 1 for ‘server_version’ label with current version. etcd_snap_db_fsync_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_snap_db_fsync_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_snap_db_fsync_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_snap_db_save_total_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_snap_db_save_total_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_snap_db_save_total_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_snap_fsync_duration_seconds_bucket Unknown cls, ins, instance, job, le, ipN/A etcd_snap_fsync_duration_seconds_count Unknown cls, ins, instance, job, ipN/A etcd_snap_fsync_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A etcd_up Unknown cls, ins, instance, job, ipN/A go_gc_duration_seconds summary cls, ins, instance, quantile, job, ipA summary of the pause duration of garbage collection cycles. go_gc_duration_seconds_count Unknown cls, ins, instance, job, ipN/A go_gc_duration_seconds_sum Unknown cls, ins, instance, job, ipN/A go_goroutines gauge cls, ins, instance, job, ipNumber of goroutines that currently exist. go_info gauge cls, version, ins, instance, job, ipInformation about the Go environment. go_memstats_alloc_bytes gauge cls, ins, instance, job, ipNumber of bytes allocated and still in use. go_memstats_alloc_bytes_total counter cls, ins, instance, job, ipTotal number of bytes allocated, even if freed. go_memstats_buck_hash_sys_bytes gauge cls, ins, instance, job, ipNumber of bytes used by the profiling bucket hash table. go_memstats_frees_total counter cls, ins, instance, job, ipTotal number of frees. go_memstats_gc_cpu_fraction gauge cls, ins, instance, job, ipThe fraction of this program’s available CPU time used by the GC since the program started. go_memstats_gc_sys_bytes gauge cls, ins, instance, job, ipNumber of bytes used for garbage collection system metadata. go_memstats_heap_alloc_bytes gauge cls, ins, instance, job, ipNumber of heap bytes allocated and still in use. go_memstats_heap_idle_bytes gauge cls, ins, instance, job, ipNumber of heap bytes waiting to be used. go_memstats_heap_inuse_bytes gauge cls, ins, instance, job, ipNumber of heap bytes that are in use. go_memstats_heap_objects gauge cls, ins, instance, job, ipNumber of allocated objects. go_memstats_heap_released_bytes gauge cls, ins, instance, job, ipNumber of heap bytes released to OS. go_memstats_heap_sys_bytes gauge cls, ins, instance, job, ipNumber of heap bytes obtained from system. go_memstats_last_gc_time_seconds gauge cls, ins, instance, job, ipNumber of seconds since 1970 of last garbage collection. go_memstats_lookups_total counter cls, ins, instance, job, ipTotal number of pointer lookups. go_memstats_mallocs_total counter cls, ins, instance, job, ipTotal number of mallocs. go_memstats_mcache_inuse_bytes gauge cls, ins, instance, job, ipNumber of bytes in use by mcache structures. go_memstats_mcache_sys_bytes gauge cls, ins, instance, job, ipNumber of bytes used for mcache structures obtained from system. go_memstats_mspan_inuse_bytes gauge cls, ins, instance, job, ipNumber of bytes in use by mspan structures. go_memstats_mspan_sys_bytes gauge cls, ins, instance, job, ipNumber of bytes used for mspan structures obtained from system. go_memstats_next_gc_bytes gauge cls, ins, instance, job, ipNumber of heap bytes when next garbage collection will take place. go_memstats_other_sys_bytes gauge cls, ins, instance, job, ipNumber of bytes used for other system allocations. go_memstats_stack_inuse_bytes gauge cls, ins, instance, job, ipNumber of bytes in use by the stack allocator. go_memstats_stack_sys_bytes gauge cls, ins, instance, job, ipNumber of bytes obtained from system for stack allocator. go_memstats_sys_bytes gauge cls, ins, instance, job, ipNumber of bytes obtained from system. go_threads gauge cls, ins, instance, job, ipNumber of OS threads created. grpc_server_handled_total counter cls, ins, instance, grpc_code, job, grpc_method, grpc_type, ip, grpc_serviceTotal number of RPCs completed on the server, regardless of success or failure. grpc_server_msg_received_total counter cls, ins, instance, job, grpc_type, grpc_method, ip, grpc_serviceTotal number of RPC stream messages received on the server. grpc_server_msg_sent_total counter cls, ins, instance, job, grpc_type, grpc_method, ip, grpc_serviceTotal number of gRPC stream messages sent by the server. grpc_server_started_total counter cls, ins, instance, job, grpc_type, grpc_method, ip, grpc_serviceTotal number of RPCs started on the server. os_fd_limit gauge cls, ins, instance, job, ipThe file descriptor limit. os_fd_used gauge cls, ins, instance, job, ipThe number of used file descriptors. process_cpu_seconds_total counter cls, ins, instance, job, ipTotal user and system CPU time spent in seconds. process_max_fds gauge cls, ins, instance, job, ipMaximum number of open file descriptors. process_open_fds gauge cls, ins, instance, job, ipNumber of open file descriptors. process_resident_memory_bytes gauge cls, ins, instance, job, ipResident memory size in bytes. process_start_time_seconds gauge cls, ins, instance, job, ipStart time of the process since unix epoch in seconds. process_virtual_memory_bytes gauge cls, ins, instance, job, ipVirtual memory size in bytes. process_virtual_memory_max_bytes gauge cls, ins, instance, job, ipMaximum amount of virtual memory available in bytes. promhttp_metric_handler_requests_in_flight gauge cls, ins, instance, job, ipCurrent number of scrapes being served. promhttp_metric_handler_requests_total counter cls, ins, instance, job, ip, codeTotal number of scrapes by HTTP status code. scrape_duration_seconds Unknown cls, ins, instance, job, ipN/A scrape_samples_post_metric_relabeling Unknown cls, ins, instance, job, ipN/A scrape_samples_scraped Unknown cls, ins, instance, job, ipN/A scrape_series_added Unknown cls, ins, instance, job, ipN/A up Unknown cls, ins, instance, job, ipN/A
14.7 - 常见问题 Pigsty etcd 模块常见问题答疑
etcd集群起什么作用? etcd 是一个分布式的、可靠的键-值存储,用于存放系统中最为关键的数据,Pigsty 使用 etcd 作为 Patroni 的 DCS(分布式配置存储)服务,用于存储 PostgreSQL 集群的高可用状态信息。
Patroni 将通过 etcd,实现集群故障检测、自动故障转移、主从切换,集群配置管理等功能。
etcd 对于 PostgreSQL 集群的高可用至关重要,而 etcd 本身的可用性与容灾,是通过使用多个分布式的节点来保证的。
etcd集群使用多大规模合适? 如果超过集群成员数一半(包括正好一半)的 etcd 实例不可用,那么 etcd 集群将进入不可用状态,拒绝对外提供服务。
例如:使用 3 节点的 etcd 集群允许最多一个节点宕机,而其他两个节点仍然可以正常工作;而使用 5 节点的 etcd 集群则可以容忍 2 节点失效。
请注意,etcd 集群中的 学习者 (Learner)实例不计入成员数,因此在 3 节点 etcd 集群中,如果有一个学习者实例,那么实际上成员数量为 2,不能容忍任一节点失效。
在生产环境中,我们建议使用奇数个 etcd 实例,对于生产环境,建议使用 3 节点或 5 节点的 etcd 集群部署以确保足够的可靠性。
etcd集群不可用会有什么影响? 如果 etcd 集群不可用,那么会影响 PostgreSQL 的管控平面,但不会影响数据平面 —— 现有的 PostgreSQL 集群将继续运行,但通过 Patroni 进行的管理操作将无法执行。
etcd 故障期间,PostgreSQL 高可用将无法实现自动故障转移,您也无法使用 patronictl 对 PostgreSQL 集群发起管理操作,例如修改配置,执行手动故障转移等。
通过 Ansible 发起的管理命令不受 etcd 故障影响:例如创建数据库,创建用户,刷新 HBA 与 Service 配置等,etcd 故障期间,您依然可以直接操作 PostgreSQL 集群来实现这些功能。
请注意,以上描述的行为仅适用于较新版本的 Patroni (>=3.0,对应 Pigsty >= 2.0)。如果您使用的是较老版本的 Patroni (<3.0,对应 Pigsty 版本为 1.x),则 etcd / consul 故障会引发极为严重的全局性影响:
所有 PostgreSQL 集群将发生降级:主库将降级为从库,拒绝写请求,etcd 故障将放大为全局性 PostgreSQL 故障。在 Patroni 3.0 引入 DCS Failsafe 功能后,这种情况得到了显著改善。
etcd集群中存储着什么数据? 在 Pigsty 中,etcd 仅用于 PostgreSQL 高可用,并不会用于存储任何其他配置或状态数据。
而 PG 高可用组件 Patroni 会自动生成并管理 etcd 中的数据,当这些数据在 etcd 中丢失时,Patroni 会自动重建。
因此默认情况下,Pigsty 中的 etcd 可以视作 “无状态服务”,可以进行销毁与重建,这为维护工作带来了极大的便利。
如果您将 etcd 用于其他目的,例如作为 Kubernetes 的元数据存储,或自行存储其他数据,那么您需要自行备份 etcd 数据,并在 etcd 集群恢复后进行数据恢复。
如何从etcd故障中恢复? 因为 Pigsty 中的 etcd 只用于 PostgreSQL 高可用,本质上是可销毁、可重建的 “无状态服务”,因此在出现故障时,您可以通过 “重启” / “重置” 来进行快速止血。
要 重启 etcd 集群,您可以使用以下 Ansible 命令:
./etcd.yml -t etcd_launch
要 重置 etcd 集群,您可以直接执行以下剧本,实现覆盖抹除式重装:
如果您自行使用 etcd 存储了其他数据,那么通常需要备份 etcd 数据,并在 etcd 集群恢复后进行数据恢复。
维护etcd有什么注意事项? 简单的版本是:不要写爆 etcd 就好 。
Pigsty v2.6+ 默认启用了 etcd 自动压实(Auto Compact)和 16GB 的后端存储配额,通常无需担心写满 etcd 的问题。
etcd 的数据模型 使得每一次写入都会产生一个新的版本。
因此如果您的 etcd 集群频繁写入,即使只有极个别的 Key,etcd 数据库的大小也可能会不断增长。
当达到容量上限时,etcd 将会拒绝写入请求,这可能导致依赖 etcd 的 PostgreSQL 高可用机制无法正常工作。
Pigsty 默认的 etcd 配置已包含以下优化:
auto-compaction-mode : periodic # 周期性自动压缩
auto-compaction-retention : "24h" # 保留 24 小时历史
quota-backend-bytes : 17179869184 # 16 GiB 配额
更多维护细节请阅读 etcd 官方文档维护指南 。
提示
对于 Pigsty v2.6 之前的版本,请参照下面的说明手动启用 etcd 自动垃圾回收。
如何启动etcd自动垃圾回收? 如果您使用的早先版本的 Pigsty (v2.0 - v2.5),我们强烈建议您通过以下步骤,在生产环境中启用 etcd 的自动压实功能,从而避免 etcd 容量配额写满导致的 etcd 不可用故障。
在 Pigsty 源码目录中,编辑 etcd 配置文件模板:roles/etcd/templates/etcd.conf.j2 ,添加以下三条配置项:
auto-compaction-mode : periodic
auto-compaction-retention : "24h"
quota-backend-bytes : 17179869184
然后将所有相关 PostgreSQL 集群设置为 维护模式 后,重新使用 ./etcd.yml 覆盖部署 etcd 集群即可。
该配置会将 etcd 默认的容量配额从 2 GiB 提高到 16 GiB,并确保只保留最近一天的写入历史版本,从而避免了 etcd 数据库大小的无限增长。
etcd中的PostgreSQL高可用数据存储在哪里? 默认情况下,Patroni 使用 pg_namespace 指定的前缀(默认为 /pg)作为所有元数据键的前缀,随后是 PostgreSQL 集群名称。
例如,名为 pg-meta 的 PG 集群,其元数据键将存储在 /pg/pg-meta 下。
etcdctl get /pg/pg-meta --prefix
其中的数据样本如下所示:
/pg/pg-meta/config
{ "ttl" :30,"loop_wait" :10,"retry_timeout" :10,"primary_start_timeout" :10,"maximum_lag_on_failover" :1048576,"maximum_lag_on_syncnode" :-1,"primary_stop_timeout" :30,"synchronous_mode" :false,"synchronous_mode_strict" :false,"failsafe_mode" :true,"pg_version" :16,"pg_cluster" :"pg-meta" ,"pg_shard" :"pg-meta" ,"pg_group" :0,"postgresql" :{ "use_slots" :true,"use_pg_rewind" :true,"remove_data_directory_on_rewind_failure" :true,"parameters" :{ "max_connections" :100,"superuser_reserved_connections" :10,"max_locks_per_transaction" :200,"max_prepared_transactions" :0,"track_commit_timestamp" :"on" ,"wal_level" :"logical" ,"wal_log_hints" :"on" ,"max_worker_processes" :16,"max_wal_senders" :50,"max_replication_slots" :50,"password_encryption" :"scram-sha-256" ,"ssl" :"on" ,"ssl_cert_file" :"/pg/cert/server.crt" ,"ssl_key_file" :"/pg/cert/server.key" ,"ssl_ca_file" :"/pg/cert/ca.crt" ,"shared_buffers" :"7969MB" ,"maintenance_work_mem" :"1993MB" ,"work_mem" :"79MB" ,"max_parallel_workers" :8,"max_parallel_maintenance_workers" :2,"max_parallel_workers_per_gather" :0,"hash_mem_multiplier" :8.0,"huge_pages" :"try" ,"temp_file_limit" :"7GB" ,"vacuum_cost_delay" :"20ms" ,"vacuum_cost_limit" :2000,"bgwriter_delay" :"10ms" ,"bgwriter_lru_maxpages" :800,"bgwriter_lru_multiplier" :5.0,"min_wal_size" :"7GB" ,"max_wal_size" :"28GB" ,"max_slot_wal_keep_size" :"42GB" ,"wal_buffers" :"16MB" ,"wal_writer_delay" :"20ms" ,"wal_writer_flush_after" :"1MB" ,"commit_delay" :20,"commit_siblings" :10,"checkpoint_timeout" :"15min" ,"checkpoint_completion_target" :0.8,"archive_mode" :"on" ,"archive_timeout" :300,"archive_command" :"pgbackrest --stanza=pg-meta archive-push %p" ,"max_standby_archive_delay" :"10min" ,"max_standby_streaming_delay" :"3min" ,"wal_receiver_status_interval" :"1s" ,"hot_standby_feedback" :"on" ,"wal_receiver_timeout" :"60s" ,"max_logical_replication_workers" :8,"max_sync_workers_per_subscription" :6,"random_page_cost" :1.1,"effective_io_concurrency" :1000,"effective_cache_size" :"23907MB" ,"default_statistics_target" :200,"log_destination" :"csvlog" ,"logging_collector" :"on" ,"log_directory" :"/pg/log/postgres" ,"log_filename" :"postgresql-%Y-%m-%d.log" ,"log_checkpoints" :"on" ,"log_lock_waits" :"on" ,"log_replication_commands" :"on" ,"log_statement" :"ddl" ,"log_min_duration_statement" :100,"track_io_timing" :"on" ,"track_functions" :"all" ,"track_activity_query_size" :8192,"log_autovacuum_min_duration" :"1s" ,"autovacuum_max_workers" :2,"autovacuum_naptime" :"1min" ,"autovacuum_vacuum_cost_delay" :-1,"autovacuum_vacuum_cost_limit" :-1,"autovacuum_freeze_max_age" :1000000000,"deadlock_timeout" :"50ms" ,"idle_in_transaction_session_timeout" :"10min" ,"shared_preload_libraries" :"timescaledb, pg_stat_statements, auto_explain" ,"auto_explain.log_min_duration" :"1s" ,"auto_explain.log_analyze" :"on" ,"auto_explain.log_verbose" :"on" ,"auto_explain.log_timing" :"on" ,"auto_explain.log_nested_statements" :true,"pg_stat_statements.max" :5000,"pg_stat_statements.track" :"all" ,"pg_stat_statements.track_utility" :"off" ,"pg_stat_statements.track_planning" :"off" ,"timescaledb.telemetry_level" :"off" ,"timescaledb.max_background_workers" :8,"citus.node_conninfo" :"sslm
ode=prefer" }}}
/pg/pg-meta/failsafe
{ "pg-meta-2" :"http://10.10.10.11:8008/patroni" ,"pg-meta-1" :"http://10.10.10.10:8008/patroni" }
/pg/pg-meta/initialize
7418384210787662172
/pg/pg-meta/leader
pg-meta-1
/pg/pg-meta/members/pg-meta-1
{ "conn_url" :"postgres://10.10.10.10:5432/postgres" ,"api_url" :"http://10.10.10.10:8008/patroni" ,"state" :"running" ,"role" :"primary" ,"version" :"4.0.1" ,"tags" :{ "clonefrom" :true,"version" :"16" ,"spec" :"8C.32G.125G" ,"conf" :"tiny.yml" } ,"xlog_location" :184549376,"timeline" :1}
/pg/pg-meta/members/pg-meta-2
{ "conn_url" :"postgres://10.10.10.11:5432/postgres" ,"api_url" :"http://10.10.10.11:8008/patroni" ,"state" :"running" ,"role" :"replica" ,"version" :"4.0.1" ,"tags" :{ "clonefrom" :true,"version" :"16" ,"spec" :"8C.32G.125G" ,"conf" :"tiny.yml" } ,"xlog_location" :184549376,"replication_state" :"streaming" ,"timeline" :1}
/pg/pg-meta/status
{ "optime" :184549376,"slots" :{ "pg_meta_2" :184549376,"pg_meta_1" :184549376} ,"retain_slots" :[ "pg_meta_1" ,"pg_meta_2" ]}
如何使用一个外部的已经存在的 etcd 集群? 配置清单中硬编码了所使用 etcd 的分组名为 etcd,这个分组里的成员将被用作 PGSQL 的 DCS 服务器。您可以使用 etcd.yml 对它们进行初始化,或直接假设它是一个已存在的外部 etcd 集群。
要使用现有的外部 etcd 集群,只要像往常一样定义它们即可,您可以跳过 etcd.yml 剧本的执行,因为集群已经存在,不需要部署。
但用户必须确保 现有 etcd 集群证书是由 Pigsty 使用的相同 CA 签名颁发的 。否则客户端无法使用 Pigsty 自签名 CA 颁发的证书来访问外部的 etcd 集群。
如何向现有etcd集群添加新的成员? 详细过程,请参考向 etcd 集群添加成员
推荐方式:使用便捷脚本
# 首先在配置清单中添加新成员定义,然后执行:
bin/etcd-add <ip> # 添加单个新成员
bin/etcd-add <ip1> # 添加多个新成员
手动方式:
etcdctl member add <etcd-?> --learner= true --peer-urls= https://<new_ins_ip>:2380 # 宣告新成员加入
./etcd.yml -l <new_ins_ip> -e etcd_init = existing # 初始化新成员
etcdctl member promote <new_ins_server_id> # 提升为正式成员
请注意,我们建议一次只添加一个新成员。
如何从现有etcd集群中移除成员? 详细过程,请参考从 etcd 集群中移除成员
推荐方式:使用便捷脚本
bin/etcd-rm <ip> # 移除指定成员
bin/etcd-rm # 移除整个 etcd 集群
手动方式:
./etcd-rm.yml -l <ins_ip> # 使用专用移除剧本
etcdctl member remove <etcd_server_id> # 从集群中踢出成员
./etcd-rm.yml -l <ins_ip> # 清理实例
如何配置 etcd RBAC 认证? Pigsty v4.0 默认启用 etcd 的 RBAC 认证。root 用户密码由 etcd_root_password 参数控制,默认值为 Etcd.Root。
在生产环境中,强烈建议修改默认密码 :
all :
vars :
etcd_root_password : 'YourSecurePassword'
客户端认证 :
# 在 etcd 节点上,环境变量已自动配置
source /etc/profile.d/etcdctl.sh
etcdctl member list
# 手动配置认证
export ETCDCTL_USER = "root:YourSecurePassword"
export ETCDCTL_CACERT = /etc/etcd/ca.crt
export ETCDCTL_CERT = /etc/etcd/server.crt
export ETCDCTL_KEY = /etc/etcd/server.key
更多详情请参考 RBAC 认证 。
15 - 模块:MINIO Pigsty 内置了 MinIO 支持,一个本地 S3 对象存储开源替代,可用于 PGSQL 模块冷备份存储。
MinIO 是一个兼容 AWS S3 的多云对象存储软件,使用 AGPLv3 协议开源。
MinIO 可以用来存储文档、图片、视频和备份。Pigsty 原生支持部署各种 MinIO 集群,具备原生多节点多磁盘高可用支持,易于扩展、安全且开箱即用,
并且有过 10PB+ 级别的大规模生产环境部署用例。
MinIO 是 Pigsty 中的一个 可选模块 。您可以将 MinIO 用作 PostgreSQL 备份 的可选存储仓库,作为默认本地 POSIX 文件系统仓库的补充。
如果使用 MinIO 备份仓库,MINIO 模块应在任何 PGSQL 模块之前安装。MinIO 需要受信任的 CA 证书才能工作,因此它依赖 NODE 模块。
快速开始 以下是一个最简单的 MinIO 单机单盘部署示例:
# 在配置清单中定义 MinIO 集群
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
./minio.yml -l minio # 在 minio 分组上部署 MinIO 模块
部署完成后,您可以通过以下方式访问 MinIO:
S3 API :https://sss.pigsty:9000(使用域名需要配置 DNS 解析)Web 控制台 :https://<minio-ip>:9001(默认用户名/密码:minioadmin / S3User.MinIO)命令行 :mcli ls sss/(管理节点上已预配置别名)部署模式 MinIO 支持三种主要部署模式:
模式 说明 适用场景 单机单盘 (SNSD)单节点,单个数据目录 开发、测试、演示 单机多盘 (SNMD)单节点,多块磁盘 资源受限的小规模部署 多机多盘 (MNMD)多节点,每节点多块磁盘 生产环境推荐
此外,您还可以使用多池部署 来扩容现有集群,或部署多套集群 。
核心特性 S3 兼容 :完全兼容 AWS S3 API,可与各种 S3 客户端和工具无缝集成高可用 :原生支持多节点多磁盘部署,容忍节点和磁盘故障安全 :默认启用 HTTPS 加密传输,支持服务端加密监控 :开箱即用的 Grafana 监控面板和 Prometheus 告警规则易用 :预配置的 mcli 客户端别名,一键部署和管理15.1 - 使用方法 快速上手,如何上手使用 MinIO ?如何可靠地接入 MinIO?如何使用 mc / rclone 客户端工具?
当您 配置 并执行 剧本 部署 MinIO 集群后,可以参考这里的说明开始使用与接入 MinIO 集群。
部署集群 在 Pigsty 中部署一个开箱即用的 单机单盘 MinIO 实例非常简单:首先在 配置清单 中定义一套 MinIO 集群:
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
然后,针对定义的分组(这里为 minio )执行 Pigsty 提供的 minio.yml 剧本即可:
请注意在 deploy.yml 中,事先定义好的 MinIO 集群将自动创建,无需手动再次执行 minio.yml 剧本。
如果您计划部署一个生产等级的大规模多节点 MinIO 集群,我们强烈建议您通读 Pigsty MinIO 配置文档 与 MinIO 官方文档 后再进行。
接入集群 请注意:MinIO 服务必须通过域名与 HTTPS 访问,所以请务必确保: MinIO 服务域名(默认为 sss.pigsty) 正确指向 MinIO 服务器节点
您可以在 node_etc_hosts 中添加静态解析记录,或者手工修改 /etc/hosts 文件 您可以在内网的 DNS 服务器上添加一条记录,如果已经有了现成的 DNS 服务 如果您启用了 Infra 节点上的 DNS 服务器,可以在 dns_records 中添加记录 对于生产环境访问 MinIO,通常我们建议使用第一种方式:静态 DNS 解析记录,避免 MinIO 对于 DNS 的额外依赖。
您应当将 MinIO 服务域名指向 MinIO 服务器节点的 IP 地址与服务端口,或者负载均衡器的 IP 地址与服务端口。
Pigsty 默认使用的 MinIO 服务域名是 sss.pigsty,在单机部署时默认指向本机,在 9000 端口提供服务。
在一些例子中,MinIO 集群上还部署了 HAProxy 实例对外暴露服务,在这种情况下,9002 是模板中使用的服务端口。
添加别名 要使用 mcli 客户端访问 minio 服务器集群,首先要配置服务器的别名(alias):
mcli alias ls # 列出 minio 别名(默认使用sss)
mcli alias set sss https://sss.pigsty:9000 minioadmin S3User.MinIO # root 用户
mcli alias set sss https://sss.pigsty:9002 minioadmin S3User.MinIO # root 用户,使用负载均衡器 9002 端口
mcli alias set pgbackrest https://sss.pigsty:9000 pgbackrest S3User.Backup # 使用备份用户
在管理节点的管理用户上,已经默认配置了名为 sss 的 MinIO 别名,可以直接使用。
MinIO 客户端工具 mcli 的完整功能参考,请查阅文档: MinIO 客户端 。
注意:请使用您实际配置的密码
上述示例中的密码 S3User.MinIO 是 Pigsty 的默认值。如果您在部署时修改了 minio_secret_key ,请使用您实际配置的密码。
用户管理 使用 mcli 可以管理 MinIO 中的业务用户,例如这里我们可以使用命令行创建两个业务用户:
mcli admin user list sss # 列出 sss 上的所有用户
set +o history # 在历史记录中隐藏密码并创建 minio 用户
mcli admin user add sss dba S3User.DBA
mcli admin user add sss pgbackrest S3User.Backup
set -o history
存储桶管理 您可以对MinIO中的存储桶进行增删改查 :
mcli ls sss/ # 列出别名 'sss' 的所有桶
mcli mb --ignore-existing sss/hello # 创建名为 'hello' 的桶
mcli rb --force sss/hello # 强制删除 'hello' 桶
对象管理 您也可以对存储桶内的对象进行增删改查 ,详情请参考官方文档:对象管理
mcli cp /www/pigsty/* sss/infra/ # 将本地软件源的内容上传到 MinIO 的 infra 桶中
mcli cp sss/infra/plugins.tgz /tmp/ # 从 minio 下载文件到本地
mcli ls sss/infra # 列出 infra 桶中的所有文件
mcli rm sss/infra/plugins.tgz # 删除 infra 桶中的特定文件
mcli cat sss/infra/repo_complete # 查看 infra 桶中的文件内容
使用rclone Pigsty 仓库中提供了 rclone , 一个方便的多云对象存储客户端,您可以使用它来访问 MinIO 服务。
yum install rclone; # EL 系列系统
apt install rclone; # Debian/Ubuntu 系统
mkdir -p ~/.config/rclone/;
tee ~/.config/rclone/rclone.conf > /dev/null <<EOF
[sss]
type = s3
access_key_id = minioadmin
secret_access_key = S3User.MinIO
endpoint = https://sss.pigsty:9000
EOF
rclone ls sss:/
注意:HTTPS 与证书信任
如果 MinIO 使用 HTTPS(默认配置),您需要确保客户端信任 Pigsty 的 CA 证书(/etc/pki/ca.crt),或者在 rclone 配置中添加 no_check_certificate = true 来跳过证书验证(不建议在生产环境使用)。
配置备份仓库 在 Pigsty 中,MinIO 默认的用例是作为 pgBackRest 的备份存储仓库。
当您修改 pgbackrest_method 为 minio 时,PGSQL 模块会自动将备份存储仓库切换到 MinIO 上。
pgbackrest_method: local # pgbackrest repo method : local,minio,[user-defined...]
pgbackrest_repo: # pgbackrest repo : https://pgbackrest.org/configuration.html#section-repository
local : # default pgbackrest repo with local posix fs
path : /pg/backup # local backup directory, `/pg/backup` by default
retention_full_type : count # retention full backups by count
retention_full : 2 # keep 2, at most 3 full backup when using local fs repo
minio : # optional minio repo for pgbackrest
type : s3 # minio is s3-compatible, so s3 is used
s3_endpoint : sss.pigsty # minio endpoint domain name, `sss.pigsty` by default
s3_region : us-east-1 # minio region, us-east-1 by default, useless for minio
s3_bucket : pgsql # minio bucket name, `pgsql` by default
s3_key : pgbackrest # minio user access key for pgbackrest
s3_key_secret : S3User.Backup # minio user secret key for pgbackrest
s3_uri_style : path # use path style uri for minio rather than host style
path : /pgbackrest # minio backup path, default is `/pgbackrest`
storage_port : 9000 # minio port, 9000 by default
storage_ca_file : /pg/cert/ca.crt # minio ca file path, `/pg/cert/ca.crt` by default
bundle : y # bundle small files into a single file
cipher_type : aes-256-cbc # enable AES encryption for remote backup repo
cipher_pass : pgBackRest # AES encryption password, default is 'pgBackRest'
retention_full_type : time # retention full backup by time on minio repo
retention_full : 14 # keep full backup for last 14 days
请注意,如果您使用了多节点部署的 MinIO 集群,并通过负载均衡器对外提供服务,您需要相应地修改这里的 s3_endpoint 与 storage_port 参数。
15.2 - 集群配置 根据需求场景选择合适的 MinIO 部署类型,并对外提供可靠的接入。
在部署 MinIO 之前,你需要在 配置清单 中定义一个 MinIO 集群,MinIO 有三种经典部署模式:
单机单盘:SNSD :单机单盘模式,可以使用任意目录作为数据盘,仅作为开发、测试、演示使用。单机多盘:SNMD :折中模式,在单台服务器上使用多块磁盘 (>=2),仅当资源极为有限时使用。多机多盘:MNMD :多机多盘模式,标准生产环境部署,具有最好的可靠性,但需要多台服务器。通常我们建议使用 SNSD 与 MNMD 这两种模式,前者用于开发测试,后者用于生产部署,SNMD 仅在资源有限(只有一台服务器)的情况下使用。
此外,还可以使用 多池部署 来实现现有 MinIO 集群的扩容,或者直接部署 多套集群 。
使用多节点 MinIO 集群时,访问任意节点都可以获取服务,因此最佳实践是在 MinIO 集群前使用负载均衡与高可用服务接入机制 。
核心参数 MinIO 部署中,MINIO_VOLUMES 是一个核心配置参数,用于指定 MinIO 的部署模式。
Pigsty 提供了一些便捷的参数用于自动根据配置清单,生成 MINIO_VOLUMES 与其他配置参数的值,但您也可以直接指定它们。
单机单盘: MINIO_VOLUMES 指向本机上的一个普通目录,默认由 minio_data 指定,默认位置为 /data/minio。 单机多盘: MINIO_VOLUMES 指向本机上的序列挂载点,同样是由 minio_data 指定,但需要用特殊语法显式覆盖指定真实挂载点,例如 /data{1...4}。 多机多盘: MINIO_VOLUMES 指向多台服务器上的序列挂载点,由以下两部分自动组合生成:首先要使用 minio_data 指定集群每个成员的磁盘挂载点序列 /data{1...4}, 还需要使用 minio_node 指定节点的命名模式 ${minio_cluster}-${minio_seq}.pigsty 多池部署: 您需要显式指定 minio_volumes 参数来分配每个存储池的节点,从而实现集群扩容 单机单盘 SNSD 模式,部署参考教程:MinIO 单机单盘部署
在 Pigsty 中,定义一个单例 MinIO 实例非常简单:
# 1 节点 1 驱动器(默认)
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
单机模式下,唯一必要的参数是 minio_seq 和 minio_cluster ,它们会唯一标识每一个 MinIO 实例。
单节点单磁盘模式仅用于开发目的,因此您可以使用一个普通的目录作为数据目录,该目录由参数 minio_data 默认为 /data/minio。
在您使用 MinIO 时,强烈建议您通过静态解析的域名记录访问 MinIO,例如,假设 minio_domain 设置的内部服务域名使用了默认的 sss.pigsty,
那么您可以在所有节点上添加一个静态解析,便于其他节点访问此服务。
node_etc_hosts : [ "10.10.10.10 sss.pigsty" ] # domain name to access minio from all nodes (required)
SNSD 仅适用于开发测试
单节点单盘模式应当仅用于开发、测试、演示目的,因为它无法容忍任何硬件故障,也无法带来多磁盘的性能改善。生产环境请使用 多机多盘 模式。
单机多盘 SNMD 模式,部署参考教程:MinIO 单机多盘部署
要在单节点上使用多块磁盘,所需的操作与 单机单盘 基本一致,但用户需要以 {{ prefix }}{x...y} 的特定格式指定 minio_data ,该格式定义了序列磁盘挂载点。
minio :
hosts : { 10.10.10.10 : { minio_seq : 1 } }
vars :
minio_cluster : minio # minio 集群名称,默认为 minio
minio_data : '/data{1...4}' # minio 数据目录,使用 {x...y} 记号来指定多块磁盘
请使用真实磁盘挂载点
请注意,SNMD 模式不支持使用普通目录作为数据目录。如果您使用 SNMD 模式拉起 MinIO,但数据目录不是有效的磁盘挂载点,MinIO 将拒绝启动。请确保使用 XFS 格式化的真实磁盘。
例如 Vagrant MinIO 沙箱 定义了一个带有4块磁盘的单节点 MinIO 集群:/data1、/data2、/data3 和 /data4。启动 MinIO 之前,你需要正确地挂载它们(请务必使用 xfs 格式化磁盘):
mkfs.xfs /dev/vdb; mkdir /data1; mount -t xfs /dev/sdb /data1; # 挂载第1块盘……
mkfs.xfs /dev/vdc; mkdir /data2; mount -t xfs /dev/sdb /data2; # 挂载第2块盘……
mkfs.xfs /dev/vdd; mkdir /data3; mount -t xfs /dev/sdb /data3; # 挂载第3块盘……
mkfs.xfs /dev/vde; mkdir /data4; mount -t xfs /dev/sdb /data4; # 挂载第4块盘……
挂载磁盘属于服务器置备的部分,超出 Pigsty 的处理范畴。挂载的磁盘应该同时写入 /etc/fstab 以便在服务器重启后可以自动挂载。
/dev/vdb /data1 xfs defaults,noatime,nodiratime 0 0
/dev/vdc /data2 xfs defaults,noatime,nodiratime 0 0
/dev/vdd /data3 xfs defaults,noatime,nodiratime 0 0
/dev/vde /data4 xfs defaults,noatime,nodiratime 0 0
SNMD 模式可以利用单机上的多块磁盘,提供更高的性能和容量,并且容忍部分磁盘故障。
但单节点模式无法容忍整个节点的故障,而且您无法在运行时添加新的节点,因此如果没有特殊原因,我们不建议在生产环境中使用 SNMD 模式。
多机多盘 MNMD 模式,部署参考教程:MinIO 多机多盘部署
除了需要 单机多盘 模式中的 minio_data 指定磁盘驱动器,使用MinIO 多节点部署需要使用一个额外的 minio_node 参数。
例如,以下配置定义了一个 MinIO 集群,其中有四个节点,每个节点有四块磁盘:
minio :
hosts :
10.10.10.10 : { minio_seq : 1 } # 实际节点名: minio-1.pigsty
10.10.10.11 : { minio_seq : 2 } # 实际节点名: minio-2.pigsty
10.10.10.12 : { minio_seq : 3 } # 实际节点名: minio-3.pigsty
10.10.10.13 : { minio_seq : 4 } # 实际节点名: minio-4.pigsty
vars :
minio_cluster : minio
minio_data : '/data{1...4}' # 每个节点使用四块磁盘
minio_node : '${minio_cluster}-${minio_seq}.pigsty' # minio 节点名称规则
minio_node 参数指定了 MinIO 节点名称的模式,用于生成每个节点的唯一名称。
默认情况下,节点名称是 ${minio_cluster}-${minio_seq}.pigsty,其中 ${minio_cluster} 是集群名称,${minio_seq} 是节点序号。
MinIO 实例的名称非常重要,会自动写入到 MinIO 节点的 /etc/hosts 中进行静态解析。MinIO 依靠这些名称来识别并访问集群中的其他节点。
在这种情况下,MINIO_VOLUMES 将被设置为 https://minio-{1...4}.pigsty/data{1...4} ,以标识四个节点上的四块盘。
您可以直接在 MinIO 集群中指定 minio_volumes 参数,来覆盖自动根据规则生成的值。
但通常不需要这样做,因为 Pigsty 会自动根据配置清单生成它。
多池部署 MinIO 的架构允许通过添加新的存储池来扩容。在 Pigsty 中,您可以通过显式指定 minio_volumes 参数来分配每个存储池的节点,从而实现集群扩容。
例如,假设您已经创建了 多机多盘 样例中定义的 MinIO 集群,现在您想要添加一个新的存储池,同样由四个节点构成。
那么,你需要直接覆盖指定 minio_volumes 参数:
minio :
hosts :
10.10.10.10 : { minio_seq : 1 }
10.10.10.11 : { minio_seq : 2 }
10.10.10.12 : { minio_seq : 3 }
10.10.10.13 : { minio_seq : 4 }
10.10.10.14 : { minio_seq : 5 }
10.10.10.15 : { minio_seq : 6 }
10.10.10.16 : { minio_seq : 7 }
10.10.10.17 : { minio_seq : 8 }
vars :
minio_cluster : minio
minio_data : "/data{1...4}"
minio_node : '${minio_cluster}-${minio_seq}.pigsty' # minio 节点名称规则
minio_volumes : 'https://minio-{1...4}.pigsty:9000/data{1...4} https://minio-{5...8}.pigsty:9000/data{1...4}'
在这里,空格分割的两个参数分别代表两个存储池,每个存储池有四个节点,每个节点有四块磁盘。更多关于存储池的信息请参考 管理预案:MinIO集群扩容
多套集群 您可以将新的 MinIO 节点部署为一个全新的 MinIO 集群,使用不同的集群名称定义一个新的分组即可,以下配置声明了两个独立的 MinIO 集群:
minio1 :
hosts :
10.10.10.10 : { minio_seq : 1 }
10.10.10.11 : { minio_seq : 2 }
10.10.10.12 : { minio_seq : 3 }
10.10.10.13 : { minio_seq : 4 }
vars :
minio_cluster : minio2
minio_data : "/data{1...4}"
minio2 :
hosts :
10.10.10.14 : { minio_seq : 5 }
10.10.10.15 : { minio_seq : 6 }
10.10.10.16 : { minio_seq : 7 }
10.10.10.17 : { minio_seq : 8 }
vars :
minio_cluster : minio2
minio_data : "/data{1...4}"
minio_alias : sss2
minio_domain : sss2.pigsty
minio_endpoint : sss2.pigsty:9000
请注意,Pigsty 默认一套部署中只有一个 MinIO 集群,如果您需要部署多个 MinIO 集群,那么一些带有默认值的参数需要显式设置,无法省略,否则会出现命名冲突,如上所示。
服务接入 MinIO 默认使用 9000 端口提供服务。多节点 MinIO 集群可以通过访问 任意一个节点 来访问其服务。
服务接入属于 NODE 模块的功能范畴,这里仅做基本介绍。
多节点 MinIO 集群的高可用接入可以使用 L2 VIP 或 HAProxy 实现。例如,您可以选择使用 keepalived 在 MinIO 集群上绑定一个 L2 VIP ,
或者使用由 NODE 模块的提供的 haproxy 组件,通过负载均衡器对外暴露 MinIO 服务。
# minio cluster with 4 nodes and 4 drivers per node
minio :
hosts :
10.10.10.10 : { minio_seq: 1 , nodename : minio-1 }
10.10.10.11 : { minio_seq: 2 , nodename : minio-2 }
10.10.10.12 : { minio_seq: 3 , nodename : minio-3 }
10.10.10.13 : { minio_seq: 4 , nodename : minio-4 }
vars :
minio_cluster : minio
minio_data : '/data{1...4}'
minio_buckets : [ { name : pgsql }, { name: infra }, { name: redis } ]
minio_users :
- { access_key: dba , secret_key: S3User.DBA, policy : consoleAdmin }
- { access_key: pgbackrest , secret_key: S3User.SomeNewPassWord , policy : readwrite }
# bind a node l2 vip (10.10.10.9) to minio cluster (optional)
node_cluster : minio
vip_enabled : true
vip_vrid : 128
vip_address : 10.10.10.9
vip_interface : eth1
# expose minio service with haproxy on all nodes
haproxy_services :
- name : minio # [REQUIRED] service name, unique
port : 9002 # [REQUIRED] service port, unique
balance : leastconn # [OPTIONAL] load balancer algorithm
options : # [OPTIONAL] minio health check
- option httpchk
- option http-keep-alive
- http-check send meth OPTIONS uri /minio/health/live
- http-check expect status 200
servers :
- { name: minio-1 ,ip: 10.10.10.10 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-2 ,ip: 10.10.10.11 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-3 ,ip: 10.10.10.12 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-4 ,ip: 10.10.10.13 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
例如,上面的配置块为 MinIO 集群的所有节点上启用了 HAProxy ,在 9002 端口上暴露 MinIO 服务,同时为集群绑定了一个二层 VIP。
当使用时,用户应当将 sss.pigsty 域名解析指向 VIP 地址 10.10.10.9,并使用 9002 端口访问 MinIO 服务。这样当任意一个节点发生故障时,VIP 会自动切换到另一个节点,保证服务的高可用性。
在这种情况下,您通常还需要在全局修改域名解析的目的地,以及 minio_endpoint 参数,修改写入管理节点 MinIO Alias 对应的端点地址:
minio_endpoint : https://sss.pigsty:9002 # 覆盖默认值: https://sss.pigsty:9000
node_etc_hosts : [ "10.10.10.9 sss.pigsty" ] # 其他节点将使用 sss.pigsty 域名来访问 MinIO
专用负载均衡 Pigsty 允许用户使用专用的负载均衡服务器组,而不是集群本身来运行 VIP 与 HAProxy。例如 prod 模板中就使用了这种方式。
proxy :
hosts :
10.10.10.18 : { nodename: proxy1 ,node_cluster: proxy ,vip_interface: eth1 ,vip_role : master }
10.10.10.19 : { nodename: proxy2 ,node_cluster: proxy ,vip_interface: eth1 ,vip_role : backup }
vars :
vip_enabled : true
vip_address : 10.10.10.20
vip_vrid : 20
haproxy_services: # expose minio service : sss.pigsty:9000
- name : minio # [REQUIRED] service name, unique
port : 9000 # [REQUIRED] service port, unique
balance : leastconn # Use leastconn algorithm and minio health check
options : [ "option httpchk" , "option http-keep-alive" , "http-check send meth OPTIONS uri /minio/health/live" , "http-check expect status 200" ]
servers : # reload service with ./node.yml -t haproxy_config,haproxy_reload
- { name: minio-1 ,ip: 10.10.10.21 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-2 ,ip: 10.10.10.22 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-3 ,ip: 10.10.10.23 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-4 ,ip: 10.10.10.24 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-5 ,ip: 10.10.10.25 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
在这种情况下,您通常还需要在全局修改 MinIO 域名的解析,将 sss.pigsty 指向负载均衡器的地址,并修改 minio_endpoint 参数,修改写入管理节点 MinIO Alias 对应的端点地址:
minio_endpoint: https://sss.pigsty:9002 # overwrite the defaults : https://sss.pigsty:9000
node_etc_hosts : [ "10.10.10.20 sss.pigsty" ] # domain name to access minio from all nodes (required)
访问服务 如果您想要访问上面通过 HAProxy 暴露的 MinIO,以 PGSQL 备份配置为例,可以修改 pgbackrest_repo 中的配置,添加新的备份仓库定义:
# 这是新添加的 HA MinIO Repo 定义,使用此配置代替之前的单机 MinIO 配置
minio_ha :
type : s3
s3_endpoint : minio-1.pigsty # s3_endpoint 可以是任何一个负载均衡器:10.10.10.1{0,1,2},或指向任意 3 个节点的域名
s3_region : us-east-1 # 你可以使用外部域名:sss.pigsty,该域名指向任一成员(`minio_domain`)
s3_bucket : pgsql # 你可使用实例名和节点名:minio-1.pigsty minio-1.pigsty minio-1.pigsty minio-1 minio-2 minio-3
s3_key : pgbackrest # 最好为 MinIO 的 pgbackrest 用户使用专门的密码
s3_key_secret : S3User.SomeNewPassWord
s3_uri_style : path
path : /pgbackrest
storage_port : 9002 # 使用负载均衡器的端口 9002 代替默认的 9000(直接访问)
storage_ca_file : /etc/pki/ca.crt
bundle : y
cipher_type : aes-256-cbc # 在您的生产环境中最好使用新的加密密码,这里可以使用集群名作为密码的一部分。
cipher_pass : pgBackRest.With.Some.Extra.PassWord.And.Salt.${pg_cluster}
retention_full_type : time
retention_full : 14
暴露管控 MinIO 默认通过 9001 端口(由 minio_admin_port 参数指定)提供Web管控界面。
将后台管理界面暴露给外部可能存在安全隐患。如果你希望这样做,请将 MinIO 添加到 infra_portal 并刷新 Nginx 配置。
# ./infra.yml -t nginx
infra_portal :
home : { domain : h.pigsty }
grafana : { domain: g.pigsty ,endpoint : "${admin_ip}:3000" , websocket : true }
prometheus : { domain: p.pigsty ,endpoint : "${admin_ip}:9090" }
alertmanager : { domain: a.pigsty ,endpoint : "${admin_ip}:9093" }
blackbox : { endpoint : "${admin_ip}:9115" }
loki : { endpoint : "${admin_ip}:3100" }
# MinIO 管理页面需要 HTTPS / Websocket 才能工作
minio : { domain: m.pigsty ,endpoint : "10.10.10.10:9001" ,scheme: https ,websocket : true }
minio10 : { domain: m10.pigsty ,endpoint : "10.10.10.10:9001" ,scheme: https ,websocket : true }
minio11 : { domain: m11.pigsty ,endpoint : "10.10.10.11:9001" ,scheme: https ,websocket : true }
minio12 : { domain: m12.pigsty ,endpoint : "10.10.10.12:9001" ,scheme: https ,websocket : true }
minio13 : { domain: m13.pigsty ,endpoint : "10.10.10.13:9001" ,scheme: https ,websocket : true }
请注意,MinIO 管控页面需要使用 HTTPS,请 不要 在生产环境中暴露未加密的 MinIO 管控页面。
这意味着,您通常需要在您的 DNS 服务器,或者本机 /etc/hosts 中添加 m.pigsty 的解析记录,以便访问 MinIO 管控页面。
与此同时,如果您使用的是 Pigsty 自签名的 CA 而不是一个正规的公共 CA ,通常您还需要手工信任该 CA 或证书,才能跳过浏览器中的 “不安全” 提示信息。
15.3 - 参数列表 MinIO 模块提供了 21 个相关配置参数,用于定制所需的 MinIO 集群。
MinIO 是一个与 S3 兼容的对象存储服务,它被用作 PostgreSQL 的可选的集中式备份存储库。
但用户也可以将其用于其他目的,如存储文件、文档、图片和视频,作为数据湖。
参数概览 MINIO 参数组用于 MinIO 集群的部署与配置,包括身份标识、存储路径、端口、认证凭据以及存储桶和用户的置备。
MINIO_REMOVE 参数组控制 MinIO 集群的移除行为,包括防误删保险、数据清理以及软件包卸载。
其中,minio_volumes 与 minio_endpoint 为自动生成的参数,但您可以显式覆盖指定这两个参数。
默认参数 MINIO:18 个参数,定义于 roles/minio/defaults/main.yml
#-----------------------------------------------------------------
# MINIO
#-----------------------------------------------------------------
#minio_seq: 1 # minio 实例标识符,必填
minio_cluster : minio # minio 集群名称,默认为 minio
minio_user : minio # minio 操作系统用户,默认为 `minio`
minio_https : true # 是否为 MinIO 启用 HTTPS?默认为 true
minio_node : '${minio_cluster}-${minio_seq}.pigsty' # minio 节点名模式
minio_data : '/data/minio' # minio 数据目录,使用 `{x...y}` 指定多个磁盘
#minio_volumes: # minio 核心参数,如果未指定,则使用拼接生成的默认值
minio_domain : sss.pigsty # minio 外部域名,默认为 `sss.pigsty`
minio_port : 9000 # minio 服务端口,默认为 9000
minio_admin_port : 9001 # minio 控制台端口,默认为 9001
minio_access_key : minioadmin # 根访问密钥,默认为 `minioadmin`
minio_secret_key : S3User.MinIO # 根密钥,默认为 `S3User.MinIO`
minio_extra_vars : '' # minio 服务器的额外环境变量
minio_provision : true # 是否执行 minio 资源置备任务?
minio_alias : sss # minio 部署的客户端别名
#minio_endpoint: https://sss.pigsty:9000 # minio 别名对应的接入点,如果未指定,则使用拼接生成的默认值
minio_buckets : # 待创建的 minio 存储桶列表
- { name : pgsql }
- { name: meta ,versioning : true }
- { name : data }
minio_users : # 待创建的 minio 用户列表
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
MINIO_REMOVE:3 个参数,定义于 roles/minio_remove/defaults/main.yml
#-----------------------------------------------------------------
# MINIO_REMOVE
#-----------------------------------------------------------------
minio_safeguard : false # 防止意外删除?默认为 false
minio_rm_data : true # 移除时是否删除 minio 数据?默认为 true
minio_rm_pkg : false # 移除时是否卸载 minio 软件包?默认为 false
minio_seq参数名称: minio_seq, 类型: int, 层次:I
MinIO 实例标识符,必需的身份参数。没有默认值,您必须手动分配这些序列号。
通常的最佳实践是,从 1 开始分配,依次加 1,并永远不使用已经分配的序列号。
序列号与集群名称 minio_cluster 一起,唯一标识每一个 MinIO 实例(例如:minio-1)。
在多节点部署中,序列号还会用于生成节点名称,写入 /etc/hosts 文件中进行静态解析。
minio_cluster参数名称: minio_cluster, 类型: string, 层次:C
MinIO 集群名称,默认为 minio。当部署多个 MinIO 集群时,可以使用此参数进行区分。
集群名称与序列号 minio_seq 一起,唯一标识每一个 MinIO 实例。
例如,当集群名为 minio,序列号为 1 时,实例名称为 minio-1。
请注意,Pigsty 默认一套部署中只有一个 MinIO 集群。如果您需要部署多个 MinIO 集群,
需要显式设置 minio_alias 、minio_domain 、minio_endpoint 等参数以避免命名冲突。
minio_user参数名称: minio_user, 类型: username, 层次:C
MinIO 操作系统用户名,默认为 minio。
MinIO 服务将以此用户身份运行,该用户的家目录(默认为 /home/minio)中将存储 MinIO 使用的 SSL 证书(位于 ~/.minio/certs/ 目录下)。
minio_https参数名称: minio_https, 类型: bool, 层次:G/C
是否为 MinIO 服务启用 HTTPS?默认为 true,即使用 HTTPS。
请注意,pgBackREST 需要 MinIO 启用 HTTPS 才能正常工作。但如果您不使用 MinIO 进行 PostgreSQL 备份,且不需要使用 HTTPS,可以将此参数设置为 false。
启用 HTTPS 后,Pigsty 会自动为 MinIO 服务器签发 SSL 证书,证书包含 minio_domain 指定的域名以及各个节点的 IP 地址。
minio_node参数名称: minio_node, 类型: string, 层次:C
MinIO 节点名称模式,用于多节点 部署。
默认值为:${minio_cluster}-${minio_seq}.pigsty,即以实例名 + .pigsty 后缀作为默认的节点名。
在这里指定的域名模式将用于生成节点名,节点名将写入所有 MinIO 节点的 /etc/hosts 文件中。
minio_data参数名称: minio_data, 类型: path, 层次:C
MinIO 数据目录(们),默认值:/data/minio,这是单节点 部署的常见目录。
对于 多机多盘 与 单机多盘 部署,您可以使用 {x...y} 的记法来指定多个磁盘。
minio_volumes参数名称: minio_volumes, 类型: string, 层次:C
MinIO 核心参数,默认不指定留空,留空情况下,该参数会自动使用以下规则拼接生成:
minio_volumes : "{% if minio_cluster_size|int > 1 %}https://{{ minio_node|replace('${minio_cluster}', minio_cluster)|replace('${minio_seq}',minio_seq_range) }}:{{ minio_port|default(9000) }}{% endif %}{{ minio_data }}"
在单机部署(无论是单盘还是多盘)模式下,minio_volumes 直接使用 minio_data 的值,进行单机部署。 在多机部署模式下,minio_volumes 会使用 minio_node, minio_port, minio_data 参数的值生成多节点的地址,用于多机部署。 在多池部署模式下,通常需要您直接指定并覆盖 minio_volumes 的值,以指定多个节点池的地址。 指定本参数时,您需要确保使用的参数与 minio_node, minio_port, minio_data 三者匹配。
minio_domain参数名称: minio_domain, 类型: string, 层次:G
MinIO 服务域名,默认为 sss.pigsty。
客户端可以通过此域名访问 MinIO S3 服务。此名称将注册到本地 DNSMASQ,并包含在 SSL 证书的 SAN(Subject Alternative Name)字段中。
建议在 node_etc_hosts 中添加静态解析记录,将此域名指向 MinIO 服务器节点的 IP 地址(单机部署),或负载均衡器的 VIP 地址(多节点部署)。
minio_port参数名称: minio_port, 类型: port, 层次:C
MinIO 服务端口,默认为 9000。
这是 MinIO S3 API 的监听端口,客户端通过此端口访问对象存储服务。在多节点部署中,此端口也用于节点间通信。
minio_admin_port参数名称: minio_admin_port, 类型: port, 层次:C
MinIO 控制台端口,默认为 9001。
这是 MinIO 内置 Web 管理控制台的监听端口。您可以通过 https://<minio-ip>:9001 访问 MinIO 的图形化管理界面。
如果希望通过 Nginx 对外暴露 MinIO 控制台,可以将其添加到 infra_portal 中。请注意,MinIO 控制台需要使用 HTTPS 和 WebSocket。
minio_access_key参数名称: minio_access_key, 类型: username, 层次:C
根访问用户名(access key),默认为 minioadmin。
这是 MinIO 的超级管理员用户名,拥有对所有存储桶和对象的完全访问权限。建议在生产环境中修改此默认值。
minio_secret_key参数名称: minio_secret_key, 类型: password, 层次:C
根访问密钥(secret key),默认为 S3User.MinIO。
这是 MinIO 超级管理员的密码,与 minio_access_key 配合使用。
安全警告:请务必修改默认密码!
使用默认密码是高危行为!请务必在您的生产环境部署中修改此密码。
提示:执行 ./configure 或 ./configure -g 时,会自动修改配置文件模板中的这些默认密码。
参数名称: minio_extra_vars, 类型: string, 层次:C
MinIO 服务器的额外环境变量。查看 MinIO Server 文档以获取完整列表。
默认值为空字符串,您可以使用多行字符串来传递多个环境变量。例如:
minio_extra_vars : |
MINIO_BROWSER_REDIRECT_URL=https://minio.example.com
MINIO_SERVER_URL=https://s3.example.com
minio_provision参数名称: minio_provision, 类型: bool, 层次:G/C
是否执行 MinIO 资源置备任务?默认为 true。
当启用时,Pigsty 将自动创建 minio_buckets 和 minio_users 中定义的存储桶和用户。
如果您不需要自动置备这些资源,可以将此参数设置为 false。
minio_alias参数名称: minio_alias, 类型: string, 层次:G
本地 MinIO 集群的 MinIO 客户端别名,默认值:sss。
此别名将被写入管理节点上管理员用户的 MinIO 客户端配置文件中(~/.mcli/config.json),
使您可以直接使用 mcli <alias> 命令访问 MinIO 集群,例如 mcli ls sss/。
如果部署多个 MinIO 集群,需要为每个集群指定不同的别名以避免冲突。
minio_endpoint参数名称:minio_endpoint, 类型: string, 层次:C
部署的客户端别名对应的端点,如果指定,这里的 minio_endpoint (例如: https://sss.pigsty:9002)将会替代默认值,作为写入管理节点 MinIO Alias 的目标端点。
mcli alias set {{ minio_alias }} { % if minio_endpoint is defined and minio_endpoint != '' %}{{ minio_endpoint }}{ % else %} https://{{ minio_domain }} :{{ minio_port }}{ % endif %} {{ minio_access_key }} {{ minio_secret_key }}
以上 MinIO Alias 会在管理节点上以默认管理用户执行。
minio_buckets参数名称: minio_buckets, 类型: bucket[], 层次:C
默认创建的 MinIO 存储桶列表:
minio_buckets :
- { name : pgsql }
- { name: meta ,versioning : true }
- { name : data }
默认创建三个存储桶,各有不同的用途和策略:
pgsql 存储桶:默认用于 PostgreSQL 的 pgBackREST 备份存储。meta 存储桶:开放式存储桶,启用了版本控制(versioning),适合存储需要版本管理的重要元数据。data 存储桶:开放式存储桶,用于其他用途,例如 Supabase 模板可能使用此存储桶存储业务数据。每个存储桶都会创建一个同名的访问策略,例如 pgsql 策略拥有对 pgsql 存储桶的所有权限,以此类推。
您还可以在存储桶定义中添加 lock 标志,启用对象锁定功能,防止存储桶中的对象被意外删除。
minio_users参数名称: minio_users, 类型: user[], 层次:C
要创建的 MinIO 用户列表,默认值:
minio_users :
- { access_key: pgbackrest ,secret_key: S3User.Backup ,policy : pgsql }
- { access_key: s3user_meta ,secret_key: S3User.Meta ,policy : meta }
- { access_key: s3user_data ,secret_key: S3User.Data ,policy : data }
默认配置会创建三个用户,分别对应三个默认存储桶:
pgbackrest:用于 PostgreSQL pgBackREST 备份,拥有 pgsql 存储桶的访问权限。s3user_meta:用于访问 meta 存储桶。s3user_data:用于访问 data 存储桶。使用默认密码是高危行为!请务必在您的部署中调整这些凭证!
提示:./configure -g 会默认修改配置文件模板中的这些密码,如果这些默认密码出现在模版文件中。
minio_safeguard参数名称: minio_safeguard, 类型: bool, 层次:G/C/A
防止意外删除的保险开关,默认值为 false。
如果启用此参数,minio-rm.yml 剧本将中止并拒绝移除 MinIO 集群,从而提供防止意外删除的保护。
建议在生产环境中启用此保险开关,防止误操作导致数据丢失:
minio_safeguard : true # 启用后,minio-rm.yml 将拒绝执行
minio_rm_data参数名称: minio_rm_data, 类型: bool, 层次:G/C/A
移除时是否删除 MinIO 数据?默认值为 true。
当启用时,minio-rm.yml 剧本将在集群移除过程中删除 MinIO 数据目录和配置文件。
minio_rm_pkg参数名称: minio_rm_pkg, 类型: bool, 层次:G/C/A
移除时是否卸载 MinIO 软件包?默认值为 false。
当启用时,minio-rm.yml 剧本将在集群移除过程中卸载 MinIO 软件包。默认禁用此选项,以便保留 MinIO 安装供将来可能的使用。
15.4 - 预置剧本 如何使用预置的 ansible 剧本来管理 MinIO 集群,常用管理命令速查。
MinIO 模块提供了两个内置剧本用于集群管理:
minio.yml剧本 minio.yml 用于在节点上安装 MinIO 模块。
minio-id : 生成/校验 minio 身份参数minio_install : 安装 miniominio_os_user : 创建操作系统用户 miniominio_pkg : 安装 minio/mcli 软件包minio_dir : 创建 minio 目录minio_config : 生成 minio 配置minio_conf : minio 主配置文件minio_cert : minio SSL 证书签发minio_dns : minio DNS 记录插入minio_launch : minio 服务启动minio_register : minio 纳入监控minio_provision : 创建 minio 别名/存储桶/业务用户minio_alias : 创建 minio 客户端别名(管理节点上)minio_bucket : 创建 minio 存储桶minio_user : 创建 minio 业务用户在执行剧本前,请先在 配置清单 中,完成 MinIO 集群的 配置 。
架构变更:Pigsty v3.6+
从 Pigsty v3.6 开始,minio.yml 剧本专注于集群安装。所有移除操作已迁移至专用的 minio-rm.yml 剧本,使用 minio_remove 角色执行。
minio-rm.yml剧本 minio-rm.yml 用于移除 MinIO 集群。
minio-id : 生成 minio 身份参数用于移除操作minio_safeguard : 安全检查,防止意外删除(默认:false)minio_pause : 暂停 3 秒,允许用户中止操作minio_deregister : 从 Victoria/Prometheus 监控中移除目标minio_svc : 停止并禁用 minio systemd 服务minio_data : 移除 minio 数据目录(可通过 minio_rm_data=false 禁用)minio_pkg : 卸载 minio 软件包(可通过 minio_rm_pkg=true 启用)移除剧本使用 minio_remove 角色,支持以下可配置参数 :
命令速查 MINIO 剧本常用命令:
./minio.yml -l <cls> # 在 <cls> 分组上安装 MINIO 模块
./minio.yml -l minio -t minio_install # 在节点上安装 MinIO 服务,准备数据目录,但不配置启动
./minio.yml -l minio -t minio_config # 重新配置 MinIO 集群
./minio.yml -l minio -t minio_launch # 重启 MinIO 集群
./minio.yml -l minio -t minio_provision # 重新执行资源置备(创建存储桶和用户)
./minio-rm.yml -l minio # 移除 MinIO 集群(使用专用移除剧本)
./minio-rm.yml -l minio -e minio_rm_data = false # 移除集群但保留数据
./minio-rm.yml -l minio -e minio_rm_pkg = true # 移除集群并卸载软件包
保护机制 出于防止误删的目的,Pigsty 的 MINIO 模块提供了防误删保险,由参数 minio_safeguard 控制。
默认情况下,minio_safeguard 为 false,允许执行移除操作。如果您希望保护 MinIO 集群不被意外删除,可以在配置清单中启用此保险:
minio_safeguard : true # 启用后,minio-rm.yml 将拒绝执行
如果您确实需要移除受保护的集群,可以在执行时使用命令行参数覆盖:
./minio-rm.yml -l minio -e minio_safeguard = false
执行演示
15.5 - 管理预案 MinIO 集群管理 SOP:创建,销毁,扩容,缩容,节点故障与磁盘故障的处理。
创建集群 要创建一个集群,在配置清单中定义好后,执行 minio.yml 剧本即可。
minio : { hosts : { 10.10.10.10 : { minio_seq: 1 } }, vars : { minio_cluster : minio } }
例如,上面的配置定义了一个 SNSD 单机单盘 MinIO 集群,使用以下命令即可创建该 MinIO 集群:
./minio.yml -l minio # 在 minio 分组上安装 MinIO 模块
销毁集群 要销毁一个集群,执行专用的 minio-rm.yml 剧本即可:
./minio-rm.yml -l minio # 移除 MinIO 集群
./minio-rm.yml -l minio -e minio_rm_data = false # 移除集群但保留数据
./minio-rm.yml -l minio -e minio_rm_pkg = true # 移除集群并卸载软件包
架构变更:Pigsty v3.6+
从 Pigsty v3.6 开始,集群移除操作已从 minio.yml 剧本迁移至专用的 minio-rm.yml 剧本。旧的 minio_clean 任务已被弃用。
移除剧本会自动完成以下操作:
从 Victoria/Prometheus 监控系统中注销 MinIO 目标 从 INFRA 节点的 DNS 服务中移除记录 停止并禁用 MinIO systemd 服务 删除 MinIO 数据目录和配置文件(可选) 卸载 MinIO 软件包(可选) 集群扩容 MinIO 无法在节点/磁盘级别上扩容,但可以在存储池(多个节点)层次上进行扩容。
现在假设您有 这样一个 四节点的 MinIO 集群,希望扩容一倍,新增一个四节点的存储池。
minio :
hosts :
10.10.10.10 : { minio_seq: 1 , nodename : minio-1 }
10.10.10.11 : { minio_seq: 2 , nodename : minio-2 }
10.10.10.12 : { minio_seq: 3 , nodename : minio-3 }
10.10.10.13 : { minio_seq: 4 , nodename : minio-4 }
vars :
minio_cluster : minio
minio_data : '/data{1...4}'
minio_buckets : [ { name : pgsql }, { name: infra }, { name: redis } ]
minio_users :
- { access_key: dba , secret_key: S3User.DBA, policy : consoleAdmin }
- { access_key: pgbackrest , secret_key: S3User.SomeNewPassWord , policy : readwrite }
# bind a node l2 vip (10.10.10.9) to minio cluster (optional)
node_cluster : minio
vip_enabled : true
vip_vrid : 128
vip_address : 10.10.10.9
vip_interface : eth1
# expose minio service with haproxy on all nodes
haproxy_services :
- name : minio # [REQUIRED] service name, unique
port : 9002 # [REQUIRED] service port, unique
balance : leastconn # [OPTIONAL] load balancer algorithm
options : # [OPTIONAL] minio health check
- option httpchk
- option http-keep-alive
- http-check send meth OPTIONS uri /minio/health/live
- http-check expect status 200
servers :
- { name: minio-1 ,ip: 10.10.10.10 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-2 ,ip: 10.10.10.11 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-3 ,ip: 10.10.10.12 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-4 ,ip: 10.10.10.13 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
首先,修改 MinIO 集群定义,新增四台节点,按顺序分配序列号 5 到 8。
这里的关键一步是修改 minio_volumes 参数,将新的四个节点指定为一个新的 存储池 。
minio :
hosts :
10.10.10.10 : { minio_seq: 1 , nodename : minio-1 }
10.10.10.11 : { minio_seq: 2 , nodename : minio-2 }
10.10.10.12 : { minio_seq: 3 , nodename : minio-3 }
10.10.10.13 : { minio_seq: 4 , nodename : minio-4 }
# 新增的四个节点
10.10.10.14 : { minio_seq: 5 , nodename : minio-5 }
10.10.10.15 : { minio_seq: 6 , nodename : minio-6 }
10.10.10.16 : { minio_seq: 7 , nodename : minio-7 }
10.10.10.17 : { minio_seq: 8 , nodename : minio-8 }
vars :
minio_cluster : minio
minio_data : '/data{1...4}'
minio_volumes : 'https://minio-{1...4}.pigsty:9000/data{1...4} https://minio-{5...8}.pigsty:9000/data{1...4}' # 新增的集群配置
# …… 省略其他配置
第二步,将这些节点交由 Pigsty 纳管:
./node.yml -l 10.10.10.14,10.10.10.15,10.10.10.16,10.10.10.17
第三步,在新节点上,使用 Ansible 剧本 安装并准备 MinIO 软件:
./minio.yml -l 10.10.10.14,10.10.10.15,10.10.10.16,10.10.10.17 -t minio_install
第四步,在 整个集群 上,使用 Ansible 剧本 重新配置 MinIO 集群:
./minio.yml -l minio -t minio_config
这一步会更新现有四个节点的 MINIO_VOLUMES 配置
第五步,一次性重启整个 MinIO 集群(请注意,不要滚动重启!):
./minio.yml -l minio -t minio_launch -f 10 # 8并发数,确保同时重启
第六步(可选):如果您使用了负载均衡,那么请确保负载均衡器的配置也已经更新。例如,将新的四个节点加入到负载均衡器的配置中:
# expose minio service with haproxy on all nodes
haproxy_services :
- name : minio # [REQUIRED] service name, unique
port : 9002 # [REQUIRED] service port, unique
balance : leastconn # [OPTIONAL] load balancer algorithm
options : # [OPTIONAL] minio health check
- option httpchk
- option http-keep-alive
- http-check send meth OPTIONS uri /minio/health/live
- http-check expect status 200
servers :
- { name: minio-1 ,ip: 10.10.10.10 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-2 ,ip: 10.10.10.11 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-3 ,ip: 10.10.10.12 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-4 ,ip: 10.10.10.13 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-5 ,ip: 10.10.10.14 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-6 ,ip: 10.10.10.15 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-7 ,ip: 10.10.10.16 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
- { name: minio-8 ,ip: 10.10.10.17 ,port: 9000 ,options : 'check-ssl ca-file /etc/pki/ca.crt check port 9000' }
然后,执行 node.yml 剧本的 haproxy 子任务,更新负载均衡器配置:
./node.yml -l minio -t haproxy_config,haproxy_reload # 更新负载均衡器配置并在线加载
如果您使用 L2 VIP 来确保可靠的负载均衡器接入,那么还需要将新的节点(如果有)加入到现有 NODE VIP 分组中:
./node.yml -l minio -t node_vip # 刷新集群 L2 VIP 配置
集群缩容 MinIO 无法在节点/磁盘级别上缩容,但可以在存储池(多个节点)层次上进行退役 —— 新增一个新存储池,将旧存储池排干迁移到新存储池,然后将旧存储池退役。
集群升级 首先,将新版本的 MinIO 软件包下载至 INFRA 节点的本地软件仓库,然后重建软件仓库索引:
./infra.yml -t repo_create
其次,使用 Ansible 批量升级 MinIO 软件包版本:
ansible minio -m package -b -a 'name=minio state=latest' # 升级 MinIO 服务器软件版本
ansible minio -m package -b -a 'name=mcli state=latest' # 升级 MinIO 客户端软件版本
最后,使用 mc 命令行工具通知 MinIO 集群重启:
mc admin service restart sss
替换故障节点 # 1. 从集群中下线故障节点
bin/node-rm <your_old_node_ip>
# 2. 替换故障节点,使用原来的节点名称(如果IP变化,您需要修改 MinIO 集群定义)
bin/node-add <your_new_node_ip>
# 3. 在新节点上安装配置 MinIO
./minio.yml -l <your_new_node_ip>
# 4. 指示 MinIO 执行恢复动作
mc admin heal
替换故障磁盘 # 1. 从集群中删除故障磁盘
umount /dev/<your_disk_device>
# 2. 替换故障磁盘,使用xfs格盘
mkfs.xfs /dev/sdb -L DRIVE1
# 3. 不要忘记设置开机自动挂载
vi /etc/fstab
# LABEL=DRIVE1 /mnt/drive1 xfs defaults,noatime 0 2
# 4. 重新挂载
mount -a
# 5. 指示 MinIO 执行恢复动作
mc admin heal
15.6 - 监控告警 如何在 Pigsty 中监控 MinIO?如何使用 MinIO 本身的管控面板?有哪些告警规则值得关注?
内置控制台 MinIO 内置了一个相当不错的管控界面,默认您可以通过任意 MinIO 实例的管控端口 (minio_admin_port ,默认为 9001),使用 HTTPS 访问此界面。
在大多数提供 MinIO 服务的配置模板中,MinIO 都会以 m.pigsty 的自定义服务对外暴露。在配置域名解析后,您可以通过 https://m.pigsty 访问 MinIO 管控界面。
使用 minio_access_key 和 minio_secret_key 配置的管理员凭证登录(默认为 minioadmin / S3User.MinIO)。
注意:HTTPS 与证书信任
MinIO 控制台需要 HTTPS 访问。如果您使用 Pigsty 自签名 CA,需要在浏览器中信任该 CA 证书,或者手动接受安全警告。
Pigsty监控 Pigsty 提供了两个与 MINIO 模块有关的监控面板:
MinIO 监控指标通过 MinIO 原生的 Prometheus 端点(/minio/v2/metrics/cluster)采集,默认由 Victoria Metrics 抓取并存储。
Pigsty告警 Pigsty 针对 MinIO 提供了以下三条告警规则,分别是:
MinIO 宕机 MinIO 节点离线 MinIO 磁盘离线 #==============================================================#
# Aliveness #
#==============================================================#
# MinIO server instance down
- alert : MinioServerDown
expr : minio_up < 1
for : 1m
labels : { level: 0, severity: CRIT, category : minio }
annotations :
summary : "CRIT MinioServerDown {{ $labels.ins }}@{{ $labels.instance }}"
description : |
minio_up[ins={{ $labels.ins }}, instance={{ $labels.instance }}] = {{ $value }} < 1
http://g.pigsty/d/minio-overview
#==============================================================#
# Error #
#==============================================================#
# MinIO node offline triggers a p1 alert
- alert : MinioNodeOffline
expr : avg_over_time(minio_cluster_nodes_offline_total{job="minio"}[5m]) > 0
for : 3m
labels : { level: 1, severity: WARN, category : minio }
annotations :
summary : "WARN MinioNodeOffline: {{ $labels.cls }} {{ $value }}"
description : |
minio_cluster_nodes_offline_total[cls={{ $labels.cls }}] = {{ $value }} > 0
http://g.pigsty/d/minio-overview?from=now-5m&to=now&var-cls={{$labels.cls}}
# MinIO disk offline triggers a p1 alert
- alert : MinioDiskOffline
expr : avg_over_time(minio_cluster_disk_offline_total{job="minio"}[5m]) > 0
for : 3m
labels : { level: 1, severity: WARN, category : minio }
annotations :
summary : "WARN MinioDiskOffline: {{ $labels.cls }} {{ $value }}"
description : |
minio_cluster_disk_offline_total[cls={{ $labels.cls }}] = {{ $value }} > 0
http://g.pigsty/d/minio-overview?from=now-5m&to=now&var-cls={{$labels.cls}}
15.7 - 指标列表 Pigsty MINIO 模块提供的完整监控指标列表与释义
MINIO 模块包含有 79 类可用监控指标。
Metric Name Type Labels Description minio_audit_failed_messages counter ip, job, target_id, cls, instance, server, insTotal number of messages that failed to send since start minio_audit_target_queue_length gauge ip, job, target_id, cls, instance, server, insNumber of unsent messages in queue for target minio_audit_total_messages counter ip, job, target_id, cls, instance, server, insTotal number of messages sent since start minio_cluster_bucket_total gauge ip, job, cls, instance, server, insTotal number of buckets in the cluster minio_cluster_capacity_raw_free_bytes gauge ip, job, cls, instance, server, insTotal free capacity online in the cluster minio_cluster_capacity_raw_total_bytes gauge ip, job, cls, instance, server, insTotal capacity online in the cluster minio_cluster_capacity_usable_free_bytes gauge ip, job, cls, instance, server, insTotal free usable capacity online in the cluster minio_cluster_capacity_usable_total_bytes gauge ip, job, cls, instance, server, insTotal usable capacity online in the cluster minio_cluster_drive_offline_total gauge ip, job, cls, instance, server, insTotal drives offline in this cluster minio_cluster_drive_online_total gauge ip, job, cls, instance, server, insTotal drives online in this cluster minio_cluster_drive_total gauge ip, job, cls, instance, server, insTotal drives in this cluster minio_cluster_health_erasure_set_healing_drives gauge pool, ip, job, cls, set, instance, server, insGet the count of healing drives of this erasure set minio_cluster_health_erasure_set_online_drives gauge pool, ip, job, cls, set, instance, server, insGet the count of the online drives in this erasure set minio_cluster_health_erasure_set_read_quorum gauge pool, ip, job, cls, set, instance, server, insGet the read quorum for this erasure set minio_cluster_health_erasure_set_status gauge pool, ip, job, cls, set, instance, server, insGet current health status for this erasure set minio_cluster_health_erasure_set_write_quorum gauge pool, ip, job, cls, set, instance, server, insGet the write quorum for this erasure set minio_cluster_health_status gauge ip, job, cls, instance, server, insGet current cluster health status minio_cluster_nodes_offline_total gauge ip, job, cls, instance, server, insTotal number of MinIO nodes offline minio_cluster_nodes_online_total gauge ip, job, cls, instance, server, insTotal number of MinIO nodes online minio_cluster_objects_size_distribution gauge ip, range, job, cls, instance, server, insDistribution of object sizes across a cluster minio_cluster_objects_version_distribution gauge ip, range, job, cls, instance, server, insDistribution of object versions across a cluster minio_cluster_usage_deletemarker_total gauge ip, job, cls, instance, server, insTotal number of delete markers in a cluster minio_cluster_usage_object_total gauge ip, job, cls, instance, server, insTotal number of objects in a cluster minio_cluster_usage_total_bytes gauge ip, job, cls, instance, server, insTotal cluster usage in bytes minio_cluster_usage_version_total gauge ip, job, cls, instance, server, insTotal number of versions (includes delete marker) in a cluster minio_cluster_webhook_failed_messages counter ip, job, cls, instance, server, insNumber of messages that failed to send minio_cluster_webhook_online gauge ip, job, cls, instance, server, insIs the webhook online? minio_cluster_webhook_queue_length counter ip, job, cls, instance, server, insWebhook queue length minio_cluster_webhook_total_messages counter ip, job, cls, instance, server, insTotal number of messages sent to this target minio_cluster_write_quorum gauge ip, job, cls, instance, server, insMaximum write quorum across all pools and sets minio_node_file_descriptor_limit_total gauge ip, job, cls, instance, server, insLimit on total number of open file descriptors for the MinIO Server process minio_node_file_descriptor_open_total gauge ip, job, cls, instance, server, insTotal number of open file descriptors by the MinIO Server process minio_node_go_routine_total gauge ip, job, cls, instance, server, insTotal number of go routines running minio_node_ilm_expiry_pending_tasks gauge ip, job, cls, instance, server, insNumber of pending ILM expiry tasks in the queue minio_node_ilm_transition_active_tasks gauge ip, job, cls, instance, server, insNumber of active ILM transition tasks minio_node_ilm_transition_missed_immediate_tasks gauge ip, job, cls, instance, server, insNumber of missed immediate ILM transition tasks minio_node_ilm_transition_pending_tasks gauge ip, job, cls, instance, server, insNumber of pending ILM transition tasks in the queue minio_node_ilm_versions_scanned counter ip, job, cls, instance, server, insTotal number of object versions checked for ilm actions since server start minio_node_io_rchar_bytes counter ip, job, cls, instance, server, insTotal bytes read by the process from the underlying storage system including cache, /proc/[pid]/io rchar minio_node_io_read_bytes counter ip, job, cls, instance, server, insTotal bytes read by the process from the underlying storage system, /proc/[pid]/io read_bytes minio_node_io_wchar_bytes counter ip, job, cls, instance, server, insTotal bytes written by the process to the underlying storage system including page cache, /proc/[pid]/io wchar minio_node_io_write_bytes counter ip, job, cls, instance, server, insTotal bytes written by the process to the underlying storage system, /proc/[pid]/io write_bytes minio_node_process_cpu_total_seconds counter ip, job, cls, instance, server, insTotal user and system CPU time spent in seconds minio_node_process_resident_memory_bytes gauge ip, job, cls, instance, server, insResident memory size in bytes minio_node_process_starttime_seconds gauge ip, job, cls, instance, server, insStart time for MinIO process per node, time in seconds since Unix epoc minio_node_process_uptime_seconds gauge ip, job, cls, instance, server, insUptime for MinIO process per node in seconds minio_node_scanner_bucket_scans_finished counter ip, job, cls, instance, server, insTotal number of bucket scans finished since server start minio_node_scanner_bucket_scans_started counter ip, job, cls, instance, server, insTotal number of bucket scans started since server start minio_node_scanner_directories_scanned counter ip, job, cls, instance, server, insTotal number of directories scanned since server start minio_node_scanner_objects_scanned counter ip, job, cls, instance, server, insTotal number of unique objects scanned since server start minio_node_scanner_versions_scanned counter ip, job, cls, instance, server, insTotal number of object versions scanned since server start minio_node_syscall_read_total counter ip, job, cls, instance, server, insTotal read SysCalls to the kernel. /proc/[pid]/io syscr minio_node_syscall_write_total counter ip, job, cls, instance, server, insTotal write SysCalls to the kernel. /proc/[pid]/io syscw minio_notify_current_send_in_progress gauge ip, job, cls, instance, server, insNumber of concurrent async Send calls active to all targets (deprecated, please use ‘minio_notify_target_current_send_in_progress’ instead) minio_notify_events_errors_total counter ip, job, cls, instance, server, insEvents that were failed to be sent to the targets (deprecated, please use ‘minio_notify_target_failed_events’ instead) minio_notify_events_sent_total counter ip, job, cls, instance, server, insTotal number of events sent to the targets (deprecated, please use ‘minio_notify_target_total_events’ instead) minio_notify_events_skipped_total counter ip, job, cls, instance, server, insEvents that were skipped to be sent to the targets due to the in-memory queue being full minio_s3_requests_4xx_errors_total counter ip, job, cls, instance, server, ins, apiTotal number of S3 requests with (4xx) errors minio_s3_requests_errors_total counter ip, job, cls, instance, server, ins, apiTotal number of S3 requests with (4xx and 5xx) errors minio_s3_requests_incoming_total gauge ip, job, cls, instance, server, insTotal number of incoming S3 requests minio_s3_requests_inflight_total gauge ip, job, cls, instance, server, ins, apiTotal number of S3 requests currently in flight minio_s3_requests_rejected_auth_total counter ip, job, cls, instance, server, insTotal number of S3 requests rejected for auth failure minio_s3_requests_rejected_header_total counter ip, job, cls, instance, server, insTotal number of S3 requests rejected for invalid header minio_s3_requests_rejected_invalid_total counter ip, job, cls, instance, server, insTotal number of invalid S3 requests minio_s3_requests_rejected_timestamp_total counter ip, job, cls, instance, server, insTotal number of S3 requests rejected for invalid timestamp minio_s3_requests_total counter ip, job, cls, instance, server, ins, apiTotal number of S3 requests minio_s3_requests_ttfb_seconds_distribution gauge ip, job, cls, le, instance, server, ins, apiDistribution of time to first byte across API calls minio_s3_requests_waiting_total gauge ip, job, cls, instance, server, insTotal number of S3 requests in the waiting queue minio_s3_traffic_received_bytes counter ip, job, cls, instance, server, insTotal number of s3 bytes received minio_s3_traffic_sent_bytes counter ip, job, cls, instance, server, insTotal number of s3 bytes sent minio_software_commit_info gauge ip, job, cls, instance, commit, server, insGit commit hash for the MinIO release minio_software_version_info gauge ip, job, cls, instance, version, server, insMinIO Release tag for the server minio_up Unknown ip, job, cls, instance, insN/A minio_usage_last_activity_nano_seconds gauge ip, job, cls, instance, server, insTime elapsed (in nano seconds) since last scan activity. scrape_duration_seconds Unknown ip, job, cls, instance, insN/A scrape_samples_post_metric_relabeling Unknown ip, job, cls, instance, insN/A scrape_samples_scraped Unknown ip, job, cls, instance, insN/A scrape_series_added Unknown ip, job, cls, instance, insN/A up Unknown ip, job, cls, instance, insN/A
15.8 - 常见问题 Pigsty MINIO 对象存储模块常见问题答疑
Pigsty 使用的 MinIO 是什么版本? MinIO 于 2025-12-03 宣布进入 维护模式 ,不再发布新的功能版本,只会发布安全补丁与维护版本,并且在 2025-10-15 停止发布二进制 RPM/DEB。
所以 Pigsty fork 了自己的 MinIO ,并使用 minio/pkger 制作了最新的 2025-12-03 版本。
这一版本修复了 MinIO CVE-2025-62506 安全漏洞,确保 Pigsty 用户的 MinIO 部署安全可靠。
您可以在 Pigsty Infra 仓库中找到 RPM/DEB 包以及构建使用的脚本。
为什么 MinIO 强制要求 HTTPS? 当 pgbackrest 使用对象存储作为备份仓库时,强制要求使用 HTTPS,以确保数据传输的安全性。
如果您的 MinIO 并非用于 pgbackrest 备份,您仍然可以选择使用 HTTP 协议。
可以通过修改参数 minio_https 来关闭 HTTPS。
从容器中访问 MinIO 提示证书无效? 除非您使用真正的企业 CA 颁发的证书,否则 MinIO 默认使用自签名证书,这会导致容器内的客户端工具(如 mc / rclone / awscli 等)无法验证 MinIO 服务器的身份,从而提示证书无效。
例如,对于 Node.js 应用程序,可以 MinIO 服务器的 CA 证书挂载到容器内,并通过环境变量 NODE_EXTRA_CA_CERTS 指定 CA 证书路径:
environment :
NODE_EXTRA_CA_CERTS : /etc/pki/ca.crt
volumes :
- /etc/pki/ca.crt:/etc/pki/ca.crt:ro
当然,如果您的 MinIO 没有用作 pgbackrest 备份仓库的话,您也可以选择关闭 MinIO 的 HTTPS 支持,改用 HTTP 协议访问。
启动多节点/多盘 MinIO 集群失败怎么办? 在 单机多盘 或 多机多盘 模式下,如果数据目录不是有效的磁盘挂载点,MinIO 会拒绝启动。
请使用已挂载的磁盘作为 MinIO 的数据目录,而不是普通目录。您只能在 单机单盘 模式下使用普通目录作为 MinIO 的数据目录,仅可用于开发测试或非关键场合。
如何向已有的 MinIO 集群中添加新的成员? 在部署之前,您最好规划 MinIO 集群容量,因为新增成员需要全局重启。
您可以通过向现有集群中添加新的服务器节点,打造一个新的存储池的方式,实现 MinIO 扩容。
请注意,MinIO 一旦部署,你无法修改现有集群的节点数量与磁盘数量!只能通过添加新的存储池来扩容。
详细步骤请参考 Pigsty 文档:集群扩容 ,以及 MinIO 官方文档:扩展 MinIO 部署
如何移除 MinIO 集群? 从 Pigsty v3.6 开始,移除 MinIO 集群需要使用专用的 minio-rm.yml 剧本:
./minio-rm.yml -l minio # 移除 MinIO 集群
./minio-rm.yml -l minio -e minio_rm_data = false # 移除集群但保留数据
如果您启用了 minio_safeguard 保护,需要显式覆盖才能执行移除:
./minio-rm.yml -l minio -e minio_safeguard = false
mcli 命令与 mc 命令有什么区别? mcli 是 MinIO 官方客户端 mc 的重命名版本。在 Pigsty 中,我们使用 mcli 而不是 mc,以避免与 Midnight Commander(一个常见的文件管理器,也使用 mc 命令)产生冲突。
两者功能完全相同,只是命令名称不同。您可以在 MinIO 客户端文档 中找到完整的命令参考。
如何监控 MinIO 集群状态? Pigsty 为 MinIO 提供了开箱即用的监控能力:
详情请参阅 监控告警 文档
16 - 模块:REDIS Pigsty 内置了 Redis 支持,开源高性能缓存,可作为 PostgreSQL 的辅助与补充,支持主从、集群、哨兵三种模式。
Redis 是广为流行的开源“高性能”内存数据结构服务器,PostgreSQL 的好搭子。
Pigsty 中的 Redis 是一套生产就绪的完整解决方案,支持主从复制、哨兵高可用与原生集群模式,集成了监控与日志功能,并提供自动化的安装、配置与运维管理剧本。
16.1 - 集群配置 根据需求场景选择合适的 Redis 模式,并通过配置清单表达您的需求
概念 Redis的实体概念模型与PostgreSQL 几乎相同,同样包括 集群(Cluster) 与 实例(Instance) 的概念。注意这里的Cluster指的不是Redis原生集群方案中的集群。
REDIS模块与PGSQL模块核心的区别在于,Redis通常采用 单机多实例 部署,而不是 PostgreSQL 的 1:1 部署:一个物理/虚拟机节点上通常会部署 多个 Redis实例,以充分利用多核CPU。因此配置 和管理 Redis实例的方式与PGSQL稍有不同。
在Pigsty管理的Redis中,节点完全隶属于集群,即目前尚不允许在一个节点上部署两个不同集群的Redis实例,但这并不影响您在在一个节点上部署多个独立 Redis 主从实例。当然这样也会有一些局限性,例如在这种情况下您就无法为同一个节点上的不同实例指定不同的密码了。
身份参数 Redis 身份参数 是定义Redis集群时必须提供的信息,包括:
工作模式 Redis有三种不同的工作模式,由 redis_mode 参数指定:
standalone:默认的独立主从模式cluster:Redis原生分布式集群模式sentinel:哨兵模式,可以为主从模式的 Redis 提供高可用能力下面给出了三种Redis集群的定义样例:
一个1节点,一主一从的 Redis Standalone 集群:redis-ms 一个1节点,3实例的Redis Sentinel集群:redis-sentinel 一个2节点,6实例的的 Redis Cluster集群: redis-cluster redis-ms : # redis 经典主从集群
hosts : { 10.10.10.10 : { redis_node: 1 , redis_instances : { 6379 : { }, 6380 : { replica_of : '10.10.10.10 6379' } } } }
vars : { redis_cluster: redis-ms ,redis_password: 'redis.ms' ,redis_max_memory : 64MB }
redis-meta : # redis 哨兵 x 3
hosts : { 10.10.10.11 : { redis_node: 1 , redis_instances : { 26379 : { } ,26380 : { } ,26381 : { } } } }
vars :
redis_cluster : redis-meta
redis_password : 'redis.meta'
redis_mode : sentinel
redis_max_memory : 16MB
redis_sentinel_monitor : # primary list for redis sentinel, use cls as name, primary ip:port
- { name: redis-ms, host: 10.10.10.10, port: 6379 ,password: redis.ms, quorum : 2 }
redis-test : # redis 原生集群: 3主 x 3从
hosts :
10.10.10.12 : { redis_node: 1 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
10.10.10.13 : { redis_node: 2 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
vars : { redis_cluster: redis-test ,redis_password: 'redis.test' ,redis_mode: cluster, redis_max_memory : 32MB }
局限性 一个节点只能属于一个 Redis 集群,这意味着您不能将一个节点同时分配给两个不同的Redis集群。 在每个 Redis 节点上,您需要为 Redis实例 分配唯一的端口号,避免端口冲突。 通常同一个 Reids 集群会使用同一个密码,但一个 Redis节点上的多个 Redis 实例无法设置不同的密码(因为 redis_exporter 只允许使用一个密码0 Redis Cluster自带高可用,而Redis主从的高可用需要在 Sentinel 中额外进行手工配置:因为我们不知道您是否会部署 Sentinel。 好在配置 Redis 主从实例的高可用非常简单,可以通过Sentinel进行配置,详情请参考管理-设置Redis主从高可用 16.2 - 参数列表 REDIS 模块提供了 21 个配置参数
REDIS 模块的参数列表。
参数概览 REDIS 参数组用于 Redis 集群的部署与配置,包括身份标识、实例定义、工作模式、内存配置、持久化以及监控。
Redis 模块包含了21个配置参数。
#redis_cluster: <集群> # Redis数据库集群名称,必选身份参数
#redis_node: 1 <节点> # Redis节点上的实例定义
#redis_instances: {} <节点> # Redis节点编号,正整数,集群内唯一,必选身份参数
redis_fs_main : /data # Redis主数据目录,默认为 `/data`
redis_exporter_enabled : true # Redis Exporter 是否启用?
redis_exporter_port : 9121 # Redis Exporter监听端口
redis_exporter_options : '' # Redis Exporter命令参数
redis_safeguard : false # 禁止抹除现存的Redis
redis_clean : true # 初始化Redis是否抹除现存实例
redis_rmdata : true # 移除Redis实例时是否一并移除数据?
redis_mode : standalone # Redis集群模式:sentinel,cluster,standalone
redis_conf : redis.conf # Redis配置文件模板,sentinel 除外
redis_bind_address : '0.0.0.0' # Redis监听地址,默认留空则会绑定主机IP
redis_max_memory : 1GB # Redis可用的最大内存
redis_mem_policy : allkeys-lru # Redis内存逐出策略
redis_password : '' # Redis密码,默认留空则禁用密码
redis_rdb_save : [ '1200 1' ] # Redis RDB 保存指令,字符串列表,空数组则禁用RDB
redis_aof_enabled : false # Redis AOF 是否启用?
redis_rename_commands : {} # Redis危险命令重命名列表
redis_cluster_replicas : 1 # Redis原生集群中每个主库配几个从库?
redis_sentinel_monitor : [] # Redis哨兵监控的主库列表,仅用于哨兵集群
redis_cluster参数名称: redis_cluster, 类型: string, 层次:C
身份参数,必选参数,必须显式在集群层面配置,将用作集群内资源的命名空间。
需要遵循特定命名规则:[a-z][a-z0-9-]*,以兼容不同约束对身份标识的要求,建议使用redis-作为集群名前缀。
redis_node参数名称: redis_node, 类型: int, 层次:I
Redis节点序列号,身份参数,必选参数,必须显式在节点(Host)层面配置。
自然数,在集群中应当是唯一的,用于区别与标识集群内的不同节点,从0或1开始分配。
redis_instances参数名称: redis_instances, 类型: dict, 层次:I
当前 Redis 节点上的 Redis 实例定义,必选参数,必须显式在节点(Host)层面配置。
内容为JSON KV对象格式。Key为数值类型端口号,Value为该实例特定的JSON配置项。
redis-test: # redis native cluster : 3m x 3s
hosts :
10.10.10.12 : { redis_node: 1 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
10.10.10.13 : { redis_node: 2 ,redis_instances : { 6379 : { } ,6380 : { } ,6381 : { } } }
vars : { redis_cluster: redis-test ,redis_password: 'redis.test' ,redis_mode: cluster, redis_max_memory : 32MB }
每一个Redis实例在对应节点上监听一个唯一端口,实例配置项中replica_of 用于设置一个实例的上游主库地址,构建主从复制关系。
redis_instances :
6379 : {}
6380 : { replica_of : '10.10.10.13 6379' }
6381 : { replica_of : '10.10.10.13 6379' }
redis_fs_main参数名称: redis_fs_main, 类型: path, 层次:C
Redis使用的主数据盘挂载点,默认为/data,Pigsty会在该目录下创建redis目录,用于存放Redis数据。
所以实际存储数据的目录为 /data/redis,该目录的属主为操作系统用户 redis,内部结构详情请参考 FHS:Redis
redis_exporter_enabled参数名称: redis_exporter_enabled, 类型: bool, 层次:C
是否启用Redis监控组件 Redis Exporter?
默认启用,在每个Redis节点上部署一个,默认监听 redis_exporter_port 9121 端口。所有本节点上 Redis 实例的监控指标都由它负责抓取。
将此参数设为 false 时,roles/redis/tasks/exporter.yml 仍会渲染配置文件,但会跳过 redis_exporter systemd 服务的启动步骤(redis_exporter_launch 任务带有 when: redis_exporter_enabled|bool 判断),可用于在节点上保留手工配置的 exporter。
redis_exporter_port参数名称: redis_exporter_port, 类型: port, 层次:C
Redis Exporter监听端口,默认值为:9121
redis_exporter_options参数名称: redis_exporter_options, 类型: string, 层次:C/I
传给 Redis Exporter 的额外命令行参数,会被渲染到 /etc/default/redis_exporter 中(参见 roles/redis/tasks/exporter.yml),默认为空字符串。REDIS_EXPORTER_OPTS 最终会附加到 systemd 服务的 ExecStart=/bin/redis_exporter $REDIS_EXPORTER_OPTS,可用于配置额外的抓取目标或过滤行为。
redis_safeguard参数名称: redis_safeguard, 类型: bool, 层次:G/C/A
Redis的防误删安全保险开关:打开后无法使用剧本抹除正在运行的 Redis 实例。
默认值为 false,如果设置为 true,那么当剧本遇到正在运行的 Redis 实例时,会中止初始化/抹除的操作,避免误删。
redis_clean参数名称: redis_clean, 类型: bool, 层次:G/C/A
Redis清理开关:是否在初始化的过程中抹除运行中的Redis实例?默认值为:true。
剧本 redis.yml 会在执行时抹除具有相同定义的现有 Redis 实例,这样可以保证剧本的幂等性。
如果您不希望 redis.yml 这样做,可以将此参数设置为 false,那么当剧本遇到正在运行的 Redis 实例时,会中止初始化/抹除的操作,避免误删。
如果安全保险参数 redis_safeguard 已经打开,那么本参数的优先级低于该参数。
redis_rmdata参数名称: redis_rmdata, 类型: bool, 层次:G/C/A
移除 Redis 实例的时候,是否一并移除 Redis 数据目录?默认为 true。
数据目录包含了 Redis 的 RDB与AOF文件,如果不抹除它们,那么新拉起的 Redis 实例将会从这些备份文件中加载数据。
该参数仅在 redis_clean 为 true 且未开启 redis_safeguard 时生效(参见 roles/redis/tasks/instance.yml 第 40~60 行),否则剧本不会触碰既有数据目录。
redis_mode参数名称: redis_mode, 类型: enum, 层次:C
Redis集群的工作模式,有三种选项:standalone, cluster, sentinel,默认值为 standalone
standalone:默认,独立的Redis主从模式cluster: Redis原生集群模式sentinel:Redis高可用组件:哨兵当使用standalone模式时,Pigsty会根据 replica_of 参数设置Redis主从复制关系。
当使用cluster模式时,Pigsty会根据 redis_cluster_replicas 参数使用所有定义的实例创建原生Redis集群。
当 redis_mode=sentinel 时,redis.yml 会执行 redis-ha 阶段(redis.yml 第 80130 行)将 redis_sentinel_monitor 中的目标批量下发到所有哨兵;当 redis_mode=cluster 时还会执行 redis-join 阶段(redis.yml 第 134180 行)调用 redis-cli --cluster create --cluster-yes ... --cluster-replicas {{ redis_cluster_replicas }}。这两个阶段均在普通 ./redis.yml -l <cluster> 中自动触发,也可以通过 -t redis-ha 或 -t redis-join 单独运行。
redis_conf参数名称: redis_conf, 类型: string, 层次:C
Redis 配置模板路径,Sentinel除外。
默认值:redis.conf,这是一个模板文件,位于 roles/redis/templates/redis.conf 。
如果你想使用自己的 Redis 配置模板,你可以将它放在 templates/ 目录中,并设置此参数为模板文件名。
注意: Redis Sentinel 使用的是另一个不同的模板文件,即 roles/redis/templates/redis-sentinel.conf 。
redis_bind_address参数名称: redis_bind_address, 类型: ip, 层次:C
Redis服务器绑定的IP地址,空字符串将使用配置清单中定义的主机名。
默认值:0.0.0.0,这将绑定到此主机上的所有可用 IPv4 地址。
在生产环境中出于安全性考虑,建议仅绑定内网 IP,即将此值设置为空字符串 ''
当该值为空字符串时,模板 roles/redis/templates/redis.conf
会使用 inventory_hostname 渲染 bind <ip>,从而绑定到清单中声明的管理地址。
redis_max_memory参数名称: redis_max_memory, 类型: size, 层次:C/I
每个 Redis 实例使用的最大内存配置,默认值:1GB。
redis_mem_policy参数名称: redis_mem_policy, 类型: enum, 层次:C
Redis 内存回收策略,默认值:allkeys-lru,
noeviction:内存达限时不保存新值:当使用主从复制时仅适用于主库allkeys-lru:保持最近使用的键;删除最近最少使用的键(LRU)allkeys-lfu:保持频繁使用的键;删除最少频繁使用的键(LFU)volatile-lru:删除带有真实过期字段的最近最少使用的键volatile-lfu:删除带有真实过期字段的最少频繁使用的键allkeys-random:随机删除键以为新添加的数据腾出空间volatile-random:随机删除带有过期字段的键volatile-ttl:删除带有真实过期字段和最短剩余生存时间(TTL)值的键。详情请参阅Redis内存回收策略 。
redis_password参数名称: redis_password, 类型: password, 层次:C/N
Redis 密码,空字符串将禁用密码,这是默认行为。
注意,由于 redis_exporter 的实现限制,您每个节点只能设置一个 redis_password。这通常不是问题,因为 pigsty 不允许在同一节点上部署两个不同的 Redis 集群。
Pigsty 会自动将此密码写入 /etc/default/redis_exporter(REDIS_PASSWORD=...)并在 redis-ha 阶段用于 redis-cli -a <password>,因此无需重复配置 exporter 或 Sentinel 的认证口令。
请在生产环境中使用强密码
redis_rdb_save参数名称: redis_rdb_save, 类型: string[], 层次:C
Redis RDB 保存指令,使用空列表则禁用 RDB。
默认值是 ["1200 1"]:如果最近20分钟至少有1个键更改,则将数据集转储到磁盘。
详情请参考 Redis持久化 。
redis_aof_enabled参数名称: redis_aof_enabled, 类型: bool, 层次:C
启用 Redis AOF 吗?默认值是 false,即不使用 AOF。
redis_rename_commands参数名称: redis_rename_commands, 类型: dict, 层次:C
重命名 Redis 危险命令,这是一个 k:v 字典:old: new,old是待重命名的命令名称,new是重命名后的名字。
默认值:{},你可以通过设置此值来隐藏像 FLUSHDB 和 FLUSHALL 这样的危险命令,下面是一个例子:
{
"keys": "op_keys" ,
"flushdb": "op_flushdb" ,
"flushall": "op_flushall" ,
"config": "op_config"
}
redis_cluster_replicas参数名称: redis_cluster_replicas, 类型: int, 层次:C
在 Redis 原生集群中,应当为一个 Master/Primary 实例配置多少个从库?默认值为: 1,即每个主库配一个从库。
redis_sentinel_monitor参数名称: redis_sentinel_monitor, 类型: master[], 层次:C
Redis哨兵监控的主库列表,只在哨兵集群上使用。每个待纳管的主库定义方式如下所示:
redis_sentinel_monitor : # primary list for redis sentinel, use cls as name, primary ip:port
- { name: redis-src, host: 10.10.10.45, port: 6379 ,password: redis.src, quorum : 1 }
- { name: redis-dst, host: 10.10.10.48, port: 6379 ,password: redis.dst, quorum : 1 }
其中,name,host 是必选参数,port,password,quorum 是可选参数,quorum 用于设置判定主库失效所需的法定人数数,通常大于哨兵实例数的一半(默认为1)。
从 Pigsty 4.0 开始还可以为某个条目添加 remove: true,此时 redis-ha 阶段只会执行 SENTINEL REMOVE <name>,用于清理不再需要的目标。
16.3 - 预置剧本 如何使用预置的 ansible 剧本来管理 Redis 集群,常用管理命令速查。
REDIS模块提供了两个剧本,用于拉起/销毁 传统主从Redis集群/节点/实例:
redis.yml用于初始化 Redis 的 redis.yml 剧本包含以下子任务:
redis_node : 初始化redis节点
- redis_install : 安装redis & redis_exporter
- redis_user : 创建操作系统用户 redis
- redis_dir : 配置 redis的FHS目录结构
redis_exporter : 配置 redis_exporter 监控
- redis_exporter_config : 生成redis_exporter配置
- redis_exporter_launch : 启动redis_exporter
redis_instance : 初始化并重启redis集群/节点/实例
- redis_check : 检查redis实例是否存在
- redis_clean : 清除现有的redis实例
- redis_config : 生成redis实例配置
- redis_launch : 启动redis实例
redis_register : 将redis注册到基础设施中(向 VictoriaMetrics 写入 ` /infra/targets/redis/*.yml` 并为 Vector 渲染 ` /etc/vector/redis.yaml` )
redis_ha : 配置redis哨兵
redis_join : 加入redis集群
示例:使用Redis剧本初始化Redis集群
redis-rm.yml用于卸载 Redis 的 redis-rm.yml 剧本包含以下子任务:
redis_deregister : 从 VictoriaMetrics 与 Vector 中移除注册信息(删除 /infra/targets/redis/*.yml、撤销 /etc/vector/redis.yaml)
redis_exporter : 停止并禁用 redis_exporter
redis : 停止并禁用 redis 集群 / 节点 / 实例
redis_data : 根据 redis_clean / redis_port 的配置删除数据目录(RDB/AOF)
redis_pkg : 卸载 redis & redis_exporter 软件包,仅当 redis_uninstall = true 时执行
16.4 - 管理预案 Redis 集群管理 SOP,创建、销毁、扩容、缩容与高可用的详细说明
以下是一些常见的 Redis 管理任务 SOP(预案):
更多问题请参考 FAQ:REDIS 。
初始化Redis 您可以使用 redis.yml 剧本来初始化 Redis 集群、节点、或实例:
# 初始化集群内所有 Redis 实例
./redis.yml -l <cluster> # 初始化 redis 集群
# 初始化特定节点上的所有 Redis 实例
./redis.yml -l 10.10.10.10 # 初始化 redis 节点
# 初始化特定 Redis 实例: 10.10.10.11:6379
./redis.yml -l 10.10.10.11 -e redis_port = 6379 -t redis
你也可以使用包装脚本命令行脚本来初始化:
bin/redis-add redis-ms # 初始化 redis 集群 'redis-ms'
bin/redis-add 10.10.10.10 # 初始化 redis 节点 '10.10.10.10'
bin/redis-add 10.10.10.10 6379 # 初始化 redis 实例 '10.10.10.10:6379'
下线Redis 您可以使用 redis-rm.yml 剧本来下线 Redis 集群、节点、或实例:
# 下线 Redis 集群 `redis-test`
./redis-rm.yml -l redis-test
# 下线 Redis 集群 `redis-test` 并卸载 Redis 软件包
./redis-rm.yml -l redis-test -e redis_uninstall = true
# 下线 Redis 节点 10.10.10.13 上的所有实例
./redis-rm.yml -l 10.10.10.13
# 下线特定 Redis 实例 10.10.10.13:6379
./redis-rm.yml -l 10.10.10.13 -e redis_port = 6379
你也可以使用包装脚本来下线 Redis 集群/节点/实例:
bin/redis-rm redis-ms # 下线 redis 集群 'redis-ms'
bin/redis-rm 10.10.10.10 # 下线 redis 节点 '10.10.10.10'
bin/redis-rm 10.10.10.10 6379 # 下线 redis 实例 '10.10.10.10:6379'
重新配置Redis 您可以部分执行 redis.yml 剧本来重新配置 Redis 集群、节点、或实例:
./redis.yml -l <cluster> -t redis_config,redis_launch
请注意,redis 无法在线重载配置,您只能使用 launch 任务进行重启来让配置生效。
使用Redis客户端 使用 redis-cli 访问 Reids 实例:
$ redis-cli -h 10.10.10.10 -p 6379 # <--- 使用 Host 与 Port 访问对应 Redis 实例
10.10.10.10:6379> auth redis.ms # <--- 使用密码验证
OK
10.10.10.10:6379> set a 10 # <--- 设置一个Key
OK
10.10.10.10:6379> get a # <--- 获取 Key 的值
"10"
Redis提供了redis-benchmark工具,可以用于Redis的性能评估,或生成一些负载用于测试。
redis-benchmark -h 10.10.10.13 -p 6379
手工设置Redis从库 https://redis.io/commands/replicaof/
# 将一个 Redis 实例提升为主库
> REPLICAOF NO ONE
"OK"
# 将一个 Redis 实例设置为另一个实例的从库
> REPLICAOF 127.0.0.1 6799
"OK"
设置Redis主从高可用 Redis独立主从集群可以通过 Redis 哨兵集群配置自动高可用,详细用户请参考 Sentinel官方文档
以四节点沙箱环境 为例,一套 Redis Sentinel 集群 redis-meta,可以用来管理很多套独立 Redis 主从集群。
以一主一从的Redis普通主从集群 redis-ms 为例,您需要在每个 Sentinel 实例上,使用 SENTINEL MONITOR 添加目标,并使用 SENTINEL SET 提供密码,高可用就配置完毕了。
# 对于每一个 sentinel,将 redis 主服务器纳入哨兵管理:(26379,26380,26381)
$ redis-cli -h 10.10.10.11 -p 26379 -a redis.meta
10.10.10.11:26379> SENTINEL MONITOR redis-ms 10.10.10.10 6379 1
10.10.10.11:26379> SENTINEL SET redis-ms auth-pass redis.ms # 如果启用了授权,需要配置密码
如果您想移除某个由 Sentinel 管理的 Redis 主从集群,使用 SENTINEL REMOVE <name> 移除即可。
您可以使用定义在 Sentinel 集群上的 redis_sentinel_monitor 参数,来自动配置管理哨兵监控管理的主库列表。
redis_sentinel_monitor : # 需要被监控的主库列表,端口、密码、法定人数(应为1/2以上的哨兵数量)为可选参数
- { name: redis-src, host: 10.10.10.45, port: 6379 ,password: redis.src, quorum : 1 }
- { name: redis-dst, host: 10.10.10.48, port: 6379 ,password: redis.dst, quorum : 1 }
redis.yml 中的 redis-ha 阶段会根据该列表在每个哨兵实例上渲染 /tmp/<cluster>.monitor 并依次执行 SENTINEL REMOVE 与 SENTINEL MONITOR 命令,
从而保证哨兵纳管状态与清单保持一致。如果只想移除某个目标而不再重新添加,可以在监控对象上设置 remove: true,剧本会在 SENTINEL REMOVE 后跳过重新注册。
使用以下命令刷新 Redis 哨兵集群上的纳管主库列表:
./redis.yml -l redis-meta -t redis-ha # 如果您的 Sentinel 集群名称不是 redis-meta,请在这里替换。
初始化 Redis 原生集群 当 redis_mode 设置为 cluster 时,redis.yml 会额外执行 redis-join 阶段 :
在 /tmp/<cluster>-join.sh 中使用 redis-cli --cluster create --cluster-yes ... --cluster-replicas {{ redis_cluster_replicas }} 把所有实例拼成原生集群。
该步骤在首次部署时自动运行,后续重新执行 ./redis.yml -l <cluster> -t redis-join 将再次生成并运行相同命令;
由于 --cluster create 并非幂等操作, 只有在你确认需要重建整个原生集群时才应单独触发这一阶段。
16.5 - 监控告警 如何监控 redis?有哪些告警规则值得关注?
监控面板 REDIS 模块提供了 3 个监控面板
Redis Overview:redis 集群概览 Redis Cluster:redis 集群详情 Redis Instance:redis 实例详情 监控 Pigsty 提供了三个与 REDIS 模块有关的监控仪表盘:
Redis Overview Redis Overview :关于所有Redis集群/实例的详细信息
Redis Cluster Redis Cluster :关于单个Redis集群的详细信息
Redis Cluster Dashboard
Redis Instance Redis Instance : 关于单个Redis实例的详细信息
Redis Instance Dashboard
告警规则 Pigsty 针对 redis 提供了以下六条预置告警规则,定义于 files/victoria/rules/redis.yml
RedisDown:redis 实例不可用RedisRejectConn:redis 实例拒绝连接RedisRTHigh:redis 实例响应时间过高RedisCPUHigh:redis 实例 CPU 使用率过高RedisMemHigh:redis 实例内存使用率过高RedisQPSHigh:redis 实例 QPS 过高#==============================================================#
# Error #
#==============================================================#
# redis down triggers a P0 alert
- alert : RedisDown
expr : redis_up < 1
for : 1m
labels : { level: 0, severity: CRIT, category : redis }
annotations :
summary : "CRIT RedisDown: {{ $labels.ins }} {{ $labels.instance }} {{ $value }}"
description : |
redis_up[ins={{ $labels.ins }}, instance={{ $labels.instance }}] = {{ $value }} == 0
http://g.pigsty/d/redis-instance?from=now-5m&to=now&var-ins={{$labels.ins}}
# redis reject connection in last 5m
- alert : RedisRejectConn
expr : redis:ins:conn_reject > 0
labels : { level: 0, severity: CRIT, category : redis }
annotations :
summary : "CRIT RedisRejectConn: {{ $labels.ins }} {{ $labels.instance }} {{ $value }}"
description : |
redis:ins:conn_reject[cls={{ $labels.cls }}, ins={{ $labels.ins }}][5m] = {{ $value }} > 0
http://g.pigsty/d/redis-instance?from=now-10m&to=now&viewPanel=88&fullscreen&var-ins={{ $labels.ins }}
#==============================================================#
# Latency #
#==============================================================#
# redis avg query response time > 160 µs
- alert : RedisRTHigh
expr : redis:ins:rt > 0.00016
for : 1m
labels : { level: 1, severity: WARN, category : redis }
annotations :
summary : "WARN RedisRTHigh: {{ $labels.cls }} {{ $labels.ins }}"
description : |
pg:ins:query_rt[cls={{ $labels.cls }}, ins={{ $labels.ins }}] = {{ $value }} > 160µs
http://g.pigsty/d/redis-instance?from=now-10m&to=now&viewPanel=97&fullscreen&var-ins={{ $labels.ins }}
#==============================================================#
# Saturation #
#==============================================================#
# redis cpu usage more than 70% for 1m
- alert : RedisCPUHigh
expr : redis:ins:cpu_usage > 0.70
for : 1m
labels : { level: 1, severity: WARN, category : redis }
annotations :
summary : "WARN RedisCPUHigh: {{ $labels.cls }} {{ $labels.ins }}"
description : |
redis:ins:cpu_all[cls={{ $labels.cls }}, ins={{ $labels.ins }}] = {{ $value }} > 60%
http://g.pigsty/d/redis-instance?from=now-10m&to=now&viewPanel=43&fullscreen&var-ins={{ $labels.ins }}
# redis mem usage more than 70% for 1m
- alert : RedisMemHigh
expr : redis:ins:mem_usage > 0.70
for : 1m
labels : { level: 1, severity: WARN, category : redis }
annotations :
summary : "WARN RedisMemHigh: {{ $labels.cls }} {{ $labels.ins }}"
description : |
redis:ins:mem_usage[cls={{ $labels.cls }}, ins={{ $labels.ins }}] = {{ $value }} > 80%
http://g.pigsty/d/redis-instance?from=now-10m&to=now&viewPanel=7&fullscreen&var-ins={{ $labels.ins }}
#==============================================================#
# Traffic #
#==============================================================#
# redis qps more than 32000 for 5m
- alert : RedisQPSHigh
expr : redis:ins:qps > 32000
for : 5m
labels : { level: 2, severity: INFO, category : redis }
annotations :
summary : "INFO RedisQPSHigh: {{ $labels.cls }} {{ $labels.ins }}"
description : |
redis:ins:qps[cls={{ $labels.cls }}, ins={{ $labels.ins }}] = {{ $value }} > 16000
http://g.pigsty/d/redis-instance?from=now-10m&to=now&viewPanel=96&fullscreen&var-ins={{ $labels.ins }}
16.6 - 指标列表 Pigsty REDIS 模块提供的完整监控指标列表与释义
REDIS 模块包含有 275 类可用监控指标。
Metric Name Type Labels Description ALERTS Unknown cls, ip, level, severity, instance, category, ins, alertname, job, alertstateN/A ALERTS_FOR_STATE Unknown cls, ip, level, severity, instance, category, ins, alertname, jobN/A redis:cls:aof_rewrite_time Unknown cls, jobN/A redis:cls:blocked_clients Unknown cls, jobN/A redis:cls:clients Unknown cls, jobN/A redis:cls:cmd_qps Unknown cls, cmd, jobN/A redis:cls:cmd_rt Unknown cls, cmd, jobN/A redis:cls:cmd_time Unknown cls, cmd, jobN/A redis:cls:conn_rate Unknown cls, jobN/A redis:cls:conn_reject Unknown cls, jobN/A redis:cls:cpu_sys Unknown cls, jobN/A redis:cls:cpu_sys_child Unknown cls, jobN/A redis:cls:cpu_usage Unknown cls, jobN/A redis:cls:cpu_usage_child Unknown cls, jobN/A redis:cls:cpu_user Unknown cls, jobN/A redis:cls:cpu_user_child Unknown cls, jobN/A redis:cls:fork_time Unknown cls, jobN/A redis:cls:key_evict Unknown cls, jobN/A redis:cls:key_expire Unknown cls, jobN/A redis:cls:key_hit Unknown cls, jobN/A redis:cls:key_hit_rate Unknown cls, jobN/A redis:cls:key_miss Unknown cls, jobN/A redis:cls:mem_max Unknown cls, jobN/A redis:cls:mem_usage Unknown cls, jobN/A redis:cls:mem_usage_max Unknown cls, jobN/A redis:cls:mem_used Unknown cls, jobN/A redis:cls:net_traffic Unknown cls, jobN/A redis:cls:qps Unknown cls, jobN/A redis:cls:qps_mu Unknown cls, jobN/A redis:cls:qps_realtime Unknown cls, jobN/A redis:cls:qps_sigma Unknown cls, jobN/A redis:cls:rt Unknown cls, jobN/A redis:cls:rt_mu Unknown cls, jobN/A redis:cls:rt_sigma Unknown cls, jobN/A redis:cls:rx Unknown cls, jobN/A redis:cls:size Unknown cls, jobN/A redis:cls:tx Unknown cls, jobN/A redis:env:blocked_clients Unknown jobN/A redis:env:clients Unknown jobN/A redis:env:cmd_qps Unknown cmd, jobN/A redis:env:cmd_rt Unknown cmd, jobN/A redis:env:cmd_time Unknown cmd, jobN/A redis:env:conn_rate Unknown jobN/A redis:env:conn_reject Unknown jobN/A redis:env:cpu_usage Unknown jobN/A redis:env:cpu_usage_child Unknown jobN/A redis:env:key_evict Unknown jobN/A redis:env:key_expire Unknown jobN/A redis:env:key_hit Unknown jobN/A redis:env:key_hit_rate Unknown jobN/A redis:env:key_miss Unknown jobN/A redis:env:mem_usage Unknown jobN/A redis:env:net_traffic Unknown jobN/A redis:env:qps Unknown jobN/A redis:env:qps_mu Unknown jobN/A redis:env:qps_realtime Unknown jobN/A redis:env:qps_sigma Unknown jobN/A redis:env:rt Unknown jobN/A redis:env:rt_mu Unknown jobN/A redis:env:rt_sigma Unknown jobN/A redis:env:rx Unknown jobN/A redis:env:tx Unknown jobN/A redis:ins Unknown cls, id, instance, ins, jobN/A redis:ins:blocked_clients Unknown cls, ip, instance, ins, jobN/A redis:ins:clients Unknown cls, ip, instance, ins, jobN/A redis:ins:cmd_qps Unknown cls, cmd, ip, instance, ins, jobN/A redis:ins:cmd_rt Unknown cls, cmd, ip, instance, ins, jobN/A redis:ins:cmd_time Unknown cls, cmd, ip, instance, ins, jobN/A redis:ins:conn_rate Unknown cls, ip, instance, ins, jobN/A redis:ins:conn_reject Unknown cls, ip, instance, ins, jobN/A redis:ins:cpu_sys Unknown cls, ip, instance, ins, jobN/A redis:ins:cpu_sys_child Unknown cls, ip, instance, ins, jobN/A redis:ins:cpu_usage Unknown cls, ip, instance, ins, jobN/A redis:ins:cpu_usage_child Unknown cls, ip, instance, ins, jobN/A redis:ins:cpu_user Unknown cls, ip, instance, ins, jobN/A redis:ins:cpu_user_child Unknown cls, ip, instance, ins, jobN/A redis:ins:key_evict Unknown cls, ip, instance, ins, jobN/A redis:ins:key_expire Unknown cls, ip, instance, ins, jobN/A redis:ins:key_hit Unknown cls, ip, instance, ins, jobN/A redis:ins:key_hit_rate Unknown cls, ip, instance, ins, jobN/A redis:ins:key_miss Unknown cls, ip, instance, ins, jobN/A redis:ins:lsn_rate Unknown cls, ip, instance, ins, jobN/A redis:ins:mem_usage Unknown cls, ip, instance, ins, jobN/A redis:ins:net_traffic Unknown cls, ip, instance, ins, jobN/A redis:ins:qps Unknown cls, ip, instance, ins, jobN/A redis:ins:qps_mu Unknown cls, ip, instance, ins, jobN/A redis:ins:qps_realtime Unknown cls, ip, instance, ins, jobN/A redis:ins:qps_sigma Unknown cls, ip, instance, ins, jobN/A redis:ins:rt Unknown cls, ip, instance, ins, jobN/A redis:ins:rt_mu Unknown cls, ip, instance, ins, jobN/A redis:ins:rt_sigma Unknown cls, ip, instance, ins, jobN/A redis:ins:rx Unknown cls, ip, instance, ins, jobN/A redis:ins:tx Unknown cls, ip, instance, ins, jobN/A redis:node:ip Unknown cls, ip, instance, ins, jobN/A redis:node:mem_alloc Unknown cls, ip, jobN/A redis:node:mem_total Unknown cls, ip, jobN/A redis:node:mem_used Unknown cls, ip, jobN/A redis:node:qps Unknown cls, ip, jobN/A redis_active_defrag_running gauge cls, ip, instance, ins, jobactive_defrag_running metric redis_allocator_active_bytes gauge cls, ip, instance, ins, joballocator_active_bytes metric redis_allocator_allocated_bytes gauge cls, ip, instance, ins, joballocator_allocated_bytes metric redis_allocator_frag_bytes gauge cls, ip, instance, ins, joballocator_frag_bytes metric redis_allocator_frag_ratio gauge cls, ip, instance, ins, joballocator_frag_ratio metric redis_allocator_resident_bytes gauge cls, ip, instance, ins, joballocator_resident_bytes metric redis_allocator_rss_bytes gauge cls, ip, instance, ins, joballocator_rss_bytes metric redis_allocator_rss_ratio gauge cls, ip, instance, ins, joballocator_rss_ratio metric redis_aof_current_rewrite_duration_sec gauge cls, ip, instance, ins, jobaof_current_rewrite_duration_sec metric redis_aof_enabled gauge cls, ip, instance, ins, jobaof_enabled metric redis_aof_last_bgrewrite_status gauge cls, ip, instance, ins, jobaof_last_bgrewrite_status metric redis_aof_last_cow_size_bytes gauge cls, ip, instance, ins, jobaof_last_cow_size_bytes metric redis_aof_last_rewrite_duration_sec gauge cls, ip, instance, ins, jobaof_last_rewrite_duration_sec metric redis_aof_last_write_status gauge cls, ip, instance, ins, jobaof_last_write_status metric redis_aof_rewrite_in_progress gauge cls, ip, instance, ins, jobaof_rewrite_in_progress metric redis_aof_rewrite_scheduled gauge cls, ip, instance, ins, jobaof_rewrite_scheduled metric redis_blocked_clients gauge cls, ip, instance, ins, jobblocked_clients metric redis_client_recent_max_input_buffer_bytes gauge cls, ip, instance, ins, jobclient_recent_max_input_buffer_bytes metric redis_client_recent_max_output_buffer_bytes gauge cls, ip, instance, ins, jobclient_recent_max_output_buffer_bytes metric redis_clients_in_timeout_table gauge cls, ip, instance, ins, jobclients_in_timeout_table metric redis_cluster_connections gauge cls, ip, instance, ins, jobcluster_connections metric redis_cluster_current_epoch gauge cls, ip, instance, ins, jobcluster_current_epoch metric redis_cluster_enabled gauge cls, ip, instance, ins, jobcluster_enabled metric redis_cluster_known_nodes gauge cls, ip, instance, ins, jobcluster_known_nodes metric redis_cluster_messages_received_total gauge cls, ip, instance, ins, jobcluster_messages_received_total metric redis_cluster_messages_sent_total gauge cls, ip, instance, ins, jobcluster_messages_sent_total metric redis_cluster_my_epoch gauge cls, ip, instance, ins, jobcluster_my_epoch metric redis_cluster_size gauge cls, ip, instance, ins, jobcluster_size metric redis_cluster_slots_assigned gauge cls, ip, instance, ins, jobcluster_slots_assigned metric redis_cluster_slots_fail gauge cls, ip, instance, ins, jobcluster_slots_fail metric redis_cluster_slots_ok gauge cls, ip, instance, ins, jobcluster_slots_ok metric redis_cluster_slots_pfail gauge cls, ip, instance, ins, jobcluster_slots_pfail metric redis_cluster_state gauge cls, ip, instance, ins, jobcluster_state metric redis_cluster_stats_messages_meet_received gauge cls, ip, instance, ins, jobcluster_stats_messages_meet_received metric redis_cluster_stats_messages_meet_sent gauge cls, ip, instance, ins, jobcluster_stats_messages_meet_sent metric redis_cluster_stats_messages_ping_received gauge cls, ip, instance, ins, jobcluster_stats_messages_ping_received metric redis_cluster_stats_messages_ping_sent gauge cls, ip, instance, ins, jobcluster_stats_messages_ping_sent metric redis_cluster_stats_messages_pong_received gauge cls, ip, instance, ins, jobcluster_stats_messages_pong_received metric redis_cluster_stats_messages_pong_sent gauge cls, ip, instance, ins, jobcluster_stats_messages_pong_sent metric redis_commands_duration_seconds_total counter cls, cmd, ip, instance, ins, jobTotal amount of time in seconds spent per command redis_commands_failed_calls_total counter cls, cmd, ip, instance, ins, jobTotal number of errors prior command execution per command redis_commands_latencies_usec_bucket Unknown cls, cmd, ip, le, instance, ins, jobN/A redis_commands_latencies_usec_count Unknown cls, cmd, ip, instance, ins, jobN/A redis_commands_latencies_usec_sum Unknown cls, cmd, ip, instance, ins, jobN/A redis_commands_processed_total counter cls, ip, instance, ins, jobcommands_processed_total metric redis_commands_rejected_calls_total counter cls, cmd, ip, instance, ins, jobTotal number of errors within command execution per command redis_commands_total counter cls, cmd, ip, instance, ins, jobTotal number of calls per command redis_config_io_threads gauge cls, ip, instance, ins, jobconfig_io_threads metric redis_config_maxclients gauge cls, ip, instance, ins, jobconfig_maxclients metric redis_config_maxmemory gauge cls, ip, instance, ins, jobconfig_maxmemory metric redis_connected_clients gauge cls, ip, instance, ins, jobconnected_clients metric redis_connected_slave_lag_seconds gauge cls, ip, slave_ip, instance, slave_state, ins, slave_port, jobLag of connected slave redis_connected_slave_offset_bytes gauge cls, ip, slave_ip, instance, slave_state, ins, slave_port, jobOffset of connected slave redis_connected_slaves gauge cls, ip, instance, ins, jobconnected_slaves metric redis_connections_received_total counter cls, ip, instance, ins, jobconnections_received_total metric redis_cpu_sys_children_seconds_total counter cls, ip, instance, ins, jobcpu_sys_children_seconds_total metric redis_cpu_sys_main_thread_seconds_total counter cls, ip, instance, ins, jobcpu_sys_main_thread_seconds_total metric redis_cpu_sys_seconds_total counter cls, ip, instance, ins, jobcpu_sys_seconds_total metric redis_cpu_user_children_seconds_total counter cls, ip, instance, ins, jobcpu_user_children_seconds_total metric redis_cpu_user_main_thread_seconds_total counter cls, ip, instance, ins, jobcpu_user_main_thread_seconds_total metric redis_cpu_user_seconds_total counter cls, ip, instance, ins, jobcpu_user_seconds_total metric redis_db_keys gauge cls, ip, instance, ins, db, jobTotal number of keys by DB redis_db_keys_expiring gauge cls, ip, instance, ins, db, jobTotal number of expiring keys by DB redis_defrag_hits gauge cls, ip, instance, ins, jobdefrag_hits metric redis_defrag_key_hits gauge cls, ip, instance, ins, jobdefrag_key_hits metric redis_defrag_key_misses gauge cls, ip, instance, ins, jobdefrag_key_misses metric redis_defrag_misses gauge cls, ip, instance, ins, jobdefrag_misses metric redis_dump_payload_sanitizations counter cls, ip, instance, ins, jobdump_payload_sanitizations metric redis_errors_total counter cls, ip, err, instance, ins, jobTotal number of errors per error type redis_evicted_keys_total counter cls, ip, instance, ins, jobevicted_keys_total metric redis_expired_keys_total counter cls, ip, instance, ins, jobexpired_keys_total metric redis_expired_stale_percentage gauge cls, ip, instance, ins, jobexpired_stale_percentage metric redis_expired_time_cap_reached_total gauge cls, ip, instance, ins, jobexpired_time_cap_reached_total metric redis_exporter_build_info gauge cls, golang_version, ip, commit_sha, instance, version, ins, job, build_dateredis exporter build_info redis_exporter_last_scrape_connect_time_seconds gauge cls, ip, instance, ins, jobexporter_last_scrape_connect_time_seconds metric redis_exporter_last_scrape_duration_seconds gauge cls, ip, instance, ins, jobexporter_last_scrape_duration_seconds metric redis_exporter_last_scrape_error gauge cls, ip, instance, ins, jobThe last scrape error status. redis_exporter_scrape_duration_seconds_count Unknown cls, ip, instance, ins, jobN/A redis_exporter_scrape_duration_seconds_sum Unknown cls, ip, instance, ins, jobN/A redis_exporter_scrapes_total counter cls, ip, instance, ins, jobCurrent total redis scrapes. redis_instance_info gauge cls, ip, os, role, instance, run_id, redis_version, tcp_port, process_id, ins, redis_mode, maxmemory_policy, redis_build_id, jobInformation about the Redis instance redis_io_threaded_reads_processed counter cls, ip, instance, ins, jobio_threaded_reads_processed metric redis_io_threaded_writes_processed counter cls, ip, instance, ins, jobio_threaded_writes_processed metric redis_io_threads_active gauge cls, ip, instance, ins, jobio_threads_active metric redis_keyspace_hits_total counter cls, ip, instance, ins, jobkeyspace_hits_total metric redis_keyspace_misses_total counter cls, ip, instance, ins, jobkeyspace_misses_total metric redis_last_key_groups_scrape_duration_milliseconds gauge cls, ip, instance, ins, jobDuration of the last key group metrics scrape in milliseconds redis_last_slow_execution_duration_seconds gauge cls, ip, instance, ins, jobThe amount of time needed for last slow execution, in seconds redis_latency_percentiles_usec summary cls, cmd, ip, instance, quantile, ins, jobA summary of latency percentile distribution per command redis_latency_percentiles_usec_count Unknown cls, cmd, ip, instance, ins, jobN/A redis_latency_percentiles_usec_sum Unknown cls, cmd, ip, instance, ins, jobN/A redis_latest_fork_seconds gauge cls, ip, instance, ins, joblatest_fork_seconds metric redis_lazyfree_pending_objects gauge cls, ip, instance, ins, joblazyfree_pending_objects metric redis_loading_dump_file gauge cls, ip, instance, ins, jobloading_dump_file metric redis_master_last_io_seconds_ago gauge cls, ip, master_host, instance, ins, job, master_portMaster last io seconds ago redis_master_link_up gauge cls, ip, master_host, instance, ins, job, master_portMaster link status on Redis slave redis_master_repl_offset gauge cls, ip, instance, ins, jobmaster_repl_offset metric redis_master_sync_in_progress gauge cls, ip, master_host, instance, ins, job, master_portMaster sync in progress redis_mem_clients_normal gauge cls, ip, instance, ins, jobmem_clients_normal metric redis_mem_clients_slaves gauge cls, ip, instance, ins, jobmem_clients_slaves metric redis_mem_fragmentation_bytes gauge cls, ip, instance, ins, jobmem_fragmentation_bytes metric redis_mem_fragmentation_ratio gauge cls, ip, instance, ins, jobmem_fragmentation_ratio metric redis_mem_not_counted_for_eviction_bytes gauge cls, ip, instance, ins, jobmem_not_counted_for_eviction_bytes metric redis_memory_max_bytes gauge cls, ip, instance, ins, jobmemory_max_bytes metric redis_memory_used_bytes gauge cls, ip, instance, ins, jobmemory_used_bytes metric redis_memory_used_dataset_bytes gauge cls, ip, instance, ins, jobmemory_used_dataset_bytes metric redis_memory_used_lua_bytes gauge cls, ip, instance, ins, jobmemory_used_lua_bytes metric redis_memory_used_overhead_bytes gauge cls, ip, instance, ins, jobmemory_used_overhead_bytes metric redis_memory_used_peak_bytes gauge cls, ip, instance, ins, jobmemory_used_peak_bytes metric redis_memory_used_rss_bytes gauge cls, ip, instance, ins, jobmemory_used_rss_bytes metric redis_memory_used_scripts_bytes gauge cls, ip, instance, ins, jobmemory_used_scripts_bytes metric redis_memory_used_startup_bytes gauge cls, ip, instance, ins, jobmemory_used_startup_bytes metric redis_migrate_cached_sockets_total gauge cls, ip, instance, ins, jobmigrate_cached_sockets_total metric redis_module_fork_in_progress gauge cls, ip, instance, ins, jobmodule_fork_in_progress metric redis_module_fork_last_cow_size gauge cls, ip, instance, ins, jobmodule_fork_last_cow_size metric redis_net_input_bytes_total counter cls, ip, instance, ins, jobnet_input_bytes_total metric redis_net_output_bytes_total counter cls, ip, instance, ins, jobnet_output_bytes_total metric redis_number_of_cached_scripts gauge cls, ip, instance, ins, jobnumber_of_cached_scripts metric redis_process_id gauge cls, ip, instance, ins, jobprocess_id metric redis_pubsub_channels gauge cls, ip, instance, ins, jobpubsub_channels metric redis_pubsub_patterns gauge cls, ip, instance, ins, jobpubsub_patterns metric redis_pubsubshard_channels gauge cls, ip, instance, ins, jobpubsubshard_channels metric redis_rdb_bgsave_in_progress gauge cls, ip, instance, ins, jobrdb_bgsave_in_progress metric redis_rdb_changes_since_last_save gauge cls, ip, instance, ins, jobrdb_changes_since_last_save metric redis_rdb_current_bgsave_duration_sec gauge cls, ip, instance, ins, jobrdb_current_bgsave_duration_sec metric redis_rdb_last_bgsave_duration_sec gauge cls, ip, instance, ins, jobrdb_last_bgsave_duration_sec metric redis_rdb_last_bgsave_status gauge cls, ip, instance, ins, jobrdb_last_bgsave_status metric redis_rdb_last_cow_size_bytes gauge cls, ip, instance, ins, jobrdb_last_cow_size_bytes metric redis_rdb_last_save_timestamp_seconds gauge cls, ip, instance, ins, jobrdb_last_save_timestamp_seconds metric redis_rejected_connections_total counter cls, ip, instance, ins, jobrejected_connections_total metric redis_repl_backlog_first_byte_offset gauge cls, ip, instance, ins, jobrepl_backlog_first_byte_offset metric redis_repl_backlog_history_bytes gauge cls, ip, instance, ins, jobrepl_backlog_history_bytes metric redis_repl_backlog_is_active gauge cls, ip, instance, ins, jobrepl_backlog_is_active metric redis_replica_partial_resync_accepted gauge cls, ip, instance, ins, jobreplica_partial_resync_accepted metric redis_replica_partial_resync_denied gauge cls, ip, instance, ins, jobreplica_partial_resync_denied metric redis_replica_resyncs_full gauge cls, ip, instance, ins, jobreplica_resyncs_full metric redis_replication_backlog_bytes gauge cls, ip, instance, ins, jobreplication_backlog_bytes metric redis_second_repl_offset gauge cls, ip, instance, ins, jobsecond_repl_offset metric redis_sentinel_master_ckquorum_status gauge cls, ip, message, instance, ins, master_name, jobMaster ckquorum status redis_sentinel_master_ok_sentinels gauge cls, ip, instance, ins, master_address, master_name, jobThe number of okay sentinels monitoring this master redis_sentinel_master_ok_slaves gauge cls, ip, instance, ins, master_address, master_name, jobThe number of okay slaves of the master redis_sentinel_master_sentinels gauge cls, ip, instance, ins, master_address, master_name, jobThe number of sentinels monitoring this master redis_sentinel_master_setting_ckquorum gauge cls, ip, instance, ins, master_address, master_name, jobShow the current ckquorum config for each master redis_sentinel_master_setting_down_after_milliseconds gauge cls, ip, instance, ins, master_address, master_name, jobShow the current down-after-milliseconds config for each master redis_sentinel_master_setting_failover_timeout gauge cls, ip, instance, ins, master_address, master_name, jobShow the current failover-timeout config for each master redis_sentinel_master_setting_parallel_syncs gauge cls, ip, instance, ins, master_address, master_name, jobShow the current parallel-syncs config for each master redis_sentinel_master_slaves gauge cls, ip, instance, ins, master_address, master_name, jobThe number of slaves of the master redis_sentinel_master_status gauge cls, ip, master_status, instance, ins, master_address, master_name, jobMaster status on Sentinel redis_sentinel_masters gauge cls, ip, instance, ins, jobThe number of masters this sentinel is watching redis_sentinel_running_scripts gauge cls, ip, instance, ins, jobNumber of scripts in execution right now redis_sentinel_scripts_queue_length gauge cls, ip, instance, ins, jobQueue of user scripts to execute redis_sentinel_simulate_failure_flags gauge cls, ip, instance, ins, jobFailures simulations redis_sentinel_tilt gauge cls, ip, instance, ins, jobSentinel is in TILT mode redis_slave_expires_tracked_keys gauge cls, ip, instance, ins, jobslave_expires_tracked_keys metric redis_slave_info gauge cls, ip, master_host, instance, read_only, ins, job, master_portInformation about the Redis slave redis_slave_priority gauge cls, ip, instance, ins, jobslave_priority metric redis_slave_repl_offset gauge cls, ip, master_host, instance, ins, job, master_portSlave replication offset redis_slowlog_last_id gauge cls, ip, instance, ins, jobLast id of slowlog redis_slowlog_length gauge cls, ip, instance, ins, jobTotal slowlog redis_start_time_seconds gauge cls, ip, instance, ins, jobStart time of the Redis instance since unix epoch in seconds. redis_target_scrape_request_errors_total counter cls, ip, instance, ins, jobErrors in requests to the exporter redis_total_error_replies counter cls, ip, instance, ins, jobtotal_error_replies metric redis_total_reads_processed counter cls, ip, instance, ins, jobtotal_reads_processed metric redis_total_system_memory_bytes gauge cls, ip, instance, ins, jobtotal_system_memory_bytes metric redis_total_writes_processed counter cls, ip, instance, ins, jobtotal_writes_processed metric redis_tracking_clients gauge cls, ip, instance, ins, jobtracking_clients metric redis_tracking_total_items gauge cls, ip, instance, ins, jobtracking_total_items metric redis_tracking_total_keys gauge cls, ip, instance, ins, jobtracking_total_keys metric redis_tracking_total_prefixes gauge cls, ip, instance, ins, jobtracking_total_prefixes metric redis_unexpected_error_replies counter cls, ip, instance, ins, jobunexpected_error_replies metric redis_up gauge cls, ip, instance, ins, jobInformation about the Redis instance redis_uptime_in_seconds gauge cls, ip, instance, ins, jobuptime_in_seconds metric scrape_duration_seconds Unknown cls, ip, instance, ins, jobN/A scrape_samples_post_metric_relabeling Unknown cls, ip, instance, ins, jobN/A scrape_samples_scraped Unknown cls, ip, instance, ins, jobN/A scrape_series_added Unknown cls, ip, instance, ins, jobN/A up Unknown cls, ip, instance, ins, jobN/A
16.7 - 常见问题 Pigsty REDIS 模块常见问题答疑
Redis初始化失败:ABORT due to existing redis instance 这意味着正在初始化的 Redis 实例已经存在了,使用 redis_clean = true 和 redis_safeguard = false 来强制清除redis数据
当您运行redis.yml来初始化一个已经在运行的redis实例,并且redis_clean 设置为false时,就会出现这种情况。
如果redis_clean设置为true(并且 redis_safeguard 也设置为false),redis.yml剧本将删除现有的redis实例并将其重新初始化为一个新的实例,这使得redis.yml剧本完全具有幂等性。
Redis初始化失败:ABORT due to redis_safeguard enabled 这意味着正准备清理的 Redis 实例打开了防误删保险:当 redis_safeguard 设置为 true 时,尝试移除一个redis实例时就会出现这种情况。
您可以关闭 redis_safeguard 来移除Redis实例。这就是 redis_safeguard 的作用。
如何在某个节点上添加一个新的Redis实例? 使用 bin/redis-add <ip> <port> 在节点上部署一个新的redis实例。
如何从节点上移除一个特定实例? 使用 bin/redis-rm <ip> <port> 从节点上移除一个单独的redis实例。
是否有计划升级到 Valkey 或最新版本? 因为 Redis 并非本项目的核心组件,目前没有计划更新至 Redis 最新的 RSAL / AGPLv3 版本或 Valkey 的计划。
Pigsty 中的 Redis 版本锁定在最后一个使用 BSD 协议的 7.2.6 版本。
这个版本经过大规模生产环境的验证,而 Pigsty 已经没有这样的场景去重新验证更新版本的稳定性与可靠性了。
17 - 模块:FERRET 使用 FerretDB 为 PostgreSQL 添加 MongoDB 兼容的协议支持
FERRET 是 Pigsty 中的一个 可选 模块,用于部署 FerretDB ——
这是一个构建在 PostgreSQL 内核与 DocumentDB 扩展之上的协议转换中间件。
能够对接使用 MongoDB 驱动的应用程序,并将这些请求转换为对 PostgreSQL 的操作。
Pigsty 是 FerretDB 社区的合作伙伴,我们制作了 FerretDB 与 DocumentDB (ferretdb 专用分支) 的二进制包,
并提供了开箱即用的配置模板 mongo.yml ,帮助您轻松部署企业级质量的 FerretDB 集群。
17.1 - 使用方法 安装客户端工具,连接并使用 FerretDB
本文档介绍如何安装 MongoDB 客户端工具并连接到 FerretDB。
安装客户端工具 您可以使用 MongoDB 的命令行工具 MongoSH 来访问 FerretDB。
使用 pig 命令添加 MongoDB 仓库,然后使用 yum 或 apt 安装 mongosh:
pig repo add mongo -u # 添加 MongoDB 官方仓库
yum install mongodb-mongosh # RHEL/CentOS/Rocky/Alma
apt install mongodb-mongosh # Debian/Ubuntu
安装完成后,您可以使用 mongosh 命令连接到 FerretDB。
连接到 FerretDB 您可以使用任何语言的 MongoDB 驱动程序通过 MongoDB 连接字符串访问 FerretDB。以下是使用 mongosh CLI 工具的示例:
$ mongosh
Current Mongosh Log ID: 67ba8c1fe551f042bf51e943
Connecting to: mongodb://127.0.0.1:27017/?directConnection= true& serverSelectionTimeoutMS = 2000& appName = mongosh+2.4.0
Using MongoDB: 7.0.77
Using Mongosh: 2.4.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
test>
使用连接字符串 FerretDB 的身份验证完全基于 PostgreSQL。由于 Pigsty 管理的 PostgreSQL 集群默认使用 scram-sha-256 认证方式,您必须在连接字符串中指定 PLAIN 认证机制:
mongosh 'mongodb://dbuser_meta:DBUser.Meta@10.10.10.10:27017?authMechanism=PLAIN'
连接字符串格式:
mongodb://<username>:<password>@<host>:<port>/<database>?authMechanism=PLAIN
使用不同的用户 您可以使用任何已在 PostgreSQL 中创建的用户连接到 FerretDB:
# 使用 dbuser_dba 用户
mongosh 'mongodb://dbuser_dba:DBUser.DBA@10.10.10.10:27017?authMechanism=PLAIN'
# 使用 mongod 超级用户
mongosh 'mongodb://mongod:DBUser.Mongo@10.10.10.10:27017?authMechanism=PLAIN'
# 连接到特定数据库
mongosh 'mongodb://test:test@10.10.10.11:27017/test?authMechanism=PLAIN'
基本操作 连接到 FerretDB 后,您可以像使用 MongoDB 一样进行操作。以下是一些基本操作示例:
数据库操作 // 切换/创建数据库
use mydb
// 显示所有数据库
show dbs
// 删除当前数据库
db . dropDatabase ()
集合操作 // 创建集合
db . createCollection ( 'users' )
// 显示所有集合
show collections
// 删除集合
db . users . drop ()
文档操作 // 插入单个文档
db . users . insertOne ({
name : 'Alice' ,
age : 30 ,
email : 'alice@example.com'
})
// 插入多个文档
db . users . insertMany ([
{ name : 'Bob' , age : 25 },
{ name : 'Charlie' , age : 35 }
])
// 查询文档
db . users . find ()
db . users . find ({ age : { $gt : 25 } })
db . users . findOne ({ name : 'Alice' })
// 更新文档
db . users . updateOne (
{ name : 'Alice' },
{ $set : { age : 31 } }
)
// 删除文档
db . users . deleteOne ({ name : 'Bob' })
db . users . deleteMany ({ age : { $lt : 30 } })
索引操作 // 创建索引
db . users . createIndex ({ name : 1 })
db . users . createIndex ({ age : - 1 })
// 查看索引
db . users . getIndexes ()
// 删除索引
db . users . dropIndex ( 'name_1' )
与 MongoDB 的差异 FerretDB 实现了 MongoDB 的线协议,但底层使用 PostgreSQL 存储数据。这意味着:
MongoDB 命令会被翻译为 SQL 语句执行 大多数基本操作与 MongoDB 兼容 某些高级功能可能有差异或不支持 您可以查阅以下资源了解详细信息:
程序语言驱动 除了 mongosh 命令行工具,您还可以使用各种编程语言的 MongoDB 驱动程序连接到 FerretDB:
Python from pymongo import MongoClient
client = MongoClient ( 'mongodb://dbuser_meta:DBUser.Meta@10.10.10.10:27017/?authMechanism=PLAIN' )
db = client . test
collection = db . users
collection . insert_one ({ 'name' : 'Alice' , 'age' : 30 })
Node.js const { MongoClient } = require ( 'mongodb' );
const uri = 'mongodb://dbuser_meta:DBUser.Meta@10.10.10.10:27017/?authMechanism=PLAIN' ;
const client = new MongoClient ( uri );
async function run () {
await client . connect ();
const db = client . db ( 'test' );
const collection = db . collection ( 'users' );
await collection . insertOne ({ name : 'Alice' , age : 30 });
}
Go import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
uri := "mongodb://dbuser_meta:DBUser.Meta@10.10.10.10:27017/?authMechanism=PLAIN"
client , err := mongo . Connect ( context . TODO (), options . Client (). ApplyURI ( uri ))
关键点:所有驱动程序都需要在连接字符串中指定 authMechanism=PLAIN 参数。
17.2 - 集群配置 配置 FerretDB 模块,定义集群拓扑
在部署 FerretDB 集群之前,您需要使用相关 参数 在配置清单中定义它。
FerretDB 集群 以下示例使用默认的单节点 pg-meta 集群的 meta 数据库作为 FerretDB 的底层存储:
all :
children :
#----------------------------------#
# ferretdb for mongodb on postgresql
#----------------------------------#
# ./mongo.yml -l ferret
ferret :
hosts :
10.10.10.10 : { mongo_seq : 1 }
vars :
mongo_cluster : ferret
mongo_pgurl : 'postgres://mongod:DBUser.Mongo@10.10.10.10:5432/meta'
这里,mongo_cluster 和 mongo_seq 是基本的身份参数。对于 FerretDB,还需要 mongo_pgurl 来指定底层 PostgreSQL 的位置。
请注意,mongo_pgurl 参数需要一个 PostgreSQL 超级用户 。在此示例中,为 FerretDB 定义了一个专用的 mongod 超级用户。
请注意,FerretDB 的 身份验证 完全基于 PostgreSQL。您可以使用 FerretDB 或 PostgreSQL 创建其他常规用户。
PostgreSQL 集群 FerretDB 2.0+ 需要一个扩展:DocumentDB ,它依赖于几个其他扩展。以下是为 FerretDB 创建 PostgreSQL 集群的模板:
all :
children :
#----------------------------------#
# pgsql (singleton on current node)
#----------------------------------#
# postgres cluster: pg-meta
pg-meta :
hosts : { 10.10.10.10 : { pg_seq: 1, pg_role : primary } }
vars :
pg_cluster : pg-meta
pg_users :
- { name: mongod ,password: DBUser.Mongo ,pgbouncer: true ,roles: [dbrole_admin ] ,superuser: true ,comment : ferretdb super user }
- { name: dbuser_meta ,password: DBUser.Meta ,pgbouncer: true ,roles: [dbrole_admin] ,comment : pigsty admin user }
- { name: dbuser_view ,password: DBUser.Viewer ,pgbouncer: true ,roles: [dbrole_readonly] ,comment : read-only viewer for meta database }
pg_databases :
- {name: meta, owner: mongod ,baseline: cmdb.sql ,comment: pigsty meta database ,schemas: [pigsty] ,extensions : [ documentdb, postgis, vector, pg_cron, rum ]}
pg_hba_rules :
- { user: dbuser_view , db: all ,addr: infra ,auth: pwd ,title : 'allow grafana dashboard access cmdb from infra nodes' }
- { user: mongod , db: all ,addr: world ,auth: pwd ,title : 'mongodb password access from everywhere' }
pg_extensions :
- documentdb, citus, postgis, pgvector, pg_cron, rum
pg_parameters :
cron.database_name : meta
pg_libs : 'pg_documentdb, pg_documentdb_core, pg_cron, pg_stat_statements, auto_explain'
关键配置要点:
用户配置 :需要创建一个具有超级用户权限的 mongod 用户,供 FerretDB 使用数据库配置 :数据库需要安装 documentdb 扩展及其依赖HBA 规则 :允许 mongod 用户从任意地址通过密码认证连接共享库 :需要在 pg_libs 中预加载 pg_documentdb 和 pg_documentdb_core高可用性 您可以使用 服务 连接到高可用的 PostgreSQL 集群,并部署多个 FerretDB 实例副本,并为 FerretDB 层绑定 L2 VIP 以实现高可用性。
ferret :
hosts :
10.10.10.45 : { mongo_seq : 1 }
10.10.10.46 : { mongo_seq : 2 }
10.10.10.47 : { mongo_seq : 3 }
vars :
mongo_cluster : ferret
mongo_pgurl : 'postgres://mongod:DBUser.Mongo@10.10.10.3:5436/test'
vip_enabled : true
vip_vrid : 128
vip_address : 10.10.10.99
vip_interface : eth1
在这个高可用配置中:
多实例部署 :在三个节点上部署 FerretDB 实例,所有实例连接到同一个 PostgreSQL 后端VIP 配置 :使用 Keepalived 绑定虚拟 IP 10.10.10.99,实现 FerretDB 层的故障转移服务地址 :使用 PostgreSQL 的服务地址(端口 5436 通常是主库服务),确保连接到正确的主库这样配置后,客户端可以通过 VIP 地址连接到 FerretDB,即使某个 FerretDB 实例故障,VIP 也会自动漂移到其他可用实例。
17.3 - 参数列表 使用 9 个参数自定义 FerretDB 组件
参数概览 FERRET 参数组用于 FerretDB 部署与配置,包括身份标识、底层 PostgreSQL 连接、监听端口以及 SSL 设置。
默认值 默认参数定义在 roles/ferret/defaults/main.yml 中:
# mongo_cluster: #CLUSTER # mongo 集群名称,必选身份参数
# mongo_seq: 0 #INSTANCE # mongo 实例序列号,必选身份参数
# mongo_pgurl: 'postgres:///' # mongo/ferretdb 底层 postgresql url,必选
mongo_ssl_enabled : false # mongo/ferretdb ssl 启用,默认为 false
mongo_listen : '' # mongo/ferretdb 监听地址,'' 表示所有地址
mongo_port : 27017 # mongo/ferretdb 监听端口,默认为 27017
mongo_ssl_port : 27018 # mongo/ferretdb tls 监听端口,默认为 27018
mongo_exporter_port : 9216 # mongo/ferretdb exporter 端口,默认为 9216
mongo_extra_vars : '' # mongo/ferretdb 的额外环境变量
mongo_cluster参数名称:mongo_cluster,类型:string,级别:C
mongo 集群名称,必选身份参数。
没有默认值,您必须为生产环境显式定义它。
集群名称需要符合正则表达式 [a-z][a-z0-9-]*,建议使用描述性名称。
mongo_seq参数名称:mongo_seq,类型:int,级别:I
mongo 实例序列号,集群内需要唯一的整数标识。
您必须为每个 mongo 实例显式定义序列号,整数从 0 或 1 开始。
mongo_pgurl参数名称:mongo_pgurl,类型:pgurl,级别:C/I
FerretDB 连接的底层 PostgreSQL URL,必选参数。
没有默认值,您必须显式定义它。这是 FerretDB 将用作其后端存储的 PostgreSQL 数据库连接串。
格式:postgres://username:password@host:port/database
请注意:
用户需要是 PostgreSQL 超级用户 目标数据库需要安装 documentdb 扩展 建议使用专用的 mongod 用户 mongo_ssl_enabled参数名称:mongo_ssl_enabled,类型:bool,级别:C
是否为 FerretDB 启用 SSL/TLS 加密。
默认值为 false。设置为 true 以启用 mongo 连接的 SSL/TLS 加密。
启用后,FerretDB 将会:
mongo_listen参数名称:mongo_listen,类型:ip,级别:C
mongo 绑定的监听地址。
默认值为空字符串 '',这意味着监听所有可用地址(0.0.0.0)。您可以指定特定的 IP 地址进行绑定。
mongo_port参数名称:mongo_port,类型:port,级别:C
mongo 客户端连接的服务端口。
默认值为 27017,这是标准的 MongoDB 端口。如果您需要避免端口冲突或有安全考虑,可以更改此端口。
mongo_ssl_port参数名称:mongo_ssl_port,类型:port,级别:C
mongo 加密连接的 TLS 监听端口。
默认值为 27018。当通过 mongo_ssl_enabled 启用 SSL/TLS 时,FerretDB 将在此端口上接受加密连接。
mongo_exporter_port参数名称:mongo_exporter_port,类型:port,级别:C
mongo 指标收集的 Exporter 端口。
默认值为 9216。此端口由 FerretDB 内置的指标导出器使用,向 Prometheus 暴露监控指标。
参数名称:mongo_extra_vars,类型:string,级别:C
FerretDB 服务器的额外环境变量。
默认值为空字符串 ''。您可以指定将传递给 FerretDB 进程的额外环境变量,格式为 KEY=VALUE,多个变量用空格分隔。
例如:
mongo_extra_vars : 'FERRETDB_LOG_LEVEL=debug FERRETDB_TELEMETRY=disable'
17.4 - 管理预案 创建、移除、扩展、收缩、升级 FerretDB 集群
本文档介绍 FerretDB 集群的日常管理操作。
创建 FerretDB 集群 在 配置清单 中 定义 FerretDB 集群后,您可以使用以下命令安装它:
./mongo.yml -l ferret # 在 ferret 分组上安装 FerretDB
由于 FerretDB 使用 PostgreSQL 作为其底层存储,多次运行此剧本通常是安全的(幂等性)。
移除 FerretDB 集群 要移除 FerretDB 集群,请使用 mongo_purge 参数运行 mongo.yml 剧本的 mongo_purge 子任务:
./mongo.yml -e mongo_purge = true -t mongo_purge
此命令将会:
停止 FerretDB 服务 移除 systemd 服务文件 清理配置文件和证书 从 Prometheus 监控中注销 连接到 FerretDB 您可以使用 MongoDB 连接串,用任何语言的 MongoDB 驱动访问 FerretDB。以下是使用 mongosh 命令行工具的示例:
mongosh 'mongodb://dbuser_meta:DBUser.Meta@10.10.10.10:27017?authMechanism=PLAIN'
mongosh 'mongodb://test:test@10.10.10.11:27017/test?authMechanism=PLAIN'
Pigsty 管理的 PostgreSQL 集群默认使用 scram-sha-256 作为默认的认证方式,因此,您必须使用 PLAIN 认证方式连接至 FerretDB。参阅 FerretDB:认证 获取详细信息。
您也可以使用其他 PostgreSQL 用户来访问 FerretDB,只要在连接串中指定即可:
mongosh 'mongodb://dbuser_dba:DBUser.DBA@10.10.10.10:27017?authMechanism=PLAIN'
快速上手 连接到 FerretDB 后,您可以像使用 MongoDB 一样进行操作:
$ mongosh 'mongodb://dbuser_meta:DBUser.Meta@10.10.10.10:27017?authMechanism=PLAIN'
MongoDB 的命令会被翻译为 SQL 命令,在底层的 PostgreSQL 中执行:
use test // CREATE SCHEMA test;
db . dropDatabase () // DROP SCHEMA test;
db . createCollection ( 'posts' ) // CREATE TABLE posts(_data JSONB,...)
db . posts . insert ({ // INSERT INTO posts VALUES(...);
title : 'Post One' ,
body : 'Body of post one' ,
category : 'News' ,
tags : [ 'news' , 'events' ],
user : { name : 'John Doe' , status : 'author' },
date : Date ()
})
db . posts . find (). limit ( 2 ). pretty () // SELECT * FROM posts LIMIT 2;
db . posts . createIndex ({ title : 1 }) // CREATE INDEX ON posts(_data->>'title');
如果您不熟悉 MongoDB,这里有一个快速上手教程,同样适用于 FerretDB:Perform CRUD Operations with MongoDB Shell
压力测试 如果您希望生成一些样例负载,可以使用 mongosh 执行以下简易测试脚本:
cat > benchmark.js <<'EOF'
const coll = "testColl";
const numDocs = 10000;
for (let i = 0; i < numDocs; i++) { // insert
db.getCollection(coll).insert({ num: i, name: "MongoDB Benchmark Test" });
}
for (let i = 0; i < numDocs; i++) { // select
db.getCollection(coll).find({ num: i });
}
for (let i = 0; i < numDocs; i++) { // update
db.getCollection(coll).update({ num: i }, { $set: { name: "Updated" } });
}
for (let i = 0; i < numDocs; i++) { // delete
db.getCollection(coll).deleteOne({ num: i });
}
EOF
mongosh 'mongodb://dbuser_meta:DBUser.Meta@10.10.10.10:27017?authMechanism=PLAIN' benchmark.js
您可以查阅 FerretDB 支持的 MongoDB 命令 ,同时还有一些 已知的区别 。对于基本的使用来说,这些差异通常不是什么大问题。
17.5 - 管理剧本 可在 FERRET 模块中使用的 Ansible 剧本
Pigsty 提供了一个内置剧本 mongo.yml 用于在节点上安装 FerretDB。
mongo.yml剧本地址:mongo.yml
功能说明:在目标主机上安装 MongoDB/FerretDB。
此剧本包含以下子任务:
子任务 说明 mongo_check检查 mongo 身份参数 mongo_dbsu创建操作系统用户 mongod mongo_install安装 ferretdb RPM/DEB 包 mongo_purge清理现有 FerretDB(默认不执行) mongo_config配置 FerretDB 服务 mongo_cert签发 FerretDB SSL 证书 mongo_launch启动 FerretDB 服务 mongo_register将 FerretDB 注册到 Prometheus
任务详解 mongo_check检查必选的身份参数是否已定义:
mongo_cluster:集群名称mongo_seq:实例序号mongo_pgurl:PostgreSQL 连接串如果任一参数缺失,剧本将报错退出。
mongo_dbsu创建 FerretDB 运行所需的操作系统用户和组:
创建 mongod 用户组 创建 mongod 用户,家目录为 /var/lib/mongod mongo_install安装 FerretDB 软件包:
在 RPM 系发行版上安装 ferretdb2 包 在 DEB 系发行版上安装对应的 deb 包 mongo_purge清理现有的 FerretDB 集群。此任务默认不执行,需要显式指定:
./mongo.yml -e mongo_purge = true -t mongo_purge
清理操作包括:
停止并禁用 ferretdb 服务 移除 systemd 服务文件 移除配置文件和 SSL 证书 从 Prometheus 监控目标中注销 mongo_config配置 FerretDB 服务:
渲染环境变量配置文件 /etc/default/ferretdb 创建 systemd 服务文件 mongo_cert当 mongo_ssl_enabled 设置为 true 时,此任务会:
生成 FerretDB 的 SSL 私钥 创建证书签名请求(CSR) 使用 CA 签发 SSL 证书 将证书文件部署到 /var/lib/mongod/ mongo_launch启动 FerretDB 服务:
重新加载 systemd 配置 启动并启用 ferretdb 服务 等待服务在指定端口上可用(默认 27017) mongo_register将 FerretDB 实例注册到 Prometheus 监控系统:
在所有 infra 节点上创建监控目标文件 目标文件路径:/infra/targets/mongo/<cluster>-<seq>.yml 包含实例的 IP、标签和指标端口信息 使用示例 # 在 ferret 分组上部署 FerretDB
./mongo.yml -l ferret
# 仅执行配置任务
./mongo.yml -l ferret -t mongo_config
# 重新签发 SSL 证书
./mongo.yml -l ferret -t mongo_cert
# 重启 FerretDB 服务
./mongo.yml -l ferret -t mongo_launch
# 清理 FerretDB 集群
./mongo.yml -l ferret -e mongo_purge = true -t mongo_purge
17.6 - 监控告警 FerretDB 模块的监控仪表板与告警规则
FERRET 模块目前提供了一个监控仪表板。
Mongo Overview Mongo Overview :Mongo/FerretDB 集群概览
这个监控面板提供了关于 FerretDB 的基本监控指标,包括:
实例状态 :FerretDB 实例的运行状态客户端连接 :客户端连接数量和请求统计资源使用 :CPU、内存、Goroutine 数量等PostgreSQL 连接池 :后端 PostgreSQL 连接池状态
由于 FerretDB 底层使用 PostgreSQL 作为存储引擎,更多的监控指标请参考 PostgreSQL 监控 。
监控指标 FerretDB 通过内置的 Exporter 在 mongo_exporter_port (默认 9216)端口暴露 Prometheus 格式的监控指标。
关键指标类别包括:
指标前缀 说明 ferretdb_*FerretDB 核心指标 ferretdb_client_*客户端连接和请求统计 ferretdb_postgresql_*PostgreSQL 后端状态 go_*Go 运行时指标 process_*进程级别指标
完整的指标列表请参阅 指标列表 。
告警规则 FerretDB 模块目前使用基本的实例存活告警:
- alert : FerretDBDown
expr : ferretdb_up == 0
for : 1m
labels :
severity : critical
annotations :
summary : "FerretDB instance {{ $labels.ins }} is down"
description : "FerretDB instance {{ $labels.ins }} on {{ $labels.ip }} has been down for more than 1 minute."
由于 FerretDB 是无状态的代理层,主要的监控和告警应该集中在底层的 PostgreSQL 集群上。
17.7 - 指标列表 FerretDB 模块提供的完整监控指标列表与释义
MONGO 模块包含有 54 类可用监控指标。
Metric Name Type Labels Description ferretdb_client_accepts_total Unknown error, cls, ip, ins, instance, jobN/A ferretdb_client_duration_seconds_bucket Unknown error, le, cls, ip, ins, instance, jobN/A ferretdb_client_duration_seconds_count Unknown error, cls, ip, ins, instance, jobN/A ferretdb_client_duration_seconds_sum Unknown error, cls, ip, ins, instance, jobN/A ferretdb_client_requests_total Unknown cls, ip, ins, opcode, instance, command, jobN/A ferretdb_client_responses_total Unknown result, argument, cls, ip, ins, opcode, instance, command, jobN/A ferretdb_postgresql_metadata_databases gauge cls, ip, ins, instance, jobThe current number of database in the registry. ferretdb_postgresql_pool_size gauge cls, ip, ins, instance, jobThe current number of pools. ferretdb_up gauge cls, version, commit, ip, ins, dirty, telemetry, package, update_available, uuid, instance, job, branch, debugFerretDB instance state. go_gc_duration_seconds summary cls, ip, ins, instance, quantile, jobA summary of the pause duration of garbage collection cycles. go_gc_duration_seconds_count Unknown cls, ip, ins, instance, jobN/A go_gc_duration_seconds_sum Unknown cls, ip, ins, instance, jobN/A go_goroutines gauge cls, ip, ins, instance, jobNumber of goroutines that currently exist. go_info gauge cls, version, ip, ins, instance, jobInformation about the Go environment. go_memstats_alloc_bytes gauge cls, ip, ins, instance, jobNumber of bytes allocated and still in use. go_memstats_alloc_bytes_total counter cls, ip, ins, instance, jobTotal number of bytes allocated, even if freed. go_memstats_buck_hash_sys_bytes gauge cls, ip, ins, instance, jobNumber of bytes used by the profiling bucket hash table. go_memstats_frees_total counter cls, ip, ins, instance, jobTotal number of frees. go_memstats_gc_sys_bytes gauge cls, ip, ins, instance, jobNumber of bytes used for garbage collection system metadata. go_memstats_heap_alloc_bytes gauge cls, ip, ins, instance, jobNumber of heap bytes allocated and still in use. go_memstats_heap_idle_bytes gauge cls, ip, ins, instance, jobNumber of heap bytes waiting to be used. go_memstats_heap_inuse_bytes gauge cls, ip, ins, instance, jobNumber of heap bytes that are in use. go_memstats_heap_objects gauge cls, ip, ins, instance, jobNumber of allocated objects. go_memstats_heap_released_bytes gauge cls, ip, ins, instance, jobNumber of heap bytes released to OS. go_memstats_heap_sys_bytes gauge cls, ip, ins, instance, jobNumber of heap bytes obtained from system. go_memstats_last_gc_time_seconds gauge cls, ip, ins, instance, jobNumber of seconds since 1970 of last garbage collection. go_memstats_lookups_total counter cls, ip, ins, instance, jobTotal number of pointer lookups. go_memstats_mallocs_total counter cls, ip, ins, instance, jobTotal number of mallocs. go_memstats_mcache_inuse_bytes gauge cls, ip, ins, instance, jobNumber of bytes in use by mcache structures. go_memstats_mcache_sys_bytes gauge cls, ip, ins, instance, jobNumber of bytes used for mcache structures obtained from system. go_memstats_mspan_inuse_bytes gauge cls, ip, ins, instance, jobNumber of bytes in use by mspan structures. go_memstats_mspan_sys_bytes gauge cls, ip, ins, instance, jobNumber of bytes used for mspan structures obtained from system. go_memstats_next_gc_bytes gauge cls, ip, ins, instance, jobNumber of heap bytes when next garbage collection will take place. go_memstats_other_sys_bytes gauge cls, ip, ins, instance, jobNumber of bytes used for other system allocations. go_memstats_stack_inuse_bytes gauge cls, ip, ins, instance, jobNumber of bytes in use by the stack allocator. go_memstats_stack_sys_bytes gauge cls, ip, ins, instance, jobNumber of bytes obtained from system for stack allocator. go_memstats_sys_bytes gauge cls, ip, ins, instance, jobNumber of bytes obtained from system. go_threads gauge cls, ip, ins, instance, jobNumber of OS threads created. mongo_up Unknown cls, ip, ins, instance, jobN/A process_cpu_seconds_total counter cls, ip, ins, instance, jobTotal user and system CPU time spent in seconds. process_max_fds gauge cls, ip, ins, instance, jobMaximum number of open file descriptors. process_open_fds gauge cls, ip, ins, instance, jobNumber of open file descriptors. process_resident_memory_bytes gauge cls, ip, ins, instance, jobResident memory size in bytes. process_start_time_seconds gauge cls, ip, ins, instance, jobStart time of the process since unix epoch in seconds. process_virtual_memory_bytes gauge cls, ip, ins, instance, jobVirtual memory size in bytes. process_virtual_memory_max_bytes gauge cls, ip, ins, instance, jobMaximum amount of virtual memory available in bytes. promhttp_metric_handler_errors_total counter job, cls, ip, ins, instance, causeTotal number of internal errors encountered by the promhttp metric handler. promhttp_metric_handler_requests_in_flight gauge cls, ip, ins, instance, jobCurrent number of scrapes being served. promhttp_metric_handler_requests_total counter job, cls, ip, ins, instance, codeTotal number of scrapes by HTTP status code. scrape_duration_seconds Unknown cls, ip, ins, instance, jobN/A scrape_samples_post_metric_relabeling Unknown cls, ip, ins, instance, jobN/A scrape_samples_scraped Unknown cls, ip, ins, instance, jobN/A scrape_series_added Unknown cls, ip, ins, instance, jobN/A up Unknown cls, ip, ins, instance, jobN/A
17.8 - 常见问题 FerretDB 与 DocumentDB 模块常见问题答疑
为什么要使用 FerretDB? MongoDB 曾经 是一项令人惊叹的技术,让开发者能够抛开关系型数据库的"模式束缚",快速构建应用程序。
然而随着时间推移,MongoDB 放弃了它的开源本质,将许可证更改为 SSPL,这使得许多开源项目和早期商业项目无法使用它。
大多数 MongoDB 用户其实并不需要 MongoDB 提供的高级功能,但他们确实需要一个易于使用的开源文档数据库解决方案。为了填补这个空白,FerretDB 应运而生。
PostgreSQL 的 JSON 功能支持已经足够完善了:二进制存储 JSONB,GIN 任意字段索引,各种 JSON 处理函数,JSON PATH 和 JSON Schema,它早已是一个功能完备,性能强大的文档数据库。
但是提供替代的功能,与 直接仿真 还是不一样的。FerretDB 可以为使用 MongoDB 驱动的应用程序提供一个丝滑迁移到 PostgreSQL 的过渡方案。
Pigsty 对 FerretDB 的支持历史? Pigsty 从 1.x 开始就提供了基于 Docker 的 FerretDB 模板,在 v2.3 中提供了原生部署支持。
它作为一个选装项,对丰富 PostgreSQL 生态大有裨益。Pigsty 社区已经与 FerretDB 社区成为了合作伙伴,后续将进行深度的合作与适配支持。
FERRET 是 Pigsty 中的一个 可选 模块。自 v2.0 以来,它需要 documentdb 扩展才能工作。
Pigsty 已经打包了这个扩展,并提供了一个 mongo.yml 模板,帮助您轻松部署 FerretDB 集群。
安装 MongoSH 您可以使用 MongoSH 作为客户端工具访问 FerretDB 集群。
推荐使用 pig 命令添加 MongoDB 仓库并安装:
pig repo add mongo -u # 添加 MongoDB 官方仓库
yum install mongodb-mongosh # RHEL/CentOS/Rocky/Alma
apt install mongodb-mongosh # Debian/Ubuntu
您也可以手动添加 MongoDB 仓库:
# RHEL/CentOS 系
cat > /etc/yum.repos.d/mongo.repo <<EOF
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/\$releasever/mongodb-org/7.0/\$basearch/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
EOF
yum install -y mongodb-mongosh
认证方式 FerretDB 的身份验证完全基于底层的 PostgreSQL。由于 Pigsty 管理的 PostgreSQL 集群默认使用 scram-sha-256 认证,您必须在连接字符串中指定 PLAIN 认证机制:
mongosh 'mongodb://user:password@host:27017?authMechanism=PLAIN'
如果忘记添加 authMechanism=PLAIN 参数,连接将会失败并报认证错误。
与 MongoDB 的兼容性 FerretDB 实现了 MongoDB 的线协议,但底层使用 PostgreSQL 存储。这意味着:
大多数基本的 CRUD 操作与 MongoDB 兼容 某些高级功能可能不支持或有差异 聚合管道支持有限 详细的兼容性信息请参阅:
为什么需要超级用户 FerretDB 2.0+ 使用 documentdb 扩展,该扩展需要超级用户权限来创建和管理内部结构。因此,在 mongo_pgurl 中指定的用户必须是 PostgreSQL 超级用户。
建议创建一个专用的 mongod 超级用户供 FerretDB 使用,而不是使用默认的 postgres 用户。
如何实现高可用 FerretDB 本身是无状态的,所有数据都存储在底层的 PostgreSQL 中。要实现高可用:
PostgreSQL 层 :使用 Pigsty 的 PGSQL 模块部署高可用 PostgreSQL 集群FerretDB 层 :部署多个 FerretDB 实例,使用 VIP 或负载均衡器详细配置请参阅 高可用配置 。
性能如何 FerretDB 的性能取决于底层的 PostgreSQL 集群。由于需要将 MongoDB 命令翻译为 SQL,会有一定的性能开销。对于大多数 OLTP 场景,性能是可接受的。
如果您需要更高的性能,可以:
使用更快的存储(NVMe SSD) 增加 PostgreSQL 的资源配置 优化 PostgreSQL 参数 使用连接池减少连接开销 18 - 模块:DOCKER Docker Daemon 服务,允许用户一键拉起容器化的无状态软件工具模板,加装各种功能。
Docker 是最流行的容器化平台,提供了标准化的软件交付能力。
Pigsty 本身并不依赖 Docker 部署任何组件,相反,它提供了部署安装 Docker 的能力 ,这是一个 可选模块 。
Pigsty 提供一系列 Docker 软件/工具/应用模板 ,供您按需选用。
这允许用户快速拉起各种容器化的无状态软件工具模板,加装各种功能。
您可以使用外部由 Pigsty 托管的高可用数据库集群,将无状态的应用放入容器之中。
Pigsty 的 Docker 模块会默认为中国大陆的用户配置国内可用的镜像仓库,以提升拉取镜像的速度(与可用性)。
您可以轻松配置 Registry 与 Proxy,以便灵活访问不同的镜像源。
18.1 - 使用方法 Docker 模块快速上手,安装,卸载,下载,仓库,镜像,代理,拉取,关于 Docker 你需要知道的内容。
Pigsty 内置了 Docker 支持,您可以用它来快速部署容器化的应用软件。
上手 Docker 是一个 可选模块 ,且在 Pigsty 的大部分配置模板中,Docker 并非默认启用 。因此,用户需要显式地 下载 并 配置 才能在 Pigsty 中使用 Docker。
例如,在默认使用的 meta 模板中,Docker 默认是不会下载安装的。不过在 rich 单节点模板中,则会下载并安装 Docker。
这两个配置的关键区别就在于这两个参数:repo_modules 与 repo_packages 。
repo_modules : infra,node,pgsql,docker # <--- 启用 Docker 仓库
repo_packages :
- node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-common, docker # <--- 下载 Docker
Docker 下载完之后,您需要在待安装 Docker 的节点上配置 docker_enabled : true 标记,并按需配置 其他参数 。
infra :
hosts :
10.10.10.10 : { infra_seq: 1 ,nodename : infra-1 }
10.10.10.11 : { infra_seq: 2 ,nodename : infra-2 }
vars :
docker_enabled : true # 在这个分组上安装 Docker !
最后,使用 您可以使用 docker.yml 剧本将其安装到节点上:
./docker.yml -l infra # 在 infra 分组上安装 Docker
安装 如果您只是临时性的希望在某些节点上,直接从互联网安装 Docker,那么可以考虑使用以下命令:
./node.yml -e '{"node_repo_modules":"node,docker","node_packages":["docker-ce,docker-compose-plugin"]}' -t node_repo,node_pkg -l <select_group_ip>
这条命令会在目标节点上,首先启用 node,docker 两个模块对应的上游软件源,然后安装 docker-ce 与 docker-compose-plugin 两个软件包(EL/Debian同名)。
如果您希望的是在 Pigsty 初始化的时候就自动下载好 Docker 相关软件包,请参考下面的说明。
卸载 因为过于简单,Pigsty 不提供 Docker 模块的卸载剧本,你可以直接使用 Ansible 指令移除 Docker
ansible minio -m package -b -a 'name=docker-ce state=absent' # 卸载 docker
这条命令会在目标节点上,首先启用 node,docker 两个模块对应的上游软件源,然后安装 docker-ce 与 docker-compose-plugin 两个软件包(EL/Debian同名)。
如果您希望的是在 Pigsty 初始化的时候就自动下载好 Docker 相关软件包,请参考下面的说明。
下载 想要在 Pigsty 安装过程中下载 Docker,在 配置清单 中修改参数 repo_modules 启用 Docker 软件仓库,
然后在 repo_packages 或 repo_extra_packages 参数中指定下载 Docker 软件包。
repo_modules : infra,node,pgsql,docker # <--- 启用 Docker 仓库
repo_packages :
- node-bootstrap, infra-package, infra-addons, node-package1, node-package2, pgsql-common, docker # <--- 下载 Docker
repo_extra_packages :
- pgsql-main docker # <--- 也可以在这里指定
这里指定的 docker(实际对应 docker-ce 与 docker-compose-plugin 两个软件包)会在默认的 install.yml 过程中自动下载到本地软件源中。
下载完成后的 Docker 软件包可以通过本地软件源,对所有节点可用。
如果您已经完成了 Pigsty 安装,本地软件源已经初始化完毕,您可以在修改配置之后执行 ./infra.yml -t repo_build 重新下载并构建离线软件源。
安装 Docker 需要用到 Docker 的 YUM/APT 仓库 ,这个仓库在 Pigsty 中默认包含,但不启用,需要将 docker 加入到 repo_modules 中启用后才能安装
仓库 下载 Docker 需要用到互联网上游软件仓库,已经在定义在默认的 repo_upstream 中,模块名为 docker
- { name: docker-ce ,description: 'Docker CE' ,module: docker ,releases: [7,8,9] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.docker.com/linux/centos/$releasever/$basearch/stable' ,china: 'https://mirrors.aliyun.com/docker-ce/linux/centos/$releasever/$basearch/stable' ,europe : 'https://mirrors.xtom.de/docker-ce/linux/centos/$releasever/$basearch/stable' }}
- { name: docker-ce ,description: 'Docker CE' ,module: docker ,releases: [11,12,20,22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'https://download.docker.com/linux/${distro_name} ${distro_codename} stable' ,china : 'https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux//${distro_name} ${distro_codename} stable' }}
您可以在 repo_modules 与 node_repo_modules 两个参数中,使用 docker 模块名引用这个仓库。
请注意,Docker 的官方软件仓库在中国大陆默认处于 封锁 状态,您需要使用中国地区的镜像站点才能正常完成下载。
如果您处在中国大陆地区遇到 Docker 本身下载失败的问题,请检查您的配置清单中,region 是否被设置为了 default,默认情况下自动配置的 region: china 可以解决这个问题。
代理 如果您的网络环境需要使用代理服务器才能访问互联网,您可以在 Pigsty 的配置清单中配置 proxy_env 参数,这个参数会被写入到 Docker 的配置文件中的 proxy 相关配置中。
proxy_env:
no_proxy: "localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16,*.pigsty,*.aliyun.com,mirrors.aliyuncs.com,mirrors.tuna.tsinghua.edu.cn,mirrors.zju.edu.cn"
#http_proxy: 'http://username:password@proxy.address.com'
#https_proxy: 'http://username:password@proxy.address.com'
#all_proxy: 'http://username:password@proxy.address.com'
在执行 configure 的过程中如果指定了 -x 参数,当前环境中的代理服务器配置会自动生成到 Pigsty 配置文件到 proxy_env 中。
除了使用代理服务器之外,您还可以通过配置 Docker镜像站点 的方式来规避封锁。
镜像站 您可以通过参数 docker_registry_mirrors 指定 Docker 的 Registry Mirrors 参数,使用未被墙掉的镜像站点:
普通墙外用户,除了官方默认的 DockerHub 站点外,还可以考虑使用 quay.io 镜像站点。如果您的内网环境已经有了成熟的镜像基础设施,您可以使用内网的 Docker 镜像站点,避免受到外网镜像站点的影响,提高下载速度。
使用公有云厂商服务的用户可以考虑使用内网免费的 Docker 镜像。例如,如果您使用阿里云,可以使用阿里云提供的内网 Docker 镜像站点(需要登陆):
[ "https://registry.cn-hangzhou.aliyuncs.com" ] # 阿里云镜像站点,需要显式登陆
如果你使用腾讯云,可以使用腾讯云提供的内网 Docker 镜像站点(需要内网):
[ "https://ccr.ccs.tencentyun.com" ] # 腾讯云镜像站点,内网专用
此外,您还可以使用 CF-Workers-docker.io 快速拉起您自己的 Docker 镜像代理。
也可以考虑使用免费的 Docker代理镜像 (风险自负!)
拉取镜像 参数 docker_image 与 docker_image_cache 可用于直接指定在 Docker 安装时,需要拉取的镜像列表。
使用这一功能,可以让 Docker 装好之后就带有指定的镜像(前提是可以成功拉取,此任务失败会自动忽略跳过)
例如,您可以在配置清单中指定需要拉取的镜像:
infra :
hosts :
10.10.10.10 : { infra_seq : 1 }
vars :
docker_enabled : true # 在这个分组上安装 Docker !
docker_image :
- redis:latest # 拉取最新版本的 Redis 镜像
另一种预先加载镜像的方式是使用本地 save 的 tgz 压缩包:如果您预先使用 docker save xxx | gzip -c > /tmp/docker/xxx.tgz 将 Docker 镜像导出保存在本地。
那么这些导出的镜像文件可以通过参数 docker_image_cache 指定的 glob 被自动加载。默认的位置是: /tmp/docker/*.tgz。
这意味着你可以事先把镜像放在 /tmp/docker 目录中,然后执行 docker.yml 安装 docker 后会自动加载这些镜像包。
例如,在 supabase自建教程 中就使用了这种技术,在拉起 Supabase,安装 Docker 之前,把本地 /tmp/supabase 目录的 *.tgz 镜像压缩包都拷贝到了目标节点的 /tmp/docker 目录下。
- name : copy local docker images
copy : src="{{ item }}" dest="/tmp/docker/"
with_fileglob : "{{ supa_images }}"
vars : # you can override this with -e cli args
supa_images : /tmp/supabase/*.tgz
应用 Pigsty 提供了一系列开箱即用的,基于 Docker Compose 的 软件模板 ,您可以用它们一键拉起使用外部由 Pigsty 管理数据库集群的业务软件。
18.2 - 参数列表 DOCKER 模块提供了 8 个配置参数
DOCKER 模块提供了 8 个配置参数。
参数概览 DOCKER 参数组用于 Docker 容器引擎的部署与配置,包括启用开关、数据目录、存储驱动、镜像加速以及监控。
您可以使用 docker.yml 剧本,在节点上安装并启用 Docker。
Docker 的默认参数定义于 roles/docker/defaults/main.yml
docker_enabled : false # 在当前节点启用 Docker?
docker_data : /var/lib/docker # Docker 数据目录,默认为 /var/lib/docker
docker_storage_driver : overlay2 # Docker 存储驱动,可选 zfs, btrfs 等
docker_cgroups_driver : systemd # Docker CGroup 驱动:cgroupfs 或 systemd
docker_registry_mirrors : [] # Docker 镜像仓库加速列表
docker_exporter_port : 9323 # Docker 监控指标导出端口,默认 9323
docker_image : [] # Docker 启动后待拉取的镜像列表
docker_image_cache : /tmp/docker/*.tgz # Docker 镜像缓存 tarball 匹配模式
docker_enabled参数名称: docker_enabled, 类型: bool, 层次:G/C/I
是否在当前节点启用Docker?默认为: false,即不启用。
docker_data参数名称: docker_data, 类型: path, 层次:G/C/I
Docker 数据目录,默认为 /var/lib/docker。
此目录用于存储 Docker 的镜像、容器、卷等数据。如果您有独立的数据磁盘,建议将此目录指向该磁盘的挂载点。
docker_storage_driver参数名称: docker_storage_driver, 类型: enum, 层次:G/C/I
Docker 存储驱动,默认为 overlay2。
请参考官方文档:https://docs.docker.com/engine/storage/drivers/select-storage-driver/
可选的存储驱动包括:
overlay2:推荐的默认驱动,适用于大多数场景fuse-overlayfs:用于无 root 权限的容器场景btrfs:使用 Btrfs 文件系统时zfs:使用 ZFS 文件系统时vfs:用于测试目的,不推荐生产使用docker_cgroups_driver参数名称: docker_cgroups_driver, 类型: enum, 层次:G/C/I
Docker使用的 CGroup FS 驱动,可以是 cgroupfs 或 systemd,默认值为: systemd
docker_registry_mirrors参数名称: docker_registry_mirrors, 类型: string[], 层次:G/C/I
Docker 镜像仓库加速地址列表,默认值为:[] 空数组。
您可以使用 Docker 镜像站点加速镜像拉取,下面是一些中国大陆可用的镜像站点示例:
[ "https://docker.m.daocloud.io" ] # DaoCloud 镜像站点
[ "https://docker.1ms.run" ] # 毫秒镜像站点
[ "https://mirror.ccs.tencentyun.com" ] # 腾讯云内网镜像站点
[ "https://registry.cn-hangzhou.aliyuncs.com" ] # 阿里云镜像站点,需要登录
您也可以考虑使用 Cloudflare Worker 搭建 Docker Proxy 来加速访问。
如果拉取速度仍然太慢,您也可以考虑使用其他 Registry:docker login quay.io
docker_exporter_port参数名称: docker_exporter_port, 类型: port, 层次:G
Docker 监控指标导出端口,默认为 9323。
Docker 守护进程会在此端口暴露 Prometheus 格式的监控指标,供监控基础设施采集。
docker_image参数名称: docker_image, 类型: string[], 层次:G/C/I
Docker 待拉取的镜像列表,默认为空列表 []。
在这里指定的 Docker 镜像名称会在安装阶段自动拉取。
docker_image_cache参数名称: docker_image_cache, 类型: path, 层次:G/C/I
本地 Docker 镜像离线缓存包 glob 匹配模式,默认为 /tmp/docker/*.tgz。
您可以使用 docker save | gzip 的方式将镜像打包,并通过此参数在 Docker 安装阶段自动导入。
匹配该模式的 .tgz 后缀 tarball 文件将使用以下方式逐个导入 Docker 中:
cat *.tgz | gzip -d -c - | docker load
18.3 - 预置剧本 如何使用预置的 ansible 剧本来管理 Docker,常用管理命令速查。
Docker 模块提供了一个默认的剧本 docker.yml ,用于安装 Docker Daemon 与 Docker Compose。
docker.yml剧本原始文件:docker.yml 中
执行本剧本,将会在带有 docker_enabled: true 标记地目标节点上安装 docker-ce 与 docker-compose-plugin,启用 dockerd 服务
以下是 docker.yml 剧本中可用的任务子集:
docker_install : 在节点上安装 Docker,Docker Compose 软件包docker_admin : 将指定的用户加入 Docker 管理员用户组中docker_config : 生成 Docker 守护进程服务配置文件docker_launch : 启动 Docker 守护进程服务docker_register : 将 Docker 守护进程注册为 Prometheus 监控目标docker_image : 尝试从 /tmp/docker/*.tgz 加载预置镜像压缩包(如果存在)Docker 模块没有提供专门的卸载剧本,如果您需要卸载 Docker,可以手工停止 docker 后卸载:
systemctl stop docker # 停止 Docker 守护进程服务
yum remove docker-ce docker-compose-plugin # 在 EL 系统上卸载 Docker
apt remove docker-ce docker-compose-plugin # 在 Debian 系统上卸载 Docker
18.4 - 指标列表 Pigsty Docker 模块提供的完整监控指标列表与释义
DOCKER 模块包含有 123 类可用监控指标。
Metric Name Type Labels Description builder_builds_failed_total counter ip, cls, reason, ins, job, instanceNumber of failed image builds builder_builds_triggered_total counter ip, cls, ins, job, instanceNumber of triggered image builds docker_up Unknown ip, cls, ins, job, instanceN/A engine_daemon_container_actions_seconds_bucket Unknown ip, cls, ins, job, instance, le, actionN/A engine_daemon_container_actions_seconds_count Unknown ip, cls, ins, job, instance, actionN/A engine_daemon_container_actions_seconds_sum Unknown ip, cls, ins, job, instance, actionN/A engine_daemon_container_states_containers gauge ip, cls, ins, job, instance, stateThe count of containers in various states engine_daemon_engine_cpus_cpus gauge ip, cls, ins, job, instanceThe number of cpus that the host system of the engine has engine_daemon_engine_info gauge ip, cls, architecture, ins, job, instance, os_version, kernel, version, graphdriver, os, daemon_id, commit, os_typeThe information related to the engine and the OS it is running on engine_daemon_engine_memory_bytes gauge ip, cls, ins, job, instanceThe number of bytes of memory that the host system of the engine has engine_daemon_events_subscribers_total gauge ip, cls, ins, job, instanceThe number of current subscribers to events engine_daemon_events_total counter ip, cls, ins, job, instanceThe number of events logged engine_daemon_health_checks_failed_total counter ip, cls, ins, job, instanceThe total number of failed health checks engine_daemon_health_check_start_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A engine_daemon_health_check_start_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A engine_daemon_health_check_start_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A engine_daemon_health_checks_total counter ip, cls, ins, job, instanceThe total number of health checks engine_daemon_host_info_functions_seconds_bucket Unknown ip, cls, ins, job, instance, le, functionN/A engine_daemon_host_info_functions_seconds_count Unknown ip, cls, ins, job, instance, functionN/A engine_daemon_host_info_functions_seconds_sum Unknown ip, cls, ins, job, instance, functionN/A engine_daemon_image_actions_seconds_bucket Unknown ip, cls, ins, job, instance, le, actionN/A engine_daemon_image_actions_seconds_count Unknown ip, cls, ins, job, instance, actionN/A engine_daemon_image_actions_seconds_sum Unknown ip, cls, ins, job, instance, actionN/A engine_daemon_network_actions_seconds_bucket Unknown ip, cls, ins, job, instance, le, actionN/A engine_daemon_network_actions_seconds_count Unknown ip, cls, ins, job, instance, actionN/A engine_daemon_network_actions_seconds_sum Unknown ip, cls, ins, job, instance, actionN/A etcd_debugging_snap_save_marshalling_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A etcd_debugging_snap_save_marshalling_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A etcd_debugging_snap_save_marshalling_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A etcd_debugging_snap_save_total_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A etcd_debugging_snap_save_total_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A etcd_debugging_snap_save_total_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A etcd_disk_wal_fsync_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A etcd_disk_wal_fsync_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A etcd_disk_wal_fsync_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A etcd_disk_wal_write_bytes_total gauge ip, cls, ins, job, instanceTotal number of bytes written in WAL. etcd_snap_db_fsync_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A etcd_snap_db_fsync_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A etcd_snap_db_fsync_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A etcd_snap_db_save_total_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A etcd_snap_db_save_total_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A etcd_snap_db_save_total_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A etcd_snap_fsync_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A etcd_snap_fsync_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A etcd_snap_fsync_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A go_gc_duration_seconds summary ip, cls, ins, job, instance, quantileA summary of the pause duration of garbage collection cycles. go_gc_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A go_gc_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A go_goroutines gauge ip, cls, ins, job, instanceNumber of goroutines that currently exist. go_info gauge ip, cls, ins, job, version, instanceInformation about the Go environment. go_memstats_alloc_bytes counter ip, cls, ins, job, instanceTotal number of bytes allocated, even if freed. go_memstats_alloc_bytes_total counter ip, cls, ins, job, instanceTotal number of bytes allocated, even if freed. go_memstats_buck_hash_sys_bytes gauge ip, cls, ins, job, instanceNumber of bytes used by the profiling bucket hash table. go_memstats_frees_total counter ip, cls, ins, job, instanceTotal number of frees. go_memstats_gc_sys_bytes gauge ip, cls, ins, job, instanceNumber of bytes used for garbage collection system metadata. go_memstats_heap_alloc_bytes gauge ip, cls, ins, job, instanceNumber of heap bytes allocated and still in use. go_memstats_heap_idle_bytes gauge ip, cls, ins, job, instanceNumber of heap bytes waiting to be used. go_memstats_heap_inuse_bytes gauge ip, cls, ins, job, instanceNumber of heap bytes that are in use. go_memstats_heap_objects gauge ip, cls, ins, job, instanceNumber of allocated objects. go_memstats_heap_released_bytes gauge ip, cls, ins, job, instanceNumber of heap bytes released to OS. go_memstats_heap_sys_bytes gauge ip, cls, ins, job, instanceNumber of heap bytes obtained from system. go_memstats_last_gc_time_seconds gauge ip, cls, ins, job, instanceNumber of seconds since 1970 of last garbage collection. go_memstats_lookups_total counter ip, cls, ins, job, instanceTotal number of pointer lookups. go_memstats_mallocs_total counter ip, cls, ins, job, instanceTotal number of mallocs. go_memstats_mcache_inuse_bytes gauge ip, cls, ins, job, instanceNumber of bytes in use by mcache structures. go_memstats_mcache_sys_bytes gauge ip, cls, ins, job, instanceNumber of bytes used for mcache structures obtained from system. go_memstats_mspan_inuse_bytes gauge ip, cls, ins, job, instanceNumber of bytes in use by mspan structures. go_memstats_mspan_sys_bytes gauge ip, cls, ins, job, instanceNumber of bytes used for mspan structures obtained from system. go_memstats_next_gc_bytes gauge ip, cls, ins, job, instanceNumber of heap bytes when next garbage collection will take place. go_memstats_other_sys_bytes gauge ip, cls, ins, job, instanceNumber of bytes used for other system allocations. go_memstats_stack_inuse_bytes gauge ip, cls, ins, job, instanceNumber of bytes in use by the stack allocator. go_memstats_stack_sys_bytes gauge ip, cls, ins, job, instanceNumber of bytes obtained from system for stack allocator. go_memstats_sys_bytes gauge ip, cls, ins, job, instanceNumber of bytes obtained from system. go_threads gauge ip, cls, ins, job, instanceNumber of OS threads created. logger_log_entries_size_greater_than_buffer_total counter ip, cls, ins, job, instanceNumber of log entries which are larger than the log buffer logger_log_read_operations_failed_total counter ip, cls, ins, job, instanceNumber of log reads from container stdio that failed logger_log_write_operations_failed_total counter ip, cls, ins, job, instanceNumber of log write operations that failed process_cpu_seconds_total counter ip, cls, ins, job, instanceTotal user and system CPU time spent in seconds. process_max_fds gauge ip, cls, ins, job, instanceMaximum number of open file descriptors. process_open_fds gauge ip, cls, ins, job, instanceNumber of open file descriptors. process_resident_memory_bytes gauge ip, cls, ins, job, instanceResident memory size in bytes. process_start_time_seconds gauge ip, cls, ins, job, instanceStart time of the process since unix epoch in seconds. process_virtual_memory_bytes gauge ip, cls, ins, job, instanceVirtual memory size in bytes. process_virtual_memory_max_bytes gauge ip, cls, ins, job, instanceMaximum amount of virtual memory available in bytes. promhttp_metric_handler_requests_in_flight gauge ip, cls, ins, job, instanceCurrent number of scrapes being served. promhttp_metric_handler_requests_total counter ip, cls, ins, job, instance, codeTotal number of scrapes by HTTP status code. scrape_duration_seconds Unknown ip, cls, ins, job, instanceN/A scrape_samples_post_metric_relabeling Unknown ip, cls, ins, job, instanceN/A scrape_samples_scraped Unknown ip, cls, ins, job, instanceN/A scrape_series_added Unknown ip, cls, ins, job, instanceN/A swarm_dispatcher_scheduling_delay_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_dispatcher_scheduling_delay_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_dispatcher_scheduling_delay_seconds_sum Unknown ip, cls, ins, job, instanceN/A swarm_manager_configs_total gauge ip, cls, ins, job, instanceThe number of configs in the cluster object store swarm_manager_leader gauge ip, cls, ins, job, instanceIndicates if this manager node is a leader swarm_manager_networks_total gauge ip, cls, ins, job, instanceThe number of networks in the cluster object store swarm_manager_nodes gauge ip, cls, ins, job, instance, stateThe number of nodes swarm_manager_secrets_total gauge ip, cls, ins, job, instanceThe number of secrets in the cluster object store swarm_manager_services_total gauge ip, cls, ins, job, instanceThe number of services in the cluster object store swarm_manager_tasks_total gauge ip, cls, ins, job, instance, stateThe number of tasks in the cluster object store swarm_node_manager gauge ip, cls, ins, job, instanceWhether this node is a manager or not swarm_raft_snapshot_latency_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_raft_snapshot_latency_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_raft_snapshot_latency_seconds_sum Unknown ip, cls, ins, job, instanceN/A swarm_raft_transaction_latency_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_raft_transaction_latency_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_raft_transaction_latency_seconds_sum Unknown ip, cls, ins, job, instanceN/A swarm_store_batch_latency_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_store_batch_latency_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_store_batch_latency_seconds_sum Unknown ip, cls, ins, job, instanceN/A swarm_store_lookup_latency_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_store_lookup_latency_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_store_lookup_latency_seconds_sum Unknown ip, cls, ins, job, instanceN/A swarm_store_memory_store_lock_duration_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_store_memory_store_lock_duration_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_store_memory_store_lock_duration_seconds_sum Unknown ip, cls, ins, job, instanceN/A swarm_store_read_tx_latency_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_store_read_tx_latency_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_store_read_tx_latency_seconds_sum Unknown ip, cls, ins, job, instanceN/A swarm_store_write_tx_latency_seconds_bucket Unknown ip, cls, ins, job, instance, leN/A swarm_store_write_tx_latency_seconds_count Unknown ip, cls, ins, job, instanceN/A swarm_store_write_tx_latency_seconds_sum Unknown ip, cls, ins, job, instanceN/A up Unknown ip, cls, ins, job, instanceN/A
18.5 - 常见问题 Pigsty Docker 模块常见问题答疑
谁能执行Docker命令? 默认情况下,Pigsty 会将当前远程节点执行剧本的管理用户(即目标节点上 ssh 远程登陆的用户),以及参数 node_admin_username 中指定的管理用户加入到 Docker 操作系统用户组中。
在这个用户组(docker)中的所有用户,可以使用 docker CLI 命令对 Docker 发起管理。
如果你想让其他用户也可以执行 Docker 命令,可以将该操作系统用户加入到 docker 组中:
usermod -aG docker <username>
使用代理服务器 在 Docker 安装过程中,如果 proxy_env 参数存在,
这里的 HTTP 代理服务器配置会被写入到 /etc/docker/daemon.json 配置文件中。
Docker 在从上游 Registry 拉取镜像时,会使用此代理服务器。
小提示,在执行 configure 过程中使用 -x 参数会将当前环境中的代理服务器配置写入到 proxy_env 中。
使用镜像站点 如果您在中国大陆受到功夫网影响,可以考虑使用墙内可用的 Docker 镜像站点,例如 quay.io:
docker login quay.io # 输入用户名密码,完成登陆
2024-06 更新,国内所有可用 Docker 镜像站点均已被墙,请使用代理服务器访问并拉取。
将Docker纳入监控 在 Docker 模块安装过程中
针对节点单独执行监控目标注册子任务 docker_register 或 register_prometheus 即可:
./docker.yml -l <your-node-selector> -t register_prometheus
使用软件模板 Pigsty 提供了一系列使用 Docker Compose 拉起的软件工具模板 ,可以开箱即用。
但需要首先安装 Docker 模块。
19.1 - 模块:MySQL 使用 Pigsty 拉起过气的 MySQL 集群,用于测试,迁移,性能评估等目的。
MySQL 曾经是“世界上最流行的开源关系型数据库”。 安装 | 配置 | 管理 | 剧本 | 监控 | 参数
概览 MySQL 模块本身目前仅在 Pigsty 专业版中提供 Beta 试用预览,注意,请不要将这里的 MySQL 用于生产环境。
安装 您可以直接使用以下命令,在 Pigsty 管理的节点上,直接从官方软件源安装 MySQL 8.0 (EL系统)
# el 7,8,9
./node.yml -t node_install -e '{"node_repo_modules":"node,mysql","node_packages":["mysql-community-server,mysql-community-client"]}'
# debian / ubuntu
./node.yml -t node_install -e '{"node_repo_modules":"node,mysql","node_packages":["mysql-server"]}'
您也可以将 MySQL 软件包加入本地软件源后,使用 MySQL 剧本 mysql.yml 进行生产环境部署。
配置 以下配置片段定义了一个单节点的 MySQL 实例,以及其中的 Database 与 User。
my-test :
hosts : { 10.10.10.10 : { mysql_seq: 1, mysql_role : primary } }
vars :
mysql_cluster : my-test
mysql_databases :
- { name : meta }
mysql_users :
- { name: dbuser_meta ,host: '%' ,password: 'dbuesr_meta' ,priv : { "*.*": "SELECT, UPDATE, DELETE, INSERT" } }
- { name: dbuser_dba ,host: '%' ,password: 'DBUser.DBA' ,priv : { "*.*": "ALL PRIVILEGES" } }
- { name: dbuser_monitor ,host: '%' ,password: 'DBUser.Monitor' ,priv : { "*.*": "SELECT, PROCESS, REPLICATION CLIENT" } ,connlimit : 3 }
管理 以下是基本的 MySQL 集群基本管理操作:
使用 mysql.yml 创建 MySQL 集群:
剧本 Pigsty 提供了一个与 MYSQL 模块相关的剧本,用于部署 MySQL 集群
mysql.yml用于部署 MySQL 模式集群的 mysql.yml 剧本包含以下子任务:
mysql-id : generate mysql instance identity
mysql_clean : remove existing mysql instance ( DANGEROUS)
mysql_dbsu : create os user mysql
mysql_install : install mysql rpm/deb packages
mysql_dir : create mysql data & conf dir
mysql_config : generate mysql config file
mysql_boot : bootstrap mysql cluster
mysql_launch : launch mysql service
mysql_pass : write mysql password
mysql_db : create mysql biz database
mysql_user : create mysql biz user
mysql_exporter : launch mysql exporter
mysql_register : register mysql service to prometheus
监控 Pigsty 提供了两个与 MYSQL 模块有关的监控面板:
MYSQL Overview 展示了 MySQL 集群的整体监控指标。
MYSQL Instance 展示了单个 MySQL 实例的监控指标详情
参数 MySQL 的可用配置项:
#-----------------------------------------------------------------
# MYSQL_IDENTITY
#-----------------------------------------------------------------
# mysql_cluster: #CLUSTER # mysql cluster name, required identity parameter
# mysql_role: replica #INSTANCE # mysql role, required, could be primary,replica
# mysql_seq: 0 #INSTANCE # mysql instance seq number, required identity parameter
#-----------------------------------------------------------------
# MYSQL_BUSINESS
#-----------------------------------------------------------------
# mysql business object definition, overwrite in group vars
mysql_users : [] # mysql business users
mysql_databases : [] # mysql business databases
mysql_services : [] # mysql business services
# global credentials, overwrite in global vars
mysql_root_username : root
mysql_root_password : DBUser.Root
mysql_replication_username : replicator
mysql_replication_password : DBUser.Replicator
mysql_admin_username : dbuser_dba
mysql_admin_password : DBUser.DBA
mysql_monitor_username : dbuser_monitor
mysql_monitor_password : DBUser.Monitor
#-----------------------------------------------------------------
# MYSQL_INSTALL
#-----------------------------------------------------------------
# - install - #
mysql_dbsu : mysql # os dbsu name, mysql by default, better not change it
mysql_dbsu_uid : 27 # os dbsu uid and gid, 306 for default mysql users and groups
mysql_dbsu_home : /var/lib/mysql # mysql home directory, `/var/lib/mysql` by default
mysql_dbsu_ssh_exchange : true # exchange mysql dbsu ssh key among same mysql cluster
mysql_packages : # mysql packages to be installed, `mysql-community*` by default
- mysql-community*
- mysqld_exporter
# - bootstrap - #
mysql_data : /data/mysql # mysql data directory, `/data/mysql` by default
mysql_listen : '0.0.0.0' # mysql listen addresses, comma separated IP list
mysql_port : 3306 # mysql listen port, 3306 by default
mysql_sock : /var/lib/mysql/mysql.sock # mysql socket dir, `/var/lib/mysql/mysql.sock` by default
mysql_pid : /var/run/mysqld/mysqld.pid # mysql pid file, `/var/run/mysqld/mysqld.pid` by default
mysql_conf : /etc/my.cnf # mysql config file, `/etc/my.cnf` by default
mysql_log_dir : /var/log # mysql log dir, `/var/log/mysql` by default
mysql_exporter_port : 9104 # mysqld_exporter listen port, 9104 by default
mysql_parameters : {} # extra parameters for mysqld
mysql_default_parameters : # default parameters for mysqld
19.2 - 模块:Kafka 使用 Pigsty 拉起 Kafka Kraft 集群,一个开源的分布式流处理平台。
Kafka 是一个开源的分布式流处理平台:安装 | 配置 | 管理 | 剧本 | 监控 | 参数 | 资源
概览 Kafka 模块本身目前仅在 Pigsty 专业版中提供 Beta 试用预览。
安装 如果您使用开源版 Pigsty,可以使用以下命令,在指定节点上安装 Kafka 及其 Java 依赖。
Pigsty 在官方 Infra 仓库中提供了 Kafka 3.8.0 的 RPM 与 DEB 安装包,如果需要使用,可以直接下载安装。
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["kafka"]}'
Kafka 依赖 Java 运行环境,因此在安装 Kafka 时,需要安装可用的 JDK (默认使用 OpenJDK 17,但其他 JDK 与版本,例如 8,11 都可以使用)
# EL7 (没有 JDK 17 支持)
./node.yml -t node_install -e '{"node_repo_modules":"node","node_packages":["java-11-openjdk-headless"]}'
# EL8 / EL9 (使用 OpenJDK 17 )
./node.yml -t node_install -e '{"node_repo_modules":"node","node_packages":["java-17-openjdk-headless"]}'
# Debian / Ubuntu (使用 OpenJDK 17)
./node.yml -t node_install -e '{"node_repo_modules":"node","node_packages":["openjdk-17-jdk"]}'
配置 单节点 Kafka 配置样例,请注意,在 Pigsty 单机部署模式下,管理节点上的 9093 端口默认已经被 AlertManager 占用。
建议在管理节点上安装 Kafka 时,Peer Poort 使用其他端口,例如(9095)。
kf-main :
hosts :
10.10.10.10 : { kafka_seq: 1, kafka_role : controller }
vars :
kafka_cluster : kf-main
kafka_data : /data/kafka
kafka_peer_port : 9095 # 9093 is already hold by alertmanager
三节点 Kraft 模式 Kafka 集群配置样例:
kf-test :
hosts :
10.10.10.11 : { kafka_seq: 1, kafka_role : controller }
10.10.10.12 : { kafka_seq: 2, kafka_role : controller }
10.10.10.13 : { kafka_seq: 3, kafka_role : controller }
vars :
kafka_cluster : kf-test
管理 以下是基本的 Kafka 集群基本管理操作:
使用 kafka.yml 创建 Kafka 集群:
./kafka.yml -l kf-main
./kafka.yml -l kf-test
创建一个名为 test 的 Topic:
kafka-topics.sh --create --topic test --partitions 1 --replication-factor 1 --bootstrap-server localhost:9092
这里 --replication-factor 1 表示每个数据只会复制一次,--partitions 1 表示只创建一个分区。
使用以下命令,查看 Kafka 中的 Topic 列表:
kafka-topics.sh --bootstrap-server localhost:9092 --list
使用 Kafka 自带的消息生产者,向 test Topic 发送消息:
kafka-console-producer.sh --topic test --bootstrap-server localhost:9092
>haha
>xixi
>hoho
>hello
>world
> ^D
使用 Kafka 自带的消费者,从 test Topic 中读取消息:
kafka-console-consumer.sh --topic test --from-beginning --bootstrap-server localhost:9092
剧本 Pigsty 提供了两个与 KAFKA 模块相关的剧本,分别用于纳管与移除节点。
此外, Pigsty 还提供了两个包装命令工具:node-add 与 node-rm,用于快速调用剧本。
kafka.yml用于部署 Kafka KRaft 模式集群的 kafka.yml 剧本包含以下子任务:
kafka-id : generate kafka instance identity
kafka_clean : remove existing kafka instance ( DANGEROUS)
kafka_user : create os user kafka
kafka_pkg : install kafka rpm/deb packages
kafka_link : create symlink to /usr/kafka
kafka_path : add kafka bin path to /etc/profile.d
kafka_svc : install kafka systemd service
kafka_dir : create kafka data & conf dir
kafka_config : generate kafka config file
kafka_boot : bootstrap kafka cluster
kafka_launch : launch kafka service
kafka_exporter : launch kafka exporter
kafka_register : register kafka service to prometheus
监控 Pigsty 提供了两个与 KAFKA 模块有关的监控面板:
KAFKA Overview 展示了 Kafka 集群的整体监控指标。
KAFKA Instance 展示了单个 Kafka 实例的监控指标详情
参数 Kafka 的可用配置项:
#kafka_cluster: #CLUSTER # kafka cluster name, required identity parameter
#kafka_role: controller #INSTANCE # kafka role, controller, broker, or controller-only
#kafka_seq: 0 #INSTANCE # kafka instance seq number, required identity parameter
kafka_clean : false # cleanup kafka during init? false by default
kafka_data : /data/kafka # kafka data directory, `/data/kafka` by default
kafka_version : 3.8.0 # kafka version string
scala_version : 2.13 # kafka binary scala version
kafka_port : 9092 # kafka broker listen port
kafka_peer_port : 9093 # kafka broker peer listen port, 9093 by default (conflict with alertmanager)
kafka_exporter_port : 9308 # kafka exporter listen port, 9308 by default
kafka_parameters : # kafka parameters to be added to server.properties
num.network.threads : 3
num.io.threads : 8
socket.send.buffer.bytes : 102400
socket.receive.buffer.bytes : 102400
socket.request.max.bytes : 104857600
num.partitions : 1
num.recovery.threads.per.data.dir : 1
offsets.topic.replication.factor : 1
transaction.state.log.replication.factor : 1
transaction.state.log.min.isr : 1
log.retention.hours : 168
log.segment.bytes : 1073741824
log.retention.check.interval.ms : 300000
#log.retention.bytes: 1073741824
#log.flush.interval.ms: 1000
#log.flush.interval.messages: 10000
资源 Pigsty 为 PostgreSQL 提供了一些 Kafka 相关的扩展插件:
kafka_fdw ,一个有趣的 FDW,允许用户直接从 PostgreSQL 中读写 Kafka Topic 数据wal2json ,用于从 PostgreSQL 中逻辑解码 WAL 日志,生成 JSON 格式的变更数据wal2mongo ,用于从 PostgreSQL 中逻辑解码 WAL 日志,生成 BSON 格式的变更数据decoder_raw ,用于从 PostgreSQL 中逻辑解码 WAL 日志,生成 SQL 格式的变更数据test_decoding ,用于从 PostgreSQL 中逻辑解码 WAL 日志,生成 RAW 格式的变更数据19.3 - 模块:DuckDB 使用 Pigsty 安装 DuckDB,一个高性能,嵌入式的分析数据库组件。
DuckDB 是一个高性能,嵌入式的分析数据库:安装 | 资源
概览 DuckDB 是一个嵌入式数据库,所以不需要部署与服务化,只需要在节点上安装 DuckDB 软件包即可使用。
安装 Pigsty 在 Infra 软件仓库中已经提供了 DuckDB 软件包 (RPM / DEB),使用以下命令即可完成安装:
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["duckdb"]}'
相关资源 Pigsty 为 PostgreSQL 提供了一些 DuckDB 相关的扩展插件:
pg_analytics ,旨在基于 DuckDB 提供高性能 OLAP 分析能力pg_lakehouse ,由 ParadeDB 出品的数据湖仓插件,封装了 DuckDB。(目前计划重命名回 pg_analytics )duckdb_fdw ,DuckDB 外部数据源包装器,允许从PG中读写 DuckDB 数据文件pg_duckdb ,由 DuckDB 官方 MotherDuck 和 Hydra 出品的扩展插件,WIP (仅在 EL 系统中提供试点)19.4 - 模块:TigerBeetle 使用 Pigsty 部署 TigerBeetle,金融会计事务专用数据库。
TigerBeetle 是一个金融会计事务专用数据库,提供了极致性能与可靠性。
概览 TigerBeetle 模块目前仅在 Pigsty 专业版中提供 Beta 试用预览。
安装 Pigsty Infra 仓库中提供了 TigerBeetle 的 RPM / DEB 软件包,使用以下命令即可完成安装:
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["tigerbeetle"]}'
即可安装,然后请参考官方文档进行配置:https://github.com/tigerbeetle/tigerbeetle
TigerBeetle需要Linux内核5.5以上版本!
请注意,TigerBeetle 仅支持 Linux 内核 5.5 或更高版本,因此默认在 EL7 (3.10) / EL8 (4.18) 系统上无法使用。
请使用 EL9 (5.14), Ubuntu 22.04 (5.15),或 Debian 12 (6.1) 与 Debian 11 (5.10),或其他支持的系统来安装 Tiger Beetle
19.5 - 模块:Kubernetes 使用 Pigsty 安装 Kubernetes,生产级无状态容器调度编排私有云平台
Kubernetes 是生产级无状态容器调度编排私有云平台。
Pigsty 提供了原生的 [ETCD ] 集群支持,可以供 Kubernetes 使用,因此也在专业版中提供了 KUBE 模块,用于部署生产级 Kubernetes 集群。
Kubernetes 模块目前仅在 Pigsty Pro 专业版本中提供 Beta 预览,在开源版本中不可用。
但您可以直接在 Pigsty 中指定节点仓库,安装 Kubernetes 软件包,并使用 Pigsty 调整环境配置,置备节点供 K8S 部署使用,解决交付的最后一公里问题。
SealOS SealOS 是一个 Kubernetes 发行版,可以用于将整个 Kubernetes 集群打包制作为一个镜像在其他地方使用
Pigsty 在 Infra 仓库中提供了 SealOS 5.0 的 RPM 与 DEB 安装包,可以直接下载安装,并使用 SealOS 管理集群。
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["sealos"]}'
Kubernetes 如果您更喜欢使用经典的 Kubeadm 来部署 Kubernetes,请参考下面的 KUBE 模块参考。
./node.yml -t node_install -e '{"node_repo_modules":"kube","node_packages":["kubeadm,kubelet,kubectl"]}'
Kubernetes 支持多种容器运行时,要是用 Containerd 容器运行时,请确保节点上已经安装了 Containerd 软件包。
./node.yml -t node_install -e '{"node_repo_modules":"node,docker","node_packages":["containerd.io"]}'
若要使用 Docker 作为容器运行时,您需要安装 Docker ,并使用 cri-dockerd 项目桥接(EL9 / D11 / U20 尚不可用):
./node.yml -t node_install -e '{"node_repo_modules":"node,infra,docker","node_packages":["docker-ce,docker-compose-plugin,cri-dockerd"]}'
剧本 kube.yml 剧本
监控 TBD
参数 Kubernetes 模块支持以下配置参数
#kube_cluster: #IDENTITY# # define kubernetes cluster name
kube_role : node # default kubernetes role (master|node)
kube_version : 1.31.0 # kubernetes version
kube_registry : registry.aliyuncs.com/google_containers # kubernetes version aliyun k8s miiror repository
kube_pod_cidr : "10.11.0.0/16" # kubernetes pod network cidr
kube_service_cidr : "10.12.0.0/16" # kubernetes service network cidr
kube_dashboard_admin_user : dashboard-admin-sa # kubernetes dashboard admin user name
19.6 - 模块:Consul 使用 Pigsty 安装部署 Consul —— Etcd 的替代品。
Consul 是一个分布式 DCS + KV + DNS + 服务注册/发现的组件。
在旧版本 (1.x) 的 Pigsty 里,默认使用 Consul 作为高可用的 DCS,现在该支持已经移除,但会在后续重新作为独立模块提供。
配置 要部署 Consul,您需要将所有节点的 IP 地址和主机名添加到 consul 分组中。
您至少需要指定一个节点的 consul_role 为 server,其他节点的 consul_role 默认为 node。
consul:
hosts:
10.10.10.10: { nodename: meta , consul_role: server }
10.10.10.11: { nodename: node-1 }
10.10.10.12: { nodename: node-2 }
10.10.10.13: { nodename: node-3 }
我们建议在严肃生产部署中使用奇数个 Consul Server,三个为宜。
参数 #-----------------------------------------------------------------
# CONSUL
#-----------------------------------------------------------------
consul_role : node # consul role, node or server, node by default
consul_dc : pigsty # consul data center name, `pigsty` by default
consul_data : /data/consul # consul data dir, `/data/consul`
consul_clean : true # consul purge flag, if true, clean consul during init
consul_ui : false # enable consul ui, the default value for consul server is true
19.7 - 模块:Victoria 使用 Pigsty 拉起 VictoriaMetrics 与 VictoriaLogs,Prometheus 与 Loki 的原位上位替代组件。
VictoriaMetrics 是 Prometheus 的原地上位替代,提供更好的性能,压缩比。
概览 Victoria 模块目前仅在 Pigsty 专业版中提供 Beta 试用预览。包含了 VictoriaMetrics 与 VictoriaLogs 组件的部署与管理。
安装 Pigsty Infra 仓库中提供了 VictoriaMetrics 的 RPM / DEB 软件包,使用以下命令即可完成安装:
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["victoria-metrics"]}'
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["victoria-metrics-cluster"]}'
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["victoria-metrics-utils"]}'
./node.yml -t node_install -e '{"node_repo_modules":"infra","node_packages":["victoria-logs"]}'
通常普通用户安装单机版 VictoriaMetrics 即可,如果需要集群部署,可以安装 victoria-metrics-cluster 软件包。
19.8 - 模块:Jupyter 使用 Pigsty 拉起 JupyterNotebook,搭建开箱即用的数据分析环境。
Run jupyter notebook with docker, you have to:
change the default password in .env : JUPYTER_TOKEN create data dir with proper permission: make dir, owned by 1000:100 make up to pull up jupyter with docker composecd ~/pigsty/app/jupyter ; make dir up
Visit http://lab.pigsty or http://10.10.10.10:8888, the default password is pigsty
Prepare Create a data directory /data/jupyter, with the default uid & gid 1000:100:
make dir # mkdir -p /data/jupyter; chown -R 1000:100 /data/jupyter
Connect to Postgres Use the jupyter terminal to install psycopg2-binary & psycopg2 package.
pip install psycopg2-binary psycopg2
# install with a mirror
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple psycopg2-binary psycopg2
pip install --upgrade pip
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
Or installation with conda:
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
then use the driver in your notebook
import psycopg2
conn = psycopg2 . connect ( 'postgres://dbuser_dba:DBUser.DBA@10.10.10.10:5432/meta' )
cursor = conn . cursor ()
cursor . execute ( 'SELECT * FROM pg_stat_activity' )
for i in cursor . fetchall ():
print ( i )
Alias make up # pull up jupyter with docker compose
make dir # create required /data/jupyter and set owner
make run # launch jupyter with docker
make view # print jupyter access point
make log # tail -f jupyter logs
make info # introspect jupyter with jq
make stop # stop jupyter container
make clean # remove jupyter container
make pull # pull latest jupyter image
make rmi # remove jupyter image
make save # save jupyter image to /tmp/docker/jupyter.tgz
make load # load jupyter image from /tmp/docker/jupyter.tgz
20 - 其他组件 21 - PIG 包管理器 PostgreSQL 扩展生态包管理器
—— Postgres Install Genius,PostgreSQL 生态中缺失的扩展包管理器
PIG 包管理器是一个专门用于安装、管理、构建 PostgreSQL 及其扩展的命令行工具,使用 Go 开发,开箱即用,简单易用,小巧玲珑(4MB)。
PIG 包管理器并非重新发明的土鳖轮子,而是 依托 (PiggyBack)现有 Linux 发行版包管理器 (apt/dnf)的一个高级抽象层。
它屏蔽了不同操作系统,不同芯片架构,以及不同 PG 大版本的管理差异,让您用简单的几行命令,就可以完成 PG 内核与 431+ 扩展的安装与管理。
请注意:对于扩展安装来说,pig 并非必须组件 ,您依然可以使用 apt / dnf 等包管理器直接访问 Pigsty PGSQL 仓库。
简介 :为什么需要专用的 PG 包管理器?上手 :快速上手与样例安装 :下载、安装、更新 pig快速上手 使用以下命令即可在您的系统上 安装 PIG 包管理器:
默认安装 (Cloudflare CDN):
curl -fsSL https://repo.pigsty.io/pig | bash
中国镜像 :
curl -fsSL https://repo.pigsty.cc/pig | bash
安装完成后,几行命令即可 快速开始 。例如,若需安装 PG 18 与相应的 pg_duckdb 扩展:
$ pig repo set # 一次性设置好 Linux, Pigsty + PGDG 仓库(覆盖式!)
$ pig install pg18 # 安装 PostgreSQL 18 内核(原生 PGDG 包)
$ pig install pg_duckdb -v 18 # 安装 pg_duckdb 扩展(针对当前 pg 18)
$ pig install -y postgis timescaledb # 针对当前活跃PG版本,安装多个扩展
$ pig install -y vector # 您可以使用扩展名称(vector)或者扩展包名称(pgvector)来安装扩展!
命令参考 你可以执行 pig help <command> 获取子命令的详细帮助。
关于 pig 命令行工具由 Vonng (冯若航 rh@vonng.com )开发,并以 Apache 2.0 许可证开源。
您还可以参考 PIGSTY 项目,提供了包括扩展交付在内的完整 PostgreSQL RDS DBaaS 使用体验。
21.1 - 上手 快速上手 pig,PostgreSQL 包管理器
下面是一个简单的上手教程,带您体验 PIG 包管理器的核心能力。
简短版本 curl -fsSL https://repo.pigsty.io/pig | bash # 从 Cloudflare 安装 PIG
pig repo set # 一次性设置好 Linux, Pigsty + PGDG 仓库(覆盖式!)
pig install -v 18 -y pg18 pg_duckdb vector # 安装 PG 18 内核,pg_duckdb, pgvector 扩展……
安装 您可以使用以下命令 一键安装 pig:
中国大陆 :
curl -fsSL https://repo.pigsty.cc/pig | bash
全球网站 (Cloudflare CDN):
curl -fsSL https://repo.pigsty.io/pig | bash
PIG 二进制包大约 4 MB,在 Linux 上会自动使用 rpm 或 dpkg 安装最新可用版本:
root@pg-meta-1:~# curl -fsSL https://repo.pigsty.cc/pig | bash
[ INFO] kernel = Linux
[ INFO] machine = x86_64
[ INFO] package = deb
[ INFO] pkg_url = https://repo.pigsty.cc/pkg/pig/v0.9.0/pig_0.9.0-1_amd64.deb
[ INFO] download = /tmp/pig_0.9.0-1_amd64.deb
[ INFO] downloading pig v0.9.0
curl -fSL https://repo.pigsty.cc/pkg/pig/v0.9.0/pig_0.9.0-1_amd64.deb -o /tmp/pig_0.9.0-1_amd64.deb
######################################################################## 100.0%
[ INFO] md5sum = 274546a010d39f1ce0aed72cf7e17e52
[ INFO] installing: dpkg -i /tmp/pig_0.9.0-1_amd64.deb
( Reading database ... 166001 files and directories currently installed.)
Preparing to unpack /tmp/pig_0.9.0-1_amd64.deb ...
Unpacking pig ( 0.9.0-1) over ( 0.8.0-1) ...
Setting up pig ( 0.9.0-1) ...
[ INFO] pig v0.9.0 installed successfully
check https://pgext.cloud for details
检查环境 PIG 是一个由 Go 编写的二进制程序,默认安装路径为 /usr/bin/pig,pig version 会打印版本信息:
root@pg-meta-1:~# pig version
pig version 0.9.0 linux/amd64
build: HEAD 80c89c6 2025-12-28T08:05:39Z
使用 pig status 命令,会打印当前环境的状态,操作系统代码,PG的安装情况,仓库的可访问性与延迟。
root@pg-meta-1:~# pig status
# [Configuration] ================================
Pig Version : 0.9.0
Pig Config : /root/.pig/config.yml
Log Level : info
Log Path : stderr
# [OS Environment] ===============================
OS Distro Code : u24
OS OSArch : amd64
OS Package Type : deb
OS Vendor ID : ubuntu
OS Version : 24
OS Version Full : 24.04
OS Version Code : noble
# [PG Environment] ===============================
Installed:
* PostgreSQL 18.1 ( Ubuntu 18.1-1.pgdg24.04+2) 81 Extensions
- PostgreSQL 17.7 ( Ubuntu 17.7-3.pgdg24.04+1) 147 Extensions
Active:
PG Version : PostgreSQL 18.1 ( Ubuntu 18.1-1.pgdg24.04+2)
Config Path : /usr/lib/postgresql/18/bin/pg_config
Binary Path : /usr/lib/postgresql/18/bin
Library Path : /usr/lib/postgresql/18/lib
Extension Path : /usr/share/postgresql/18/extension
# [Pigsty Environment] ===========================
Inventory Path : /root/pigsty/pigsty.yml
Pigsty Home : /root/pigsty
# [Network Conditions] ===========================
google.com ping ok: 156 ms
pigsty.io ping ok: 250 ms
pigsty.cc ping ok: 626 ms
Internet Access : true
Pigsty Repo : pigsty.io
Inferred Region : default
Latest Pigsty Ver : v4.0.0
列出扩展 使用 pig ext list 命令,可以打印内置的 PG 扩展数据目录。
[ root@pg-meta ~] # pig ext list
Name Version Cate Flags License RPM DEB PG Ver Description
---- ------- ---- ------ ------- ------ ------ ------ ---------------------
timescaledb added 2.24.0 TIME -dsl-- Timescale PIGSTY 14-18 postgresql-18-timescaledb-tsl Enables scalable inserts and complex queries for time-series dat
timescaledb_toolkit avail 1.22.0 TIME -ds-t- Timescale PIGSTY 15-18 postgresql-18-timescaledb-toolkit Library of analytical hyperfunctions, time-series pipelining, an
timeseries avail 0.1.8 TIME -d---- PostgreSQL PIGSTY 13-18 postgresql-18-pg-timeseries Convenience API for time series stack
periods avail 1.2.3 TIME -ds--- PostgreSQL PGDG 13-18 postgresql-18-periods Provide Standard SQL functionality for PERIODs and SYSTEM VERSIO
temporal_tables avail 1.2.2 TIME -ds--r BSD 2-Clause PIGSTY 13-18 postgresql-18-temporal-tables temporal tables
.........
pg_fact_loader n/a 2.0.1 ETL -ds--x MIT PGDG 13-17 postgresql-18-pg-fact-loader build fact tables with Postgres
pg_bulkload n/a 3.1.22 ETL bds--- BSD 3-Clause PIGSTY 13-17 postgresql-18-pg-bulkload pg_bulkload is a high speed data loading utility for PostgreSQL
test_decoding avail - ETL --s--x PostgreSQL CONTRIB 13-18 postgresql-18 SQL-based test/example module for WAL logical decoding
pgoutput avail - ETL --s--- PostgreSQL CONTRIB 13-18 postgresql-18 Logical Replication output plugin
( 440 Rows) ( State: added| avail| n/a, Flags: b = HasBin, d = HasDDL, s = HasLib, l = NeedLoad, t = Trusted, r = Relocatable, x = Unknown)
所有的扩展元数据都在一份名为 extension.csv 的数据文件中定义,
这份文件会随着 pig 版本发布不断更新,您可以直接使用 pig ext reload 命令更新这份数据文件。
更新后的文件会默认放置于 ~/.pig/extension.csv 中,您可以查阅与更改 —— 您也可以在本项目中找到该数据文件的 权威版本 。
添加仓库 要想安装扩展,首先需要添加上游仓库。pig repo 可用于管理 Linux APT/YUM/DNF 软件仓库配置。
您可以使用简单粗暴直接的版本 pig repo set 覆盖式写入现有仓库配置,该命令确保系统中只存在必须的仓库配置:
pig repo set # 一次性配置好所有仓库,包括 Linux 系统仓库,PGDG,PIGSTY (PGSQL+INFRA) 仓库
警告 :pig repo set 会备份并清理现有的仓库配置,然后添加所需的仓库,实现 Overwrite 语义,请务必注意!
或者选择使用温和的 pig repo add 添加所需的仓库:
pig repo add pgdg pigsty # 添加 PGDG 官方仓库 和 PIGSTY 补充仓库
pig repo add pgsql # 【可选】您也可以选择将 PGDG 和 PIGSTY 合在一起,当成一个 "pgsql" 模块整体添加
pig repo update # 更新缓存:apt update / yum makecache
PIG 会检测您的网络环境,并选择使用 Cloudflare 全球 CDN,或者中国境内云 CDN,但您可以通过 --region 参数强制指定区域。
pig repo set --region= china # 使用中国区域镜像仓库加速下载
pig repo add pgdg --region= default --update # 强制指定使用 PGDG 上游仓库
PIG 本身不支持离线安装,您可以自行下载 RPM/DEB 包,拷贝到网络隔离的生产服务器安装。
相关项目 PIGSTY 提供本地软件仓库,支持可以使用 pig 从本地软件仓库安装已经下载好的扩展。
安装 PG 添加仓库后,您可以使用 pig ext add 子命令安装扩展(以及相关软件包)
pig ext add -v 18 -y pgsql timescaledb postgis vector pg_duckdb pg_mooncake # 安装 PG 18 内核与扩展,自动确认
# 该命令会自动执行翻译,将软件包翻译为
INFO[ 20:34:44] translate alias 'pgsql' to package: postgresql$v postgresql$v -server postgresql$v -libs postgresql$v -contrib postgresql$v -plperl postgresql$v -plpython3 postgresql$v -pltcl
INFO[ 20:34:44] translate extension 'timescaledb' to package: timescaledb-tsl_18
INFO[ 20:34:44] translate extension 'postgis' to package: postgis36_18
INFO[ 20:34:44] translate extension 'vector' to package: pgvector_18
INFO[ 20:34:44] translate extension 'pg_duckdb' to package: pg_duckdb_18
INFO[ 20:34:44] translate extension 'pg_mooncake' to package: pg_mooncake_18
INFO[ 20:34:44] installing packages: dnf install -y postgresql18 postgresql18-server postgresql18-libs postgresql18-contrib postgresql18-plperl postgresql18-plpython3 postgresql18-pltcl timescaledb-tsl_18 postgis36_18 pgvector_18 pg_duckdb_18 pg_mooncake_18
这里使用了 “别名翻译” 机制,将清爽的 PG 内核/扩展 逻辑包名翻译为实际的 RPM/DEB 列表。如果您不需要别名翻译机制,可以直接使用 apt/dnf 安装,
或者使用变体 pig install 的 -n|--no-translation 参数:
pig install vector # 带有翻译机制,安装当前 PG 18 对应的 pgvector_18 或 postgresql-18-pgvector
pig install vector -n # 关闭翻译机制,安装名为 vector 的日志收集组件(来自 pigsty-infra 仓库)
别名翻译 PostgreSQL 内核与扩展对应着一系列的 RPM/DEB 包,记住这些包是一件麻烦事,所以 pig 提供了许多常用的别名,帮助您简化安装过程:
例如在 EL 系统上, 下面的别名将会被翻译为右侧的对应 RPM 包列表:
pgsql : "postgresql$v postgresql$v-server postgresql$v-libs postgresql$v-contrib postgresql$v-plperl postgresql$v-plpython3 postgresql$v-pltcl"
pg18 : "postgresql18 postgresql18-server postgresql18-libs postgresql18-contrib postgresql18-plperl postgresql18-plpython3 postgresql18-pltcl"
pg17-client : "postgresql17"
pg17-server : "postgresql17-server postgresql17-libs postgresql17-contrib"
pg17-devel : "postgresql17-devel"
pg17-basic : "pg_repack_17* wal2json_17* pgvector_17*"
pg16-mini : "postgresql16 postgresql16-server postgresql16-libs postgresql16-contrib"
pg15-full : "postgresql15 postgresql15-server postgresql15-libs postgresql15-contrib postgresql15-plperl postgresql15-plpython3 postgresql15-pltcl postgresql14-llvmjit postgresql15-test postgresql15-devel"
pg14-main : "postgresql14 postgresql14-server postgresql14-libs postgresql14-contrib postgresql14-plperl postgresql14-plpython3 postgresql14-pltcl pg_repack_14* wal2json_14* pgvector_14*"
pg13-core : "postgresql13 postgresql13-server postgresql13-libs postgresql13-contrib postgresql13-plperl postgresql13-plpython3 postgresql13-pltcl"
注意这里的 $v 占位符会被替换为 PG 大版本号,因此当您使用 pgsql 别名时,$v 会被实际替代为 18,17 这样的大版本号。
因此,当您安装 pg17-server 别名时,EL 上实际安装的是 postgresql17-server, postgresql17-libs, postgresql17-contrib,在 Debian / Ubuntu 上安装的是 postgresql-17 ,pig 会处理好所有细节。
常用 PostgreSQL 别名 EL 使用的别名翻译列表
"pgsql" : "postgresql $v postgresql $v -server postgresql $v -libs postgresql $v -contrib postgresql $v -plperl postgresql $v -plpython3 postgresql $v -pltcl" ,
"pgsql-mini" : "postgresql $v postgresql $v -server postgresql $v -libs postgresql $v -contrib" ,
"pgsql-core" : "postgresql $v postgresql $v -server postgresql $v -libs postgresql $v -contrib postgresql $v -plperl postgresql $v -plpython3 postgresql $v -pltcl" ,
"pgsql-full" : "postgresql $v postgresql $v -server postgresql $v -libs postgresql $v -contrib postgresql $v -plperl postgresql $v -plpython3 postgresql $v -pltcl postgresql $v -llvmjit postgresql $v -test postgresql $v -devel" ,
"pgsql-main" : "postgresql $v postgresql $v -server postgresql $v -libs postgresql $v -contrib postgresql $v -plperl postgresql $v -plpython3 postgresql $v -pltcl pg_repack_ $v wal2json_ $v pgvector_ $v " ,
"pgsql-client" : "postgresql $v " ,
"pgsql-server" : "postgresql $v -server postgresql $v -libs postgresql $v -contrib" ,
"pgsql-devel" : "postgresql $v -devel" ,
"pgsql-basic" : "pg_repack_ $v wal2json_ $v pgvector_ $v " ,
Debian / Ubuntu 系统使用的别名翻译
"pgsql" : "postgresql- $v postgresql-client- $v postgresql-plpython3- $v postgresql-plperl- $v postgresql-pltcl- $v " ,
"pgsql-mini" : "postgresql- $v postgresql-client- $v " ,
"pgsql-core" : "postgresql- $v postgresql-client- $v postgresql-plpython3- $v postgresql-plperl- $v postgresql-pltcl- $v " ,
"pgsql-full" : "postgresql- $v postgresql-client- $v postgresql-plpython3- $v postgresql-plperl- $v postgresql-pltcl- $v postgresql-server-dev- $v " ,
"pgsql-main" : "postgresql- $v postgresql-client- $v postgresql-plpython3- $v postgresql-plperl- $v postgresql-pltcl- $v postgresql- $v -repack postgresql- $v -wal2json postgresql- $v -pgvector" ,
"pgsql-client" : "postgresql-client- $v " ,
"pgsql-server" : "postgresql- $v " ,
"pgsql-devel" : "postgresql-server-dev- $v " ,
"pgsql-basic" : "postgresql- $v -repack postgresql- $v -wal2json postgresql- $v -pgvector" ,
上面这些别名可以直接使用,并通过参数实例化大版本号,也可以使用另一种带有大版本号的别名变体:即将 pgsql 替换为 pg18, pg17, pgxx 等具体大版本号。
例如,对于 PostgreSQL 18,可以直接使用下面这些别名:
pgsqlpg18pg17pg16pg15pg14pg13pgsqlpg18pg17pg16pg15pg14pg13pgsql-minipg18-minipg17-minipg16-minipg15-minipg14-minipg13-minipgsql-corepg18-corepg17-corepg16-corepg15-corepg14-corepg13-corepgsql-fullpg18-fullpg17-fullpg16-fullpg15-fullpg14-fullpg13-fullpgsql-mainpg18-mainpg17-mainpg16-mainpg15-mainpg14-mainpg13-mainpgsql-clientpg18-clientpg17-clientpg16-clientpg15-clientpg14-clientpg13-clientpgsql-serverpg18-serverpg17-serverpg16-serverpg15-serverpg14-serverpg13-serverpgsql-develpg18-develpg17-develpg16-develpg15-develpg14-develpg13-develpgsql-basicpg18-basicpg17-basicpg16-basicpg15-basicpg14-basicpg13-basic
安装扩展 pig 会检测当前系统环境中的 PostgreSQL 安装情况。如果检测到环境中(以 PATH 中的 pg_config 为准)有活跃的 PG 安装,那么 pig 会自动安装对应 PG 大版本所需的扩展,无需您显式指定 PG 大版本。
pig install pg_smtp_client # 更简单
pig install pg_smtp_client -v 18 # 显示指定大版本,更稳定可靠
pig install pg_smtp_client -p /usr/lib/postgresql/16/bin/pg_config # 另一种指定 PG 版本的方式
dnf install pg_smtp_client_18 # 最直接……,但并非所有扩展都这么简单……
提示:如需将特定大版本的 PostgreSQL 内核二进制加入 PATH,可用 pig ext link 命令:
pig ext link pg17 # 创建 /usr/pgsql 软链接,并写入 /etc/profile.d/pgsql.sh
. /etc/profile.d/pgsql.sh # 立即生效,更新 PATH 环境变量
如果你想要安装特定版本的软件,可以使用 name=ver 的语法:
pig ext add -v 17 pgvector = 0.7.2 # install pgvector 0.7.2 for PG 17
pig ext add pg16 = 16.5 # install PostgreSQL 16 with a specific minor version
警告 :请注意,目前只有 PGDG YUM 仓库提供扩展历史版本,PIGSTY 仓库与 PGDG APT 仓库都只提供扩展的 最新版本 。
显示扩展 pig ext status 命令可以用于显示当前安装的扩展。
$ pig ext status -v 18
Installed:
- PostgreSQL 18.0 80 Extensions
No active PostgreSQL found in PATH:
- /root/.local/bin
- /root/bin
- /usr/local/sbin
- /usr/local/bin
- /usr/sbin
- /usr/bin
Extension Stat : 11 Installed ( PIGSTY 3, PGDG 8) + 69 CONTRIB = 80 Total
Name Version Cate Flags License Repo Package Description
---- ------- ---- ------ ------- ------ ------------ ---------------------
timescaledb 2.23.0 TIME -dsl-- Timescale PIGSTY timescaledb-tsl_18* Enables scalable inserts and complex queries for time-series dat
postgis 3.6.0 GIS -ds--- GPL-2.0 PGDG postgis36_18* PostGIS geometry and geography spatial types and functions
postgis_topology 3.6.0 GIS -ds--- GPL-2.0 PGDG postgis36_18* PostGIS topology spatial types and functions
postgis_raster 3.6.0 GIS -ds--- GPL-2.0 PGDG postgis36_18* PostGIS raster types and functions
postgis_sfcgal 3.6.0 GIS -ds--r GPL-2.0 PGDG postgis36_18* PostGIS SFCGAL functions
postgis_tiger_geocoder 3.6.0 GIS -ds-t- GPL-2.0 PGDG postgis36_18* PostGIS tiger geocoder and reverse geocoder
address_standardizer 3.6.0 GIS -ds--r GPL-2.0 PGDG postgis36_18* Used to parse an address into constituent elements. Generally us
address_standardizer_data_us 3.6.0 GIS -ds--r GPL-2.0 PGDG postgis36_18* Address Standardizer US dataset example
vector 0.8.1 RAG -ds--r PostgreSQL PGDG pgvector_18* vector data type and ivfflat and hnsw access methods
pg_duckdb 1.1.0 OLAP -dsl-- MIT PIGSTY pg_duckdb_18* DuckDB Embedded in Postgres
pg_mooncake 0.2.0 OLAP -d---- MIT PIGSTY pg_mooncake_18* Columnstore Table in Postgres
如果您的当前系统路径中找不到 PostgreSQL(以 PATH 中的 pg_config 为准),那么请务必通过 -v|-p 指定 PG 大版本号或 pg_config 路径。
扫描扩展 pig ext scan 提供更底层的扩展扫描功能,将扫描指定 PostgreSQL 目录下的共享库,从而发现安装了哪些扩展:
root@s37451:~# pig ext scan
Installed:
* PostgreSQL 17.6 ( Debian 17.6-2.pgdg13+1) 70 Extensions
- PostgreSQL 15.14 ( Debian 15.14-1.pgdg13+1) 69 Extensions
- PostgreSQL 14.19 ( Debian 14.19-1.pgdg13+1) 66 Extensions
- PostgreSQL 13.22 ( Debian 13.22-1.pgdg13+1) 64 Extensions
- PostgreSQL 18.0 ( Debian 18.0-1.pgdg13+3) 70 Extensions
- PostgreSQL 16.10 ( Debian 16.10-1.pgdg13+1) 70 Extensions
Active:
PG Version : PostgreSQL 17.6 ( Debian 17.6-2.pgdg13+1)
Config Path : /usr/lib/postgresql/17/bin/pg_config
Binary Path : /usr/lib/postgresql/17/bin
Library Path : /usr/lib/postgresql/17/lib
Extension Path : /usr/share/postgresql/17/extension
Name Version SharedLibs Description Meta
---- ------- ---------- --------------------- ------
amcheck 1.4 functions for verifying relation integrity relocatable = true module_pathname = $libdir /amcheck lib = amcheck.so
...
pg_duckdb 1.1.0 DuckDB Embedded in Postgres module_pathname = $libdir /pg_duckdb relocatable = false schema = public lib = libduckdb.so, pg_duckdb.so
pg_mooncake 0.2.0 Real-time analytics on Postgres tables module_pathname = pg_mooncake relocatable = false requires = pg_duckdb superuser = true lib = pg_mooncake.so
pg_prewarm 1.2 prewarm relation data module_pathname = $libdir /pg_prewarm relocatable = true lib = pg_prewarm.so
pg_smtp_client 0.2.1 PostgreSQL extension to send email using SMTP relocatable = false superuser = false schema = smtp_client module_pathname = $libdir /pg_smtp_client lib = pg_smtp_client.so
...
Encoding Libs: cyrillic_and_mic, euc2004_sjis2004, euc_cn_and_mic, euc_jp_and_sjis, euc_kr_and_mic, euc_tw_and_big5, latin2_and_win1250, latin_and_mic, utf8_and_big5, utf8_and_cyrillic, utf8_and_euc2004, utf8_and_euc_cn, utf8_and_euc_jp, utf8_and_euc_kr, utf8_and_euc_tw, utf8_and_gb18030, utf8_and_gbk, utf8_and_iso8859, utf8_and_iso8859_1, utf8_and_johab, utf8_and_sjis, utf8_and_sjis2004, utf8_and_uhc, utf8_and_win
Built-in Libs: dict_snowball, libpqwalreceiver, llvmjit
容器实战 您可以创建一台全新的虚拟机,或者使用下面的 Docker 容器进行功能测试,创建一个 d13 目录,创建 Dockerfile:
FROM debian:13
USER root
WORKDIR /root /
CMD [ "/bin/bash" ]
RUN apt update && apt install -y ca-certificates curl && curl https://repo.pigsty.io/pig | bash
docker build -t d13:latest .
docker run -it d13:latest /bin/bash
pig repo set --region= china # 添加中国区域的仓库
pig install -y pg18 # 安装 PGDG 18 内核包
pig install -y postgis timescaledb pgvector pg_duckdb
21.2 - 简介 为什么我们还需要一个新的包管理器?尤其是针对 Postgres 扩展?
你是否曾因安装或升级 PostgreSQL 扩展而头疼?翻查过时的文档、晦涩难懂的配置脚本,或是在 GitHub 上苦寻分支与补丁?
Postgres 丰富的扩展生态同时意味着复杂的部署流程 —— 在多发行版、多架构环境下尤为棘手。而 PIG 可以为您解决这些烦恼。
这正是 Pig 诞生的初衷。Pig 由 Go 语言开发,致力于一站式管理 Postgres 及其 430+ 扩展。
无论是 TimescaleDB、Citus、PGVector,还是 30+ Rust 扩展,亦或 自建 Supabase 所需的全部组件 —— Pig 统一的 CLI 让一切触手可及。
它彻底告别源码编译与杂乱仓库,直接提供版本对齐的 RPM/DEB 包,完美兼容 Debian、Ubuntu、RedHat 等主流发行版,支持 x86 与 Arm 架构,无需猜测,无需折腾。
Pig 并非重复造轮子,而是充分利用系统原生包管理器(APT、YUM、DNF),严格遵循 PGDG 官方 打包规范,确保无缝集成。
你无需在"标准做法"与"快捷方式"之间权衡;Pig 尊重现有仓库,遵循操作系统最佳实践,与现有仓库和软件包和谐共存。
如果你的 Linux 系统和 PostgreSQL 大版本不在 支持的列表 中,你还可以使用 pig build 直接针对特定组合编译扩展。
想让你的 Postgres 如虎添翼、远离繁琐?欢迎访问 PIG 官方文档 获取文档、指南,并查阅庞大的 扩展列表 ,
让你的本地 Postgres 数据库一键进化为全能的多模态数据中台。
如果说 Postgres 的未来是无可匹敌的可扩展性 ,那么 Pig 就是帮你解锁它的神灯。毕竟,从没有人抱怨 “扩展太多”。
《ANNOUNCE pig: The Postgres Extension Wizard 》
Linux 兼容性 PIG 与 Pigsty 扩展仓库支持以下 Linux 发行版和 PostgreSQL 版本组合:
OS 代码 厂商 大版本 小版本 全名 PG 版本 备注 el7.x86_64EL 7 7.9 CentOS 7 x86 13-15 EOL el8.x86_64EL 8 8.10 RockyLinux 8 x86 13-18 即将EOL el8.aarch64EL 8 8.10 RockyLinux 8 ARM 13-18 即将EOL el9.x86_64EL 9 9.6 RockyLinux 9 x86 13-18 ✅ el9.aarch64EL 9 9.6 RockyLinux 9 ARM 13-18 ✅ el10.x86_64EL 10 10.0 RockyLinux 10 x86 13-18 ✅ el10.aarch64EL 10 10.0 RockyLinux 10 ARM 13-18 ✅ d11.x86_64Debian 11 11.11 Debian 11 x86 13-18 EOL d11.aarch64Debian 11 11.11 Debian 11 ARM 13-18 EOL d12.x86_64Debian 12 12.12 Debian 12 x86 13-18 ✅ d12.aarch64Debian 12 12.12 Debian 12 ARM 13-18 ✅ d13.x86_64Debian 13 13.1 Debian 13 x86 13-18 ✅ d13.aarch64Debian 13 13.1 Debian 13 ARM 13-18 ✅ u20.x86_64Ubuntu 20 20.04.6 Ubuntu 20.04 x86 13-18 EOL u20.aarch64Ubuntu 20 20.04.6 Ubuntu 20.04 ARM 13-18 EOL u22.x86_64Ubuntu 22 22.04.5 Ubuntu 22.04 x86 13-18 ✅ u22.aarch64Ubuntu 22 22.04.5 Ubuntu 22.04 ARM 13-18 ✅ u24.x86_64Ubuntu 24 24.04.3 Ubuntu 24.04 x86 13-18 ✅ u24.aarch64Ubuntu 24 24.04.3 Ubuntu 24.04 ARM 13-18 ✅
说明:
EL 指 RHEL 兼容发行版,包括 RHEL、CentOS、RockyLinux、AlmaLinux、OracleLinux 等EOL 表示该操作系统已经或即将停止支持,建议升级到更新版本✅ 表示完整支持,推荐使用PG 版本 13-18 表示支持 PostgreSQL 13、14、15、16、17、18 六个大版本 21.3 - 安装 如何下载与安装 pig 包管理器
脚本安装 安装 pig 最简单的方式是运行以下安装脚本:
默认安装 (Cloudflare CDN):
curl -fsSL https://repo.pigsty.io/pig | bash
中国镜像 :
curl -fsSL https://repo.pigsty.cc/pig | bash
该脚本会从 Pigsty 软件仓库 下载最新版 pig 的 RPM / DEB 包,并通过 rpm 或 dpkg 进行安装。
指定版本 您可以指定特定版本进行安装,将版本号作为参数传入即可:
默认安装 (Cloudflare CDN):
curl -fsSL https://repo.pigsty.io/pig | bash -s 0.9.0
中国镜像 :
curl -fsSL https://repo.pigsty.cc/pig | bash -s 0.9.0
发布页下载 你也可以直接从 Pigsty 仓库下载 pig 安装包(RPM/DEB/ 压缩包):GitHub 最新版本发布页
latest
└── v0.9.0
├── pig_0.9.0-1_amd64.deb
├── pig_0.9.0-1_arm64.deb
├── pig-0.9.0-1.aarch64.rpm
├── pig-0.9.0-1.x86_64.rpm
├── pig-v0.9.0.linux-amd64.tar.gz
├── pig-v0.9.0.linux-arm64.tar.gz
├── pig-v0.9.0.darwin-amd64.tar.gz
└── pig-v0.9.0.darwin-arm64.tar.gz
将其解压后,将二进制文件放入您的 PATH 系统路径中即可。
仓库安装 pig 软件位于 pigsty-infra 仓库中。你可以将该仓库添加到操作系统后,使用操作系统的包管理器进行安装:
YUM 对于 RHEL,RockyLinux,CentOS,Alma Linux,OracleLinux 等 EL 系发行版:
sudo tee /etc/yum.repos.d/pigsty-infra.repo > /dev/null <<-'EOF'
[pigsty-infra]
name=Pigsty Infra for $basearch
baseurl=https://repo.pigsty.io/yum/infra/$basearch
enabled = 1
gpgcheck = 0
module_hotfixes=1
EOF
sudo yum makecache;
sudo yum install -y pig
APT 对于 Debian,Ubuntu 等 DEB 系发行版:
sudo tee /etc/apt/sources.list.d/pigsty-infra.list > /dev/null <<EOF
deb [trusted=yes] https://repo.pigsty.io/apt/infra generic main
EOF
sudo apt update;
sudo apt install -y pig
更新 若要将现有 pig 版本升级至最新可用版本,可以使用以下命令:
pig update # 将 pig 自身升级到最新版
若要将现有 pig 的扩展数据升级至最新可用版本,可以使用以下命令:
pig ext reload # 将 pig 扩展数据更新至最新版本
卸载 apt remove -y pig # Debian / Ubuntu 等 Debian 系统
yum remove -y pig # RHEL / CentOS / RockyLinux 等 EL 系发行版
rm -rf /usr/bin/pig # 若直接使用二进制安装,删除二进制文件即可
构建 你也可以自行构建 pig。pig 使用 Go 语言开发,构建非常容易,源码托管在 github.com/pgsty/pig
git clone https://github.com/pgsty/pig.git; cd pig
go get -u; go build
所有 RPM / DEB 包都通过 GitHub CI/CD 流程使用 goreleaser 自动化构建。
21.4 - 版本 pig —— PostgreSQL 包管理器的发布说明
最新稳定版本是 v0.9.0 。
v0.9.0 将命令 pig sty install 重构为 pig sty deploy 为命令 pig sty conf 添加新参数,与 configure 脚本对齐。 将 llvmjit 包添加至 pgsql-full 别名中 校验和
ea0c098d0829720b6e364d2f2a91328876962c7f0ae94eee7bdcde0bd43313fa pig-0.9.0-1.aarch64.rpm
707f4e1fde76d3faa05165ac11e97969c22a8740c97ef84da52727d0328990cc pig-0.9.0-1.x86_64.rpm
56aeb61674ddfb64368e6f5535e06a38b76f62e3d6c9536a63be7df6babed93e pig-v0.9.0.darwin-amd64.tar.gz
a213d16817d6124ffa83d93ad880a040598b6ed3fe23a74d43420c095ed43de4 pig-v0.9.0.darwin-arm64.tar.gz
6a1a1836217fa723ca42bc2276ecf1453cd2ee0acacddfc313164701b24a452f pig-v0.9.0.linux-amd64.tar.gz
5e5728aa5922138c61c900a731f97cdc1b9653c14d7fe804b6753fb6f222b8b0 pig-v0.9.0.linux-arm64.tar.gz
e80d2cb3ceb5fd58fc0262ab4b39b44e8dcccb7712151c73a41ba50cb510353b pig_0.9.0-1_amd64.deb
ecb504efffde8d696b765579332fc0b3304751fa8077c4c0394e7f3c44aa0fe2 pig_0.9.0-1_arm64.deb
发布:https://github.com/pgsty/pig/releases/tag/v0.9.0
v0.8.0 扩展更新
扩展总数达到 440 个 新增扩展:pg_ai_query 0.1.1 新增扩展:pg_textsearch 0.1.0 新增扩展:pg_clickhouse 0.1.0 pg_biscuit 从 1.0 升级至 2.0.1(切换至新仓库,更名为 biscuit) pg_search 从 0.20.3 升级至 0.20.5 pg_duckdb 升级至官方正式版 1.1.1 vchord_bm25 从 0.2.2 升级至 0.3.0 pg_semver 从 0.40.0 升级至 0.41.0 pg_timeseries 从 0.1.7 升级至 0.1.8 修复 debian/ubuntu pg18 扩展问题:supautils、pg_summarize、pg_vectorize、pg_tiktoken、pg_tzf、pglite_fusion、pgsmcrypto、pgx_ulid、plprql pigsty 版本号同步至 4.0.0 仓库更新
因上游变更移除 pgdg yum sysupdate 仓库 因上游变更移除 pgdg yum llvmjit 软件包 修复 el9.aarch64 上 patroni 3.0.4 重复软件包问题 为 el 仓库定义添加优先级,docker 仓库不可用时自动跳过 添加 epel 10 / pgdg 9/10 操作系统小版本热修复 校验和
e457832fb290e2f9975bf719966dc36e650bdcbf8505d319c9e0431f4c03bc9e pig-0.8.0-1.aarch64.rpm
c97b1bfdd7541f0f464cab0ecc273e65535c8dd2603c38d5cf8dccbf7e95b523 pig-0.8.0-1.x86_64.rpm
d892f06d3d3b440671529f40e6cc7949686e0167e2a4758adc666b8a3d75254d pig-v0.8.0.darwin-amd64.tar.gz
222413bafdf5a62dc682dac32ea1118cbc34ec3544e2a1b85076ec450b9cc7ae pig-v0.8.0.darwin-arm64.tar.gz
d50aa9806bbab8fee5ad9228e104fc9e7ead48729228116b5bf889000791fedc pig-v0.8.0.linux-amd64.tar.gz
d2f410f7b243a8323c8d479f462a0267ac72d217aa4a506c80b5a9927d12dff8 pig-v0.8.0.linux-arm64.tar.gz
4ccd330a995911d4f732e8c9d62aa0db479c21c9596f64c4bc129ec43f156abe pig_0.8.0-1_amd64.deb
5cb9eccce659110f3ba58e502575564bd6befffd51992a43d84df5a17f8eb8a0 pig_0.8.0-1_arm64.deb
发布:https://github.com/pgsty/pig/releases/tag/v0.8.0
v0.7.5 扩展更新
timescaledb 2.23.1 -> 2.24.0 pg_search 0.20.0 -> 0.20.3 convert 0.0.4 -> 0.0.5 pglinter 1.0.0 -> 1.0.1 pgdd 0.6.0 -> 0.6.1 pg_session_jwt 0.3.3 -> 0.4.0 pg_anon 2.4.1 -> 2.5.1 pg_enigma 0.4.0 -> 0.5.0 wrappers 0.5.6 -> 0.5.7 pg_vectorize 0.25.0 -> 0.26.0 仓库更新
使用修复后的阿里云 PGDG 镜像仓库
校验和
9de11ac1404fc4100074113f2a5d50e4ec42c353b6e122a0b29edc17e53feca6 pig-0.7.5-1.aarch64.rpm
071d655580f1cc63b33d41a8fb49368556b7b5a276318f4bd772a6ab50e22b34 pig-0.7.5-1.x86_64.rpm
befe0a8f786e5243669ed7219acde8156d13d9adb0a5c2fb88ccf0f614a51f9b pig-v0.7.5.darwin-amd64.tar.gz
4766b4e9ba390a32a7115e9f2dd6b65cf158439e28f9c099bab5c7f2e588bae2 pig-v0.7.5.darwin-arm64.tar.gz
dc45726c5e7fccd502cacaffc94c659570844151cdc279f2cac6500836071ade pig-v0.7.5.linux-amd64.tar.gz
1483cf967d4bc9c12d4c6724567644d6b88fcd2a93aaf1d317fc6ad4e1672c13 pig-v0.7.5.linux-arm64.tar.gz
0152b7bd254eccadd640e563845abd9fa62efa68f11c6b67a5f9f0eebfa2d92e pig_0.7.5-1_amd64.deb
7d22116d26ca09c5e2b8afbf086bb1acb1aea1148905efcc38944c18908fb105 pig_0.7.5-1_arm64.deb
发布:https://github.com/pgsty/pig/releases/tag/v0.7.5
v0.7.4 更新扩展版本与元数据:pg_search,pgmq,pg_stat_monitor 更新 PGDG 仓库 URL 变化,extras 仓库现在位于 yum 仓库顶层 将 ivorysql 更新至 5.0 版本,与 PG 18 兼容 将 Percona Postgres TDE 内核更新至 18.1 Checksums
5769b0051f04dcda22dd92b30b8effc8ddfa40097308bded76ce2b38d012ce57 pig-0.7.4-1.aarch64.rpm
d15c829fa2e3ce8dcd1adc063c107607b8e70f2cf747646aaa2fa257cdbf979c pig-0.7.4-1.x86_64.rpm
bb4c90e253a3d470e50316e633a41e90ed2d4a5c5a1fd3a8dbb68ee87d831d47 pig-v0.7.4.darwin-amd64.tar.gz
faaf7ac7b08390f5048c081bb7a78100714387e35dc890e26d9746fc1caef415 pig-v0.7.4.darwin-arm64.tar.gz
037cacddd0dc1283f13dd2c9bace87ad7f2c74ffc245e629f1420be94bbf93df pig-v0.7.4.linux-amd64.tar.gz
2ce819b2c3686cfb9f86790fdf61acd30bf7798bd6cd3c4f589df22e273dc867 pig-v0.7.4.linux-arm64.tar.gz
97f62d62f1cca61ce6d335efed88e3855d94ea2cd4ed941f2755fbac73931fcd pig_0.7.4-1_amd64.deb
d2b80af89ed42601716f6b41eda3f8bee16db34023527df9deef8a43aa25a498 pig_0.7.4-1_arm64.deb
发布:https://github.com/pgsty/pig/releases/tag/v0.7.4
v0.7.3 新增 pig repo reload 命令,更新仓库元数据 修复 EL PGDG sysupdate aarch64 仓库问题。 修复 EL10.aarch64 PGDG 仓库重命名问题。 订正了若干扩展版本 更新 Pigsty 版本至 3.7.0 校验和
786d72f6b685d6d6abf5f255f0a7de9204988a05630a26a53bfc7631823c0c6f pig-0.7.3-1.aarch64.rpm
da59e24ef79d1164e348bacc43e3222e8e2778ec0e103e7ffc0c6df064758e8f pig-0.7.3-1.x86_64.rpm
73062a979749095e89abc07dd583d34d4f57908bb4ee935cf7640f129ca6a2cb pig-v0.7.3.darwin-amd64.tar.gz
ca5f5576f6d0d9be1d10cad769821be9daa62220b2fb56b94d6e4c0cede6da61 pig-v0.7.3.darwin-arm64.tar.gz
d193b4b87cf9a6e4775b1b07709802d30f0233ccb1b728843a09decb545168d3 pig-v0.7.3.linux-amd64.tar.gz
e7f612df0e8e4d9fac6df3765862b9e491bb50aad651856abf7a6935986e6f99 pig-v0.7.3.linux-arm64.tar.gz
3d5306ce95dcf704dd498b05325d942637564b13115f1e5a5bb9ef6781df1ba6 pig_0.7.3-1_amd64.deb
32e695ba2d49a741d8cd92008f8f2dec29f10754d35b732035f48517b382c30d pig_0.7.3-1_arm64.deb
发布:https://github.com/pgsty/pig/releases/tag/v0.7.3
v0.7.2 批量更新扩展,数量达到 437 个
新增 PGDG EL10 Sysupdate 仓库
新增 LLVM APT 仓库
在 pig build 命令中使用可选的本地 extension.csv 扩展定义问题。
更新的扩展: vchord pg_later pgvectorscale pglite_fusion pgx_ulid pg_search citus timescaledb pg_profile pg_stat_monitor documentdb
新增的扩展:pglinter pg_typeid pg_enigma pg_retry pg_biscuit pg_weighted_statistics
校验和
f303c391fc28bc74832712e0aa58319abe0ebcae4f6c07fdf9a9e542b735d2ec pig-0.7.2-1.aarch64.rpm
c096a61a4e3a49b1238659664bbe2cd7f29954c43fb6bb8e8e9fb271f95a612e pig-0.7.2-1.x86_64.rpm
5e037c891dff23b46856485108d6f64bede5216dfbd4f38a481f0d0672ee910b pig-v0.7.2.darwin-amd64.tar.gz
736b4b47999c543c3c886781f4d8dddbf4276f363c35c7bf50094b6f18d14600 pig-v0.7.2.darwin-arm64.tar.gz
20b13f059efed29dd76f6927b3e8d7b597c0c8d734f9e22ba3d0a2af6dbcd3bf pig-v0.7.2.linux-amd64.tar.gz
9548b530c05f2ffdc8d73b8f890718d47b74a51eb62852a99c08b1b52e47f014 pig-v0.7.2.linux-arm64.tar.gz
b6faad9f92b926546a10f590274f2cb2afff21b9cea878094cfc5caf09e67d2c pig_0.7.2-1_amd64.deb
452f73f1fa035e5417ab49fc51d797925550179ffcc023e8f03d80144309212a pig_0.7.2-1_arm64.deb
发布:https://github.com/pgsty/pig/releases/tag/v0.7.2
v0.7.1 校验和
a696c9ec784e2fc248e5f3d87cc8aae4116e890f78c5997957d30593f2c85ca6 pig-0.7.1-1.aarch64.rpm
f669538a99cd1dc592d3005b949628fcceb9e78114fc78862d7726b340ee194d pig-0.7.1-1.x86_64.rpm
e42bdaaf93b720c5b76b32b57362320e4b447109740c76089aefe030b7c8b836 pig-v0.7.1.darwin-amd64.tar.gz
b4c240aadad34e785666ee0a755d9b7455724f790c2d088a1dd7c37ad3b2a457 pig-v0.7.1.darwin-arm64.tar.gz
ffc687add0ca71ac90cba5749c8a7a6075cf7618cba85584072831cf3eb182f7 pig-v0.7.1.linux-amd64.tar.gz
7b0d1f158150d0a40c525692f02b6bce9f5b4ac523a4e59278d702c334e222e1 pig-v0.7.1.linux-arm64.tar.gz
43e91a3bea273d7cacb2d7a58c0a5745501dbd06348b5cb3af971171fae70268 pig_0.7.1-1_amd64.deb
fc2a34aeb46e07cb0ae93611de47d6622c3bd46fe4c415ce4c9091840e0e08a2 pig_0.7.1-1_arm64.deb
发布:https://github.com/pgsty/pig/releases/tag/v0.7.1
v0.7.0 提供针对 Debian 13 和 EL 10 发行版的支持 大批量扩展更新至最新版本,带有 PostgreSQL 18 支持。 几乎所有 Rust 扩展现已通过 pgrx 0.16.1 支持 PG 18 pig build 命令彻底重做pig build pkg <pkg> 现在会一条龙完成扩展的下载,依赖安装,构建pig build pgrx 命令现在从 pig build rust 中分离pig build pgrx [-v pgrx_version] 现在可以直接使用现有的 PG 安装pig build dep 现在会处理 EL 和 Debian 系统下的扩展依赖pig build ext 命令现在有了更为紧凑和美观的输出,可在 EL 下不依赖 build 脚本直接构建 RPMpig build spec 现在支持直接从Pigsty仓库下载 spec 文件包pig build repo / pig repo add / pig repo set 现在默认使用 node,pgsql,infra 仓库模块,取代原本的 node,pgdg,pigsty大量优化了错误日志记录。 基于 hugo 与 hextra 全新目录网站 校验和
ad60f9abcde954769e46eb23de61965e pig_0.7.0-1_amd64.deb
aa15d7088d561528e38b2778fe8f7cf9 pig_0.7.0-1_arm64.deb
05549fe01008e04f8d5a59d4f2a5f0b8 pig-0.7.0-1.aarch64.rpm
0cc9e46c7c72d43c127a6ad115873b67 pig-0.7.0-1.x86_64.rpm
ddacfb052f3f3e5567a02e92fdb31cdd pig-v0.7.0.darwin-amd64.tar.gz
17d25b565308d3d35513e4b0d824946b pig-v0.7.0.darwin-arm64.tar.gz
ee7e055ceff638039956765fb747f80b pig-v0.7.0.linux-amd64.tar.gz
284e674807b87447d4b33691fd7a420d pig-v0.7.0.linux-arm64.tar.gz
发布:https://github.com/pgsty/pig/releases/tag/v0.7.0
v0.6.2 使用 PG 18 官方正式仓库取代原本的 Testing Beta 仓库 instead of testing repo 在接收 Pigsty 版本字符串的时候,自动添加 v 前缀 改进了网络检查与下载的逻辑 校验和
01f5b7dc20644226c762dbb229768347 pig_0.6.2-1_amd64.deb
ce4f00256adc12cbea91467b7f2241cd pig_0.6.2-1_arm64.deb
cefc36ae8f348aede533b30836fba720 pig-0.6.2-1.aarch64.rpm
d04a287c6eb92b11ecbf99542c2db602 pig-0.6.2-1.x86_64.rpm
e637ca86a7f38866c67686b060223d9a pig-v0.6.2.darwin-amd64.tar.gz
79749bc69c683586bd8d761bdf6af98e pig-v0.6.2.darwin-arm64.tar.gz
ad4f02993c7d7d8eec142f0224551bb4 pig-v0.6.2.linux-amd64.tar.gz
9793affa4a0cb60e9753e65b7cba3dca pig-v0.6.2.linux-arm64.tar.gz
发布:https://github.com/pgsty/pig/releases/tag/v0.6.2
v0.6.1 新增 el10 与 debian 13 trixie 的支持存根 专门的新文档网站: https://pgext.cloud/pig 使用 go 1.25 重新构建,新增 CI/CD 管道 在中国大陆使用 PIGSTY PGDG 镜像 移除空的 pgdg-el10fix 仓库 使用 Pigsty WiltonDB 镜像 修复 EL 10 专用的 EPEL 仓库 pig version 输出构建环境信息 发布:https://github.com/pgsty/pig/releases/tag/v0.6.1
v0.6.0 新扩展目录:https://ext.pgsty.com 新子命令:pig install 简化 pig ext install 添加新内核支持:带 pg_tde 的 percona 添加新包:Google GenAI MCP 数据库工具箱 添加新仓库:percona 仓库和 clickhouse 仓库 将扩展摘要信息链接更改为 https://ext.pgsty.com 修复 orioledb 在 Debian/Ubuntu 系统上的问题 修复 EL 发行版上的 epel 仓库 将 golang 升级到 1.24.5 将 pigsty 升级到 v3.6.0 校验和
1804766d235b9267701a08f95903bc3b pig_0.6.0-1_amd64.deb
35f4efa35c1eaecdd12aa680d29eadcb pig_0.6.0-1_arm64.deb
b523b54d9f2d7dcc5999bcc6bd046b1d pig-0.6.0-1.aarch64.rpm
9434d9dca7fd9725ea574c5fae1a7f52 pig-0.6.0-1.x86_64.rpm
f635c12d9ad46a779aa7174552977d11 pig-v0.6.0.linux-amd64.tar.gz
165af4e63ec0031d303fe8b6c35c5732 pig-v0.6.0.linux-arm64.tar.gz
发布:https://github.com/pgsty/pig/releases/tag/v0.6.0
v0.5.0 将扩展列表更新至 422 个 新扩展:来自 AWS 的 pgactive 将 timescaledb 升级到 2.20.3 将 citus 升级到 13.1.0 将 vchord 升级到 0.4.3 修复错误:pgvectorscale debian/ubuntu pg17 失败 将 kubernetes 仓库升级到 1.33 将默认 pigsty 版本升级到 3.5.0 校验和
9ec6f3caf3edbe867caab5de0e0ccb33 pig_0.5.0-1_amd64.deb
4fbb0a42cd8a88bce50b3c9d85745d77 pig_0.5.0-1_arm64.deb
9cf8208396b068cab438f72c90d39efe pig-0.5.0-1.aarch64.rpm
d9a8d78c30f45e098b29c3d16471aa8d pig-0.5.0-1.x86_64.rpm
761df804ff7b83965c41492700717674 pig-v0.5.0.linux-amd64.tar.gz
5d1830069d98030728f08835f883ea39 pig-v0.5.0.linux-arm64.tar.gz
发布:https://github.com/pgsty/pig/releases/tag/v0.5.0
v0.4.2 将扩展列表更新至 421 个 为 Debian / Ubuntu 添加 openhalo/orioledb 支持 pgdd 0.6.0 (pgrx 0.14.1) convert 0.0.4 (pgrx 0.14.1) pg_idkit 0.3.0 (pgrx 0.14.1) pg_tokenizer.rs 0.1.0 (pgrx 0.13.1) pg_render 0.1.2 (pgrx 0.12.8) pgx_ulid 0.2.0 (pgrx 0.12.7) pg_ivm 1.11.0 适用于 debian/ubuntu orioledb 1.4.0 beta11 重新添加 el7 仓库 校验和
bbf83fa3e3ec9a4dca82eeed921ae90a pig_0.4.2-1_amd64.deb
e45753335faf80a70d4f2ef1d3100d72 pig_0.4.2-1_arm64.deb
966d60bbc2025ba9cc53393011605f9f pig-0.4.2-1.aarch64.rpm
1f31f54da144f10039fa026b7b6e75ad pig-0.4.2-1.x86_64.rpm
1eec26c4e69b40921e209bcaa4fe257a pig-v0.4.2.linux-amd64.tar.gz
768d43441917a3625c462ce9f2b9d4ef pig-v0.4.2.linux-arm64.tar.gz
发布:https://github.com/pgsty/pig/releases/tag/v0.4.2
v0.4.1 将扩展列表更新至 414 个 在 pig ext scan 映射中添加 citus_wal2json 和 citus_pgoutput 添加 PG 18 beta 仓库 添加 PG 18 包别名 发布:https://github.com/pgsty/pig/releases/tag/v0.4.1
v0.4.0 更新扩展列表,可用扩展达到 407 个 添加 pig do 子命令用于执行 Pigsty playbook 任务 添加 pig pt 子命令用于包装 Patroni 命令行工具 添加扩展别名:openhalo 和 orioledb 添加 gitlab-ce / gitlab-ee 仓库区分 使用最新 Go 1.24.2 构建并升级依赖项版本 修复特定条件下 pig ext status 的 panic 问题 修复 pig ext scan 无法匹配多个扩展的问题 发布:https://github.com/pgsty/pig/releases/tag/v0.4.0
v0.3.4 curl https://repo.pigsty.io/pig | bash -s 0.3.4
常规扩展元数据更新 使用阿里云 epel 镜像代替损坏的清华大学 tuna 镜像 升级 pigsty 版本字符串 在仓库列表中添加 gitlab 仓库 发布:https://github.com/pgsty/pig/releases/tag/v0.3.4
v0.3.3 添加 pig build dep 命令安装扩展构建依赖项 更新默认仓库列表 为 mssql 模块(wiltondb/babelfish)使用 pigsty.io 镜像 将 docker 模块合并到 infra 从 el7 目标中移除 pg16/17 允许在 el7 中安装扩展 更新包别名 发布:https://github.com/pgsty/pig/releases/tag/v0.3.3
v0.3.2 增强功能
新扩展 使用 upx 减少二进制大小 移除嵌入的 pigsty 以减少二进制大小 发布:https://github.com/pgsty/pig/releases/tag/v0.3.2
v0.3.1 常规错误修复
修复仓库格式字符串 修复扩展信息链接 更新 pg_mooncake 元数据 发布:https://github.com/pgsty/pig/releases/tag/v0.3.1
v0.3.0 pig 项目现在有了新的 主页 ,以及 PostgreSQL 扩展 目录 。
发布:https://github.com/pgsty/pig/releases/tag/v0.3.0
v0.2.2 Pig v0.2.2 中提供 404 个扩展
发布:https://github.com/pgsty/pig/releases/tag/v0.2.2
v0.2.0 发布:https://github.com/pgsty/pig/releases/tag/v0.2.0
v0.1.4 发布:https://github.com/pgsty/pig/releases/tag/v0.1.4
v0.1.3 v0.1.3,常规更新,现在可用 390 个扩展!
发布:https://github.com/pgsty/pig/releases/tag/v0.1.3
v0.1.2 351 个 PostgreSQL 扩展,包括强大的 postgresql-anonymizer 2.0
发布:https://github.com/pgsty/pig/releases/tag/v0.1.2
v0.1.0 pig CLI v0.1 发布
发布:https://github.com/pgsty/pig/releases/tag/v0.1.0
v0.0.1 创世发布
发布:https://github.com/pgsty/pig/releases/tag/v0.0.1
21.5 - 命令参考 21.6 - pig pig CLI 命令参考概览
pig CLI 提供了全面的工具集,用于管理 PostgreSQL 安装、扩展、软件仓库以及从源码构建扩展。使用 pig help <command> 查看命令文档。
概览 pig - PostgreSQL 的 Linux 包管理器
Usage:
pig [ command]
Examples:
pig repo add -ru # 覆盖现有仓库并更新缓存
pig install pg17 # 安装 PostgreSQL 17 PGDG 软件包
pig install pg_duckdb # 安装指定的 PostgreSQL 扩展
pig install pgactive -v 18 # 为特定 PG 版本安装扩展
访问 https://pig.pgsty.com 获取详情
PostgreSQL Extension Manager
ext 管理 PostgreSQL 扩展 ( pgext)
repo 管理 Linux 软件仓库 ( apt/dnf)
build 构建 Postgres 扩展
Pigsty Management Commands
do 运行管理任务
sty 管理 Pigsty 安装
Additional Commands:
completion 生成指定 shell 的自动补全脚本
help 获取任何命令的帮助信息
install 使用原生包管理器安装软件包
status 显示环境状态
update 升级 pig 自身
version 显示 pig 版本信息
Flags:
--debug 启用调试模式
-h, --help 获取帮助信息
-H, --home string Pigsty 主目录路径
-i, --inventory string 配置清单路径
--log-level string 日志级别: debug, info, warn, error, fatal, panic ( 默认 "info" )
--log-path string 日志文件路径,默认为终端输出
使用 "pig [command] --help" 获取命令的详细信息。
pig repo 管理 PostgreSQL 软件包的 APT/YUM 仓库,详情请参考 pig repo
pig repo list # 列出可用仓库
pig repo info pgdg # 显示仓库详情
pig repo status # 检查当前仓库状态
pig repo add pgdg pigsty -u # 添加仓库
pig repo rm old-repo # 移除仓库
pig repo update # 更新软件包缓存
pig repo create /www/pigsty # 创建本地仓库
pig repo cache # 创建离线包
pig repo boot # 从离线包引导
pig ext 管理 PostgreSQL 扩展和内核包,详情请参考 pig ext
pig ext list duck # 搜索扩展
pig ext info pg_duckdb # 扩展详情
pig ext status # 显示已安装的扩展
pig ext add pg_duckdb -y # 安装扩展
pig ext rm old_extension # 移除扩展
pig ext update # 更新扩展
pig ext scan # 扫描已安装的扩展
pig ext import pg_duckdb # 下载以供离线使用
pig ext link 17 # 链接 PG 版本到 PATH
pig ext reload # 刷新扩展目录
pig build 从源码构建 PostgreSQL 扩展,详情请参考 pig build
# 环境设置
pig build spec # 初始化构建规格
pig build repo # 设置仓库
pig build tool # 安装构建工具
pig build rust -y # 安装 Rust(用于 Rust 扩展)
pig build pgrx # 安装 PGRX 框架
# 构建扩展
pig build pkg citus # 完整构建流程 = get + dep + ext
pig build get citus # 下载源码
pig build dep citus # 安装依赖
pig build ext citus # 构建包
pig sty 安装 Pigsty 发行版,详情请参考 pig sty
pig sty init # 安装 Pigsty 到 ~/pigsty
pig sty boot # 安装 Ansible 依赖
pig sty conf # 生成配置
pig sty deploy # 运行部署 playbook
21.7 - pig ext 使用 pig ext 子命令管理 PostgreSQL 扩展
pig ext 命令是一个用于管理 PostgreSQL 扩展的全能工具。它允许用户搜索、安装、移除、更新和管理 PostgreSQL 扩展,甚至支持内核包的管理。
命令 描述 备注 ext list搜索扩展 ext info显示扩展详细信息 ext status显示已安装的扩展 ext scan扫描已安装的扩展 ext add安装扩展 需要 sudo 或 root 权限 ext rm移除扩展 需要 sudo 或 root 权限 ext update更新扩展 需要 sudo 或 root 权限 ext import下载扩展以供离线使用 需要 sudo 或 root 权限 ext link链接 PG 版本到 PATH 需要 sudo 或 root 权限 ext reload刷新扩展目录
快速入门 在安装 PostgreSQL 扩展前,你需要先添加 pig repo add :
pig repo add pgdg pigsty -u # 温和方式添加 pgdg 和 pigsty 仓库
pig repo set -u # 粗暴方式移除并添加所有所需仓库
然后你可以搜索并安装 PostgreSQL 扩展:
pig ext install pg_duckdb
pig ext install pg_partman
pig ext install pg_cron
pig ext install pg_repack
pig ext install pg_stat_statements
pig ext install pg_stat_kcache
可用扩展及其名称请查阅 扩展列表 。
使用说明:
未指定 PostgreSQL 版本时,工具会尝试从 PATH 中的 pg_config 自动检测当前活动的 PostgreSQL 安装。 PostgreSQL 可通过主版本号(-v)或 pg_config 路径(-p)指定。若指定 -v,pig 会使用该版本 PGDG 内核包的默认路径。EL 发行版为 /usr/pgsql-$v/bin/pg_config, DEB 发行版为 /usr/lib/postgresql/$v/bin/pg_config 等。 若指定 -p,则直接用该路径定位 PostgreSQL。 扩展管理器会根据操作系统自动适配不同的包格式:RHEL/CentOS/Rocky Linux/AlmaLinux 使用 RPM 包 Debian/Ubuntu 使用 DEB 包 某些扩展可能有依赖项,安装时会自动解决。 谨慎使用 -y 参数,它会自动确认所有提示。 Pigsty 假定你已安装官方 PGDG 内核包,如未安装,可用如下命令:
pig ext install pg17 # 安装 PostgreSQL 17 内核(除 devel 包)
ext list 列出(或搜索)扩展目录中的可用扩展。
pig ext list # 列出所有扩展
pig ext list duck # 搜索包含 "duck" 的扩展
pig ext list vector ai # 搜索多个关键词
pig ext list -c RAG # 按分类筛选
pig ext list -v 17 # 按 PG 版本筛选
pig ext ls olap # 列出 olap 类别扩展
pig ext ls gis -v 16 # 列出 PG 16 的 GIS 类扩展
选项:
-c|--category:按分类筛选(TIME, GIS, RAG, FTS, OLAP, FEAT, LANG, TYPE, UTIL, FUNC, ADMIN, STAT, SEC, FDW, SIM, ETL)-v|--version:按 PG 版本筛选默认扩展目录定义在 cli/ext/assets/extension.csv
可用 pig ext reload 命令更新到最新扩展目录,数据将下载到 ~/.pig/extension.csv。
ext info 显示指定扩展的详细信息。
pig ext info postgis # 显示 PostGIS 详细信息
pig ext info timescaledb # 显示 TimescaleDB 信息
pig ext info vector postgis # 显示多个扩展信息
ext status 显示当前 PostgreSQL 实例已安装扩展的状态。
pig ext status # 显示已安装扩展
pig ext status -c # 包含 contrib 扩展
pig ext status -v 16 # 显示 PG 16 已安装扩展
选项:
-c|--contrib: 结果中包含 contrib 扩展ext scan 扫描当前 PostgreSQL 实例已安装的扩展。
pig ext scan [ -v version]
该命令会扫描 postgres 扩展目录,查找所有实际已安装的扩展。
ext add 安装一个或多个 PostgreSQL 扩展。也可以使用别名 pig install。
pig ext add pg_duckdb # 安装 pg_duckdb
pig ext add pg_duckdb -v 17 # 为 PG 17 安装
pig ext add pg_duckdb -y # 自动确认安装
pig ext add vector postgis # 安装多个扩展
# 使用别名
pig install pg_duckdb
pig install pg_duckdb -v 17 -y
# 安装 PostgreSQL 内核
pig ext install pgsql # 安装最新版 postgresql 内核
pig ext a pg17 # 安装 postgresql 17 内核包
pig ext ins pg16 # 安装 postgresql 16 内核包
pig ext install pg15-core # 安装 postgresql 15 核心包
pig ext install pg14-main -y # 安装 pg 14 + 常用扩展(vector, repack, wal2json)
选项:
-v|--version:指定 PG 大版本-y|--yes:自动确认安装-n|--no-translation:禁用别名翻译ext rm 移除一个或多个 PostgreSQL 扩展。也可以使用别名 pig remove。
pig ext rm pg_duckdb # 移除 pg_duckdb
pig ext rm pg_duckdb -v 17 # 移除 PG 17 版本
pig ext rm pgvector -y # 自动确认移除
pig remove pg_duckdb # 使用别名
ext update 将已安装扩展更新到最新版。
pig ext update # 更新所有已安装扩展
pig ext update pg_duckdb # 更新特定扩展
pig ext update postgis timescaledb # 更新多个扩展
pig ext update -y # 自动确认更新
ext import 下载扩展包到本地仓库,便于离线安装。
pig ext import postgis # 导入 PostGIS 包
pig ext import timescaledb pg_cron # 导入多个扩展包
pig ext import pg16 # 导入 PostgreSQL 16 包
pig ext import pgsql-common # 导入常用工具包
pig ext import -d /www/pigsty postgis # 指定路径导入
选项:
-d|--repo: 指定仓库目录(默认:/www/pigsty)ext link 将指定 PG 版本链接到系统 PATH。
pig ext link 17 # 链接 PG 17 到 PATH
pig ext link 16 # 链接 PG 16 到 /usr/pgsql
pig ext link /usr/pgsql-16 # 从指定路径链接到 /usr/pgsql
pig ext link null # 取消当前 PostgreSQL 链接
该命令会创建 /usr/pgsql 软链接,并写入 /etc/profile.d/pgsql.sh。
ext reload 从 GitHub 刷新扩展元数据。
更新后的文件会放置于 ~/.pig/extension.csv 中。
21.8 - pig repo 使用 pig repo 子命令管理软件仓库
pig repo 命令是一个综合性的软件包仓库管理工具。它提供了添加、移除、创建和管理软件仓库的功能,支持 RPM 系统(RHEL/CentOS/Rocky/Alma)和 Debian 系统(Debian/Ubuntu)。
命令 描述 备注 repo list打印可用仓库与模块列表 repo info获取仓库详细信息 repo status显示当前仓库状态 repo add添加新仓库 需要 sudo 或 root 权限 repo set清空、覆盖并更新仓库 需要 sudo 或 root 权限 repo rm移除仓库 需要 sudo 或 root 权限 repo update更新仓库缓存 需要 sudo 或 root 权限 repo create创建本地 YUM/APT 仓库 需要 sudo 或 root 权限 repo cache从本地仓库创建离线包 需要 sudo 或 root 权限 repo boot从离线包引导仓库 需要 sudo 或 root 权限
快速入门 # 方法 1:清理干净现有仓库,添加所有必要仓库并更新缓存(推荐)
pig repo add all --remove --update # 移除旧仓库,添加所有必要仓库,更新缓存
# 方法 1 变体:一步到位
pig repo set # = pig repo add all --remove --update
# 方法 2:温和方式 - 仅添加所需仓库,保留你目前的仓库配置
pig repo add pgsql # 添加 PGDG 和 Pigsty 仓库并更新缓存
pig repo add pigsty --region= china # 添加 Pigsty 仓库,指定使用中国区域
pig repo add pgdg --region= default # 添加 PGDG ,指定使用默认区域
pig repo add infra --region= europe # 添加 INFRA 仓库 ,指定使用欧洲区域
# 如果上面没有-u|--update 选项一步到位,请额外执行此命令
pig repo update # 更新系统包缓存
模块 在 pig 中,APT/YUM 仓库被组织为 模块 —— 服务于特定目的的一组仓库。
模块 说明 仓库列表 all安装 PG 所需的全部核心模块 node + infra + pgsqlpgsqlPGDG + Pigsty PG 扩展 pigsty-pgsql + pgdgpigstyPigsty Infra + PGSQL 仓库 pigsty-infra, pigsty-pgsql pgdgPGDG 官方仓库 pgdg-common, pgdg13-18 nodeLinux 系统仓库 base, updates, extras, epel… infra基础设施组件仓库 pigsty-infra, nginx, docker-ce betaPostgreSQL Beta 版本 pgdg19-beta, pgdg-beta extraPGDG Non-Free 与三方扩展 pgdg-extras, timescaledb, citus groongaPGroonga 仓库 groonga mssqlWiltonDB 仓库 wiltondb perconaPercona PG + PG_TDE percona
除此之外,pig 还自带了一些其他数据库的 APT/DNF 仓库:redis, kubernetes, grafana, clickhouse, gitlab, haproxy, mongodb, mysql,在此不再展开。
通常来说,为了安装 PostgreSQL node (Linux 系统仓库) 和 pgsql(PGDG + Pigsty)是必选项,infra 仓库是可选项(包含了一些工具,IvorySQL Kernel 等)。
您可以使用特殊的 all 模块,一次性添加所有需要的仓库到系统中,对绝大多数用户来说,这是合适的起点。
pig repo add all # 添加 node,pgsql,infra 三个仓库到系统中
pig repo add # 不添加任何参数时,默认使用 all 模块
pig repo set # 使用 set 替代 add 时,将清理备份现有仓库定义并覆盖式更新
仓库定义 Pigsty 中可用仓库的完整定义位于 cli/repo/assets/repo.yml 。
您可以创建 ~/.pig/repo.yml 文件,显式修改并覆盖 pig 的仓库定义。在编辑仓库定义文件时,您可以在 baseurl 处添加额外的区域镜像,例如指定中国,欧洲地区的镜像仓库 URL。当 pig 使用 --region 参数指定特定的区域时,pig 会优先查找对应区域的仓库 URL,如果不存在,则会 Fallback 到 default 的仓库 URL。
repo list pig repo list 将列出当前系统可用的所有仓库模块。
pig repo list # 列出当前系统可用仓库
pig repo list all # 列出所有仓库(不过滤)
repo info 显示特定仓库或模块的详细信息,包括 URL、元数据和区域镜像,以及 .repo / .list 仓库文件内容。
pig repo info pgdg # 显示 pgdg 模块的信息
pig repo info pigsty pgdg # 显示多个模块的信息
pig repo info all # 显示所有模块的信息
repo status 显示系统上的当前仓库配置。
repo add 添加仓库配置文件到系统。需要 root/sudo 权限。
pig repo add pgdg # 添加 PGDG 仓库
pig repo add pgdg pigsty # 添加多个仓库
pig repo add all # 添加所有必要仓库 (pgdg + pigsty + node)
pig repo add pigsty -u # 添加并更新缓存
pig repo add all -r # 添加前移除现有仓库
pig repo add all -ru # 移除、添加并更新(完全重置)
pig repo add pgdg --region= china # 使用中国镜像
选项:
-r|--remove:添加新仓库前移除现有仓库-u|--update:添加仓库后运行包缓存更新--region <region>:使用区域镜像仓库(default / china / europe)平台 模块位置 EL /etc/yum.repos.d/<module>.repoDebian /etc/apt/sources.list.d/<module>.list
repo set 等同于 repo add --remove --update。清空现有仓库并设置新仓库,然后更新缓存。
pig repo set # 替换为默认仓库
pig repo set pgdg pigsty # 替换为特定仓库并更新
pig repo set all --region= china # 使用中国镜像
repo rm 移除仓库配置文件并备份它们。
pig repo rm # 移除所有仓库
pig repo rm pgdg # 移除特定仓库
pig repo rm pgdg pigsty -u # 移除并更新缓存
平台 备份位置 EL /etc/yum.repos.d/backup/Debian /etc/apt/sources.list.d/backup/
repo update 更新包管理器缓存以反映仓库更改。
平台 等效命令 EL dnf makecacheDebian apt update
repo create 为离线安装创建本地包仓库。
pig repo create # 在默认位置创建 (/www/pigsty)
pig repo create /srv/repo # 在自定义位置创建
平台 依赖软件 EL createrepo_cDebian dpkg-dev
repo cache 创建仓库内容的压缩 tarball 用于离线分发。
pig repo cache # 默认:/www 到 /tmp/pkg.tgz
pig repo cache -f # 强制覆盖现有文件
pig repo cache -d /srv # 自定义源目录
选项:
-d, --dir:源目录(默认:/www/)-p, --path:输出路径(默认:/tmp/pkg.tgz)-f:强制覆盖现有包repo boot 从离线包解压并设置本地仓库。
pig repo boot # 默认:/tmp/pkg.tgz 到 /www
pig repo boot -p /mnt/pkg.tgz # 自定义包路径
pig repo boot -d /srv # 自定义目标目录
选项:
-p, --path:包路径(默认:/tmp/pkg.tgz)-d, --dir:目标目录(默认:/www/)21.9 - pig sty 使用 pig sty 子命令管理 Pigsty 安装
pig 也可作为 Pigsty 的命令行工具使用 —— 这是一款开箱即用的免费 PostgreSQL RDS 解决方案。
它为你的 PostgreSQL 集群带来高可用(HA)、PITR、监控、基础设施即代码(IaC)以及丰富的扩展支持。
命令 描述 备注 sty init安装 Pigsty sty boot安装 Ansible 依赖 需要 sudo 或 root 权限 sty conf生成配置 sty deploy运行部署 playbook sty list列出可用 Pigsty 版本 sty get下载 Pigsty 源码压缩包
快速入门 你可以使用 pig sty 子命令在当前节点引导部署 Pigsty。
pig sty init # 安装 Pigsty 到 ~/pigsty
pig sty boot # 安装 Ansible 依赖
pig sty conf # 生成配置
pig sty deploy # 运行部署 playbook
详细入门指南请参阅:https://pigsty.io/docs/setup/install/
sty init 下载并安装 Pigsty 发行版到 ~/pigsty 目录。
pig sty init # 使用最新版本安装到 ~/pigsty
pig sty init -f # 安装并覆盖已有 pigsty 目录
pig sty init -p /tmp/pigsty # 安装到指定目录 /tmp/pigsty
pig sty init -v 3.4 # 获取并安装指定版本 v3.4.1
pig sty init 3 # 获取并安装指定主版本 v3 最新
选项:
-p|--path:目标安装目录(默认 “~/pigsty”)-f|--force:强制覆盖已存在的 pigsty 目录-v|--version:pigsty 版本号-d|--dir:下载目录(默认 “/tmp”)sty boot 安装 Ansible 及其依赖。
pig sty boot # 安装 Ansible
pig sty boot -y # 自动确认
pig sty boot -r china # 使用中国区域镜像
pig sty boot -k # 保留已有仓库
pig sty boot -p /path/to/pkg # 指定离线包路径
选项:
-r|--region:区域(default, china, europe…)-p|--path:离线包路径-k|--keep:保留已有仓库详见:https://pigsty.io/zh/docs/setup/offline/#bootstrap
sty conf 使用 ./configure 配置 Pigsty,生成配置文件。
pig sty conf # 使用默认 meta.yml 配置
pig sty conf -g # 生成随机密码(推荐!)
pig sty conf -c rich # 使用 conf/rich.yml 模板(包含更多扩展)
pig sty conf -c ha/full # 使用 conf/ha/full.yml 4 节点高可用模板
pig sty conf -c slim # 使用 conf/slim.yml 模板(最小化安装)
pig sty conf -c supabase # 使用 conf/supabase.yml 模板(自托管)
pig sty conf -v 17 -c rich # 使用 conf/rich.yml 模板,PostgreSQL 17
pig sty conf -r china -s # 使用中国区镜像源,跳过 IP 探测
pig sty conf -x # 从环境变量写入代理配置到配置文件
pig sty conf -c full -g -o ha.yml # 完整 HA 模板,随机密码输出到 ha.yml
选项:
-c|--conf:配置模板名称(meta/rich/slim/full/supabase/…)--ip:主节点 IP 地址-v|--version:PostgreSQL 主版本(18/17/16/15/14/13)-r|--region:上游仓库区域(default/china/europe)-o|--output:输出配置文件路径(默认:pigsty.yml)-s|--skip:跳过 IP 探测-p|--port:SSH 端口-x|--proxy:从环境变量写入代理配置-n|--non-interactive:非交互模式-g|--generate:生成随机默认密码(推荐!)详见:https://pigsty.io/docs/setup/install/#configure
sty deploy 使用 deploy.yml 剧本部署 Pigsty。
pig sty deploy # 执行 deploy.yml(如果找不到则使用 install.yml)
pig sty install # 与 deploy 相同(向后兼容)
pig sty d # 短别名
pig sty de # 短别名
pig sty ins # 短别名
此命令从您的 Pigsty 安装目录执行 deploy.yml 剧本。为保持向后兼容性,如果 deploy.yml 不存在但 install.yml 存在,将使用 install.yml 代替。
警告 :此操作会修改您的系统。请谨慎使用!
sty list 列出可用的 Pigsty 版本。
sty get 下载 Pigsty 源码压缩包。
pig sty get # 下载最新版本
pig sty get v3.4.0 # 下载指定版本
21.10 - pig build 使用 pig build 子命令从源码构建扩展
pig build 命令是一个强大的工具,简化了从源码构建 PostgreSQL 扩展的整个工作流程。它提供了完整的构建基础设施设置、依赖管理,以及标准和自定义 PostgreSQL 扩展在不同操作系统上的编译环境。
命令 描述 备注 build spec初始化构建规范仓库 build repo初始化所需仓库 需要 sudo 或 root 权限 build tool初始化构建工具 需要 sudo 或 root 权限 build rust安装 Rust 工具链 需要 sudo 或 root 权限 build pgrx安装并初始化 pgrx 需要 sudo 或 root 权限 build proxy初始化构建代理 build get下载源代码 tarball build dep安装扩展构建依赖 需要 sudo 或 root 权限 build ext构建扩展包 需要 sudo 或 root 权限 build pkg完整构建流程:get、dep、ext 需要 sudo 或 root 权限
快速入门 设置构建环境并构建扩展的最快方式:
# 步骤 1:初始化构建规范
pig build spec
# 步骤 2:构建扩展(完整流程)
pig build pkg citus
# 构建的包将位于:
# - EL: ~/rpmbuild/RPMS/
# - Debian: ~/
更精细的控制方式:
# 设置环境
pig build spec # 初始化构建规范
pig build repo # 设置仓库
pig build tool # 安装构建工具
# 构建过程
pig build get citus # 下载源码
pig build dep citus # 安装依赖
pig build ext citus # 构建包
# 或一次完成所有三个步骤
pig build pkg citus # get + dep + ext
构建基础设施 目录结构 ~/ext/ # 默认构建规范目录
├── Makefile # 主构建 makefile
├── <extension>/ # 每个扩展的目录
│ ├── Makefile # 扩展特定的 makefile
│ ├── <extension>.spec # RPM 规范文件(EL)
│ └── debian/ # Debian 打包文件
│ ├── control
│ ├── rules
│ └── ...
构建输出位置:
EL 系统 :~/rpmbuild/RPMS/<arch>/Debian 系统 :~/(deb 文件)build spec 设置构建规范仓库和目录结构。
pig build spec # 在默认位置初始化 ~/ext
功能:
克隆或更新扩展构建规范仓库 创建必要的目录结构 设置 makefile 和构建脚本 准备平台特定的打包文件 仓库位置: 默认 ~/ext/,包含 100+ 扩展的构建规范。
build repo 初始化构建扩展所需的包仓库。
pig build repo # 等同于:pig repo set -ru
功能: 移除现有仓库、添加所有必需仓库(pgdg、pigsty、node)、更新包缓存。
安装必要的开发工具和编译器。
pig build tool # 安装默认工具集
pig build tool mini # 最小工具集
pig build tool full # 完整工具集
pig build tool rust # 添加 Rust 开发工具
工具包:
最小(mini): GCC/Clang 编译器、Make 和构建必需品、PostgreSQL 开发头文件、基本库默认: 所有最小工具、额外编译器(g++、clang++)、开发库、打包工具(rpmbuild、dpkg-dev)完整(full): 所有默认工具、语言特定工具(Python、Perl、Ruby 开发)、高级调试工具、性能分析工具build rust 安装 Rust 编程语言工具链,基于 Rust 的扩展所需。
pig build rust # 带确认安装
pig build rust -y # 自动确认安装
安装内容: Rust 编译器(rustc)、Cargo 包管理器、Rust 标准库、开发工具。
build pgrx 安装并初始化 PGRX(Rust 的 PostgreSQL 扩展框架)。
pig build pgrx # 安装最新稳定版 (0.16.1)
pig build pgrx -v 0.15.0 # 安装特定版本
前提条件: 必须先安装 Rust 工具链、PostgreSQL 开发头文件。
build proxy 为受限互联网访问的构建环境设置代理配置。
pig build proxy # 交互式设置
pig build proxy user@host:8080 # 直接配置
pig build proxy http://proxy.company.com:3128
build get 下载扩展源代码 tarball。
pig build get citus # 单个扩展
pig build get citus pgvector # 多个扩展
pig build get all # 所有可用扩展
pig build get std # 标准扩展
build dep 安装构建扩展所需的依赖。
pig build dep citus # 单个扩展
pig build dep citus pgvector # 多个扩展
pig build dep citus --pg 17,16 # 为特定 PG 版本
build ext 编译扩展并创建安装包。
pig build ext citus # 构建单个扩展
pig build ext citus pgvector # 构建多个
pig build ext citus --pg 17 # 为特定 PG 版本
pig build ext citus -s # 包含调试符号(仅 RPM)
build pkg 执行完整的构建流程:下载、依赖和构建。
pig build pkg citus # 构建单个扩展
pig build pkg citus pgvector # 构建多个
pig build pkg citus --pg 17,16 # 为多个 PG 版本
pig build pkg citus -s # 包含调试符号
常见工作流 工作流 1:构建标准扩展 # 1. 设置构建环境(一次性)
pig build spec
pig build repo
pig build tool
# 2. 构建扩展
pig build pkg pg_partman
# 3. 安装构建的包
sudo rpm -ivh ~/rpmbuild/RPMS/x86_64/pg_partman*.rpm # EL
sudo dpkg -i ~/pg_partman*.deb # Debian
工作流 2:构建 Rust 扩展 # 1. 设置 Rust 环境
pig build spec
pig build tool
pig build rust -y
pig build pgrx
# 2. 构建 Rust 扩展
pig build pkg pgmq
# 3. 安装
sudo pig ext add pgmq
工作流 3:构建多个版本 # 为多个 PostgreSQL 版本构建扩展
pig build pkg citus --pg 15,16,17
# 结果为每个版本生成包:
# citus_15-*.rpm
# citus_16-*.rpm
# citus_17-*.rpm
故障排除 找不到构建工具 # 安装构建工具
pig build tool
# 对于特定编译器
sudo dnf groupinstall "Development Tools" # EL
sudo apt install build-essential # Debian
缺少依赖 # 安装扩展依赖
pig build dep <extension>
# 检查错误消息以了解特定包
# 如需要,手动安装
sudo dnf install <package> # EL
sudo apt install <package> # Debian
找不到 PostgreSQL 头文件 # 安装 PostgreSQL 开发包
sudo pig ext install pg17-devel
# 或指定 pg_config 路径
export PG_CONFIG = /usr/pgsql-17/bin/pg_config
Rust/PGRX 问题 # 重新安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 更新 PGRX
cargo install cargo-pgrx --force
# 重新初始化 PGRX
cargo pgrx init
扩展构建矩阵 常见构建的扩展 扩展 类型 构建时间 复杂度 特殊要求 pg_repack C 快速 简单 无 pg_partman SQL/PLPGSQL 快速 简单 无 citus C 中等 中等 无 timescaledb C 慢 复杂 CMake postgis C 非常慢 复杂 GDAL、GEOS、Proj pg_duckdb C++ 中等 中等 C++17 编译器 pgroonga C 中等 中等 Groonga 库 pgvector C 快速 简单 无 plpython3 C 中等 中等 Python 开发 pgrx 扩展 Rust 慢 复杂 Rust、PGRX
22 - Linux 软件源 用于交付 PostgreSQL 扩展的基础设施和软件包仓库
Pigsty 为主流 Linux 发行版 提供了 PostgreSQL 扩展仓库,其中包含 340+ 额外的 PostgreSQL 扩展。
Pigsty 扩展仓库旨在与 PGDG 官方仓库配合使用,共同使用时可以安装多达 400+ PostgreSQL 扩展 。
兼容性概览 系统 / 架构 代码 x86_64 aarch64 EL8 el8 18 17 16 15 14 13 18 17 16 15 14 13 EL9 el9 18 17 16 15 14 13 18 17 16 15 14 13 EL10 el10 18 17 16 15 14 13 18 17 16 15 14 13 Debian 12 d12 18 17 16 15 14 13 18 17 16 15 14 13 Debian 13 d13 18 17 16 15 14 13 18 17 16 15 14 13 Ubuntu 22.04 u22 18 17 16 15 14 13 18 17 16 15 14 13 Ubuntu 24.04 u24 18 17 16 15 14 13 18 17 16 15 14 13
快速上手 你可以使用 pig 命令行工具来方便地启用 infra 和 pgsql 仓库:
curl https://repo.pigsty.io/pig | bash # 下载安装最新版本的 pig 命令行工具
pig repo add all -u # 添加 Linux / PGDG / Pigsty 仓库并更新缓存
curl https://repo.pigsty.cc/pig | bash # 从中国镜像站下载安装最新版本的 pig 命令行工具
pig repo add -u # 添加 Linux / PGDG / Pigsty 仓库并更新缓存
手工添加 您也可以使用经典的 apt / dnf / yum 命令,将仓库手工添加到系统中。
# 将 Pigsty 的 GPG 公钥添加到系统密钥链中,以验证软件包签名
curl -fsSL https://repo.pigsty.io/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
# 获取 Debian / Ubuntu 发行版的代号(jammy, focal, bullseye, bookworm),并将相应的上游仓库地址写入 /etc/apt/sources.list.d/ 中
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty-io.list > /dev/null <<EOF
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.io/apt/infra generic main
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.io/apt/pgsql/${distro_codename} ${distro_codename} main
EOF
# 刷新 APT 仓库缓存
sudo apt update
# 将 Pigsty 的 GPG 公钥添加到系统密钥链中,以验证软件包签名
curl -fsSL https://repo.pigsty.io/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
# 将 Pigsty 仓库的定义写入 /etc/yum.repos.d/ 目录中
sudo tee /etc/yum.repos.d/pigsty-io.repo > /dev/null <<-'EOF'
[pigsty-infra]
name=Pigsty Infra for $basearch
baseurl=https://repo.pigsty.io/yum/infra/$basearch
skip_if_unavailable = 1
enabled = 1
priority = 1
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty
module_hotfixes=1
[pigsty-pgsql]
name=Pigsty PGSQL For el$releasever.$basearch
baseurl=https://repo.pigsty.io/yum/pgsql/el$releasever.$basearch
skip_if_unavailable = 1
enabled = 1
priority = 1
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty
module_hotfixes=1
EOF
# 刷新 YUM 仓库缓存
sudo yum makecache;
所有的 RPM / DEB 软件包都使用指纹为 (B9BD8B20) 的 GPG 密钥 进行签名,以确保软件包的完整性。
仓库组成 Pigsty 仓库由两个主要部分组成:INFRA 和 PGSQL ,提供 x86_64 和 aarch64 架构下的 DEB / RPM 包。
INFRA 仓库中的软件包与 PostgreSQL / Linux 大版本无关,包括 Prometheus、Grafana、以及一些 PostgreSQL 管理工具,
通常由 Go 等语言编写的,只有芯片架构(x86_64 | aarch64)的区别。
Linux 软件包 x86_64 aarch64 EL rpm✓ ✓ Debian deb✓ ✓
PGSQL 仓库中的软件包通常特定于 Linux 大版本(例如 el9, d12),也通常与 PostgreSQL 大版本相关(例如 pg17,pg16 )。
这个仓库中包含了 PostgreSQL 内核分支、扩展插件与工具,通常由类 C 语言编写。
兼容性详情 OS 系统代码 厂商 大版本 小版本 全名 PG 大版本 备注 el7.x86_64EL 7 7.9 CentOS 7 x86 15 14 13 EOL el8.x86_64EL 8 8.10 RockyLinux 8 x86 18 17 16 15 14 13 即将 EOL el8.aarch64EL 8 8.10 RockyLinux 8 ARM 18 17 16 15 14 13 即将 EOL el9.x86_64EL 9 9.6 RockyLinux 9 x86 18 17 16 15 14 13 OK el9.aarch64EL 9 9.6 RockyLinux 9 ARM 18 17 16 15 14 13 OK el10.x86_64EL 10 10.0 RockyLinux 10 x86 18 17 16 15 14 13 OK el10.aarch64EL 10 10.0 RockyLinux 10 ARM 18 17 16 15 14 13 OK d11.x86_64Debian 11 11.11 Debian 11 x86 17 16 15 14 13 EOL d11.aarch64Debian 11 11.11 Debian 11 ARM 17 16 15 14 13 EOL d12.x86_64Debian 12 12.12 Debian 12 x86 18 17 16 15 14 13 OK d12.aarch64Debian 12 12.12 Debian 12 ARM 18 17 16 15 14 13 OK d13.x86_64Debian 13 13.1 Debian 13 x86 18 17 16 15 14 13 OK d13.aarch64Debian 13 13.1 Debian 13 ARM 18 17 16 15 14 13 OK u20.x86_64Ubuntu 20 20.04.6 Ubuntu 20.04 x86 17 16 15 14 13 EOL u20.aarch64Ubuntu 20 20.04.6 Ubuntu 20.04 ARM 17 16 15 14 13 EOL u22.x86_64Ubuntu 22 22.04.5 Ubuntu 22.04 x86 18 17 16 15 14 13 OK u22.aarch64Ubuntu 22 22.04.5 Ubuntu 22.04 ARM 18 17 16 15 14 13 OK u24.x86_64Ubuntu 24 24.04.3 Ubuntu 24.04 x86 18 17 16 15 14 13 OK u24.aarch64Ubuntu 24 24.04.3 Ubuntu 24.04 ARM 18 17 16 15 14 13 OK
源代码 用于构建仓库内软件的源代码文件位于以下仓库中:
22.1 - INFRA 仓库 可观测性/PostgreSQL 工具软件仓库,Linux 发行版大版本无关的软件包
pigsty-infra 仓库包含与任何 PostgreSQL 版本和 Linux 主版本无关的通用软件包,
包括 Prometheus & Grafana 技术栈、PostgreSQL 管理工具,以及许多用 Go 编写的实用工具。
该仓库由 冯若航 (Vonng ) @ Pigsty 维护,
您可以在 https://github.com/pgsty/infra-pkg 找到所有构建源代码与命令。
为 RHEL / Debian / Ubuntu 发行版提供预构建的 RPM / DEB 包,支持 x86_64 和 aarch64 架构。
托管于 Cloudflare CDN,提供免费的全球访问。
Linux 包类型 x86_64 aarch64 EL rpm✓ ✓ Debian deb✓ ✓
Infra 仓库的更新记录可以参考 发布 - Infra 变更日志 。
快速上手 您可以使用 pig CLI 工具添加 pigsty-infra 仓库,它会自动从 apt/yum/dnf 中选择合适的包管理器。
curl https://repo.pigsty.io/pig | bash # 下载并安装 pig CLI 工具
pig repo add infra # 将 pigsty-infra 仓库文件添加到您的系统
pig repo update # 使用 apt / dnf 更新本地仓库缓存
# 在中国大陆或 Cloudflare 不可用时使用
curl https://repo.pigsty.cc/pig | bash # 从中国 CDN 镜像安装 pig
pig repo add infra # 将 pigsty-infra 仓库文件添加到您的系统
pig repo update # 使用 apt / dnf 更新本地仓库缓存
# 您可以使用以下命令管理 infra 仓库:
pig repo add infra -u # 添加仓库文件,并更新缓存
pig repo add infra -ru # 删除所有现有仓库,添加仓库并创建缓存
pig repo set infra # = pigsty repo add infra -ru
pig repo add all # 将 infra、node、pgsql 仓库添加到您的系统
pig repo set all # 删除现有仓库,添加上述仓库并更新缓存
手动设置 您也可以不使用 pig CLI 工具直接使用此仓库,手动将其添加到您的 Linux 操作系统仓库列表中:
APT 仓库 在 Debian / Ubuntu 兼容的 Linux 发行版上,您可以手动添加 GPG 密钥 和 APT 仓库文件:
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名,或者直接信任
curl -fsSL https://repo.pigsty.io/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
# 获取 Debian 发行版代号(distro_codename=jammy, focal, bullseye, bookworm)
# 并将相应的上游仓库地址写入 APT List 文件
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty-infra.list > /dev/null <<EOF
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.io/apt/infra generic main
EOF
# 刷新 APT 仓库缓存
sudo apt update
# 在中国大陆或 Cloudflare 不可用时使用
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名,或者直接信任
curl -fsSL https://repo.pigsty.cc/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
# 获取 Debian 发行版代号(distro_codename=jammy, focal, bullseye, bookworm)
# 并将相应的上游仓库地址写入 APT List 文件
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty-infra.list > /dev/null <<EOF
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.cc/apt/infra generic main
EOF
# 刷新 APT 仓库缓存
sudo apt update
# 如果您不想信任任何 GPG 密钥,直接信任仓库
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty-infra.list > /dev/null <<EOF
deb [trust=yes] https://repo.pigsty.io/apt/infra generic main
EOF
sudo apt update
YUM 仓库 在 RHEL 兼容的 Linux 发行版上,您可以手动添加 GPG 密钥 和 YUM 仓库文件:
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名
curl -fsSL https://repo.pigsty.io/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
# 将 Pigsty 仓库定义文件添加到 /etc/yum.repos.d/ 目录
sudo tee /etc/yum.repos.d/pigsty-infra.repo > /dev/null <<-'EOF'
[pigsty-infra]
name=Pigsty Infra for $basearch
baseurl=https://repo.pigsty.io/yum/infra/$basearch
skip_if_unavailable = 1
enabled = 1
priority = 1
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty
module_hotfixes=1
EOF
# 刷新 YUM/DNF 仓库缓存
sudo yum makecache;
# 在中国大陆或 Cloudflare 不可用时使用
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名
curl -fsSL https://repo.pigsty.cc/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
# 将 Pigsty 仓库定义文件添加到 /etc/yum.repos.d/ 目录
sudo tee /etc/yum.repos.d/pigsty-infra.repo > /dev/null <<-'EOF'
[pigsty-infra]
name=Pigsty Infra for $basearch
baseurl=https://repo.pigsty.cc/yum/infra/$basearch
skip_if_unavailable = 1
enabled = 1
priority = 1
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty
module_hotfixes=1
EOF
# 刷新 YUM/DNF 仓库缓存
sudo yum makecache;
# 如果您不想信任任何 GPG 密钥,直接信任仓库
sudo tee /etc/yum.repos.d/pigsty-infra.repo > /dev/null <<-'EOF'
[pigsty-infra]
name=Pigsty Infra for $basearch
baseurl=https://repo.pigsty.io/yum/infra/$basearch
skip_if_unavailable = 1
enabled = 1
priority = 1
gpgcheck = 0
module_hotfixes=1
EOF
sudo yum makecache;
22.1.1 - 软件清单 Infra 仓库中可用的软件清单
Grafana 技术栈 Victoria 技术栈 自行安装使用 victoria grafana 数据源插件时注意
Pigsty 将 victoria 数据源扩展拆分为特定架构的专用分包,因此如果您选择自行安装这些插件到您自己的 grafana 中使用时,
请在 /etc/grafana/grafana.ini 中配置以下参数,以允许使用未签名的插件。
allow_loading_unsigned_plugins = victoriametrics-logs-datasource,victoriametrics-metrics-datasource
Prometheus 技术栈 指标导出器 对象存储 数据库 PostgreSQL 相关工具、数据库管理系统和其他实用程序
工具 Pig 包管理器、PostgreSQL 工具和其他数据库相关实用程序
22.1.2 - 发布日志 pigsty-infra 仓库变更日志和可观测性包发布说明
2025-12-25 名称 旧版本 新版本 备注 pig0.8.00.9.0例行更新 etcd3.6.63.6.7例行更新 uv- 0.9.18新增 PY 包管理器 ccm- 2.0.76新增 claude code asciinema- 3.0.1新增命令行录屏工具 ivorysql5.05.1grafana12.3.012.3.1vector0.51.10.52.0prometheus3.8.03.8.1alertmanager0.29.00.30.0victoria-logs1.41.01.43.1pgbackrest_exporter0.21.00.22.0grafana-victorialogs-ds0.22.40.23.2
2025-12-16 名称 旧版本 新版本 备注 victoria-metrics1.131.01.132.0victoria-logs1.40.01.41.0blackbox_exporter0.27.00.28.0duckdb1.4.21.4.3rclone1.72.01.72.1pev21.17.01.19.0pg_exporter1.0.31.1.0pig0.7.40.8.0genai-toolbox0.22.00.23.0minio2025090716130920251203120000by pgsty
2025-12-04 名称 旧版本 新版本 备注 rustfs- 1.0.0-a71新增 seaweedfs- 4.1.0新增 garage- 2.1.0新增 rclone1.71.21.72.0vector0.51.00.51.1prometheus3.7.33.8.0victoria-metrics0.130.00.131.0victoria-logs0.38.00.40.0victoria-traces- 0.5.1新增 grafana-victorialogs-ds0.22.10.22.4redis_exporter1.80.01.80.1mongodb_exporter0.47.10.47.2genai-toolbox0.21.00.22.0
2025-11-23 名称 旧版本 新版本 备注 pgschema- 1.4.2新增 pgflo- 0.0.15新增 vector0.51.00.51.1问题修复 sealos5.0.15.1.1etcd3.6.53.6.6duckdb1.4.11.4.2pg_exporter1.0.21.0.3pig0.7.10.7.2grafana12.1.012.3.0pg_timetable6.1.06.2.0genai-toolbox0.16.00.21.0timescaledb-tools0.18.00.18.1从 PGSQL 移入 INFRA 仓库 timescaledb-event-streamer0.12.00.20.0tigerbeetle0.16.600.16.65victoria-metrics1.129.11.130.0victoria-logs1.37.21.38.0grafana-victorialogs-ds0.21.40.22.1grafana-victoriametrics-ds0.19.60.19.7grafana-plugins12.0.012.3.0
2025-11-11 名称 旧版本 新版本 备注 grafana12.1.012.2.1下载地址发生变化 prometheus3.6.03.7.3pushgateway1.11.11.11.2alertmanager0.28.10.29.0nginx_exporter1.5.01.5.1node_exporter1.9.11.10.2pgbackrest_exporter0.20.00.21.0redis_exporter1.77.01.80.0duckdb1.4.01.4.1dblab0.33.00.34.2pg_timetable5.13.06.1.0vector0.50.00.51.0rclone1.71.11.71.2victoria-metrics1.126.01.129.1victoria-logs1.35.01.37.2grafana-victorialogs-ds0.21.00.21.4grafana-victoriametrics-ds0.19.40.19.6grafana-infinity-ds3.5.03.6.0genai-toolbox0.16.00.18.0pev21.16.01.17.0pig0.6.20.7.1
2025-10-18 名称 旧版本 新版本 备注 prometheus3.5.03.6.0nginx_exporter1.4.21.5.0mysqld_exporter0.17.20.18.0redis_exporter1.75.01.77.0mongodb_exporter0.47.00.47.1victoria-metrics1.121.01.126.0victoria-logs1.25.11.35.0duckdb1.3.21.4.0etcd3.6.43.6.5restic0.18.00.18.1tigerbeetle0.16.540.16.60grafana-victorialogs-ds0.19.30.21.0grafana-victoriametrics-ds0.18.30.19.4grafana-infinity-ds3.3.03.5.0genai-toolbox0.9.00.16.0grafana12.1.012.2.0vector0.49.00.50.0rclone1.70.31.71.1minio2025072315540220250907161309mcli2025072105280820250813083541
2025-08-15 名称 旧版本 新版本 备注 grafana12.0.012.1.0pg_exporter1.0.11.0.2pig0.6.00.6.1vector0.48.00.49.0redis_exporter1.74.01.75.0mongodb_exporter0.46.00.47.0victoria-metrics1.121.01.123.0victoria-logs1.25.01.28.0grafana-victoriametrics-ds0.17.00.18.3grafana-victorialogs-ds0.18.30.19.3grafana-infinity-ds3.3.03.4.1etcd3.6.13.6.4ferretdb2.3.12.5.0tigerbeetle0.16.500.16.54genai-toolbox0.9.00.12.0
2025-07-24 名称 旧版本 新版本 备注 ferretdb- 2.4.0与 documentdb 1.105 配合 etcd- 3.6.3minio- 20250723155402mcli- 20250721052808ivorysql- 4.5-0ffca11-20250709修复 libxcrypt 依赖问题
2025-07-16 名称 旧版本 新版本 备注 genai-toolbox0.8.00.9.0各种 DBMS 的 MCP 工具箱 victoria-metrics1.120.01.121.0拆分为各种包 victoria-logs1.24.01.25.0拆分为各种包 prometheus3.4.23.5.0duckdb1.3.11.3.2etcd3.6.13.6.2tigerbeetle0.16.480.16.50grafana-victoriametrics-ds0.16.00.17.0rclone1.69.31.70.3pig0.5.00.6.0pev21.15.01.16.0pg_exporter1.0.01.0.1
2025-07-04 名称 旧版本 新版本 备注 prometheus3.4.13.4.2- grafana12.0.112.0.2- vector0.47.00.48.0- rclone1.69.01.70.2- vip-manager3.0.04.0.0- blackbox_exporter0.26.00.27.0- redis_exporter1.72.11.74.0- duckdb1.3.01.3.1- etcd3.6.03.6.1- ferretdb2.2.02.3.1- dblab0.32.00.33.0- tigerbeetle0.16.410.16.48- grafana-victorialogs-ds0.16.30.18.1- grafana-victoriametrics-ds0.15.10.16.0- grafana-infinity-ds3.2.13.3.0- victoria-logs1.22.21.24.0- victoria-metrics1.117.11.120.0-
2025-06-01 名称 旧版本 新版本 备注 grafana- 12.0.1- prometheus- 3.4.1- keepalived_exporter- 1.7.0- redis_exporter- 1.73.0- victoria-metrics- 1.118.0- victoria-logs- 1.23.1- tigerbeetle- 0.16.42- grafana-victorialogs-ds- 0.17.0- grafana-infinity-ds- 3.2.2-
2025-05-22 名称 旧版本 新版本 备注 dblab- 0.32.0- prometheus- 3.4.0- duckdb- 1.3.0- etcd- 3.6.0- pg_exporter- 1.0.0- ferretdb- 2.2.0- rclone- 1.69.3- minio- 20250422221226最后一个带管理 GUI 的版本 mcli- 20250416181326- nginx_exporter- 1.4.2- keepalived_exporter- 1.6.2- pgbackrest_exporter- 0.20.0- redis_exporter- 1.27.1- victoria-metrics- 1.117.1- victoria-logs- 1.22.2- pg_timetable- 5.13.0- tigerbeetle- 0.16.41- pev2- 1.15.0- grafana- 12.0.0- grafana-victorialogs-ds- 0.16.3- grafana-victoriametrics-ds- 0.15.1- grafana-infinity-ds- 3.2.1- grafana-plugins- 12.0.0-
2025-04-23 名称 旧版本 新版本 备注 mtail- 3.0.8新 pig- 0.4.0- pg_exporter- 0.9.0- prometheus- 3.3.0- pushgateway- 1.11.1- keepalived_exporter- 1.6.0- redis_exporter- 1.70.0- victoria-metrics- 1.115.0- victoria-logs- 1.20.0- duckdb- 1.2.2- pg_timetable- 5.12.0- vector- 0.46.1- minio- 20250422221226- mcli- 20250416181326-
2025-04-05 名称 旧版本 新版本 备注 pig- 0.3.4- etcd- 3.5.21- restic- 0.18.0- ferretdb- 2.1.0- tigerbeetle- 0.16.34- pg_exporter- 0.8.1- node_exporter- 1.9.1- grafana- 11.6.0- zfs_exporter- 3.8.1- mongodb_exporter- 0.44.0- victoria-metrics- 1.114.0- minio- 20250403145628- mcli- 20250403170756-
2025-03-23 名称 旧版本 新版本 备注 etcd- 3.5.20- pgbackrest_exporter- 0.19.0重新构建 victoria-logs- 1.17.0- victoria-logs-cli- 1.17.0-
2025-03-17 名称 旧版本 新版本 备注 kafka- 4.0.0- prometheus- 3.2.1- alertmanager- 0.28.1- blackbox_exporter- 0.26.0- node_exporter- 1.9.0- mysqld_exporter- 0.17.2- kafka_exporter- 1.9.0- redis_exporter- 1.69.0- duckdb- 1.2.1- etcd- 3.5.19- ferretdb- 2.0.0- tigerbeetle- 0.16.31- vector- 0.45.0- victoria-metrics- 1.114.0- victoria-logs- 1.16.0- rclone- 1.69.1- pev2- 1.14.0- grafana-victorialogs-ds- 0.16.0- grafana-victoriametrics-ds- 0.14.0- grafana-infinity-ds- 3.0.0- timescaledb-event-streamer- 0.12.0新 restic- 0.17.3新 juicefs- 1.2.3新
2025-02-12 名称 旧版本 新版本 备注 pushgateway1.10.01.11.0- alertmanager0.27.00.28.0- nginx_exporter1.4.01.4.1- pgbackrest_exporter0.18.00.19.0- redis_exporter1.66.01.67.0- mongodb_exporter0.43.00.43.1- victoria-metrics1.107.01.111.0- victoria-logs1.3.21.9.1- duckdb1.1.31.2.0- etcd3.5.173.5.18- pg_timetable5.10.05.11.0- ferretdb1.24.02.0.0- tigerbeetle0.16.130.16.27- grafana11.4.011.5.1- vector0.43.10.44.0- minio2024121813154420250207232109- mcli2024112117215420250208191421- rclone1.68.21.69.0-
2024-11-19 名称 旧版本 新版本 备注 prometheus2.54.03.0.0- victoria-metrics1.102.11.106.1- victoria-logs0.28.01.0.0- mysqld_exporter0.15.10.16.0- redis_exporter1.62.01.66.0- mongodb_exporter0.41.20.42.0- keepalived_exporter1.3.31.4.0- duckdb1.1.21.1.3- etcd3.5.163.5.17- tigerbeetle16.80.16.13- grafana- 11.3.0- vector- 0.42.0-
22.2 - PGSQL 仓库 PostgreSQL 扩展和内核分支仓库
pigsty-pgsql 仓库包含特定于 PostgreSQL 主版本的软件包(通常也特定于特定的 Linux 发行版主版本),包括扩展和一些内核分支。
您可以参考 发布 - RPM 变更日志 / 发布 - DEB 变更日志 查阅最近的版本更新情况。
快速上手 PIG 您可以安装 pig CLI 工具,并使用它添加 pgdg / pigsty 仓库(推荐):
pig repo add pigsty # 添加 pigsty-pgsql 仓库
pig repo add pigsty -u # 添加 pigsty-pgsql 仓库,并更新本地缓存
pig repo add pigsty -u --region= default # 强制使用全球默认区域的仓库(pigsty.io)
pig repo add pigsty -u --region= china # 使用中国镜像仓库 (pigsty.cc)
pig repo add pgsql -u # pgsql = pgdg + pigsty-pgsql (同时添加 Pigsty 与 PGDG 官方仓库)
pig repo add -u # all = node + pgsql (pgdg + pigsty) + infra,一次性添加所有仓库
提示 :如果您在中国大陆区域,可以考虑使用中国 CDN 镜像(将 pigsty.io 替换为 pigsty.cc)
APT 您也可以直接在 Debian / Ubuntu 上使用 apt 启用此仓库:
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名
curl -fsSL https://repo.pigsty.io/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
# 获取 Debian 发行版代号(distro_codename=jammy, focal, bullseye, bookworm),并将相应的上游仓库地址写入 APT List 文件
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty-io.list > /dev/null <<EOF
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.io/apt/pgsql/${distro_codename} ${distro_codename} main
EOF
# 刷新 APT 仓库缓存
sudo apt update
# 在中国大陆或 Cloudflare 不可用时使用
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名
curl -fsSL https://repo.pigsty.cc/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
# 获取 Debian 发行版代号,并将相应的上游仓库地址写入 APT List 文件
distro_codename = $( lsb_release -cs)
sudo tee /etc/apt/sources.list.d/pigsty-io.list > /dev/null <<EOF
deb [signed-by=/etc/apt/keyrings/pigsty.gpg] https://repo.pigsty.cc/apt/pgsql/${distro_codename} ${distro_codename} main
EOF
# 刷新 APT 仓库缓存
sudo apt update
DNF 您也可以直接在兼容 EL 的系统上使用 dnf/yum 启用此仓库:
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名
curl -fsSL https://repo.pigsty.io/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
# 将 Pigsty 仓库定义文件添加到 /etc/yum.repos.d/ 目录,包括两个仓库
sudo tee /etc/yum.repos.d/pigsty-pgsql.repo > /dev/null <<-'EOF'
[pigsty-pgsql]
name=Pigsty PGSQL For el$releasever.$basearch
baseurl=https://repo.pigsty.io/yum/pgsql/el$releasever.$basearch
skip_if_unavailable = 1
enabled = 1
priority = 1
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty
module_hotfixes=1
EOF
# 刷新 YUM/DNF 仓库缓存
sudo yum makecache;
# 在中国大陆或 Cloudflare 不可用时使用
# 将 Pigsty 的 GPG 公钥添加到您的系统密钥链以验证包签名
curl -fsSL https://repo.pigsty.cc/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
# 将 Pigsty 仓库定义文件添加到 /etc/yum.repos.d/ 目录
sudo tee /etc/yum.repos.d/pigsty-pgsql.repo > /dev/null <<-'EOF'
[pigsty-pgsql]
name=Pigsty PGSQL For el$releasever.$basearch
baseurl=https://repo.pigsty.cc/yum/pgsql/el$releasever.$basearch
skip_if_unavailable = 1
enabled = 1
priority = 1
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty
module_hotfixes=1
EOF
# 刷新 YUM/DNF 仓库缓存
sudo yum makecache;
源代码 此仓库的构建脚本与源代码在 GitHub 上开源:
如果平台不受支持,您也可以自行从源代码构建软件包。
pig build 提供了简便的扩展构建基础设施,您可以方便地在自己的系统上制作 RPM/DEB 包。
兼容性 系统 / 架构 代码 x86_64 aarch64 EL8 el8 18 17 16 15 14 13 18 17 16 15 14 13 EL9 el9 18 17 16 15 14 13 18 17 16 15 14 13 EL10 el10 18 17 16 15 14 13 18 17 16 15 14 13 Debian 12 d12 18 17 16 15 14 13 18 17 16 15 14 13 Debian 13 d13 18 17 16 15 14 13 18 17 16 15 14 13 Ubuntu 22.04 u22 18 17 16 15 14 13 18 17 16 15 14 13 Ubuntu 24.04 u24 18 17 16 15 14 13 18 17 16 15 14 13
22.2.1 - DNF 变更日志 PostgreSQL 和扩展 RPM 包变更日志和发布说明
2025-12-25 名称 旧版本 新版本 备注 pg_duckdb1.1.01.1.1pg_search0.20.40.20.5vchord_bm250.2.20.3.0pg_semver0.40.00.41.0pg_timeseries0.1.70.1.8
2025-12-16 名称 旧版本 新版本 备注 pg_textsearch- 0.1.0新增扩展 pg_clickhouse- 0.1.0新增扩展 pg_ai_query- 0.1.1新增扩展 timescaledb2.23.12.24.0pg_search0.20.00.20.4pg_duckdb1.1.0-11.1.0-2官方发布的版本 pg_biscuit1.02.0.1切换至新仓库 pg_convert0.0.40.0.5移除 pg13 支持 pgdd0.6.00.6.1移除 pg13 支持 pglinter1.0.01.0.1pg_session_jwt0.3.30.4.0pg_anon2.4.12.5.1pg_enigma0.4.00.5.0wrappers0.5.60.5.7pg_vectorize0.25.00.26.0synchdb- 1.3仅 EL9 可用
2025-11-20 名称 旧版本 新版本 备注 vchord0.5.31.0.0pg_later0.3.10.4.0pgvectorscale0.8.00.9.0-pg13, +pg18 pglite_fusion0.0.50.0.6pgx_ulid0.2.10.2.2pg_search0.19.50.19.7恢复由 PIGSTY 构建 citus13.2.013.2.0使用官方 tag 构建 timescaledb2.23.02.23.1pg_profile4.104.11pglinter1.0.0new pg_typeid0.3.0对齐 pg18 支持 pg_enigma0.4.0vonng patched pgrx version pg_retry1.0.0新增,pg17-18 pg_biscuit1.0新增,pg16-18 pg_weighted_statistics1.0.0新增,pg13-18 pg_stat_monitor2.2.02.3.0修复 PGDG pg18 缺失问题 documentdb0.1060.107ferretdb 分支 polardb15.1515.15.5.0-38948055
2025-11-10 为几乎所有扩展添加 PostgreSQL 18 支持
名称 旧版本 新版本 备注 omni_csv- 0.1.1新增扩展 omni_datasets- 0.1.0新增扩展 omni_shmem- 0.1.0新增扩展 pg_csv- 1.0.1新增扩展 pg_dbms_errlog- 2.2新增扩展 pg_rrule- 0.2.0新增扩展 plxslt- 0.20140221新增扩展 anon2.3.02.4.1+pg18 collection1.0.01.1.0+pg18 credcheck3.04.2+pg18 emaj4.7.04.7.1+pg18 explain_ui0.0.10.0.2+pg18 firebird_fdw1.4.01.4.1+pg18 logerrors2.1.32.1.5+pg18 multicorn3.03.2+pg18 omni0.2.90.2.14+pg18 omni_email00.1.0+pg18 omni_httpc0.1.50.1.10+pg18 omni_httpd0.4.60.4.11+pg18 omni_id0.4.20.4.3+pg18 omni_kube0.1.10.4.2+pg18 omni_ledger0.1.20.1.3+pg18 omni_sql0.5.10.5.3+pg18 omni_sqlite0.1.20.2.2+pg18 omni_types0.3.40.3.6+pg18 omni_vfs0.2.10.2.2+pg18 omni_worker0.1.00.2.1+pg18 periods1.2.21.2.3+pg18 pg_bestmatch0.0.10.0.2+pg18 pg_cardano1.0.51.1.1+pg18 pg_checksums1.11.3+pg18 pg_duckdb0.3.11.1.0+pg18 pg_failover_slots1.1.01.2.0+pg18 pg_graphql1.5.111.5.12+pg18 pg_idkit0.3.10.4.0+pg18 pg_later0.3.00.3.1+pg18 pg_mooncake0.1.20.2.0+pg18 pg_net0.9.20.20.0+pg18 pg_parquet0.4.30.5.1+pg18 pg_render0.1.20.1.3+pg18 pg_session_jwt0.3.10.3.3+pg18 pg_smtp_client0.2.00.2.1+pg18 pg_sphere1.5.11.5.2+pg18 pg_statement_rollback1.41.5+pg18 pg_store_plans1.81.9+pg18 pg_tle1.5.11.5.2+pg18 pg_tokenizer0.1.00.1.1+pg18 pg_uuidv71.6.01.7.0+pg18 pgactive2.1.62.1.7+pg18 pglogical2.4.52.4.6+pg18 pglogical_origin2.4.52.4.6+pg18 pgmq1.5.11.7.0+pg18 pgsmcrypto0.1.00.1.1+pg18 pgx_ulid0.2.00.2.1+pg18 pldbgapi1.81.9+pg18 pljava1.6.81.6.10+pg18 plprql1.0.018.0.0+pg18 roaringbitmap0.5.40.5.5+pg18 semver0.32.10.40.0+pg18 supautils2.10.03.0.2+pg18 tds_fdw2.0.42.0.5+pg18 timescaledb2.22.02.23.0+pg18 timescaledb_toolkit1.21.01.22.0+pg18 timeseries0.1.60.1.7+pg18 pg_tzf0.2.20.2.3+pg18 vchord0.5.10.5.3+pg18 vchord_bm250.2.10.2.2+pg18 vectorize0.22.20.25.0+pg18 wrappers0.5.40.5.6+pg18 gzip1.0.11.0.0+pg18 hypopg1.4.11.4.2+pg18 mobilitydb1.2.01.3.0+pg18 mongo_fdw5.5.15.5.3+pg18 orafce4.14.44.14.6+pg18 pg_hint_plan1.7.11.8.0+pg18 pg_ivm1.111.13+pg18 pg_partman5.2.45.3.1+pg18 pg_search0.18.10.19.2+pg18 pg_show_plans2.1.62.1.7+pg18 pgpcre10.20190509+pg18 pgroonga4.0.04.0.4+pg18 pgroonga_database4.0.04.0.4+pg18 plpgsql_check2.8.22.8.3+pg18 uint1.202312061.20250815+pg18 uint1281.1.01.1.1+pg18 omni_*2025052520251108+pg18 acl1.0.4+pg18 aggs_for_arrays1.3.3+pg18 aggs_for_vecs1.4.0+pg18 arraymath1.1+pg18 asn1oid1.6+pg18 aws_s30.0.1+pg18 base361.0.0+pg18 base620.0.1+pg18 bzip1.0.0+pg18 chkpass1.0+pg18 convert0.0.4+pg18 count_distinct3.0.2+pg18 country0.0.3+pg18 cryptint1.0.0+pg18 currency0.0.3+pg18 data_historization1.1.0+pg18 db_migrator1.0.0+pg18 dbt20.61.7+pg18 ddl_historization0.0.7+pg18 ddsketch1.0.1+pg18 decoder_raw1.0+pg18 decoderbufs3.2.0+pg18 emailaddr0+pg18 envvar1.0.1+pg18 faker0.5.3+pg18 financial1.0.1+pg18 fio1.0+pg18 first_last_agg0.1.4+pg18 floatfile1.3.1+pg18 floatvec1.1.1+pg18 geoip0.3.0+pg18 hashlib1.1+pg18 hashtypes0.1.5+pg18 hll2.18+pg18 hunspell_*1.0+pg18 imgsmlr1.0+pg18 index_advisor0.2.0+pg18 kafka_fdw0.0.3+pg18 login_hook1.7+pg18 oracle_fdw2.8.0+pg18 pg_auth_mon3.0+pg18 pg_background1.3+pg18 pg_bigm1.2+pg18 pg_cron1.6.7+pg18 pg_profile4.10+pg18 pg_stat_kcache2.3.0+pg18 pgdd0.6.0+pg18 pgjwt0.2.0+pg18 pgnodemx1.7+pg18 pgsodium3.1.9+pg18 pgtap1.3.3+pg18 plprofiler4.2.5+pg18 plproxy2.11.0+pg18 plr8.4.8+pg18 plv83.2.4+pg18 pointcloud1.2.5+pg18 powa5.0.1+pg18 prefix1.2.10+pg18 q3c2.0.1+pg18 redis_fdw1.0+pg18 session_variable3.4+pg18 set_user4.1.0+pg18 system_stats3.2+pg18 temporal_tables1.2.2+pg18 topn2.7.0+pg18 unit7.10+pg18 zhparser2.3+pg18 zstd1.1.2+pg18
2025-09-04 名称 旧版本 新版本 备注 timescaledb2.21.12.22.0citus13.1.013.2.0documentdb0.105.00.106.0work with ferretdb 2.5 ddlx0.290.30+ pg18 icu_ext1.9.01.10.0+ pg18 asn1oid1.51.6+ pg18 uint1281.0.01.1.0+ pg18 toastinfo1.51.6+ pg18 vchord0.4.30.5.1pgrx 0.16.0 pg_idkit0.3.00.3.1pgrx 0.15.0 pg_search0.17.30.18.0pgrx 0.15.0 pg_parquet0.4.00.4.3pgrx 0.16.0 wrappers0.5.30.5.4pgrx 0.14.3 pg_rewrite- 2.0.0+ Debian/Ubuntu (PGDG) pg_tracing- 0.1.3-2+ pg 14/18 pg_curl2.42.4.5new version epoch pg_rewrite- 2.0.0Import from PGDG pg_tracing- 1.3.0+ pg14 / pg18 pgactive2.1.52.1.6+ pg18 pgsentinel1.11.21.2 pg_tle1.5.1-11.5.1-2+ pg18 redis_fdw+ pg18 pgextwlist1.171.19+ pg18 wal2json1.6+ pg18 pgvector0.8.1+ pg18
2025-07-24 名称 旧版本 新版本 备注 orioledbbeta11 1.4beta12 1.5与 oriolepg 17.11 配合 oriolepg17.917.11与 orioledb 1.5 beta12 配合 documentdb0.104.00.105.0与 ferretdb 2.4 配合 timescaledb2.20.02.21.1supautils2.9.22.10.0.so 位置变更plv83.2.33.2.4postgresql_anonymizer3.1.12.3.0(pgrx 0.14.3) wrappers0.5.00.5.3(pgrx 0.14.3) pgrx 版本变更 pgvectorscale0.7.10.8.0(pgrx 0.12.9) pg_search0.15.80.17.0修复 el icu 依赖问题,直接下载
2025-06-24 名称 旧版本 新版本 备注 citus13.0.313.1.0timescaledb2.20.02.21.0vchord0.3.00.4.3pgactive- 2.1.5需要 pgfeutils documentdb0.103.00.104.0添加 arm 支持
2025-05-26 2025-05-22 2025-05-07 2025-03-20 名称 旧版本 新版本 备注 timescaledb- 2.19.0citus- 13.0.2documentdb- 1.102pg_analytics- 0.3.7pg_search- 0.15.8emaj- 4.6.0pgsql_tweaks- 0.11.0pgvectorscale- 0.6.0pg_session_jwt- 0.2.0wrappers- 0.4.5pg_parquet- 0.3.1vchord- 0.2.2pg_tle1.2.01.5.0supautils2.5.02.6.0sslutils1.31.4pg_profile4.74.8pg_jsonschema0.3.20.3.3pg_incremental1.1.11.2.0ddl_historization0.70.0.7pg_sqlog3.1.71.6pg_random- - pg_stat_monitor2.1.02.1.1pg_profile4.74.8
2024-10-16 名称 旧版本 新版本 备注 pg_timeseries- 0.1.6pgmq- 1.4.4pg_protobuf- 16 17pg_uuidv7- 1.6pg_readonly- latestpgddl- 0.28pg_safeupdate- latestpg_stat_monitor- 2.1pg_profile- 4.7system_stats- 3.2pg_auth_mon- 3.0login_hook- 1.6logerrors- 2.1.3pg_orphaned- latestpgnodemx- 1.7sslutils- 1.4+pg16, +pg17)
22.2.2 - APT 变更日志 PostgreSQL 和扩展 DEB 包变更日志和发布说明
2025-12-25 名称 旧版本 新版本 备注 pg_duckdb1.1.01.1.1pg_search0.20.40.20.5vchord_bm250.2.20.3.0pg_semver0.40.00.41.0pg_timeseries0.1.70.1.8supautils3.0.2-13.0.2-2修复 pg18 pg_summarize0.0.1-10.0.1-2修复 pg18
2025-12-16 名称 旧版本 新版本 备注 pg_textsearch- 0.1.0新增 pg_clickhouse- 0.1.0新增 pg_ai_query- 0.1.1新增 timescaledb2.23.12.24.0pg_search0.20.00.20.4pg_duckdb1.1.0-11.1.0-2官方版本 pg_biscuit1.02.0.1新仓库 pg_convert0.0.40.0.5移除 pg13 支持 pgdd0.6.00.6.1移除 pg13 支持 pglinter1.0.01.0.1pg_session_jwt0.3.30.4.0pg_anon2.4.12.5.1pg_enigma0.4.00.5.0wrappers0.5.60.5.7pg_vectorize0.25.00.26.0修复 pg18 pg_tiktoken- - 修复 pg18 pg_tzf- - 修复 pg18 pglite_fusion- - 修复 pg18 pgsmcrypto- - 修复 pg18 pgx_ulid- - 修复 pg18 plprql- - 修复 pg18 synchdb- 1.3仅支持 Ubuntu 22/24
2025-11-20 名称 旧版本 新版本 备注 vchord0.5.31.0.0pg_later0.3.10.4.0pgvectorscale0.8.00.9.0-pg13, +pg18 pglite_fusion0.0.50.0.6pgx_ulid0.2.10.2.2pg_search0.19.50.19.7resume PIGSTY building citus13.2.013.2.0official tag timescaledb2.23.02.23.1pg_profile4.104.11pglinter1.0.0new pg_typeid0.3.0head with pg18 support pg_enigma0.4.0vonng patched pgrx version pg_retry1.0.0new, pg17-18 pg_biscuit1.0new, pg16-18 pg_weighted_statistics1.0.0new, pg13-18 documentdb0.1060.107ferretdb fork polardb15.1515.15.5.0-38948055
2025-11-10 为几乎所有扩展添加 PostgreSQL 18 支持
名称 旧版本 新版本 备注 omni_csv- 0.1.1new omni_datasets- 0.1.0new omni_shmem- 0.1.0new pg_csv- 1.0.1new pljs- 1.0.3new plxslt- 0.20140221new credcheck3.04.2+pg18 dbt20.45.00.61.7+pg18 h34.1.34.2.3+pg18 h3_postgis4.1.34.2.3+pg18 mongo_fdw1.15.5.3+pg18 multicorn3.03.2+pg18 orafce4.14.44.14.6+pg18 pg_hint_plan1.7.01.8.0+pg18 pg_search0.18.10.19.2+pg18 pg_show_plans2.1.62.1.7+pg18 pgactive2.1.62.1.7+pg18 pgpcre10.20190509+pg18 plpgsql_check2.8.22.8.3+pg18 roaringbitmap0.5.40.5.5+pg18 uint1.202312061.20250815+pg18 uint1281.1.01.1.1+pg18 anon2.3.02.4.1+pg18 collection1.0.01.1.0+pg18 emaj4.7.04.7.1+pg18 explain_ui0.0.10.0.2+pg18 firebird_fdw1.4.01.4.1+pg18 login_hook1.61.7+pg18 logerrors2.1.32.1.5+pg18 mobilitydb1.2.01.3.0+pg18 omni0.2.90.2.14+pg18 omni_httpc0.1.50.1.10+pg18 omni_httpd0.4.60.4.11+pg18 omni_kube0.1.10.4.2+pg18 omni_sql0.5.10.5.3+pg18 omni_sqlite0.1.20.2.2+pg18 omni_worker0.1.00.2.1+pg18 pg_cardano1.0.51.1.1+pg18 pg_checksums1.21.3+pg18 pg_cron1.6.51.6.7+pg18 pg_duckdb0.3.11.1.0+pg18 pg_failover_slots1.1.01.2.0+pg18 pg_graphql1.5.111.5.12+pg18 pg_idkit0.3.10.4.0+pg18 pg_mooncake0.1.20.2.0+pg18 pg_net0.9.20.20.0+pg18 pg_parquet0.4.30.5.1+pg18 pg_partman5.2.45.3.0+pg18 pg_session_jwt0.3.10.3.3+pg18 pg_sphere1.5.11.5.2+pg18 pg_stat_monitor2.2.02.3.0+pg18 pg_statement_rollback1.41.5+pg18 pg_store_plans1.81.9+pg18 pg_task1.0.02.1.12+pg18 pg_tle1.5.11.5.2+pg18 pg_uuidv71.6.01.7.0+pg18 pglogical2.4.52.4.6+pg18 pgmq1.5.11.7.0+pg18 pgroonga4.0.04.0.4+pg18 pgsql_tweaks0.11.31.0.2+pg18 pldbgapi1.81.9+pg18 plprql1.0.018.0.0+pg18 supautils2.10.03.0.2+pg18 timescaledb2.22.02.23.0+pg18 timescaledb_toolkit1.21.01.22.0+pg18 vchord0.5.10.5.3+pg18 vectorize0.22.20.25.0+pg18 wrappers0.5.40.5.6+pg18 acl1.0.4- +pg18 aggs_for_arrays1.3.3- +pg18 aggs_for_vecs1.4.0- +pg18 base361.0.0- +pg18 hashlib1.1- +pg18 hll2.18- +pg18 imgsmlr1.0- +pg18 index_advisor0.2.0- +pg18 kafka_fdw0.0.3- +pg18 pg_auth_mon3.0- +pg18 pg_background1.3- +pg18 pg_bigm1.2- +pg18 pg_profile4.10- +pg18 pg_stat_kcache2.3.0- +pg18 pgdd0.6.0- +pg18 pgjwt0.2.0- +pg18 pgmp1.0.5- +pg18 plprofiler4.2.5- +pg18 plv83.2.4- +pg18 redis_fdw1.0- +pg18 repmgr5.5.0- +pg18 system_stats3.2- +pg18 topn2.7.0- +pg18 zhparser2.3- +pg18
2025-09-06 名称 旧版本 新版本 备注 timescaledb2.21.12.22.0citus13.1.013.2.0documentdb0.105.00.106.0work with ferretdb 2.5 ddlx0.290.30+ pg18 uint1281.0.01.1.0+ pg18 vchord0.4.30.5.1pgrx 0.16.0 pg_idkit0.3.00.3.1pgrx 0.15.0 pg_search0.17.30.18.0pgrx 0.15.0 pg_parquet0.4.00.4.3pgrx 0.16.0 wrappers0.5.30.5.4pgrx 0.14.3 pg_rewrite- 2.0.0+ Debian/Ubuntu pg_tracing- 0.1.3-2+ pg 14/18 pg_curl2.42.4.5pg_ivm1.111.12+ pg18 pg_rewrite- 2.0.0new extension pg_tracing- 1.3.0+ pg14 / pg18 pgactive2.1.52.1.6+ pg18 pgsentinel1.11.21.2 pg_tle1.5.1-11.5.1-2+ pg18 redis_fdw+ pg18 emaj4.64.7table_version1.11.01.11.1
2025-07-24 名称 旧版本 新版本 备注 orioledbbeta11 1.4beta12 1.5与 oriolepg 17.11 配合 oriolepg17.917.11与 orioledb 1.5 beta12 配合 documentdb0.104.00.105.0与 ferretdb 2.4 配合 timescaledb2.20.02.21.1supautils2.9.22.10.0.so 位置变更plv83.2.33.2.4postgresql_anonymizer3.1.12.3.0 (pgrx 0.14.3)wrappers0.5.00.5.3 (pgrx 0.14.3)pgrx 版本变更 pgvectorscale0.7.10.8.0 (pgrx 0.12.9)pg_search0.15.80.17.0 (download)修复 el icu 依赖问题 pg_profile4.8.04.10.0
2025-07-04 名称 旧版本 新版本 备注 orioledb1.4 beta11重新构建 pgvectorscale0.7.10.7.1重新构建修复错误 pg_stat_monitor2.1.12.2.0pgsql_tweaks0.11.10.11.3pg_tle1.5.01.5.1pg_curl2.42.4.5
2025-06-24 名称 旧版本 新版本 备注 citus13.0.313.1.0timescaledb2.20.02.21.0vchord0.3.00.4.3pgactive- 2.1.5需要 pgfeutils documentdb0.103.00.104.0添加 arm 支持
2025-05-26 2025-05-22 2025-05-07 2025-03-20 名称 旧版本 新版本 备注 timescaledb- 2.19.0citus- 13.0.2documentdb- 1.102pg_analytics- 0.3.7pg_search- 0.15.8pg_ivm- 1.10emaj- 4.6.0pgsql_tweaks- 0.11.0pgvectorscale- 0.6.0pg_session_jwt- 0.2.0wrappers- 0.4.5pg_parquet- 0.3.1vchord- 0.2.2pg_tle1.2.01.5.0supautils2.5.02.6.0sslutils1.31.4pg_profile4.74.8pg_jsonschema0.3.20.3.3pg_incremental1.1.11.2.0ddl_historization0.70.0.7pg_sqlog3.1.71.6pg_random- - pg_stat_monitor2.1.02.1.1pg_profile4.74.8
2024-10-16 名称 旧版本 新版本 备注 pg_ivm- 1.9pg_timeseries- 0.1.6pgmq- 1.4.4pg_protobuf- 16 17pg_uuidv7- 1.6pg_readonly- latestpgddl- 0.28pg_safeupdate- latestpg_stat_monitor- 2.1pg_profile- 4.7system_stats- 3.2pg_auth_mon- 3.0login_hook- 1.6logerrors- 2.1.3pg_orphaned- latestpgnodemx- 1.7sslutils- 1.4 (+16,17)
22.3 - PGDG 仓库 PostgreSQL 官方 APT/YUM 仓库
Pigsty PGSQL 仓库旨在与 PostgreSQL PGDG 官方仓库 配合使用。
Pigsty 依赖 PGDG 仓库中原生的 PostgreSQL 内核软件包,在此基础上提供了额外的 340+ 扩展插件。
PGDG Pigsty 镜像仓库最后同步于:2025-12-29 12:00:00
快速上手 您可以安装 pig CLI 工具,并使用它添加 pgdg / pigsty 仓库(推荐):
pig repo add pgdg # 添加 PGDG 仓库
pig repo add pgdg -u # 添加 PGDG 仓库,并更新本地缓存
pig repo add pgdg -u --region= default # 强制使用全球默认区域的仓库(postgresql.org)
pig repo add pgdg -u --region= china # 使用中国镜像仓库 (repo.pigsty.cc)
pig repo add pgsql -u # pgsql = pgdg + pigsty-pgsql (同时添加 Pigsty 与 PGDG 官方仓库)
pig repo add -u # all = node + pgsql (pgdg + pigsty) + infra,一次性添加所有仓库
镜像 2025年5月中旬,PGDG 关闭了 rsync/ftp 同步渠道,导致全球几乎所有 PGDG 镜像站失去同步。根据观察,目前只有 YANDEX,XTOM,PIGSTY 提供定期同步。
Pigsty 在中国区域提供了 PGDG 镜像的子集,更新频率约为一周一更新。对于 EL 7-10,Debian 11-13,Ubuntu 20.04 - 24.04 提供 x86_64 与 arm64 架构的镜像仓库。覆盖范围为所有生命周期内的 PG 大版本(PG12 - 19alpha)。
2025-11 更新通知:阿里云/清华TUNA 恢复更新
目前阿里云/清华TUNA镜像站已经恢复 PGDG 仓库的同步。
仓库配置 EL YUM/DNF 仓库 - { name: pgdg13 ,description: 'PostgreSQL 13' ,module: pgsql ,releases: [7,8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/13/redhat/rhel-$releasever-$basearch' ,china: 'https://repo.pigsty.cc/yum/pgdg/13/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/13/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg14 ,description: 'PostgreSQL 14' ,module: pgsql ,releases: [7,8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/14/redhat/rhel-$releasever-$basearch' ,china: 'https://repo.pigsty.cc/yum/pgdg/14/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/14/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg15 ,description: 'PostgreSQL 15' ,module: pgsql ,releases: [7,8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/15/redhat/rhel-$releasever-$basearch' ,china: 'https://repo.pigsty.cc/yum/pgdg/15/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/15/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg16 ,description: 'PostgreSQL 16' ,module: pgsql ,releases: [ 8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/16/redhat/rhel-$releasever-$basearch' ,china: 'https://repo.pigsty.cc/yum/pgdg/16/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/16/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg17 ,description: 'PostgreSQL 17' ,module: pgsql ,releases: [ 8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/17/redhat/rhel-$releasever-$basearch' ,china: 'https://repo.pigsty.cc/yum/pgdg/17/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/17/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg18 ,description: 'PostgreSQL 18' ,module: pgsql ,releases: [ 8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/18/redhat/rhel-$releasever-$basearch' ,china: 'https://repo.pigsty.cc/yum/pgdg/18/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/18/redhat/rhel-$releasever-$basearch' }}
- { name: pgdg19-beta ,description: 'PostgreSQL 19 Beta' ,module: beta ,releases: [ 8,9,10] ,arch: [x86_64, aarch64] ,baseurl : { default: 'https://download.postgresql.org/pub/repos/yum/testing/19/redhat/rhel-$releasever-$basearch' ,china: 'https://repo.pigsty.cc/yum/pgdg/testing/19/redhat/rhel-$releasever-$basearch' ,europe : 'https://mirrors.xtom.de/postgresql/repos/yum/testing/19/redhat/rhel-$releasever-$basearch' }}
Debian / Ubuntu APT 仓库 - { name: pgdg ,description: 'PGDG' ,module: pgsql ,releases: [11,12,13, 22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://apt.postgresql.org/pub/repos/apt/ ${distro_codename}-pgdg main' ,china : 'https://repo.pigsty.cc/apt/pgdg/ ${distro_codename}-pgdg main' }}
- { name: pgdg-beta ,description: 'PGDG Beta' ,module: beta ,releases: [11,12,13, 22,24] ,arch: [x86_64, aarch64] ,baseurl : { default : 'http://apt.postgresql.org/pub/repos/apt/ ${distro_codename}-pgdg-testing main 19' ,china : 'https://repo.pigsty.cc/apt/pgdg/ ${distro_codename}-pgdg-testing main 19' }}
APT GPG 密钥 PGDG APT 仓库使用以下 GPG 密钥签名: B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 (ACCC4CF8)
MD5 校验和为 f54c5c1aa1329dc26e33b29762faaec4,详情参考 https://www.postgresql.org/download/linux/debian/
sudo curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc
. /etc/os-release
sudo sh -c "echo 'deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $VERSION_CODENAME -pgdg main' > /etc/apt/sources.list.d/pgdg.list"
sudo curl -fsSL https://repo.pigsty.cc/apt/pgdg/ACCC4CF8.key -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc
. /etc/os-release
sudo sh -c "echo 'deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://repo.pigsty.cc/apt/pgdg/ $VERSION_CODENAME -pgdg main' > /etc/apt/sources.list.d/pgdg.list"
YUM GPG 密钥 PGDG YUM 仓库使用 https://ftp.postgresql.org/pub/repos/yum/keys/ 中的一系列密钥进行签名。请自行按需选取使用。
兼容性 OS 系统代码 厂商 大版本 PG 大版本 备注 el7.x86_64 EL 7 18 17 16 15 14 13 EOL el8.x86_64 EL 8 18 17 16 15 14 13 即将 EOL el8.aarch64 EL 8 18 17 16 15 14 13 即将 EOL el9.x86_64 EL 9 18 17 16 15 14 13 OK el9.aarch64 EL 9 18 17 16 15 14 13 OK el10.x86_64 EL 10 18 17 16 15 14 13 OK el10.aarch64 EL 10 18 17 16 15 14 13 OK d11.x86_64 Debian 11 18 17 16 15 14 13 EOL d11.aarch64 Debian 11 18 17 16 15 14 13 EOL d12.x86_64 Debian 12 18 17 16 15 14 13 OK d12.aarch64 Debian 12 18 17 16 15 14 13 OK d13.x86_64 Debian 13 18 17 16 15 14 13 OK d13.aarch64 Debian 13 18 17 16 15 14 13 OK u20.x86_64 Ubuntu 20 18 17 16 15 14 13 EOL u20.aarch64 Ubuntu 20 18 17 16 15 14 13 EOL u22.x86_64 Ubuntu 22 18 17 16 15 14 13 OK u22.aarch64 Ubuntu 22 18 17 16 15 14 13 OK u24.x86_64 Ubuntu 24 18 17 16 15 14 13 OK u24.aarch64 Ubuntu 24 18 17 16 15 14 13 OK
22.4 - GPG 密钥 导入 Pigsty 仓库使用的 GPG 公钥以验证软件包签名完整性
你可以通过检查 GPG 签名来验证从 Pigsty 仓库下载的软件包的完整性,本文会介绍如何导入用于签名软件包的 GPG 密钥。
你也可以生成自己的 GPG 密钥,构建自己的仓库,并用它来签发你自己的软件包。
摘要 Pigsty 仓库中所有的 RPM / DEB 软件包都使用 GPG 密钥(指纹:B9BD8B20)进行签名,以确保软件包的完整性和来源的可信度。
完整摘要: 9592A7BC7A682E7333376E09E7935D8DB9BD8B20 Ruohang Feng (Pigsty) rh@vonng.com
pub rsa4096 2024-07-16 [SC]
9592A7BC7A682E7333376E09E7935D8DB9BD8B20
uid [ultimate] Ruohang Feng (Pigsty) <rh@vonng.com>
sub rsa4096 2024-07-16 [E]
你可以在这里找到 Pigsty 使用的 GPG 公钥:
默认地址:https://repo.pigsty.io/key 中国镜像:https://repo.pigsty.cc/key 导入 在 RHEL 兼容的 Linux 发行版上,你可以使用以下命令导入此密钥:
curl -fsSL https://repo.pigsty.io/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
curl -fsSL https://repo.pigsty.cc/key | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-pigsty >/dev/null
在 Debian / Ubuntu 兼容的 Linux 发行版上,你可以使用以下命令导入此密钥:
curl -fsSL https://repo.pigsty.io/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
curl -fsSL https://repo.pigsty.cc/key | sudo gpg --dearmor -o /etc/apt/keyrings/pigsty.gpg
公钥 Pigsty 仓库使用的 GPG 公钥内容如下:
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBGaV5PwBEACbErI+7yOrsXTT3mR83O6Fw9WyHJqozhyNPF3dA1gAtWpfWqd4
S9x6vBjVwUbIRn21jYgov0hDiaLABNQhRzifvVr0r1IjBW8lhA8zJGaO42Uz0aBW
YIkajOklsXgYMX+gSmy5WXzM31sDQVMnzptHh9dwW067hMM5pJKDslu2pLMwSb9K
QgIFcYsaR0taBkcDg4dNu1gncriD/GcdXIS0/V4R82DIYeIqj2S0lt0jDTACbUz3
C6esrTw2XerCeHKHb9c/V+KMhqvLJOOpy/aJWLrTGBoaH7xw6v0qg32OYiBxlUj9
VEzoQbDfbRkR+jlxiuYP3scUs/ziKrSh+0mshVbeuLRSNfuHLa7C4xTEnATcgD1J
MZeMaJXIcDt+DN+1aHVQjY5YNvr5wA3ykxW51uReZf7/odgqVW3+1rhW5pd8NQKQ
qoVUHOtIrC9KaiGfrczEtJTNUxcNZV9eBgcKHYDXB2hmR2pIf7WvydgXTs/qIsXg
SIzfKjisi795Dd5GrvdLYXVnu9YzylWlkJ5rjod1wnSxkI/CcCJaoPLnXZA9KV7A
cpMWWaUEXP/XBIwIU+vxDd1taBIaPIOv1KIdzvG7QqAQtf5Lphi5HfaGvBud/CVt
mvWhRPJMr1J0ER2xAgU2iZR7dN0vSF6zDqc0W09RAoC0nDS3tupDX2BrOwARAQAB
tCRSdW9oYW5nIEZlbmcgKFBpZ3N0eSkgPHJoQHZvbm5nLmNvbT6JAlEEEwEIADsW
IQSVkqe8emguczM3bgnnk12Nub2LIAUCZpXk/AIbAwULCQgHAgIiAgYVCgkICwIE
FgIDAQIeBwIXgAAKCRDnk12Nub2LIOMuEACBLVc09O4icFwc45R3KMvOMu14Egpn
UkpmBKhErjup0TIunzI0zZH6HG8LGuf6XEdH4ItCJeLg5349UE00BUHNmxk2coo2
u4Wtu28LPqmxb6sqpuRAaefedU6vqfs7YN6WWp52pVF1KdOHkIOcgAQ9z3ZHdosM
I/Y/UxO2t4pjdCAfJHOmGPrbgLcHSMpoLLxjuf3YIwS5NSfjNDd0Y8sKFUcMGLCF
5P0lv5feLLdZvh2Una34UmHKhZlXC5E3vlY9bf/LgsRzXRFQosD0RsCXbz3Tk+zF
+j/eP3WhUvJshqIDuY6eJYCzMjiA8sM5gety+htVJuD0mewp+qAhjxE0d4bIr4qO
BKQzBt9tT2ackCPdgW42VPS+IZymm1oMET0hgZfKiVpwsKO6qxeWn4RW2jJ0zkUJ
MsrrxOPFdZQAtuFcLwa5PUAHHs6XQT2vzxDpeE9lInQ14lshofU5ZKIeb9sbvb/w
P+xnDqvZ1pcotEIBvDK0S0jHbHHqtioIUdDFvdCBlBlYP1TQRNPlJ7TJDBBvhj8i
fmjQsYSV1u36aHOJVGYNHv+SyJpVd3nHCZn97ADM9qHnDm7xljyHXPzIx4FMmBGJ
UTiLH5yxa1xhWr42Iv3TykaQJVbpydmBuegFR8WbWitAvVqI3HvRG+FalLsjJruc
8YDAf7gHdj/937kCDQRmleT8ARAAmJxscC76NZzqFBiaeq2+aJxOt1HGPqKb4pbz
jLKRX9sFkeXuzhfZaNDljnr2yrnQ75rit9Aah/loEhbSHanNUDCNmvOeSEISr9yA
yfOnqlcVOtcwWQK57n6MvlCSM8Js3jdoSmCFHVtdFFwxejE5ok0dk1VFYDIg6DRk
ZBMuxGO7ZJW7TzCxhK4AL+NNYA2wX6b+IVMn6CA9kwNwCNrrnGHR1sblSxZp7lPo
+GsqzYY0LXGR2eEicgKd4lk38gaO8Q4d1mlpX95vgdhGKxR+CM26y9QU0qrO1hXP
Fw6lX9HfIUkVNrqAa1mzgneYXivnLvcj8gc7bFAdweX4MyBHsmiPm32WqjUJFAmw
kcKYaiyfDJ+1wusa/b+7RCnshWc8B9udYbXfvcpOGgphpUuvomKT8at3ToJfEWmR
BzToYYTsgAAX8diY/X53BHCE/+MhLccglEUYNZyBRkTwDLrS9QgNkhrADaTwxsv1
8PwnVKve/ZxwOU0QGf4ZOhA2YQOE5hkRDR5uY2OHsOS5vHsd9Y6kNNnO8EBy99d1
QiBJOW3AP0nr4Cj1/NhdigAujsYRKiCAuPT7dgqART58VU4bZ3PgonMlziLe7+ht
YYxV+wyP6LVqicDd0MLLvG7r/JOiWuABOUxsFFaRecehoPJjeAEQxnWJjedokXKL
HVOFaEkAEQEAAYkCNgQYAQgAIBYhBJWSp7x6aC5zMzduCeeTXY25vYsgBQJmleT8
AhsMAAoJEOeTXY25vYsgG8sP/3UdsWuiwTsf/x4BTW82K+Uk9YwZDnUNH+4dUMED
bKT1C6CbuSZ7Mnbi2rVsmGzOMs9MehIx6Ko8/iCR2OCeWi8Q+wM+iffAfWuT1GK6
7f/VIfoYBUWEa+kvDcPgEbd5Tu7ZdUO/jROVBSlXRSjzK9LpIj7GozBTJ8Vqy5x7
oqbWPPEYtGDVHime8o6f5/wfhNgL3mFnoq6srK7KhwACwfTXlNqAlGiXGa30Yj+b
Cj6IvmxoII49E67/ovMEmzDCb3RXiaL6OATy25P+HQJvWvAam7Qq5Xn+bZg65Mup
vXq3zoX0a7EKXc5vsJVNtTlXO1ATdYszKP5uNzkHrNAN52VRYaowq1vPy/MVMbSI
rL/hTFKr7ZNhmC7jmS3OuJyCYQsfEerubtBUuc/W6JDc2oTI3xOG1S2Zj8f4PxLl
H7vMG4E+p6eOrUGw6VQXjFsH9GtwhkPh/ZGMKENb2+JztJ02674Cok4s5c/lZFKz
mmRUcNjX2bm2K0GfGG5/hAog/CHCeUZvwIh4hZLkdeJ1QsIYpN8xbvY7QP6yh4VB
XrL18+2sontZ45MsGResrRibB35x7IrCrxZsVtRJZthHqshiORPatgy+AiWcAtEv
UWEnnC1xBSasNebw4fSE8AJg9JMCRw+3GAetlotOeW9q7PN6yrXD9rGuV/QquQNd
/c7w
=4rRi
-----END PGP PUBLIC KEY BLOCK-----
使用 如果你想要分发自己的仓库并使用自己的 GPG 密钥进行签名,以下是简单介绍:
安装 GPG 软件包 brew install gnupg pinentry-mac
sudo apt install gnupg2 pinentry-curses
sudo dnf install gnupg2 pinentry-curses
生成 GPG 密钥 你可以使用以下命令生成一个新的 GPG 密钥对:
导入 GPG 私钥 如果你有一个 GPG 私钥文件(例如 mykey.secret),你可以使用以下命令导入它:
gpg --import mykey.secret
列出 GPG 密钥 你可以列出已经导入的 GPG 公钥和私钥:
$ gpg --list-key
[ keyboxd]
---------
pub rsa4096 2024-07-16 [ SC]
9592A7BC7A682E7333376E09E7935D8DB9BD8B20
uid [ unknown] Ruohang Feng ( Pigsty) <rh@vonng.com>
sub rsa4096 2024-07-16 [ E]
$ gpg --list-secret-key
[ keyboxd]
---------
sec rsa4096 2024-07-16 [ SC]
9592A7BC7A682E7333376E09E7935D8DB9BD8B20
uid [ unknown] Ruohang Feng ( Pigsty) <rh@vonng.com>
ssb rsa4096 2024-07-16 [ E]
签名 RPM 包 如果你想要用 GPG 私钥签名你的 RPM 包,可以在 ~/.rpmmacros 文件中指定 GPG 密钥:
%_signature gpg
%_gpg_path ~/.gnupg
%_gpg_name B9BD8B20
%_gpg_digest_algo sha256
这里的 %_gpg_name 是你的 GPG 密钥的指纹,请将 Pigsty 密钥指纹 B9BD8B20 替换为你自己的密钥指纹。
rpm --addsign yourpackage.rpm
签名 DEB 包 如果你想要用 GPG 私钥签名你的 DEB 包,可以在 reprepro 配置文件中指定 GPG 密钥:
Origin : Pigsty
Label : Pigsty INFRA
Codename : generic
Architectures : amd64 arm64
Components : main
Description : pigsty apt repository for infra components
SignWith : 9592A7BC7A682E7333376E09E7935D8DB9BD8B20
同理,将这里的 SignWith 替换为你自己的 GPG 密钥指纹即可,reprepro 会自动使用它进行签名。
23 - PG Exporter 高级 PostgreSQL 与 PgBouncer 监控指标导出器
为 Prometheus / Victoria 打造的极致 PostgreSQL 监控体验:超过 600+ 监控指标、声明式配置 与 动态规划 能力。
快速上手 | GitHub | 在线演示
功能特性 特性 描述 全指标覆盖 监控 PostgreSQL(10-18+)与 pgBouncer(1.8-1.24+),全指标覆盖 声明式配置 通过 YAML 配置文件定义自定义指标,精细控制超时、缓存和跳过条件 采集器定制 使用声明式 YAML 配置定义自己的指标,支持动态查询规划 自动发现 自动发现并监控 PostgreSQL 实例中的多个数据库 动态规划 根据 PostgreSQL 版本、扩展和服务器特性自动调整指标采集策略 生产就绪 在真实环境中经过 6 年以上、12K+ 核心的实战检验,具备企业级可靠性 健康检查 提供全面的 HTTP 端点用于服务健康检查和流量路由,支持主从检测 智能缓存 内置缓存机制,可配置 TTL,减少数据库负载并提升性能 扩展感知 原生支持 pg_stat_statements、pg_wait_sampling, citus, timesacledb
快速安装 PG Exporter 提供多种 安装方式 ,适配各种基础设施:
docker run -d --name pg_exporter -p 9630:9630 -e PG_EXPORTER_URL = "postgres://user:pass@host:5432/postgres" pgsty/pg_exporter:latest # 基于 RPM 的系统
sudo tee /etc/yum.repos.d/pigsty-infra.repo > /dev/null <<-'EOF'
[pigsty-infra]
name=Pigsty Infra for $basearch
baseurl=https://repo.pigsty.io/yum/infra/$basearch
enabled = 1
gpgcheck = 0
module_hotfixes=1
EOF
sudo yum makecache;
sudo yum install -y pg_exporter sudo tee /etc/apt/sources.list.d/pigsty-infra.list > /dev/null <<EOF
deb [trusted=yes] https://repo.pigsty.io/apt/infra generic main
EOF
sudo apt update;
sudo apt install -y pg-exporter wget https://github.com/pgsty/pg_exporter/releases/download/v1.1.0/pg_exporter-v1.1.0.linux-amd64.tar.gz
tar -xf pg_exporter-v1.1.0.linux-amd64.tar.gz
sudo install pg_exporter-v1.1.0.linux-amd64/pg_exporter /usr/bin/
sudo install pg_exporter-v1.1.0.linux-amd64/pg_exporter.yml /etc/pg_exporter.yml # 从源码构建
git clone https://github.com/pgsty/pg_exporter.git
cd pg_exporter
make build 快速开始 几分钟内即可启动 PG Exporter,参见 快速上手 :
# 使用 PostgreSQL 连接 URL 运行
PG_EXPORTER_URL = 'postgres://user:pass@localhost:5432/postgres' pg_exporter
# 访问指标
curl http://localhost:9630/metrics
文档目录 在线演示 通过在线演示环境体验 PG Exporter 的实际效果:https://g.pgsty.com
演示展示了由 PG Exporter 监控的真实 PostgreSQL 集群,包含:
使用 Grafana 的实时指标可视化 多个 PostgreSQL 版本和配置 扩展特定的指标和监控 由 Pigsty 驱动的完整可观测性堆栈 社区与支持 开源协议 PG Exporter 是基于 Apache License 2.0 许可的开源软件。
Copyright 2018-2025 © 冯若航 / rh@vonng.com
23.1 - 快速上手 几分钟内启动并运行 PG Exporter
PG Exporter 是一款先进的 PostgreSQL 与 pgBouncer 指标导出器,专为 Prometheus 设计。本指南将帮助您快速启动并运行。
前置条件 在开始之前,请确保您具备:
PostgreSQL 10+ 或 pgBouncer 1.8+ 实例用于监控 具有适当监控权限的用户账户 Prometheus 兼容系统(用于指标抓取) 对 PostgreSQL 连接字符串的基本了解 快速开始 最快速地启动 PG Exporter:
# 下载并安装最新版本
curl -L https://github.com/pgsty/pg_exporter/releases/latest/download/pg_exporter-$( uname -s) -$( uname -m) .tar.gz | tar xz
sudo install pg_exporter /usr/bin/
# 使用 PostgreSQL 连接 URL 运行
PG_EXPORTER_URL = 'postgres://user:pass@localhost:5432/postgres' pg_exporter
# 验证指标是否可用
curl http://localhost:9630/metrics
基本概念 连接字符串 PG Exporter 使用标准的 PostgreSQL 连接 URL:
postgres://[user][:password]@[host][:port]/[database][?param=value]
示例:
本地 PostgreSQL:postgres:///postgres 带认证的远程连接:postgres://monitor:password@db.example.com:5432/postgres 使用 SSL:postgres://user:pass@host/db?sslmode=require pgBouncer:postgres://pgbouncer:password@localhost:6432/pgbouncer 内置指标 PG Exporter 开箱即用提供 4 个核心内置指标:
指标 类型 描述 pg_upGauge 如果导出器能够连接到 PostgreSQL 则为 1,否则为 0 pg_versionGauge PostgreSQL 服务器版本号 pg_in_recoveryGauge 如果服务器处于恢复模式(从库)则为 1,主库则为 0 pg_exporter_build_infoGauge 导出器版本和构建信息
配置文件 所有其他指标(600+)都在 pg_exporter.yml 配置文件中定义。默认情况下,PG Exporter 会按以下顺序查找此文件:
通过 --config 标志指定的路径 PG_EXPORTER_CONFIG 环境变量中的路径当前目录(./pg_exporter.yml) 系统配置(/etc/pg_exporter.yml 或 /etc/pg_exporter/) 首次监控设置 步骤 1:创建监控用户 创建一个专用的 PostgreSQL 用户用于监控:
-- 创建监控用户
CREATE USER pg_monitor WITH PASSWORD 'secure_password' ;
-- 授予必要权限
GRANT pg_monitor TO pg_monitor ;
GRANT CONNECT ON DATABASE postgres TO pg_monitor ;
-- 对于 PostgreSQL 10+,pg_monitor 角色提供对监控视图的读取权限
-- 对于更早版本,您可能需要额外的授权
步骤 2:测试连接 验证导出器能够连接到您的数据库:
# 设置连接 URL
export PG_EXPORTER_URL = 'postgres://pg_monitor:secure_password@localhost:5432/postgres'
# 以干运行模式运行以测试配置
pg_exporter --dry-run
步骤 3:运行导出器 启动 PG Exporter:
# 使用默认设置运行
pg_exporter
# 或使用自定义标志
pg_exporter \
--url= 'postgres://pg_monitor:secure_password@localhost:5432/postgres' \
--web.listen-address= ':9630' \
--log.level= info
步骤 4:配置 Prometheus 在您的 prometheus.yml 中将 PG Exporter 添加为目标:
scrape_configs :
- job_name : 'postgresql'
static_configs :
- targets : [ 'localhost:9630' ]
labels :
instance : 'postgres-primary'
步骤 5:验证指标 检查指标是否正在被采集:
# 查看原始指标
curl http://localhost:9630/metrics | grep pg_
# 检查导出器统计信息
curl http://localhost:9630/stat
# 验证服务器检测
curl http://localhost:9630/explain
自动发现模式 PG Exporter 可以自动发现并监控 PostgreSQL 实例中的所有数据库:
# 启用自动发现(默认行为)
pg_exporter --auto-discovery
# 排除特定数据库
pg_exporter --auto-discovery \
--exclude-database= "template0,template1,postgres"
# 仅包含特定数据库
pg_exporter --auto-discovery \
--include-database= "app_db,analytics_db"
当启用自动发现时:
集群级指标(1xx-5xx)每个实例采集一次 数据库级指标(6xx-8xx)为每个发现的数据库采集 指标使用 datname 标签来区分不同的数据库 监控 pgBouncer 要监控 pgBouncer 而不是 PostgreSQL:
# 连接到 pgBouncer 管理数据库
PG_EXPORTER_URL = 'postgres://pgbouncer:password@localhost:6432/pgbouncer' \
pg_exporter --config= /etc/pg_exporter.yml
导出器会自动检测 pgBouncer 并:
使用 pgbouncer 命名空间作为指标前缀 执行 pgBouncer 专用采集器(9xx 系列) 提供 pgBouncer 专用的健康检查 使用 Docker 在容器中运行 PG Exporter:
docker run -d \
--name pg_exporter \
-p 9630:9630 \
-e PG_EXPORTER_URL = "postgres://user:pass@host.docker.internal:5432/postgres" \
pgsty/pg_exporter:latest
使用自定义配置:
docker run -d \
--name pg_exporter \
-p 9630:9630 \
-v /path/to/pg_exporter.yml:/etc/pg_exporter.yml \
-e PG_EXPORTER_URL = "postgres://user:pass@db:5432/postgres" \
pgsty/pg_exporter:latest
健康检查 PG Exporter 为负载均衡器和编排器提供健康检查端点:
# 基本健康检查
curl http://localhost:9630/up
# 返回:连接正常返回 200,否则返回 503
# 主库检测
curl http://localhost:9630/primary
# 返回:主库返回 200,从库返回 404,未知返回 503
# 从库检测
curl http://localhost:9630/replica
# 返回:从库返回 200,主库返回 404,未知返回 503
故障排查 连接问题 # 使用详细日志测试
pg_exporter --log.level= debug --dry-run
# 检查服务器规划
pg_exporter --explain
权限错误 确保监控用户具有必要的权限:
-- 检查当前权限
SELECT * FROM pg_roles WHERE rolname = 'pg_monitor' ;
-- 如需要,授予额外权限
GRANT USAGE ON SCHEMA pg_catalog TO pg_monitor ;
GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO pg_monitor ;
抓取缓慢 如果抓取超时:
检查慢查询:curl http://localhost:9630/stat 在配置中调整采集器超时 对昂贵的查询使用缓存(在采集器配置中设置 ttl) 如果不需要,禁用昂贵的采集器 下一步 23.2 - 安装指南 如何下载和安装 PG Exporter
PG Exporter 提供多种安装方式以适应不同的部署场景。本指南涵盖了各平台的所有可用安装选项及详细说明。
Pigsty 最简单的使用 pg_exporter 的方式是使用 Pigsty ,这是一个完整的 PostgreSQL 发行版,内置了基于 pg_exporter、Prometheus 和 Grafana 的可观测性最佳实践。您甚至不需要了解 pg_exporter 的任何细节,它会直接为您提供所有指标和仪表盘面板。
curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty;
发布版本 您也可以直接从 GitHub 发布页面 下载 pg_exporter 软件包(RPM/DEB/Tarball):
v1.1.0 发布文件:
您可以直接使用操作系统的包管理器(rpm/dpkg)安装,或者将二进制文件放入 $PATH 中。
软件仓库 pg_exporter 软件包也可以在 pigsty-infra 仓库中获取。您可以将该仓库添加到系统中,然后使用操作系统包管理器安装:
YUM 适用于 RHEL、RockyLinux、CentOS、Alma Linux、OracleLinux 等 EL 系发行版:
sudo tee /etc/yum.repos.d/pigsty-infra.repo > /dev/null <<-'EOF'
[pigsty-infra]
name=Pigsty Infra for $basearch
baseurl=https://repo.pigsty.io/yum/infra/$basearch
enabled = 1
gpgcheck = 0
module_hotfixes=1
EOF
sudo yum makecache;
sudo yum install -y pg_exporter
APT 适用于 Debian、Ubuntu 及兼容的 Linux 发行版:
sudo tee /etc/apt/sources.list.d/pigsty-infra.list > /dev/null <<EOF
deb [trusted=yes] https://repo.pigsty.io/apt/infra generic main
EOF
sudo apt update;
sudo apt install -y pg-exporter
Docker 我们在 Docker Hub 上提供了 amd64 和 arm64 架构的预构建镜像:pgsty/pg_exporter 。
# 基本用法
docker run -d \
--name pg_exporter \
-p 9630:9630 \
-e PG_EXPORTER_URL = "postgres://user:password@host:5432/postgres" \
pgsty/pg_exporter:latest
# 使用自定义配置
docker run -d \
--name pg_exporter \
-p 9630:9630 \
-v /path/to/pg_exporter.yml:/etc/pg_exporter.yml:ro \
-e PG_EXPORTER_CONFIG = "/etc/pg_exporter.yml" \
-e PG_EXPORTER_URL = "postgres://user:password@host:5432/postgres" \
pgsty/pg_exporter:latest
# 启用自动发现
docker run -d \
--name pg_exporter \
-p 9630:9630 \
-e PG_EXPORTER_URL = "postgres://user:password@host:5432/postgres" \
-e PG_EXPORTER_AUTO_DISCOVERY = "true" \
-e PG_EXPORTER_EXCLUDE_DATABASE = "template0,template1" \
pgsty/pg_exporter:latest
二进制安装 pg_exporter 可以作为独立的二进制文件安装。从发布页面下载适合您平台的 tarball,解压后将二进制文件放入 $PATH 即可使用。
兼容性 当前 pg_exporter 支持 PostgreSQL 10 及以上版本,但设计上可以兼容任何 PostgreSQL 主版本(向下兼容到 9.x)。
使用旧版本(9.6 及以下)的唯一问题是,由于这些版本已停止维护,我们移除了对应的旧版指标采集器分支定义。
您可以随时获取这些旧版配置文件,用于监控历史版本的 PostgreSQL。
PostgreSQL 版本 支持状态 10 ~ 18 ✅ 完全支持 9.6 及更早 ⚠️ 需要旧版配置
pg_exporter 支持 pgBouncer 1.8+,因为 v1.8 是第一个支持 SHOW 命令的版本。
pgBouncer 版本 支持状态 1.8.x ~ 1.25.x ✅ 完全支持 1.8.x 之前 ⚠️ 无指标
23.3 - 配置参考 PG Exporter 的配置选项与采集器定义
PG Exporter 使用强大而灵活的配置系统,允许您定义自定义指标、控制采集行为并优化性能。本指南涵盖了从基础设置到高级自定义的所有配置方面。
指标采集器 PG Exporter 使用声明式的 YAML 配置系统,为指标采集提供极大的灵活性和控制能力。本指南涵盖了为您的特定监控需求配置 PG Exporter 的所有方面。
配置概述 PG Exporter 的配置以 采集器 为核心 —— 每个采集器是一个独立的指标查询及其关联元数据。配置可以是:
单一的 YAML 文件(pg_exporter.yml) 包含多个 YAML 文件的目录(按字母顺序合并) 通过命令行或环境变量指定的自定义路径 配置加载 PG Exporter 按以下顺序搜索配置:
命令行参数:--config=/path/to/config 环境变量:PG_EXPORTER_CONFIG=/path/to/config 当前目录:./pg_exporter.yml 系统配置文件:/etc/pg_exporter.yml 系统配置目录:/etc/pg_exporter/ 采集器结构 每个采集器是 YAML 配置中的一个顶级对象,具有唯一名称和多种属性:
collector_branch_name : # 此采集器的唯一标识符
name : metric_namespace # 指标前缀(默认为分支名称)
desc : "采集器描述" # 人类可读的描述
query : | # 要执行的 SQL 查询
SELECT column1, column2
FROM table
# 执行控制
ttl : 10 # 缓存生存时间(秒)
timeout : 0.1 # 查询超时(秒)
fatal : false # 如果为 true,失败将导致整个抓取失败
skip : false # 如果为 true,禁用此采集器
# 版本兼容性
min_version : 100000 # 最小 PostgreSQL 版本(包含)
max_version : 999999 # 最大 PostgreSQL 版本(不包含)
# 执行标签
tags : [ cluster, primary] # 执行条件
# 谓词查询(可选)
predicate_queries :
- name : "check_function"
predicate_query : |
SELECT EXISTS (...)
# 指标定义
metrics :
- column_name :
usage : GAUGE # GAUGE、COUNTER、LABEL 或 DISCARD
rename : metric_name # 可选:重命名指标
description : "帮助文本" # 指标描述
default : 0 # NULL 时的默认值
scale : 1000 # 值的缩放因子
核心配置元素 采集器分支名称 顶级键在整个配置中唯一标识一个采集器:
pg_stat_database : # 必须唯一
name : pg_db # 实际的指标命名空间
查询定义 检索指标的 SQL 查询:
query : |
SELECT
datname,
numbackends,
xact_commit,
xact_rollback,
blks_read,
blks_hit
FROM pg_stat_database
WHERE datname NOT IN ('template0', 'template1')
指标类型 查询结果中的每一列必须映射到一个指标类型:
用途 描述 示例 GAUGE可上下波动的瞬时值 当前连接数 COUNTER只增不减的累计值 总事务数 LABEL用作 Prometheus 标签 数据库名称 DISCARD忽略此列 内部值
缓存控制(TTL) ttl 参数控制结果缓存:
# 快速查询 - 最小缓存
pg_stat_activity :
ttl : 1 # 缓存 1 秒
# 昂贵查询 - 较长缓存
pg_table_bloat :
ttl : 3600 # 缓存 1 小时
最佳实践:
将 TTL 设置为小于您的抓取间隔 对昂贵的查询使用较长的 TTL TTL 为 0 表示禁用缓存 超时控制 防止查询运行时间过长:
timeout : 0.1 # 默认 100ms
timeout : 1.0 # 复杂查询使用 1 秒
timeout : -1 # 禁用超时(不推荐)
版本兼容性 控制哪些 PostgreSQL 版本可以运行此采集器:
min_version : 100000 # PostgreSQL 10.0+
max_version : 140000 # 低于 PostgreSQL 14.0
版本格式:MMMMMMPP00,其中:
MMMMMM = 主版本(6 位数字)PP = 次版本(2 位数字)示例:100000 = 10.0,130200 = 13.2,160100 = 16.1 标签系统 标签控制采集器的执行时机和位置:
内置标签 标签 描述 cluster每个 PostgreSQL 集群执行一次 primary / master仅在主服务器上执行 standby / replica仅在从服务器上执行 pgbouncer仅用于 pgBouncer 连接
前缀标签 前缀 示例 描述 dbname:dbname:postgres仅在特定数据库上执行 username:username:monitor仅使用特定用户时执行 extension:extension:pg_stat_statements仅当扩展已安装时执行 schema:schema:public仅当模式存在时执行 not:not:slow当导出器没有该标签时执行
自定义标签 向导出器传递自定义标签:
pg_exporter --tag= "production,critical"
然后在配置中使用:
expensive_metrics :
tags : [ critical] # 仅在有 'critical' 标签时运行
谓词查询 在执行主查询之前进行条件检查:
predicate_queries :
- name : "检查 pg_stat_statements"
predicate_query : |
SELECT EXISTS (
SELECT 1 FROM pg_extension
WHERE extname = 'pg_stat_statements'
)
只有当所有谓词返回 true 时,主查询才会执行。
指标定义 基本定义 metrics :
- numbackends :
usage : GAUGE
description : "已连接的后端进程数"
高级选项 metrics :
- checkpoint_write_time :
usage : COUNTER
rename : write_time # 重命名指标
scale : 0.001 # 将毫秒转换为秒
default : 0 # NULL 时使用 0
description : "检查点写入时间(秒)"
采集器组织 PG Exporter 自带预先组织好的采集器:
范围 类别 描述 0xx 文档 示例和文档 1xx 基础 服务器信息、设置、元数据 2xx 复制 复制、槽位、接收器 3xx 持久化 I/O、检查点、WAL 4xx 活动 连接、锁、查询 5xx 进度 Vacuum、索引创建进度 6xx 数据库 每数据库统计 7xx 对象 表、索引、函数 8xx 可选 昂贵/可选指标 9xx pgBouncer 连接池指标 10xx+ 扩展 扩展特定指标
实际示例 简单的 Gauge 采集器 pg_connections :
desc : "当前数据库连接"
query : |
SELECT
count(*) as total,
count(*) FILTER (WHERE state = 'active') as active,
count(*) FILTER (WHERE state = 'idle') as idle,
count(*) FILTER (WHERE state = 'idle in transaction') as idle_in_transaction
FROM pg_stat_activity
WHERE pid != pg_backend_pid()
ttl : 1
metrics :
- total : {usage: GAUGE, description : "总连接数" }
- active : {usage: GAUGE, description : "活跃连接数" }
- idle : {usage: GAUGE, description : "空闲连接数" }
- idle_in_transaction : {usage: GAUGE, description : "事务中空闲连接数" }
带标签的 Counter pg_table_stats :
desc : "表统计信息"
query : |
SELECT
schemaname,
tablename,
n_tup_ins,
n_tup_upd,
n_tup_del,
n_live_tup,
n_dead_tup
FROM pg_stat_user_tables
ttl : 10
metrics :
- schemaname : {usage : LABEL}
- tablename : {usage : LABEL}
- n_tup_ins : {usage: COUNTER, description : "插入的元组数" }
- n_tup_upd : {usage: COUNTER, description : "更新的元组数" }
- n_tup_del : {usage: COUNTER, description : "删除的元组数" }
- n_live_tup : {usage: GAUGE, description : "活跃元组数" }
- n_dead_tup : {usage: GAUGE, description : "死亡元组数" }
版本特定采集器 pg_wal_stats :
desc : "WAL 统计信息(PG 14+)"
min_version : 140000
query : |
SELECT
wal_records,
wal_bytes,
wal_buffers_full,
wal_write_time,
wal_sync_time
FROM pg_stat_wal
ttl : 10
tags : [ cluster]
metrics :
- wal_records : {usage : COUNTER}
- wal_bytes : {usage : COUNTER}
- wal_buffers_full : {usage : COUNTER}
- wal_write_time : {usage: COUNTER, scale : 0.001 }
- wal_sync_time : {usage: COUNTER, scale : 0.001 }
扩展依赖采集器 pg_stat_statements_metrics :
desc : "查询性能统计"
tags : [ extension:pg_stat_statements]
query : |
SELECT
sum(calls) as total_calls,
sum(total_exec_time) as total_time,
sum(mean_exec_time * calls) / sum(calls) as mean_time
FROM pg_stat_statements
ttl : 60
metrics :
- total_calls : {usage : COUNTER}
- total_time : {usage: COUNTER, scale : 0.001 }
- mean_time : {usage: GAUGE, scale : 0.001 }
自定义采集器 创建自己的指标 在配置目录中创建新的 YAML 文件: # /etc/pg_exporter/custom_metrics.yml
app_metrics :
desc : "应用特定指标"
query : |
SELECT
(SELECT count(*) FROM users WHERE active = true) as active_users,
(SELECT count(*) FROM orders WHERE created_at > NOW() - '1 hour'::interval) as recent_orders,
(SELECT avg(processing_time) FROM jobs WHERE completed_at > NOW() - '5 minutes'::interval) as avg_job_time
ttl : 30
metrics :
- active_users : {usage: GAUGE, description : "当前活跃用户数" }
- recent_orders : {usage: GAUGE, description : "最近一小时的订单数" }
- avg_job_time : {usage: GAUGE, description : "平均作业处理时间" }
测试您的采集器: pg_exporter --explain --config= /etc/pg_exporter/
条件指标 使用谓词查询实现条件指标:
partition_metrics :
desc : "分区表指标"
predicate_queries :
- name : "检查是否使用了分区"
predicate_query : |
SELECT EXISTS (
SELECT 1 FROM pg_class
WHERE relkind = 'p' LIMIT 1
)
query : |
SELECT
parent.relname as parent_table,
count(*) as partition_count,
sum(pg_relation_size(child.oid)) as total_size
FROM pg_inherits
JOIN pg_class parent ON parent.oid = pg_inherits.inhparent
JOIN pg_class child ON child.oid = pg_inherits.inhrelid
WHERE parent.relkind = 'p'
GROUP BY parent.relname
ttl : 300
metrics :
- parent_table : {usage : LABEL}
- partition_count : {usage : GAUGE}
- total_size : {usage : GAUGE}
性能优化 查询优化技巧 使用适当的 TTL 值 :
快速查询:1-10 秒 中等查询:10-60 秒 昂贵查询:300-3600 秒 设置合理的超时 :
默认:100ms 复杂查询:500ms-1s 生产环境中不要禁用超时 使用集群级标签 :
tags : [ cluster] # 每集群运行一次,而不是每数据库
禁用昂贵的采集器 :
pg_table_bloat :
skip : true # 如果不需要则禁用
监控采集器性能 检查采集器执行统计:
# 查看采集器统计
curl http://localhost:9630/stat
# 检查哪些采集器较慢
curl http://localhost:9630/metrics | grep pg_exporter_collector_duration
配置故障排查 验证配置 # 干运行 - 显示解析后的配置
pg_exporter --dry-run
# 解释 - 显示计划的查询
pg_exporter --explain
常见问题 问题 解决方案 指标缺失 检查标签和版本兼容性 抓取缓慢 增加 TTL、添加超时、禁用昂贵查询 内存使用高 减少结果集大小,使用 LIMIT 权限错误 验证监控用户的查询权限
调试日志 启用调试日志进行故障排查:
pg_exporter --log.level= debug
23.4 - API 参考 PG Exporter 的 HTTP API 端点参考
PG Exporter 提供全面的 REST API,用于指标采集、健康检查、流量路由和运维控制。所有端点都通过配置的端口(默认:9630)以 HTTP 方式暴露。
端点概览 指标端点 GET /metrics 暴露所有采集指标的主端点,格式为 Prometheus 格式。
请求 curl http://localhost:9630/metrics
响应 # HELP pg_up PostgreSQL server is up and accepting connections
# TYPE pg_up gauge
pg_up 1
# HELP pg_version PostgreSQL server version number
# TYPE pg_version gauge
pg_version 140000
# HELP pg_in_recovery PostgreSQL server is in recovery mode
# TYPE pg_in_recovery gauge
pg_in_recovery 0
# HELP pg_exporter_build_info PG Exporter build information
# TYPE pg_exporter_build_info gauge
pg_exporter_build_info{version="1.1.0",branch="main",revision="abc123"} 1
# ... 更多指标
响应格式 指标遵循 Prometheus 暴露格式:
# HELP <metric_name> <description>
# TYPE <metric_name> <type>
<metric_name>{<label_name>="<label_value>",...} <value> <timestamp>
健康检查 健康检查端点提供多种方式来监控 PG Exporter 和目标数据库的状态。
GET /up 简单的二元健康检查。
响应码 状态码 状态 描述 200 OK 导出器和数据库都正常运行 503 Service Unavailable 数据库宕机或无法访问
示例 # 检查服务是否正常
curl -I http://localhost:9630/up
HTTP/1.1 200 OK
Content-Type: text/plain; charset = utf-8
GET /health /up 的别名,行为相同。
curl http://localhost:9630/health
GET /liveness Kubernetes 存活探针端点。
# 存活探针配置
livenessProbe :
httpGet :
path : /liveness
port : 9630
initialDelaySeconds : 30
periodSeconds : 10
GET /readiness Kubernetes 就绪探针端点。
# 就绪探针配置
readinessProbe :
httpGet :
path : /readiness
port : 9630
initialDelaySeconds : 5
periodSeconds : 5
流量路由 这些端点专为负载均衡器和代理设计,根据服务器角色路由流量。
GET /primary 检查服务器是否为主库(master)实例。
响应码 状态码 状态 描述 200 OK 服务器是主库且接受写入 404 Not Found 服务器不是主库(是从库) 503 Service Unavailable 服务器宕机
别名 /leader/master/read-write/rw示例 # 检查服务器是否为主库
curl -I http://localhost:9630/primary
# 在 HAProxy 配置中使用
backend pg_primary
option httpchk GET /primary
server pg1 10.0.0.1:5432 check port 9630
server pg2 10.0.0.2:5432 check port 9630
GET /replica 检查服务器是否为从库(standby)实例。
响应码 状态码 状态 描述 200 OK 服务器是从库且处于恢复状态 404 Not Found 服务器不是从库(是主库) 503 Service Unavailable 服务器宕机
别名 /standby/slave/read-only/ro示例 # 检查服务器是否为从库
curl -I http://localhost:9630/replica
# 在负载均衡器配置中使用
backend pg_replicas
option httpchk GET /replica
server pg2 10.0.0.2:5432 check port 9630
server pg3 10.0.0.3:5432 check port 9630
GET /read 检查服务器是否可以处理读流量(主库和从库都可以)。
响应码 状态码 状态 描述 200 OK 服务器正常运行且可以处理读请求 503 Service Unavailable 服务器宕机
示例 # 检查服务器是否可以处理读请求
curl -I http://localhost:9630/read
# 将读流量路由到任何可用服务器
backend pg_read
option httpchk GET /read
server pg1 10.0.0.1:5432 check port 9630
server pg2 10.0.0.2:5432 check port 9630
server pg3 10.0.0.3:5432 check port 9630
运维端点 POST /reload 在不重启导出器的情况下重新加载配置。
请求 curl -X POST http://localhost:9630/reload
响应 {
"status" : "success" ,
"message" : "Configuration reloaded successfully" ,
"timestamp" : "2024-01-15T10:30:00Z"
}
响应码 状态码 状态 描述 200 OK 配置重新加载成功 500 Internal Server Error 重新加载失败
使用场景 更新采集器定义 更改查询参数 修改缓存 TTL 值 添加或移除采集器 注意
配置重新加载不会影响数据库连接。要更改连接参数,需要重启导出器。
GET /explain 显示所有已配置采集器的查询执行规划信息。
请求 curl http://localhost:9630/explain
响应 Collector: pg_stat_database
Query: SELECT datname, numbackends FROM pg_stat_database
Tags: [cluster]
TTL: 10s
Timeout: 100ms
Version: 100000-999999
Status: Active
Collector: pg_stat_replication
Query: SELECT client_addr, state FROM pg_stat_replication
Tags: [primary]
TTL: 5s
Timeout: 100ms
Version: 100000-999999
Status: Active (primary only)
...
GET /stat 显示运行时统计信息,包括采集器执行时间和成功/失败计数。
请求 curl http://localhost:9630/stat
响应 Collector Statistics:
pg_stat_database:
Executions: 1234
Successes: 1230
Failures: 4
Avg Duration: 2.5ms
Last Execution: 2024-01-15T10:29:55Z
pg_stat_activity:
Executions: 1234
Successes: 1234
Failures: 0
Avg Duration: 1.2ms
Last Execution: 2024-01-15T10:29:55Z
...
此端点对于识别慢速或有问题的采集器非常有用。
在负载均衡器中使用 HAProxy 配置示例 # 主库后端 - 用于写流量
backend pg_primary
mode tcp
option httpchk GET /primary
http-check expect status 200
server pg1 10.0.0.1:5432 check port 9630 inter 3000 fall 2 rise 2
server pg2 10.0.0.2:5432 check port 9630 inter 3000 fall 2 rise 2 backup
# 从库后端 - 用于读流量
backend pg_replicas
mode tcp
balance roundrobin
option httpchk GET /replica
http-check expect status 200
server pg2 10.0.0.2:5432 check port 9630 inter 3000 fall 2 rise 2
server pg3 10.0.0.3:5432 check port 9630 inter 3000 fall 2 rise 2
# 读后端 - 用于任何可以处理读请求的服务器
backend pg_read
mode tcp
balance leastconn
option httpchk GET /read
http-check expect status 200
server pg1 10.0.0.1:5432 check port 9630 inter 3000 fall 2 rise 2
server pg2 10.0.0.2:5432 check port 9630 inter 3000 fall 2 rise 2
server pg3 10.0.0.3:5432 check port 9630 inter 3000 fall 2 rise 2
Nginx 配置示例 upstream pg_primary {
server 10.0.0.1 : 5432 ;
server 10.0.0.2 : 5432 backup ;
}
upstream pg_replicas {
server 10.0.0.2 : 5432 ;
server 10.0.0.3 : 5432 ;
}
server {
listen 5432 ;
location / {
proxy_pass http://pg_primary ;
health_check uri=/primary port=9630 ;
}
}
23.5 - 部署指南 生产环境部署策略与最佳实践
本指南涵盖生产环境的部署策略、最佳实践和实际配置。
pg_exporter 本身可以通过以下方式配置:
命令行参数 (优先级较高)环境变量 (优先级较低)指标采集器通过 YAML 配置文件(目录/文件)进行配置:
/etc/pg_exporter.yml(默认)/etc/pg_exporter/(包含多个文件的目录)配置文件使用 YAML 格式,由 采集器定义 组成,指定要采集的指标以及如何采集。
命令行参数 所有配置选项都可以通过命令行标志指定:
pg_exporter \
--url= "postgres://user:pass@localhost:5432/postgres" \
--config= "/etc/pg_exporter/pg_exporter.yml" \
--web.listen-address= ":9630" \
--auto-discovery \
--exclude-database= "template0,template1" \
--log.level= "info"
运行 pg_exporter --help 获取完整的可用标志列表:
Flags:
-h, --[ no-] help 显示上下文相关帮助(也可尝试 --help-long 和 --help-man)。
-u, --url= URL postgres 目标 URL
-c, --config= CONFIG 配置目录或文件路径
--[ no-] web.systemd-socket 使用 systemd socket 激活监听器代替端口监听器(仅限 Linux)。
--web.listen-address= :9630 ...
暴露指标和 Web 界面的地址。可重复指定多个地址。示例:` :9100` 或 ` [ ::1] :9100` 用于 http,` vsock://:9100` 用于 vsock
--web.config.file= "" 可启用 TLS 或认证的配置文件路径。参见:https://github.com/prometheus/exporter-toolkit/blob/master/docs/web-configuration.md
-l, --label= "" 常量标签:逗号分隔的 label = value 对列表 ( $PG_EXPORTER_LABEL )
-t, --tag= "" 标签,逗号分隔的服务器标签列表 ( $PG_EXPORTER_TAG )
-C, --[ no-] disable-cache 强制不使用缓存 ( $PG_EXPORTER_DISABLE_CACHE )
-m, --[ no-] disable-intro 禁用采集器级别的内省指标 ( $PG_EXPORTER_DISABLE_INTRO )
-a, --[ no-] auto-discovery 自动抓取给定服务器的所有数据库 ( $PG_EXPORTER_AUTO_DISCOVERY )
-x, --exclude-database= "template0,template1,postgres"
启用自动发现时排除的数据库 ( $PG_EXPORTER_EXCLUDE_DATABASE )
-i, --include-database= "" 启用自动发现时包含的数据库 ( $PG_EXPORTER_INCLUDE_DATABASE )
-n, --namespace= "" 内置指标的前缀,默认为 ( pg| pgbouncer) ( $PG_EXPORTER_NAMESPACE )
-f, --[ no-] fail-fast 启动时立即失败而不是等待 ( $PG_EXPORTER_FAIL_FAST )
-T, --connect-timeout= 100 连接超时(毫秒),默认 100 ( $PG_EXPORTER_CONNECT_TIMEOUT )
-P, --web.telemetry-path= "/metrics"
暴露指标的 URL 路径 ( $PG_EXPORTER_TELEMETRY_PATH )
-D, --[ no-] dry-run 干运行并打印原始配置
-E, --[ no-] explain 解释服务器计划的查询
--log.level= "info" 日志级别:debug| info| warn| error]
--log.format= "logfmt" 日志格式:logfmt| json
--[ no-] version 显示应用程序版本
环境变量 所有命令行参数都有对应的环境变量:
PG_EXPORTER_URL = 'postgres://:5432/?sslmode=disable'
PG_EXPORTER_CONFIG = /etc/pg_exporter.yml
PG_EXPORTER_LABEL = ""
PG_EXPORTER_TAG = ""
PG_EXPORTER_DISABLE_CACHE = false
PG_EXPORTER_AUTO_DISCOVERY = true
PG_EXPORTER_EXCLUDE_DATABASE = "template0,template1,postgres"
PG_EXPORTER_INCLUDE_DATABASE = ""
PG_EXPORTER_NAMESPACE = "pg"
PG_EXPORTER_FAIL_FAST = false
PG_EXPORTER_CONNECT_TIMEOUT = 100
PG_EXPORTER_TELEMETRY_PATH = "/metrics"
PG_EXPORTER_OPTS = '--log.level=info'
pg_exporter
部署架构 最简单的部署方式是每个 PostgreSQL 实例配置一个导出器:
┌─────────────┐ ┌──────────────┐ ┌────────────┐
│ Prometheus │────▶│ PG Exporter │────▶│ PostgreSQL │
└─────────────┘ └──────────────┘ └────────────┘
:9630 :5432
多数据库环境 使用自动发现来监控多个数据库(默认启用):
┌─────────────┐ ┌────────────────┐ ┌────────────┐
│ Prometheus │────▶│ PG Exporter │────▶│ PostgreSQL │
└─────────────┘ │ 启用自动发现 │ │ ├─ db1 │
│ │ │ ├─ db2 │
└────────────────┘ │ └─ db3 │
└────────────┘
生产配置 PostgreSQL 用户设置 创建一个具有最小必要权限的专用监控用户:
-- 创建监控角色
CREATE ROLE pg_monitor WITH LOGIN PASSWORD 'strong_password' CONNECTION LIMIT 5 ;
-- 授予必要权限
GRANT pg_monitor TO pg_monitor ; -- PostgreSQL 10+ 内置角色
GRANT CONNECT ON DATABASE postgres TO pg_monitor ;
-- 对于特定数据库
GRANT CONNECT ON DATABASE app_db TO pg_monitor ;
GRANT USAGE ON SCHEMA public TO pg_monitor ;
-- 扩展监控的额外权限
GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO pg_monitor ;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA pg_catalog TO pg_monitor ;
连接安全 使用 SSL/TLS # 带 SSL 的连接字符串
PG_EXPORTER_URL = 'postgres://pg_monitor:password@db.example.com:5432/postgres?sslmode=require&sslcert=/path/to/client.crt&sslkey=/path/to/client.key&sslrootcert=/path/to/ca.crt'
使用 .pgpass 文件 # 创建 .pgpass 文件
echo "db.example.com:5432:*:pg_monitor:password" > ~/.pgpass
chmod 600 ~/.pgpass
# 在 URL 中不使用密码
PG_EXPORTER_URL = 'postgres://pg_monitor@db.example.com:5432/postgres'
Systemd 服务配置 完整的生产环境 systemd 设置:
[Unit]
Description = Prometheus exporter for PostgreSQL/Pgbouncer server metrics
Documentation = https://github.com/pgsty/pg_exporter
After = network.target
[Service]
EnvironmentFile = -/etc/default/pg_exporter
User = prometheus
ExecStart = /usr/bin/pg_exporter $PG_EXPORTER_OPTS
Restart = on-failure
[Install]
WantedBy = multi-user.target
环境文件 /etc/default/pg_exporter:
PG_EXPORTER_URL = 'postgres://:5432/?sslmode=disable'
PG_EXPORTER_CONFIG = /etc/pg_exporter.yml
PG_EXPORTER_LABEL = ""
PG_EXPORTER_TAG = ""
PG_EXPORTER_DISABLE_CACHE = false
PG_EXPORTER_AUTO_DISCOVERY = true
PG_EXPORTER_EXCLUDE_DATABASE = "template0,template1,postgres"
PG_EXPORTER_INCLUDE_DATABASE = ""
PG_EXPORTER_NAMESPACE = "pg"
PG_EXPORTER_FAIL_FAST = false
PG_EXPORTER_CONNECT_TIMEOUT = 100
PG_EXPORTER_TELEMETRY_PATH = "/metrics"
PG_EXPORTER_OPTS = '--log.level=info'
服务管理 启动和停止服务 # 启动服务
sudo systemctl start pg_exporter
# 停止服务
sudo systemctl stop pg_exporter
# 重启服务
sudo systemctl restart pg_exporter
# 查看服务状态
sudo systemctl status pg_exporter
# 设置开机自启
sudo systemctl enable pg_exporter
查看日志 # 实时查看日志
journalctl -u pg_exporter -f
# 查看最近的日志
journalctl -u pg_exporter --since "1 hour ago"
# 查看错误日志
journalctl -u pg_exporter -p err
Docker 部署 基本 Docker 运行 docker run -d \
--name pg_exporter \
--restart unless-stopped \
-p 9630:9630 \
-e PG_EXPORTER_URL = "postgres://user:pass@host:5432/postgres" \
pgsty/pg_exporter:latest
Docker Compose version : '3.8'
services :
pg_exporter :
image : pgsty/pg_exporter:latest
container_name : pg_exporter
restart : unless-stopped
ports :
- "9630:9630"
environment :
- PG_EXPORTER_URL=postgres://pg_monitor:password@postgres:5432/postgres
- PG_EXPORTER_AUTO_DISCOVERY=true
- PG_EXPORTER_EXCLUDE_DATABASE=template0,template1
volumes :
- ./pg_exporter.yml:/etc/pg_exporter.yml:ro
depends_on :
- postgres
Kubernetes 部署 Deployment 示例 apiVersion : apps/v1
kind : Deployment
metadata :
name : pg-exporter
labels :
app : pg-exporter
spec :
replicas : 1
selector :
matchLabels :
app : pg-exporter
template :
metadata :
labels :
app : pg-exporter
annotations :
prometheus.io/scrape : "true"
prometheus.io/port : "9630"
spec :
containers :
- name : pg-exporter
image : pgsty/pg_exporter:latest
ports :
- containerPort : 9630
env :
- name : PG_EXPORTER_URL
valueFrom :
secretKeyRef :
name : pg-credentials
key : connection-url
- name : PG_EXPORTER_AUTO_DISCOVERY
value : "true"
livenessProbe :
httpGet :
path : /liveness
port : 9630
initialDelaySeconds : 30
periodSeconds : 10
readinessProbe :
httpGet :
path : /readiness
port : 9630
initialDelaySeconds : 5
periodSeconds : 5
resources :
limits :
cpu : 200m
memory : 256Mi
requests :
cpu : 100m
memory : 128Mi
Service 示例 apiVersion : v1
kind : Service
metadata :
name : pg-exporter
labels :
app : pg-exporter
spec :
ports :
- port : 9630
targetPort : 9630
name : metrics
selector :
app : pg-exporter
Prometheus 配置 静态配置 scrape_configs :
- job_name : 'postgresql'
static_configs :
- targets :
- 'pg-exporter-1:9630'
- 'pg-exporter-2:9630'
- 'pg-exporter-3:9630'
服务发现 scrape_configs :
- job_name : 'postgresql'
kubernetes_sd_configs :
- role : pod
relabel_configs :
- source_labels : [ __meta_kubernetes_pod_label_app]
regex : pg-exporter
action : keep
- source_labels : [ __meta_kubernetes_pod_ip]
target_label : __address__
replacement : ${1}:9630
监控与告警 推荐的告警规则 groups :
- name : pg_exporter
rules :
# 导出器宕机告警
- alert : PgExporterDown
expr : up{job="postgresql"} == 0
for : 5m
labels :
severity : critical
annotations :
summary : "PG Exporter 宕机"
description : "{{ $labels.instance }} 的 PG Exporter 已宕机超过 5 分钟"
# 数据库连接失败告警
- alert : PostgreSQLDown
expr : pg_up == 0
for : 1m
labels :
severity : critical
annotations :
summary : "PostgreSQL 连接失败"
description : "无法连接到 {{ $labels.instance }} 上的 PostgreSQL"
# 抓取时间过长告警
- alert : PgExporterSlowScrape
expr : pg_exporter_last_scrape_duration_seconds > 30
for : 5m
labels :
severity : warning
annotations :
summary : "PG Exporter 抓取缓慢"
description : "{{ $labels.instance }} 的抓取时间超过 30 秒"
23.6 - 发布注记 PG Exporter 版本发布历史
pg_exporter 的最新稳定版本是 v1.1.0
v1.1.0 使用 Go 1.25.5 和最新依赖构建,采集器更新:
采集器变更:
pg_setting:针对 PG10-18 兼容性进行重大重构,支持 missing_ok新增 13 个指标:max_parallel_workers、max_parallel_workers_per_gather、max_parallel_maintenance_workers、shared_buffers、maintenance_work_mem、effective_cache_size、fsync、full_page_writes、autovacuum、autovacuum_max_workers、checkpoint_timeout、checkpoint_completion_target、hot_standby、synchronous_commit、io_method 将 work_memory_size 重命名为 work_mem min_version 从 9.6 改为 10,显式 ::int 类型转换 pg_size:修复日志目录大小检测,使用 logging_collector 检查代替路径模式匹配pg_table:性能优化,用 JOIN 替换 LATERAL 子查询以提升查询性能;修复 tuples 和 frozenxid 指标类型从 COUNTER 改为 GAUGE;超时从 1s 增加到 2spg_vacuuming:新增 PG17 采集器分支,包含新指标 indexes_total、indexes_processed、dead_tuple_bytes 用于索引 vacuum 进度跟踪pg_query:超时从 1s 增加到 2s 以应对高负载场景pg_io:修复 reuses 描述中的拼写错误(“in reused” -> “is reused”)pg_checkpointer:修复 pg_checkpointer_10 描述(“9.4+” -> “9.4-17”)pg_db_confl:修复 pg_db_confl_15 描述(“9.1 - 16” -> “9.1 - 15”)pg_db、pg_indexing、pg_clustering、pg_backup 格式对齐修复其他变更:
校验和
https://github.com/pgsty/pg_exporter/releases/download/v1.0.3/checksums.txt
9c65f43e76213bb8a49d1eab2c76a27d9ab694e67bc79f0ad12769ea362b5ca2 pg-exporter_1.1.0-1_amd64.deb
bcd2cacb4febc5fb92f9eda8e733c161c8c6721416e16ec91a773503241c972d pg-exporter_1.1.0-1_arm64.deb
2c9d4a9cb06d07af0b6dd9dd6e568af073dc9f6775abde63b45f0aae34d171b1 pg-exporter_1.1.0-1_ppc64le.deb
2934ab5b0fb16dca5a96ec1e8f230e32c72b30ca076b5e5ddf8ec553c821f7b8 pg_exporter-1.1.0-1.aarch64.rpm
3c9955f31ba93532cc7f95ff60b0658f4b6eca6a827710e2f70c0716b34eab43 pg_exporter-1.1.0-1.ppc64le.rpm
9fdefbd8e7660dcb130207901a27762e0a381857ba8cf12b63184744f92dea05 pg_exporter-1.1.0-1.x86_64.rpm
7159002016754309e0ed625a9a48049d21177883fa11d1e448eb7655ceb690cc pg_exporter-1.1.0.darwin-amd64.tar.gz
7d55ac5cda0b1fd8ffbd5e76b9c1c1784ac8e353104a206caaadce89adda6d65 pg_exporter-1.1.0.darwin-arm64.tar.gz
8211ec24277554b9b1a36920d7865153e21c2621031d3d08f22d94cdd2ddf02f pg_exporter-1.1.0.linux-amd64.tar.gz
d17ab7f9bf04442e642483d432d005d25bb62e0c9caa73cb7e69ee19eb89b3ae pg_exporter-1.1.0.linux-arm64.tar.gz
c074aeb345cc30f7b6e16aa153ae3d9a12789e4425987590c3fd77c4e68a40b6 pg_exporter-1.1.0.linux-ppc64le.tar.gz
13d653e2abb023ce9526bdc2815135b82f49c044d237030f3f56b09fb016fcb7 pg_exporter-1.1.0.windows-amd64.tar.gz
https://github.com/pgsty/pg_exporter/releases/tag/v1.1.0
v1.0.3 使用 Go 1.25.4 和最新依赖构建 修复 #80 与 libpq 环境变量冲突 由 @kadaffy 将 auto-discovery 默认值改为 true 校验和
https://github.com/pgsty/pg_exporter/releases/download/v1.0.3/checksums.txt
7efa1a77dfd5b94813c32c7ac015b1d479b1f04fb958f6b1ed5af333e354d015 pg-exporter_1.0.3-1_amd64.deb
41e18bf18eba2ab90ac371bfb46e9152da9fe628ebd8e26766cac08325eb3b07 pg-exporter_1.0.3-1_arm64.deb
7da8ed738d254c120d42aa51d6137f84e7f4e3188bc764d4f9a1438220363a43 pg-exporter_1.0.3-1_ppc64le.deb
a214b555981156da7b7d248b1f728f8ac88a07ac8f77a66c5d8e43b40670d6b4 pg_exporter-1.0.3-1.aarch64.rpm
d876fc66e208612ebffe3c43dabce88b088d915f92584260d710b85a3a131413 pg_exporter-1.0.3-1.ppc64le.rpm
75f62d314fec50c836c534996c884d25ecea77810ab33e7ba0e9c4b783e775b4 pg_exporter-1.0.3-1.x86_64.rpm
47829a19707284bcee1b8dc47cc7d0172398bb533e6b4043950f787486712769 pg_exporter-1.0.3.darwin-amd64.tar.gz
38b6ccb72315cadea542b1f2a7b7022d0e8d48ffd4ab177bb69a0a909b99af6b pg_exporter-1.0.3.darwin-arm64.tar.gz
36e8dff84d61a7593ff1fcec567ca4ffeaecd0be2f9eabd227ceac71b12a919a pg_exporter-1.0.3.linux-amd64.tar.gz
6477e8ef873773a09c4f39a29444f21b5b2c71e717e52ca425bcc8e8e5448791 pg_exporter-1.0.3.linux-arm64.tar.gz
a083b51ebed2b280e2eaa0f19558494e7fa6f122a0a86a1d117206fcd090820c pg_exporter-1.0.3.linux-ppc64le.tar.gz
a1f9b27b7190f478726d96f270a72d9dc4d3f2bcc3b0326b7c4a2607e62ea588 pg_exporter-1.0.3.windows-amd64.tar.gz
https://github.com/pgsty/pg_exporter/releases/tag/v1.0.3
v1.0.2 使用 Go 1.25.0 和最新依赖构建 专属网站和主页:https://exp.pgsty.com 使用 goreleaser 通过 CI/CD 流水线发布更多操作系统/架构:新增 Windows amd64 支持 新增 Linux ppc64le 支持 校验和
https://github.com/pgsty/pg_exporter/releases/download/v1.0.2/checksums.txt
683bf97f22173f2f2ec319a88e136939c2958a1f5ced4f4aa09a1357fc1c44c5 pg-exporter_1.0.2-1_amd64.deb
f62d479a92be2d03211c162b8419f968cea87ceef5b1f25f2bcd390e0b72ccb5 pg-exporter_1.0.2-1_arm64.deb
e1bbfc5a4c1b93e6f92bc7adcb4364583ab763e76e156aa5c979d6d1040f4c7a pg-exporter_1.0.2-1_ppc64le.deb
f51d5b45448e6bbec3467d1d1dc049b1e16976f723af713c4262541ac55a039c pg_exporter-1.0.2-1.aarch64.rpm
18380011543674e4c48b2410266b41165974d780cbc8918fc562152ba623939e pg_exporter-1.0.2-1.ppc64le.rpm
198372d894b9598c166a0e91ca36d3c9271cb65298415f63dbffcf6da611f2bb pg_exporter-1.0.2-1.x86_64.rpm
cbe7e07df6d180507c830cdab4cf86d40ccd62774723946307b5331d4270477d pg_exporter-1.0.2.darwin-amd64.tar.gz
20c4a35fa244287766c1d1a19cd2e393b3fa451a96a81e5635401e69bef04b97 pg_exporter-1.0.2.darwin-arm64.tar.gz
d742111185f6a89fff34bfd304b851c8eb7a8e38444f0220786e11ed1934eff1 pg_exporter-1.0.2.linux-amd64.tar.gz
0b1f4c97c1089c4767d92eb22419b8f29c9f46fb90ddfd1e8514cc42dc41054f pg_exporter-1.0.2.linux-arm64.tar.gz
895083fd2c7fc5409cc1a2dbaaef1e47ac7aa6a3fd5db2359012922d90bcdcc3 pg_exporter-1.0.2.linux-ppc64le.tar.gz
5f751228e7120604af9a482fb70197489fa633c38a0f2b6a3489393fbc6a10aa pg_exporter-1.0.2.windows-amd64.tar.gz
https://github.com/pgsty/pg_exporter/releases/tag/v1.0.2
v1.0.1 新增 DockerHub 镜像:pgsty/pg_exporter 升级 Go 依赖到最新版本,使用 Go 1.24.5 构建 默认禁用 pg_tsdb_hypertable 采集器,因为 timescaledb 目录已变更 校验和
d5e2d6a656eef0ae1b29cd49695f9773 pg_exporter-1.0.1-1.aarch64.rpm
cb01bb78d7b216a235363e9342803cb3 pg_exporter-1.0.1-1.x86_64.rpm
67093a756b04845f69ad333b6d458e81 pg_exporter-v1.0.1.darwin-amd64.tar.gz
2d3fdc10045d1cf494b9c1ee7f94f127 pg_exporter-v1.0.1.darwin-arm64.tar.gz
e242314461becfa99c3978ae72838ab0 pg_exporter-v1.0.1.linux-amd64.tar.gz
63de91da9ef711a53718bc60b89c82a6 pg_exporter-v1.0.1.linux-arm64.tar.gz
718f6afc004089f12c1ca6553f9b9ba5 pg-exporter_1.0.1_amd64.deb
57da7a8005cdf91ba8c1fb348e0d7367 pg-exporter_1.0.1_arm64.deb
https://github.com/pgsty/pg_exporter/releases/tag/v1.0.1
v1.0.0 新增 PostgreSQL 18 指标支持
新采集器分支 pg_wal_18:移除 write、sync、write_time、sync_time 指标 移至 pg_stat_io 新采集器分支 pg_checkpointer_18:新指标 num_done 新指标 slru_written 新采集器分支 pg_db_18:新指标 parallel_workers_to_launch 新指标 parallel_workers_launched 新采集器分支 pg_table_18:table_parallel_workers_to_launchtable_parallel_workers_launched 新采集器分支 pg_io_18:新增 WAL 统计系列 新指标 read_bytes 新指标 write_bytes 新指标 extend_bytes 移除 op_bytes(因为是固定值) 新采集器分支 pg_vacuuming_18: 8637bc1a05b93eedfbfd3816cca468dd pg_exporter-1.0.0-1.aarch64.rpm
a28c4c0dcdd3bf412268a2dbff79f5b9 pg_exporter-1.0.0-1.x86_64.rpm
229129209b8e6bc356c28043c7c22359 pg_exporter-v1.0.0.darwin-amd64.tar.gz
d941c2c28301269e62a8853c93facf12 pg_exporter-v1.0.0.darwin-arm64.tar.gz
5bbb94db46cacca4075d4c341c54db37 pg_exporter-v1.0.0.linux-amd64.tar.gz
da9ad428a50546a507a542d808f1c0fa pg_exporter-v1.0.0.linux-arm64.tar.gz
0fa2395d9d7a43ab87e5c87e5b06ffcc pg-exporter_1.0.0_amd64.deb
fed56f8a37e30cc59e85f03c81fce3f5 pg-exporter_1.0.0_arm64.deb
https://github.com/pgsty/pg_exporter/releases/tag/v1.0.0
v0.9.0 默认采集器
新增 timescaledb 超表指标采集器 新增 citus 分布式节点指标采集器 新增 pg_wait_sampling 等待事件采集器 pg_slot 全面改进:新增 16/17 pg_replication_slot 指标允许 pg_slot 采集器从 16/17 开始在从库上运行 重构 pg_wait 采集器,从所有进程聚合 限制 pg_clustering、pg_indexing、pg_vacuuming 只在主库运行 将所有 reset_time 标记为 GAUGE 而非 COUNTER 修复 pg_recovery_prefetch_skip_fpw 类型从 GAUGE 改为 COUNTER 修复 pg_recv.state 类型从 LABEL 改为 GAUGE 采集器格式改为紧凑模式 新增默认指标 pg_exporter_build_info / pgbouncer_exporter_build_info 为 pg_meta 采集器新增 server_encoding 为 pg_setting 采集器新增 12 个设置指标:wal_block_size segment_size wal_segment_size wal_level wal_log_hints work_mem hugepage_count hugepage_status max_wal_size min_wal_size max_slot_wal_keep_size 导出器代码库
使用最小 PG 版本后缀规范化采集器分支名称 为二进制包添加许可证文件 将 pgsty/pg_exporter 仓库移至 pgsty/pg_exporter 重构 server.go 以降低 Compatible 和 PostgresPrecheck 复杂度 使用额外数字前缀重命名指标采集器以便排序 升级依赖到最新版本 在所有非致命采集器之前执行致命采集器,快速失败 https://github.com/pgsty/pg_exporter/releases/tag/v0.9.0
v0.8.1 https://github.com/pgsty/pg_exporter/releases/tag/v0.8.1
v0.8.0 新增 PgBouncer 1.24 新指标支持(stat、pool、database) 修复:310-pg_size.yml 在日志目录设置不正确时失败 #64 ,由 @Süleyman Vurucu 贡献 使用最新 Go 1.24 构建并升级所有依赖 使用标准 log/slog 重构日志,替代 go-kit 完整变更日志 :https://github.com/pgsty/pg_exporter/compare/v0.7.1…v0.8.0https://github.com/pgsty/pg_exporter/releases/tag/v0.8.0
v0.7.1 使用 dependabot 进行例行更新
功能:支持将配置指定为 Reader,由 @ringerc 在 #62 贡献 升级 golang.org/x/crypto 从 0.21.0 到 0.31.0,由 @dependabot 在 #63 贡献 修复一些拼写错误 完整变更日志 :https://github.com/pgsty/pg_exporter/compare/v0.7.0…v0.7.1https://github.com/pgsty/pg_exporter/releases/tag/v0.7.1
v0.7.0 为最新 Go 版本重构代码库。
https://github.com/pgsty/pg_exporter/releases/tag/v0.7.0
v0.6.0 https://github.com/pgsty/pg_exporter/releases/tag/v0.6.0
v0.5.0 导出器增强
使用 nfpm 构建 rpm 和 deb 新增 column.default,当指标值为 NULL 时替换 新增 column.scale,当指标值为浮点/整数时乘以缩放因子(例如微秒转秒) 修复 /stat 端点输出 新增 Docker 容器 pgsty/pg_exporter 指标采集器
将 bgwriter 和 pg_wal 时间单位缩放为秒 移除 pg_class 采集器,将其移至 pg_table 和 pg_index 为 pg_table 新增 pg_class 指标 为 pg_index 新增 pg_class 指标 默认启用 pg_table_size 将 pg_query、pg_db、pg_bgwriter、pg_ssl、pgbouncer_stat 时间指标缩放为秒 https://github.com/pgsty/pg_exporter/releases/tag/v0.5.0
v0.4.1 更新默认采集器在对象监控中省略 citus 和 timescaledb 模式 避免重复的 pg_statio 元组 支持 pgbouncer v1.16 Bug 修复:pg_repl 采集器在 pg 12 上重叠 新参数:-T connect-timeout PG_EXPORTER_CONNECT_TIMEOUT
这在监控远程 Postgres 实例时很有用 现在 pg_exporter.yaml 在 rpm 包中重命名为 pg_exporter.yml https://github.com/pgsty/pg_exporter/releases/tag/v0.4.1
v0.4.0 新增 PG 14 支持 默认指标配置全面改进(但您仍可使用旧配置) 新增 auto-discovery、include-database 和 exclude-database 选项 新增多数据库监控实现(使用 auto-discovery = on) https://github.com/pgsty/pg_exporter/releases/tag/v0.4.0
v0.3.2 修复 shadow DSN 边界情况 修复拼写错误和文档 https://github.com/pgsty/pg_exporter/releases/tag/v0.3.2
v0.3.1 修复默认配置问题(特别是低于 13 的版本)
设置 primary_conninfo 在 PG13 之前不存在 为 pg_func 采集器添加 funcid 标签以避免函数名重复标签 修复版本字符串为 pg_exporter https://github.com/pgsty/pg_exporter/releases/tag/v0.3.1
v0.3.0 https://github.com/pgsty/pg_exporter/releases/tag/v0.3.0
更改默认配置,支持 PostgreSQL 13 新指标(pg_slru、pg_shmem、pg_query13、pg_backup 等) 新增一系列用于健康/恢复状态检查的 REST API 新增一个带有假 pg_up 0 指标的虚拟服务器,在 PgExporter 初始化之前提供服务 如果未指定 sslmode,向 URL 添加 sslmode=disable 修复拼写错误和 Bug v0.2.0 新增 yum 包和 Linux 服务定义 在查询配置中新增 ‘skip’ 标志 修复 pgbouncer_up 指标 新增配置重载支持 https://github.com/pgsty/pg_exporter/releases/tag/v0.2.0
v0.1.2 修复 pgbouncer_up 指标 新增动态配置重载 移除 ‘shard’ 相关逻辑 在默认设置中添加 ‘bulky’ 模式 https://github.com/pgsty/pg_exporter/releases/tag/v0.1.2
v0.1.1 修复 pg_exporter 在启动时如果任何查询失败会挂起的 Bug。
https://github.com/pgsty/pg_exporter/releases/tag/v0.1.1
v0.1.0 可以工作了,看起来不错。
https://github.com/pgsty/pg_exporter/releases/tag/v0.1.0
v0.0.4 在真实生产环境中测试了大约 2 周,200+ 节点。看起来不错!
https://github.com/pgsty/pg_exporter/releases/tag/v0.0.4
v0.0.3 v0.0.3 发布,在生产环境中测试
此版本已在生产环境中测试。
这个项目仍在快速发展中,如果您想在生产中使用,请谨慎尝试。
https://github.com/pgsty/pg_exporter/releases/tag/v0.0.3
v0.0.2 现在可以尝试了
https://github.com/pgsty/pg_exporter/releases/tag/v0.0.2
v0.0.1 新增 pgbouncer 模式
https://github.com/pgsty/pg_exporter/releases/tag/v0.0.1