PostgreSQL源码分析——pg_waldump

2024-06-19 12:04

本文主要是介绍PostgreSQL源码分析——pg_waldump,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

PG中有个可以打印WAL日志信息的工具,pg_waldump,对于开发人员来说,掌握该工具是十分有必要的。

用法

具体用法这里不去详解,可见官网pg_waldump文档。

postgres@slpc:~$ pg_waldump --help
pg_waldump decodes and displays PostgreSQL write-ahead logs for debugging.Usage:pg_waldump [OPTION]... [STARTSEG [ENDSEG]]Options:-b, --bkp-details      output detailed information about backup blocks-e, --end=RECPTR       stop reading at WAL location RECPTR-f, --follow           keep retrying after reaching end of WAL-n, --limit=N          number of records to display-p, --path=PATH        directory in which to find log segment files or adirectory with a ./pg_wal that contains such files(default: current directory, ./pg_wal, $PGDATA/pg_wal)-q, --quiet            do not print any output, except for errors-r, --rmgr=RMGR        only show records generated by resource manager RMGR;use --rmgr=list to list valid resource manager names-s, --start=RECPTR     start reading at WAL location RECPTR-t, --timeline=TLI     timeline from which to read log records(default: 1 or the value used in STARTSEG)-V, --version          output version information, then exit-x, --xid=XID          only show records with transaction ID XID-z, --stats[=record]   show statistics instead of records(optionally, show per-record statistics)-?, --help             show this help, then exit

具体的,我们举一个例子:

postgres=# create table t1(a int);
CREATE TABLEpostgres=# select pg_current_wal_lsn();pg_current_wal_lsn 
--------------------0/1696C78
(1 row)
-- 插入一条数据
postgres=# insert into t1 values(1);
INSERT 0 1
postgres=# select pg_current_wal_insert_lsn();pg_current_wal_insert_lsn 
---------------------------0/1696D18
(1 row)
postgres=# select txid_current();txid_current 
--------------735
(1 row)-- 查看WAL日志
postgres@slpc:~/pgsql$ pg_waldump -p pgdata/pg_wal/ -s 0/1696C78 -e 0/1696D18
-- 插入一条数据,堆表, 事务ID 735   
rmgr: Heap        len (rec/tot):     59/    59, tx:        734, lsn: 0/01696C78, prev 0/01696C40, desc: INSERT+INIT off 1 flags 0x00, blkref #0: rel 1663/13010/16384 blk 0 
rmgr: Transaction len (rec/tot):     34/    34, tx:        734, lsn: 0/01696CB8, prev 0/01696C78, desc: COMMIT 2023-09-23 10:58:39.915785 CST
rmgr: Standby     len (rec/tot):     54/    54, tx:          0, lsn: 0/01696CE0, prev 0/01696CB8, desc: RUNNING_XACTS nextXid 735 latestCompletedXid 733 oldestRunningXid 734; 1 xacts: 734-- 设置wal_debug = on
postgres=# set wal_debug = on;
SET
postgres=# select pg_current_wal_lsn();pg_current_wal_lsn 
--------------------0/1696E28
(1 row)postgres=# insert into t1 values(2);
LOG:  INSERT @ 0/1696EC0:  - Heap/INSERT: off 2 flags 0x00
LOG:  INSERT @ 0/1696EE8:  - Transaction/COMMIT: 2023-09-23 11:27:25.399199+08
LOG:  xlog flush request 0/1696EE8; write 0/1696E28; flush 0/1696E28
INSERT 0 1
postgres=# select pg_current_wal_lsn();pg_current_wal_lsn 
--------------------0/1696F20
(1 row)postgres@slpc:~/pgsql$ pg_waldump -p pgdata/pg_wal/ -s 0/1696E28 -e 0/1696F20
rmgr: Heap        len (rec/tot):     54/   150, tx:        736, lsn: 0/01696E28, prev 0/01696DF0, desc: INSERT off 2 flags 0x00, blkref #0: rel 1663/13010/16384 blk 0 FPW
rmgr: Transaction len (rec/tot):     34/    34, tx:        736, lsn: 0/01696EC0, prev 0/01696E28, desc: COMMIT 2023-09-23 11:27:25.399199 CST
rmgr: Standby     len (rec/tot):     50/    50, tx:          0, lsn: 0/01696EE8, prev 0/01696EC0, desc: RUNNING_XACTS nextXid 737 latestCompletedXid 736 oldestRunningXid 737
pg_waldump源码分析

