]> begriffs open source - ai-pg/blob - full-docs/html/bgworker.html
Include links to all subsection html pages, with shorter paths too
[ai-pg] / full-docs / html / bgworker.html
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Chapter 46. Background Worker Processes</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="spi-spi-start-transaction.html" title="SPI_start_transaction" /><link rel="next" href="logicaldecoding.html" title="Chapter 47. Logical Decoding" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">Chapter 46. Background Worker Processes</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="spi-spi-start-transaction.html" title="SPI_start_transaction">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="server-programming.html" title="Part V. Server Programming">Up</a></td><th width="60%" align="center">Part V. Server Programming</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="logicaldecoding.html" title="Chapter 47. Logical Decoding">Next</a></td></tr></table><hr /></div><div class="chapter" id="BGWORKER"><div class="titlepage"><div><div><h2 class="title">Chapter 46. Background Worker Processes</h2></div></div></div><a id="id-1.8.13.2" class="indexterm"></a><p>
3   PostgreSQL can be extended to run user-supplied code in separate processes.
4   Such processes are started, stopped and monitored by <code class="command">postgres</code>,
5   which permits them to have a lifetime closely linked to the server's status.
6   These processes are attached to <span class="productname">PostgreSQL</span>'s
7   shared memory area and have the option to connect to databases internally; they can also run
8   multiple transactions serially, just like a regular client-connected server
9   process.  Also, by linking to <span class="application">libpq</span> they can connect to the
10   server and behave like a regular client application.
11  </p><div class="warning"><h3 class="title">Warning</h3><p>
12    There are considerable robustness and security risks in using background
13    worker processes because, being written in the <code class="literal">C</code> language,
14    they have unrestricted access to data.  Administrators wishing to enable
15    modules that include background worker processes should exercise extreme
16    caution.  Only carefully audited modules should be permitted to run
17    background worker processes.
18   </p></div><p>
19   Background workers can be initialized at the time that
20   <span class="productname">PostgreSQL</span> is started by including the module name in
21   <code class="varname">shared_preload_libraries</code>.  A module wishing to run a background
22   worker can register it by calling
23   <code class="function">RegisterBackgroundWorker(<code class="type">BackgroundWorker</code>
24   *<em class="parameter"><code>worker</code></em>)</code>
25   from its <code class="function">_PG_init()</code> function.
26   Background workers can also be started
27   after the system is up and running by calling
28   <code class="function">RegisterDynamicBackgroundWorker(<code class="type">BackgroundWorker</code>
29   *<em class="parameter"><code>worker</code></em>, <code class="type">BackgroundWorkerHandle</code>
30   **<em class="parameter"><code>handle</code></em>)</code>.  Unlike
31   <code class="function">RegisterBackgroundWorker</code>, which can only be called from
32   within the postmaster process,
33   <code class="function">RegisterDynamicBackgroundWorker</code> must be called
34   from a regular backend or another background worker.
35  </p><p>
36   The structure <code class="structname">BackgroundWorker</code> is defined thus:
37 </p><pre class="programlisting">
38 typedef void (*bgworker_main_type)(Datum main_arg);
39 typedef struct BackgroundWorker
40 {
41     char        bgw_name[BGW_MAXLEN];
42     char        bgw_type[BGW_MAXLEN];
43     int         bgw_flags;
44     BgWorkerStartTime bgw_start_time;
45     int         bgw_restart_time;       /* in seconds, or BGW_NEVER_RESTART */
46     char        bgw_library_name[MAXPGPATH];
47     char        bgw_function_name[BGW_MAXLEN];
48     Datum       bgw_main_arg;
49     char        bgw_extra[BGW_EXTRALEN];
50     pid_t       bgw_notify_pid;
51 } BackgroundWorker;
52 </pre><p>
53   </p><p>
54    <code class="structfield">bgw_name</code> and <code class="structfield">bgw_type</code> are
55    strings to be used in log messages, process listings and similar contexts.
56    <code class="structfield">bgw_type</code> should be the same for all background
57    workers of the same type, so that it is possible to group such workers in a
58    process listing, for example.  <code class="structfield">bgw_name</code> on the
59    other hand can contain additional information about the specific process.
60    (Typically, the string for <code class="structfield">bgw_name</code> will contain
61    the type somehow, but that is not strictly required.)
62   </p><p>
63    <code class="structfield">bgw_flags</code> is a bitwise-or'd bit mask indicating the
64    capabilities that the module wants.  Possible values are:
65    </p><div class="variablelist"><dl class="variablelist"><dt><span class="term"><code class="literal">BGWORKER_SHMEM_ACCESS</code></span></dt><dd><p>
66        <a id="id-1.8.13.8.2.1.2.1.1" class="indexterm"></a>
67        Requests shared memory access.  This flag is required.
68       </p></dd><dt><span class="term"><code class="literal">BGWORKER_BACKEND_DATABASE_CONNECTION</code></span></dt><dd><p>
69        <a id="id-1.8.13.8.2.2.2.1.1" class="indexterm"></a>
70        Requests the ability to establish a database connection through which it
71        can later run transactions and queries.  A background worker using
72        <code class="literal">BGWORKER_BACKEND_DATABASE_CONNECTION</code> to connect to a
73        database must also attach shared memory using
74        <code class="literal">BGWORKER_SHMEM_ACCESS</code>, or worker start-up will fail.
75       </p></dd></dl></div><p>
76
77   </p><p>
78    <code class="structfield">bgw_start_time</code> is the server state during which
79    <code class="command">postgres</code> should start the process; it can be one of
80    <code class="literal">BgWorkerStart_PostmasterStart</code> (start as soon as
81    <code class="command">postgres</code> itself has finished its own initialization; processes
82    requesting this are not eligible for database connections),
83    <code class="literal">BgWorkerStart_ConsistentState</code> (start as soon as a consistent state
84    has been reached in a hot standby, allowing processes to connect to
85    databases and run read-only queries), and
86    <code class="literal">BgWorkerStart_RecoveryFinished</code> (start as soon as the system has
87    entered normal read-write state).  Note the last two values are equivalent
88    in a server that's not a hot standby.  Note that this setting only indicates
89    when the processes are to be started; they do not stop when a different state
90    is reached.
91   </p><p>
92    <code class="structfield">bgw_restart_time</code> is the interval, in seconds, that
93    <code class="command">postgres</code> should wait before restarting the process in
94    the event that it crashes.  It can be any positive value,
95    or <code class="literal">BGW_NEVER_RESTART</code>, indicating not to restart the
96    process in case of a crash.
97   </p><p>
98    <code class="structfield">bgw_library_name</code> is the name of a library in
99    which the initial entry point for the background worker should be sought.
100    The named library will be dynamically loaded by the worker process and
101    <code class="structfield">bgw_function_name</code> will be used to identify the
102    function to be called.  If calling a function in the core code, this must
103    be set to <code class="literal">"postgres"</code>.
104   </p><p>
105    <code class="structfield">bgw_function_name</code> is the name of the function
106    to use as the initial entry point for the new background worker.  If
107    this function is in a dynamically loaded library, it must be marked
108    <code class="literal">PGDLLEXPORT</code> (and not <code class="literal">static</code>).
109   </p><p>
110    <code class="structfield">bgw_main_arg</code> is the <code class="type">Datum</code> argument
111    to the background worker main function.  This main function should take a
112    single argument of type <code class="type">Datum</code> and return <code class="type">void</code>.
113    <code class="structfield">bgw_main_arg</code> will be passed as the argument.
114    In addition, the global variable <code class="literal">MyBgworkerEntry</code>
115    points to a copy of the <code class="structname">BackgroundWorker</code> structure
116    passed at registration time; the worker may find it helpful to examine
117    this structure.
118   </p><p>
119    On Windows (and anywhere else where <code class="literal">EXEC_BACKEND</code> is
120    defined) or in dynamic background workers it is not safe to pass a
121    <code class="type">Datum</code> by reference, only by value. If an argument is required, it
122    is safest to pass an int32 or other small value and use that as an index
123    into an array allocated in shared memory. If a value like a <code class="type">cstring</code>
124    or <code class="type">text</code> is passed then the pointer won't be valid from the
125    new background worker process.
126   </p><p>
127    <code class="structfield">bgw_extra</code> can contain extra data to be passed
128    to the background worker.  Unlike <code class="structfield">bgw_main_arg</code>, this data
129    is not passed as an argument to the worker's main function, but it can be
130    accessed via <code class="literal">MyBgworkerEntry</code>, as discussed above.
131   </p><p>
132    <code class="structfield">bgw_notify_pid</code> is the PID of a PostgreSQL
133    backend process to which the postmaster should send <code class="literal">SIGUSR1</code>
134    when the process is started or exits.  It should be 0 for workers registered
135    at postmaster startup time, or when the backend registering the worker does
136    not wish to wait for the worker to start up.  Otherwise, it should be
137    initialized to <code class="literal">MyProcPid</code>.
138   </p><p>Once running, the process can connect to a database by calling
139    <code class="function">BackgroundWorkerInitializeConnection(<em class="parameter"><code>char *dbname</code></em>, <em class="parameter"><code>char *username</code></em>, <em class="parameter"><code>uint32 flags</code></em>)</code> or
140    <code class="function">BackgroundWorkerInitializeConnectionByOid(<em class="parameter"><code>Oid dboid</code></em>, <em class="parameter"><code>Oid useroid</code></em>, <em class="parameter"><code>uint32 flags</code></em>)</code>.
141    This allows the process to run transactions and queries using the
142    <code class="literal">SPI</code> interface.  If <code class="varname">dbname</code> is NULL or
143    <code class="varname">dboid</code> is <code class="literal">InvalidOid</code>, the session is not connected
144    to any particular database, but shared catalogs can be accessed.
145    If <code class="varname">username</code> is NULL or <code class="varname">useroid</code> is
146    <code class="literal">InvalidOid</code>, the process will run as the superuser created
147    during <code class="command">initdb</code>. If <code class="literal">BGWORKER_BYPASS_ALLOWCONN</code>
148    is specified as <code class="varname">flags</code> it is possible to bypass the restriction
149    to connect to databases not allowing user connections.
150    If <code class="literal">BGWORKER_BYPASS_ROLELOGINCHECK</code> is specified as
151    <code class="varname">flags</code> it is possible to bypass the login check for the
152    role used to connect to databases.
153    A background worker can only call one of these two functions, and only
154    once.  It is not possible to switch databases.
155   </p><p>
156    Signals are initially blocked when control reaches the
157    background worker's main function, and must be unblocked by it; this is to
158    allow the process to customize its signal handlers, if necessary.
159    Signals can be unblocked in the new process by calling
160    <code class="function">BackgroundWorkerUnblockSignals</code> and blocked by calling
161    <code class="function">BackgroundWorkerBlockSignals</code>.
162   </p><p>
163    If <code class="structfield">bgw_restart_time</code> for a background worker is
164    configured as <code class="literal">BGW_NEVER_RESTART</code>, or if it exits with an exit
165    code of 0 or is terminated by <code class="function">TerminateBackgroundWorker</code>,
166    it will be automatically unregistered by the postmaster on exit.
167    Otherwise, it will be restarted after the time period configured via
168    <code class="structfield">bgw_restart_time</code>, or immediately if the postmaster
169    reinitializes the cluster due to a backend failure.  Backends which need
170    to suspend execution only temporarily should use an interruptible sleep
171    rather than exiting; this can be achieved by calling
172    <code class="function">WaitLatch()</code>. Make sure the
173    <code class="literal">WL_POSTMASTER_DEATH</code> flag is set when calling that function, and
174    verify the return code for a prompt exit in the emergency case that
175    <code class="command">postgres</code> itself has terminated.
176   </p><p>
177    When a background worker is registered using the
178    <code class="function">RegisterDynamicBackgroundWorker</code> function, it is
179    possible for the backend performing the registration to obtain information
180    regarding the status of the worker.  Backends wishing to do this should
181    pass the address of a <code class="type">BackgroundWorkerHandle *</code> as the second
182    argument to <code class="function">RegisterDynamicBackgroundWorker</code>.  If the
183    worker is successfully registered, this pointer will be initialized with an
184    opaque handle that can subsequently be passed to
185    <code class="function">GetBackgroundWorkerPid(<em class="parameter"><code>BackgroundWorkerHandle *</code></em>, <em class="parameter"><code>pid_t *</code></em>)</code> or
186    <code class="function">TerminateBackgroundWorker(<em class="parameter"><code>BackgroundWorkerHandle *</code></em>)</code>.
187    <code class="function">GetBackgroundWorkerPid</code> can be used to poll the status of the
188    worker: a return value of <code class="literal">BGWH_NOT_YET_STARTED</code> indicates that
189    the worker has not yet been started by the postmaster;
190    <code class="literal">BGWH_STOPPED</code> indicates that it has been started but is
191    no longer running; and <code class="literal">BGWH_STARTED</code> indicates that it is
192    currently running.  In this last case, the PID will also be returned via the
193    second argument.
194    <code class="function">TerminateBackgroundWorker</code> causes the postmaster to send
195    <code class="literal">SIGTERM</code> to the worker if it is running, and to unregister it
196    as soon as it is not.
197   </p><p>
198    In some cases, a process which registers a background worker may wish to
199    wait for the worker to start up.  This can be accomplished by initializing
200    <code class="structfield">bgw_notify_pid</code> to <code class="literal">MyProcPid</code> and
201    then passing the <code class="type">BackgroundWorkerHandle *</code> obtained at
202    registration time to
203    <code class="function">WaitForBackgroundWorkerStartup(<em class="parameter"><code>BackgroundWorkerHandle
204    *handle</code></em>, <em class="parameter"><code>pid_t *</code></em>)</code> function.
205    This function will block until the postmaster has attempted to start the
206    background worker, or until the postmaster dies.  If the background worker
207    is running, the return value will be <code class="literal">BGWH_STARTED</code>, and
208    the PID will be written to the provided address.  Otherwise, the return
209    value will be <code class="literal">BGWH_STOPPED</code> or
210    <code class="literal">BGWH_POSTMASTER_DIED</code>.
211   </p><p>
212    A process can also wait for a background worker to shut down, by using the
213    <code class="function">WaitForBackgroundWorkerShutdown(<em class="parameter"><code>BackgroundWorkerHandle
214    *handle</code></em>)</code> function and passing the
215    <code class="type">BackgroundWorkerHandle *</code> obtained at registration. This
216    function will block until the background worker exits, or postmaster dies.
217    When the background worker exits, the return value is
218    <code class="literal">BGWH_STOPPED</code>, if postmaster dies it will return
219    <code class="literal">BGWH_POSTMASTER_DIED</code>.
220   </p><p>
221    Background workers can send asynchronous notification messages, either by
222    using the <code class="command">NOTIFY</code> command via <acronym class="acronym">SPI</acronym>,
223    or directly via <code class="function">Async_Notify()</code>.  Such notifications
224    will be sent at transaction commit.
225    Background workers should not register to receive asynchronous
226    notifications with the <code class="command">LISTEN</code> command, as there is no
227    infrastructure for a worker to consume such notifications.
228   </p><p>
229    The <code class="filename">src/test/modules/worker_spi</code> module
230    contains a working example,
231    which demonstrates some useful techniques.
232   </p><p>
233    The maximum number of registered background workers is limited by
234    <a class="xref" href="runtime-config-resource.html#GUC-MAX-WORKER-PROCESSES">max_worker_processes</a>.
235   </p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="spi-spi-start-transaction.html" title="SPI_start_transaction">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="server-programming.html" title="Part V. Server Programming">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="logicaldecoding.html" title="Chapter 47. Logical Decoding">Next</a></td></tr><tr><td width="40%" align="left" valign="top">SPI_start_transaction </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> Chapter 47. Logical Decoding</td></tr></table></div></body></html>