gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

233 line
18KB

  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 47. 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 V1.79.1" /><link rel="prev" href="spi-spi-start-transaction.html" title="SPI_start_transaction" /><link rel="next" href="logicaldecoding.html" title="Chapter 48. Logical Decoding" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">Chapter 47. 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 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="logicaldecoding.html" title="Chapter 48. Logical Decoding">Next</a></td></tr></table><hr></hr></div><div class="chapter" id="BGWORKER"><div class="titlepage"><div><div><h2 class="title">Chapter 47. 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 have the option to attach to <span class="productname">PostgreSQL</span>'s
  7. shared memory area and 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 *worker</code>)</code>
  24. from its <code class="function">_PG_init()</code>. Background workers can also be started
  25. after the system is up and running by calling the function
  26. <code class="function">RegisterDynamicBackgroundWorker(<code class="type">BackgroundWorker
  27. *worker, BackgroundWorkerHandle **handle</code>)</code>. Unlike
  28. <code class="function">RegisterBackgroundWorker</code>, which can only be called from within
  29. the postmaster, <code class="function">RegisterDynamicBackgroundWorker</code> must be
  30. called from a regular backend or another background worker.
  31. </p><p>
  32. The structure <code class="structname">BackgroundWorker</code> is defined thus:
  33. </p><pre class="programlisting">
  34. typedef void (*bgworker_main_type)(Datum main_arg);
  35. typedef struct BackgroundWorker
  36. {
  37. char bgw_name[BGW_MAXLEN];
  38. char bgw_type[BGW_MAXLEN];
  39. int bgw_flags;
  40. BgWorkerStartTime bgw_start_time;
  41. int bgw_restart_time; /* in seconds, or BGW_NEVER_RESTART */
  42. char bgw_library_name[BGW_MAXLEN];
  43. char bgw_function_name[BGW_MAXLEN];
  44. Datum bgw_main_arg;
  45. char bgw_extra[BGW_EXTRALEN];
  46. int bgw_notify_pid;
  47. } BackgroundWorker;
  48. </pre><p>
  49. </p><p>
  50. <code class="structfield">bgw_name</code> and <code class="structfield">bgw_type</code> are
  51. strings to be used in log messages, process listings and similar contexts.
  52. <code class="structfield">bgw_type</code> should be the same for all background
  53. workers of the same type, so that it is possible to group such workers in a
  54. process listing, for example. <code class="structfield">bgw_name</code> on the
  55. other hand can contain additional information about the specific process.
  56. (Typically, the string for <code class="structfield">bgw_name</code> will contain
  57. the type somehow, but that is not strictly required.)
  58. </p><p>
  59. <code class="structfield">bgw_flags</code> is a bitwise-or'd bit mask indicating the
  60. capabilities that the module wants. Possible values are:
  61. </p><div class="variablelist"><dl class="variablelist"><dt><span class="term"><code class="literal">BGWORKER_SHMEM_ACCESS</code></span></dt><dd><p>
  62. <a id="id-1.8.13.8.2.1.2.1.1" class="indexterm"></a>
  63. Requests shared memory access. Workers without shared memory access
  64. cannot access any of <span class="productname">PostgreSQL's</span> shared
  65. data structures, such as heavyweight or lightweight locks, shared
  66. buffers, or any custom data structures which the worker itself may
  67. wish to create and use.
  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. </p><p>
  77. <code class="structfield">bgw_start_time</code> is the server state during which
  78. <code class="command">postgres</code> should start the process; it can be one of
  79. <code class="literal">BgWorkerStart_PostmasterStart</code> (start as soon as
  80. <code class="command">postgres</code> itself has finished its own initialization; processes
  81. requesting this are not eligible for database connections),
  82. <code class="literal">BgWorkerStart_ConsistentState</code> (start as soon as a consistent state
  83. has been reached in a hot standby, allowing processes to connect to
  84. databases and run read-only queries), and
  85. <code class="literal">BgWorkerStart_RecoveryFinished</code> (start as soon as the system has
  86. entered normal read-write state). Note the last two values are equivalent
  87. in a server that's not a hot standby. Note that this setting only indicates
  88. when the processes are to be started; they do not stop when a different state
  89. is reached.
  90. </p><p>
  91. <code class="structfield">bgw_restart_time</code> is the interval, in seconds, that
  92. <code class="command">postgres</code> should wait before restarting the process, in
  93. case it crashes. It can be any positive value,
  94. or <code class="literal">BGW_NEVER_RESTART</code>, indicating not to restart the
  95. process in case of a crash.
  96. </p><p>
  97. <code class="structfield">bgw_library_name</code> is the name of a library in
  98. which the initial entry point for the background worker should be sought.
  99. The named library will be dynamically loaded by the worker process and
  100. <code class="structfield">bgw_function_name</code> will be used to identify the
  101. function to be called. If loading a function from the core code, this must
  102. be set to "postgres".
  103. </p><p>
  104. <code class="structfield">bgw_function_name</code> is the name of a function in
  105. a dynamically loaded library which should be used as the initial entry point
  106. for a new background worker.
  107. </p><p>
  108. <code class="structfield">bgw_main_arg</code> is the <code class="type">Datum</code> argument
  109. to the background worker main function. This main function should take a
  110. single argument of type <code class="type">Datum</code> and return <code class="type">void</code>.
  111. <code class="structfield">bgw_main_arg</code> will be passed as the argument.
  112. In addition, the global variable <code class="literal">MyBgworkerEntry</code>
  113. points to a copy of the <code class="structname">BackgroundWorker</code> structure
  114. passed at registration time; the worker may find it helpful to examine
  115. this structure.
  116. </p><p>
  117. On Windows (and anywhere else where <code class="literal">EXEC_BACKEND</code> is
  118. defined) or in dynamic background workers it is not safe to pass a
  119. <code class="type">Datum</code> by reference, only by value. If an argument is required, it
  120. is safest to pass an int32 or other small value and use that as an index
  121. into an array allocated in shared memory. If a value like a <code class="type">cstring</code>
  122. or <code class="type">text</code> is passed then the pointer won't be valid from the
  123. new background worker process.
  124. </p><p>
  125. <code class="structfield">bgw_extra</code> can contain extra data to be passed
  126. to the background worker. Unlike <code class="structfield">bgw_main_arg</code>, this data
  127. is not passed as an argument to the worker's main function, but it can be
  128. accessed via <code class="literal">MyBgworkerEntry</code>, as discussed above.
  129. </p><p>
  130. <code class="structfield">bgw_notify_pid</code> is the PID of a PostgreSQL
  131. backend process to which the postmaster should send <code class="literal">SIGUSR1</code>
  132. when the process is started or exits. It should be 0 for workers registered
  133. at postmaster startup time, or when the backend registering the worker does
  134. not wish to wait for the worker to start up. Otherwise, it should be
  135. initialized to <code class="literal">MyProcPid</code>.
  136. </p><p>Once running, the process can connect to a database by calling
  137. <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
  138. <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>.
  139. This allows the process to run transactions and queries using the
  140. <code class="literal">SPI</code> interface. If <code class="varname">dbname</code> is NULL or
  141. <code class="varname">dboid</code> is <code class="literal">InvalidOid</code>, the session is not connected
  142. to any particular database, but shared catalogs can be accessed.
  143. If <code class="varname">username</code> is NULL or <code class="varname">useroid</code> is
  144. <code class="literal">InvalidOid</code>, the process will run as the superuser created
  145. during <code class="command">initdb</code>. If <code class="literal">BGWORKER_BYPASS_ALLOWCONN</code>
  146. is specified as <code class="varname">flags</code> it is possible to bypass the restriction
  147. to connect to databases not allowing user connections.
  148. A background worker can only call one of these two functions, and only
  149. once. It is not possible to switch databases.
  150. </p><p>
  151. Signals are initially blocked when control reaches the
  152. background worker's main function, and must be unblocked by it; this is to
  153. allow the process to customize its signal handlers, if necessary.
  154. Signals can be unblocked in the new process by calling
  155. <code class="function">BackgroundWorkerUnblockSignals</code> and blocked by calling
  156. <code class="function">BackgroundWorkerBlockSignals</code>.
  157. </p><p>
  158. If <code class="structfield">bgw_restart_time</code> for a background worker is
  159. configured as <code class="literal">BGW_NEVER_RESTART</code>, or if it exits with an exit
  160. code of 0 or is terminated by <code class="function">TerminateBackgroundWorker</code>,
  161. it will be automatically unregistered by the postmaster on exit.
  162. Otherwise, it will be restarted after the time period configured via
  163. <code class="structfield">bgw_restart_time</code>, or immediately if the postmaster
  164. reinitializes the cluster due to a backend failure. Backends which need
  165. to suspend execution only temporarily should use an interruptible sleep
  166. rather than exiting; this can be achieved by calling
  167. <code class="function">WaitLatch()</code>. Make sure the
  168. <code class="literal">WL_POSTMASTER_DEATH</code> flag is set when calling that function, and
  169. verify the return code for a prompt exit in the emergency case that
  170. <code class="command">postgres</code> itself has terminated.
  171. </p><p>
  172. When a background worker is registered using the
  173. <code class="function">RegisterDynamicBackgroundWorker</code> function, it is
  174. possible for the backend performing the registration to obtain information
  175. regarding the status of the worker. Backends wishing to do this should
  176. pass the address of a <code class="type">BackgroundWorkerHandle *</code> as the second
  177. argument to <code class="function">RegisterDynamicBackgroundWorker</code>. If the
  178. worker is successfully registered, this pointer will be initialized with an
  179. opaque handle that can subsequently be passed to
  180. <code class="function">GetBackgroundWorkerPid(<em class="parameter"><code>BackgroundWorkerHandle *</code></em>, <em class="parameter"><code>pid_t *</code></em>)</code> or
  181. <code class="function">TerminateBackgroundWorker(<em class="parameter"><code>BackgroundWorkerHandle *</code></em>)</code>.
  182. <code class="function">GetBackgroundWorkerPid</code> can be used to poll the status of the
  183. worker: a return value of <code class="literal">BGWH_NOT_YET_STARTED</code> indicates that
  184. the worker has not yet been started by the postmaster;
  185. <code class="literal">BGWH_STOPPED</code> indicates that it has been started but is
  186. no longer running; and <code class="literal">BGWH_STARTED</code> indicates that it is
  187. currently running. In this last case, the PID will also be returned via the
  188. second argument.
  189. <code class="function">TerminateBackgroundWorker</code> causes the postmaster to send
  190. <code class="literal">SIGTERM</code> to the worker if it is running, and to unregister it
  191. as soon as it is not.
  192. </p><p>
  193. In some cases, a process which registers a background worker may wish to
  194. wait for the worker to start up. This can be accomplished by initializing
  195. <code class="structfield">bgw_notify_pid</code> to <code class="literal">MyProcPid</code> and
  196. then passing the <code class="type">BackgroundWorkerHandle *</code> obtained at
  197. registration time to
  198. <code class="function">WaitForBackgroundWorkerStartup(<em class="parameter"><code>BackgroundWorkerHandle
  199. *handle</code></em>, <em class="parameter"><code>pid_t *</code></em>)</code> function.
  200. This function will block until the postmaster has attempted to start the
  201. background worker, or until the postmaster dies. If the background worker
  202. is running, the return value will be <code class="literal">BGWH_STARTED</code>, and
  203. the PID will be written to the provided address. Otherwise, the return
  204. value will be <code class="literal">BGWH_STOPPED</code> or
  205. <code class="literal">BGWH_POSTMASTER_DIED</code>.
  206. </p><p>
  207. A process can also wait for a background worker to shut down, by using the
  208. <code class="function">WaitForBackgroundWorkerShutdown(<em class="parameter"><code>BackgroundWorkerHandle
  209. *handle</code></em>)</code> function and passing the
  210. <code class="type">BackgroundWorkerHandle *</code> obtained at registration. This
  211. function will block until the background worker exits, or postmaster dies.
  212. When the background worker exits, the return value is
  213. <code class="literal">BGWH_STOPPED</code>, if postmaster dies it will return
  214. <code class="literal">BGWH_POSTMASTER_DIED</code>.
  215. </p><p>
  216. If a background worker sends asynchronous notifications with the
  217. <code class="command">NOTIFY</code> command via the Server Programming Interface
  218. (<acronym class="acronym">SPI</acronym>), it should call
  219. <code class="function">ProcessCompletedNotifies</code> explicitly after committing
  220. the enclosing transaction so that any notifications can be delivered. If a
  221. background worker registers to receive asynchronous notifications with
  222. the <code class="command">LISTEN</code> through <acronym class="acronym">SPI</acronym>, the worker
  223. will log those notifications, but there is no programmatic way for the
  224. worker to intercept and respond to those notifications.
  225. </p><p>
  226. The <code class="filename">src/test/modules/worker_spi</code> module
  227. contains a working example,
  228. which demonstrates some useful techniques.
  229. </p><p>
  230. The maximum number of registered background workers is limited by
  231. <a class="xref" href="runtime-config-resource.html#GUC-MAX-WORKER-PROCESSES">max_worker_processes</a>.
  232. </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">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="server-programming.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="logicaldecoding.html">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">Home</a></td><td width="40%" align="right" valign="top"> Chapter 48. Logical Decoding</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1