From da07a1e856511dca59cbb1357616e26baa64428e Mon Sep 17 00:00:00 2001 From: Alvaro Herrera Date: Thu, 6 Dec 2012 14:57:52 -0300 Subject: Background worker processes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Background workers are postmaster subprocesses that run arbitrary user-specified code. They can request shared memory access as well as backend database connections; or they can just use plain libpq frontend database connections. Modules listed in shared_preload_libraries can register background workers in their _PG_init() function; this is early enough that it's not necessary to provide an extra GUC option, because the necessary extra resources can be allocated early on. Modules can install more than one bgworker, if necessary. Care is taken that these extra processes do not interfere with other postmaster tasks: only one such process is started on each ServerLoop iteration. This means a large number of them could be waiting to be started up and postmaster is still able to quickly service external connection requests. Also, shutdown sequence should not be impacted by a worker process that's reasonably well behaved (i.e. promptly responds to termination signals.) The current implementation lets worker processes specify their start time, i.e. at what point in the server startup process they are to be started: right after postmaster start (in which case they mustn't ask for shared memory access), when consistent state has been reached (useful during recovery in a HOT standby server), or when recovery has terminated (i.e. when normal backends are allowed). In case of a bgworker crash, actions to take depend on registration data: if shared memory was requested, then all other connections are taken down (as well as other bgworkers), just like it were a regular backend crashing. The bgworker itself is restarted, too, within a configurable timeframe (which can be configured to be never). More features to add to this framework can be imagined without much effort, and have been discussed, but this seems good enough as a useful unit already. An elementary sample module is supplied. Author: Álvaro Herrera This patch is loosely based on prior patches submitted by KaiGai Kohei, and unsubmitted code by Simon Riggs. Reviewed by: KaiGai Kohei, Markus Wanner, Andres Freund, Heikki Linnakangas, Simon Riggs, Amit Kapila --- doc/src/sgml/bgworker.sgml | 146 +++++++++++++++++++++++++++++++++++++++++++++ doc/src/sgml/filelist.sgml | 1 + doc/src/sgml/postgres.sgml | 1 + 3 files changed, 148 insertions(+) create mode 100644 doc/src/sgml/bgworker.sgml (limited to 'doc/src') diff --git a/doc/src/sgml/bgworker.sgml b/doc/src/sgml/bgworker.sgml new file mode 100644 index 00000000000..912c7deb8f7 --- /dev/null +++ b/doc/src/sgml/bgworker.sgml @@ -0,0 +1,146 @@ + + + + Background Worker Processes + + + Background workers + + + + PostgreSQL can be extended to run user-supplied code in separate processes. + Such processes are started, stopped and monitored by postgres, + which permits them to have a lifetime closely linked to the server's status. + These processes have the option to attach to PostgreSQL's + shared memory area and to connect to databases internally; they can also run + multiple transactions serially, just like a regular client-connected server + process. Also, by linking to libpq they can connect to the + server and behave like a regular client application. + + + + + There are considerable robustness and security risks in using background + worker processes because, being written in the C language, + they have unrestricted access to data. Administrators wishing to enable + modules that include background worker process should exercise extreme + caution. Only carefully audited modules should be permitted to run + background worker processes. + + + + + Only modules listed in shared_preload_libraries can run + background workers. A module wishing to run a background worker needs + to register it by calling + RegisterBackgroundWorker(BackgroundWorker *worker) + from its _PG_init(). + The structure BackgroundWorker is defined thus: + +typedef void (*bgworker_main_type)(void *main_arg); +typedef void (*bgworker_sighdlr_type)(SIGNAL_ARGS); +typedef struct BackgroundWorker +{ + char *bgw_name; + int bgw_flags; + BgWorkerStartTime bgw_start_time; + int bgw_restart_time; /* in seconds, or BGW_NEVER_RESTART */ + bgworker_main_type bgw_main; + void *bgw_main_arg; + bgworker_sighdlr_type bgw_sighup; + bgworker_sighdlr_type bgw_sigterm; +} BackgroundWorker; + + + + + bgw_name is a string to be used in log messages, process + listings and similar contexts. + + + + bgw_flags is a bitwise-or'd bitmask indicating the + capabilities that the module wants. Possible values are + BGWORKER_SHMEM_ACCESS (requesting shared memory access) + and BGWORKER_BACKEND_DATABASE_CONNECTION (requesting the + ability to establish a database connection, through which it can later run + transactions and queries). + + + + bgw_start_time is the server state during which + postgres should start the process; it can be one of + BgWorkerStart_PostmasterStart (start as soon as + postgres itself has finished its own initialization; processes + requesting this are not eligible for database connections), + BgWorkerStart_ConsistentState (start as soon as a consistent state + has been reached in a HOT standby, allowing processes to connect to + databases and run read-only queries), and + BgWorkerStart_RecoveryFinished (start as soon as the system has + entered normal read-write state). Note the last two values are equivalent + in a server that's not a HOT standby. Note that this setting only indicates + when the processes are to be started; they do not stop when a different state + is reached. + + + + bgw_restart_time is the interval, in seconds, that + postgres should wait before restarting the process, in + case it crashes. It can be any positive value, + or BGW_NEVER_RESTART, indicating not to restart the + process in case of a crash. + + + + bgw_main is a pointer to the function to run when + the process is started. This function must take a single argument of type + void * and return void. + bgw_main_arg will be passed to it as its only + argument. Note that the global variable MyBgworkerEntry + points to a copy of the BackgroundWorker structure + passed at registration time. + + + + bgw_sighup and bgw_sigterm are + pointers to functions that will be installed as signal handlers for the new + process. If bgw_sighup is NULL, then SIG_IGN + is used; if bgw_sigterm is NULL, a handler is installed that + will terminate the process after logging a suitable message. + + + Once running, the process can connect to a database by calling + BackgroundWorkerInitializeConnection(char *dbname, char *username). + This allows the process to run transactions and queries using the + SPI interface. If dbname is NULL, + the session is not connected to any particular database, but shared catalogs + can be accessed. If username is NULL, the process will run as + the superuser created during initdb. + BackgroundWorkerInitializeConnection can only be called once per background + process, it is not possible to switch databases. + + + + Signals are initially blocked when control reaches the + bgw_main function, and must be unblocked by it; this is to + allow the process to further customize its signal handlers, if necessary. + Signals can be unblocked in the new process by calling + BackgroundWorkerUnblockSignals and blocked by calling + BackgroundWorkerBlockSignals. + + + + Background workers are expected to be continuously running; if they exit + cleanly, postgres will restart them immediately. Consider doing + interruptible sleep when they have nothing to do; this can be achieved by + calling WaitLatch(). Make sure the + WL_POSTMASTER_DEATH flag is set when calling that function, and + verify the return code for a prompt exit in the emergency case that + postgres itself has terminated. + + + + The worker_spi contrib module contains a working example, + which demonstrates some useful techniques. + + diff --git a/doc/src/sgml/filelist.sgml b/doc/src/sgml/filelist.sgml index db4cc3a3fba..368f9321c88 100644 --- a/doc/src/sgml/filelist.sgml +++ b/doc/src/sgml/filelist.sgml @@ -50,6 +50,7 @@ + diff --git a/doc/src/sgml/postgres.sgml b/doc/src/sgml/postgres.sgml index 4ef1fc1a6e6..15e4ef641e7 100644 --- a/doc/src/sgml/postgres.sgml +++ b/doc/src/sgml/postgres.sgml @@ -218,6 +218,7 @@ &plpython; &spi; + &bgworker; -- cgit v1.2.3