Postgresql-后台进程

通俗来讲,就是运行在后台的一个或多个工作线程。 可以以扩展的方式存在。该进程的启动/停止/监控都是通过postgres来管理的。

1
2
3
4
5
6
7
8
9
10
11
12
13
# source:src/include/postmaster/bgworker.h
typedef struct BackgroundWorker
{
char bgw_name[BGW_MAXLEN]; //后台bgw的名称
int bgw_flags;
BgWorkerStartTime bgw_start_time;
int bgw_restart_time; /* in seconds, or BGW_NEVER_RESTART */
char bgw_library_name[BGW_MAXLEN]; # 动态库的名称
char bgw_function_name[BGW_MAXLEN]; # bgw的进程主函数
Datum bgw_main_arg; # 进程主函数的入参
char bgw_extra[BGW_EXTRALEN]; # MyBgworkerEntry的参数。
pid_t bgw_notify_pid; /* SIGUSR1 this backend on start/stop */
} BackgroundWorker;



bgw_flags取值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
* Pass this flag to have your worker be able to connect to shared memory.
*/
#define BGWORKER_SHMEM_ACCESS 0x0001 # 是否允许访问共享内存


/*
* This flag means the bgworker requires a database connection. The connection
* is not established automatically; the worker must establish it later.
* It requires that BGWORKER_SHMEM_ACCESS was passed too.
*/
#define BGWORKER_BACKEND_DATABASE_CONNECTION 0x0002 # 是否允许连接数据库

/*
* This class is used internally for parallel queries, to keep track of the
* number of active parallel workers and make sure we never launch more than
* max_parallel_workers parallel workers at the same time. Third party
* background workers should not use this class.
*/
#define BGWORKER_CLASS_PARALLEL 0x0010 # 是否允许并行执行query

bgw_start_time启动模式取值:

1
2
3
4
5
6
typedef enum
{
BgWorkerStart_PostmasterStart, # 紧随postmaster一起启动(不能连接数据库)
BgWorkerStart_ConsistentState, # 只是在热备模式中是一致状态,就允许启动(只能是只读模式)
BgWorkerStart_RecoveryFinished # 数据库进入一切正常模式,能正常的进行读写
} BgWorkerStartTime;

如何启动工作:

  • static(RegisterBackgroundWorker)
  1. 首先判断Postmaster是否启动
  2. 判断动态库是否添加配置文件shard_preload_libraries以及动态库名字是否等于”postgres”
  3. SanityCheckBackgroundWorker(worker, LOG) 参数
    1. 检查 bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION
    2. workrt->bgw_restart_time
  4. bgw_notify_pid 是否 == 0
  5. ++numworkers > max_worker_processes 判断后台worker processes 是否大于最大max_worker_processes
  6. 插入slist_push_head(); 单链表;

GDB调试postgres数据

1
2
3
4
5
6
7
8
9
bgw_name = "logical replication launcher", '\000' <repeats 35 times>, 
bgw_flags = 3,
bgw_start_time = BgWorkerStart_RecoveryFinished,
bgw_restart_time = 5,
bgw_library_name = "postgres", '\000' <repeats 55 times>,
bgw_function_name = "ApplyLauncherMain", '\000' <repeats 46 times>,
bgw_main_arg = 0,
bgw_extra = '\000' <repeats 127 times>,
bgw_notify_pid = 0

示例

欣赏此文? 求鼓励,求支持!