pg_waldump的源码比较简单,在src/bin/pg_waldump中, 执行pg_waldump -p pgdata/pg_wal/ -s 0/1696E28 -e 0/1696F20进行调试。

main(int argc, char **argv)
--> XLogReaderAllocate(WalSegSz, waldir,XL_ROUTINE(.page_read = WALDumpReadPage,.segment_open = WALDumpOpenSegment, .segment_close = WALDumpCloseSegment), &private);// 因为我们是读wal日志的一个范围,从起点到终点,所以,这里第1步要做的就是先找到起始的wal日志记录
--> XLogFindNextRecord(xlogreader_state, private.startptr);for (;;){// 开始读取后续WAL日志/* try to read the next record */record = XLogReadRecord(xlogreader_state, &errormsg);/* perform any per-record work */if (!config.quiet){if (config.stats == true)XLogDumpCountRecord(&config, &stats, xlogreader_state);elseXLogDumpDisplayRecord(&config, xlogreader_state);}/* check whether we printed enough */config.already_displayed_records++;if (config.stop_after_records > 0 &&config.already_displayed_records >= config.stop_after_records)break;}
--> XLogReaderFree(xlogreader_state);	

更详细的代码可以查看:

int main(int argc, char **argv)
{uint32		xlogid;uint32		xrecoff;XLogReaderState *xlogreader_state;XLogDumpPrivate private;XLogDumpConfig config;XLogDumpStats stats;XLogRecord *record;XLogRecPtr	first_record;private.timeline = 1;private.startptr = InvalidXLogRecPtr;     // 起点private.endptr = InvalidXLogRecPtr;       // 终点private.endptr_reached = false;while ((option = getopt_long(argc, argv, "be:fn:p:qr:s:t:x:z", long_options, &optindex)) != -1){switch (option){case 'e':if (sscanf(optarg, "%X/%X", &xlogid, &xrecoff) != 2){pg_log_error("could not parse end WAL location \"%s\"",optarg);goto bad_argument;}private.endptr = (uint64) xlogid << 32 | xrecoff;break;case 's':if (sscanf(optarg, "%X/%X", &xlogid, &xrecoff) != 2){pg_log_error("could not parse start WAL location \"%s\"",optarg);goto bad_argument;}elseprivate.startptr = (uint64) xlogid << 32 | xrecoff;break;// ...}}// .../* done with argument parsing, do the actual work *//* we have everything we need, start reading */// 初始化XLogReader,分配读取所需的内存空间xlogreader_state = XLogReaderAllocate(WalSegSz, waldir, XL_ROUTINE(.page_read = WALDumpReadPage,.segment_open = WALDumpOpenSegment,.segment_close = WALDumpCloseSegment), &private);/* first find a valid recptr to start from */// 找到第一个lsn >= startptr的有效日志记录first_record = XLogFindNextRecord(xlogreader_state, private.startptr);if (first_record == InvalidXLogRecPtr)fatal_error("could not find a valid record after %X/%X",LSN_FORMAT_ARGS(private.startptr));/** Display a message that we're skipping data if `from` wasn't a pointer* to the start of a record and also wasn't a pointer to the beginning of* a segment (e.g. we were used in file mode).*/if (first_record != private.startptr &&XLogSegmentOffset(private.startptr, WalSegSz) != 0)printf(ngettext("first record is after %X/%X, at %X/%X, skipping over %u byte\n","first record is after %X/%X, at %X/%X, skipping over %u bytes\n",(first_record - private.startptr)),LSN_FORMAT_ARGS(private.startptr),LSN_FORMAT_ARGS(first_record),(uint32) (first_record - private.startptr));for (;;){/* try to read the next record */record = XLogReadRecord(xlogreader_state, &errormsg);if (!record){if (!config.follow || private.endptr_reached)break;else{pg_usleep(1000000L);	/* 1 second */continue;}}/* apply all specified filters */if (config.filter_by_rmgr != -1 &&config.filter_by_rmgr != record->xl_rmid)continue;if (config.filter_by_xid_enabled &&config.filter_by_xid != record->xl_xid)continue;/* perform any per-record work */if (!config.quiet){if (config.stats == true)XLogDumpCountRecord(&config, &stats, xlogreader_state);elseXLogDumpDisplayRecord(&config, xlogreader_state);}/* check whether we printed enough */config.already_displayed_records++;if (config.stop_after_records > 0 &&config.already_displayed_records >= config.stop_after_records)break;}if (config.stats == true && !config.quiet)XLogDumpDisplayStats(&config, &stats);if (errormsg)fatal_error("error in WAL record at %X/%X: %s",LSN_FORMAT_ARGS(xlogreader_state->ReadRecPtr),errormsg);XLogReaderFree(xlogreader_state);return EXIT_SUCCESS;bad_argument:fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);return EXIT_FAILURE;
}

参考文档:
pg_waldump

这篇关于PostgreSQL源码分析——pg_waldump的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1074976

相关文章

Java汇编源码如何查看环境搭建

《Java汇编源码如何查看环境搭建》:本文主要介绍如何在IntelliJIDEA开发环境中搭建字节码和汇编环境,以便更好地进行代码调优和JVM学习,首先,介绍了如何配置IntelliJIDEA以方... 目录一、简介二、在IDEA开发环境中搭建汇编环境2.1 在IDEA中搭建字节码查看环境2.1.1 搭建步

Redis主从复制实现原理分析

《Redis主从复制实现原理分析》Redis主从复制通过Sync和CommandPropagate阶段实现数据同步,2.8版本后引入Psync指令,根据复制偏移量进行全量或部分同步,优化了数据传输效率... 目录Redis主DodMIK从复制实现原理实现原理Psync: 2.8版本后总结Redis主从复制实

锐捷和腾达哪个好? 两个品牌路由器对比分析

《锐捷和腾达哪个好?两个品牌路由器对比分析》在选择路由器时,Tenda和锐捷都是备受关注的品牌,各自有独特的产品特点和市场定位,选择哪个品牌的路由器更合适,实际上取决于你的具体需求和使用场景,我们从... 在选购路由器时,锐捷和腾达都是市场上备受关注的品牌,但它们的定位和特点却有所不同。锐捷更偏向企业级和专

Spring中Bean有关NullPointerException异常的原因分析

《Spring中Bean有关NullPointerException异常的原因分析》在Spring中使用@Autowired注解注入的bean不能在静态上下文中访问,否则会导致NullPointerE... 目录Spring中Bean有关NullPointerException异常的原因问题描述解决方案总结

python中的与时间相关的模块应用场景分析

《python中的与时间相关的模块应用场景分析》本文介绍了Python中与时间相关的几个重要模块:`time`、`datetime`、`calendar`、`timeit`、`pytz`和`dateu... 目录1. time 模块2. datetime 模块3. calendar 模块4. timeit

python-nmap实现python利用nmap进行扫描分析

《python-nmap实现python利用nmap进行扫描分析》Nmap是一个非常用的网络/端口扫描工具,如果想将nmap集成进你的工具里,可以使用python-nmap这个python库,它提供了... 目录前言python-nmap的基本使用PortScanner扫描PortScannerAsync异

Oracle数据库执行计划的查看与分析技巧

《Oracle数据库执行计划的查看与分析技巧》在Oracle数据库中,执行计划能够帮助我们深入了解SQL语句在数据库内部的执行细节,进而优化查询性能、提升系统效率,执行计划是Oracle数据库优化器为... 目录一、什么是执行计划二、查看执行计划的方法(一)使用 EXPLAIN PLAN 命令(二)通过 S

PostgreSQL如何查询表结构和索引信息

《PostgreSQL如何查询表结构和索引信息》文章介绍了在PostgreSQL中查询表结构和索引信息的几种方法,包括使用`d`元命令、系统数据字典查询以及使用可视化工具DBeaver... 目录前言使用\d元命令查看表字段信息和索引信息通过系统数据字典查询表结构通过系统数据字典查询索引信息查询所有的表名可

PostgreSQL如何用psql运行SQL文件

《PostgreSQL如何用psql运行SQL文件》文章介绍了两种运行预写好的SQL文件的方式:首先连接数据库后执行,或者直接通过psql命令执行,需要注意的是,文件路径在Linux系统中应使用斜杠/... 目录PostgreSQ编程L用psql运行SQL文件方式一方式二总结PostgreSQL用psql运

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置