バージョンごとのドキュメント一覧

第48章 バックグラウンドワーカープロセス

<title>Background Worker Processes</title>

PostgreSQL can be extended to run user-supplied code in separate processes. Such processes are started, stopped and monitored by <command>postgres</command>, which permits them to have a lifetime closely linked to the server's status. These processes are attached to <productname>PostgreSQL</productname>'s shared memory area and have the option to connect to databases internally; they can also run multiple transactions serially, just like a regular client-connected server process. Also, by linking to <application>libpq</application> they can connect to the server and behave like a regular client application. PostgreSQLはユーザ提供のコードを別のプロセスとして実行するように拡張できます。 このプロセスはpostgresによって起動、終了、監視され、サーバの状態に密接にリンクした寿命を持つことができます。 これらのプロセスはPostgreSQLの共有メモリ領域にアタッチされ、データベースの内部に接続するオプションを持ちます。 これらはまた、通常のクライアントに接続された実際のサーバプロセスのように複数のトランザクションを連続して実行することができます。 また、アプリケーションはlibpqとリンクすることにより通常のクライアントアプリケーションのようにサーバに接続して動作することができます。

警告

There are considerable robustness and security risks in using background worker processes because, being written in the <literal>C</literal> language, they have unrestricted access to data. Administrators wishing to enable modules that include background worker processes should exercise extreme caution. Only carefully audited modules should be permitted to run background worker processes. バックグラウンドワーカーを使うにあたっては、堅牢性とセキュリティリスクを考慮しなくてはなりません。なぜならば、C言語で書かれており、データへのアクセスが制限されていないためです。 バックグラウンドワーカープロセスを含むモジュールを有効にしたいと思っている管理者は、細心の注意を払って実践してください。 バックグラウンドワーカープロセスの実行は、注意深く検査されたモジュールだけを許可する必要があります。

Background workers can be initialized at the time that <productname>PostgreSQL</productname> is started by including the module name in <varname>shared_preload_libraries</varname>. A module wishing to run a background worker can register it by calling <function>RegisterBackgroundWorker(<type>BackgroundWorker</type> *<parameter>worker</parameter>)</function> from its <function>_PG_init()</function> function. Background workers can also be started after the system is up and running by calling <function>RegisterDynamicBackgroundWorker(<type>BackgroundWorker</type> *<parameter>worker</parameter>, <type>BackgroundWorkerHandle</type> **<parameter>handle</parameter>)</function>. Unlike <function>RegisterBackgroundWorker</function>, which can only be called from within the postmaster process, <function>RegisterDynamicBackgroundWorker</function> must be called from a regular backend or another background worker. バックグラウンドワーカーは、モジュールをshared_preload_librariesに記すことによって、PostgreSQLスタート時に初期化できます。 バックグラウンドワーカーとして実行したいモジュールは、_PG_init()関数からRegisterBackgroundWorker(BackgroundWorker *worker)を呼び出すことで登録できます。 バックグラウンドワーカーはシステム起動後もRegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)を呼び出すことによって開始することができます。 postmasterプロセスからのみ呼び出すことができるRegisterBackgroundWorkerとは異なり、RegisterDynamicBackgroundWorkerは通常のバックエンドまたは他のバックグラウンドワーカーから呼び出す必要があります。

The structure <structname>BackgroundWorker</structname> is defined thus: BackgroundWorkerの構造体は以下のように定義されます。

typedef void (*bgworker_main_type)(Datum main_arg);
typedef struct BackgroundWorker
{
    char        bgw_name[BGW_MAXLEN];
    char        bgw_type[BGW_MAXLEN];
    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];
    Datum       bgw_main_arg;
    char        bgw_extra[BGW_EXTRALEN];
    pid_t       bgw_notify_pid;
} BackgroundWorker;

<structfield>bgw_name</structfield> and <structfield>bgw_type</structfield> are strings to be used in log messages, process listings and similar contexts. <structfield>bgw_type</structfield> should be the same for all background workers of the same type, so that it is possible to group such workers in a process listing, for example. <structfield>bgw_name</structfield> on the other hand can contain additional information about the specific process. (Typically, the string for <structfield>bgw_name</structfield> will contain the type somehow, but that is not strictly required.) bgw_namebgw_typeは、ログメッセージ、プロセス一覧、および同様の場面で使用される文字列です。 bgw_typeは、同じ種類のバックグラウンドワーカーで全て同じになるため、例えば同じ種類のワーカーをプロセス一覧でグループ化することができます。 一方でbgw_nameは、特定のプロセスに関する追加情報を含むことができます。 (通常、bgw_nameの文字列は何らかの形で種類に関する情報を含んでいますが、必須であるというわけではありません。)

<structfield>bgw_flags</structfield> is a bitwise-or'd bit mask indicating the capabilities that the module wants. Possible values are: bgw_flagsは、モジュールが要求する機能をOR演算したビットマスクです。可能な値は以下の通りです。

BGWORKER_SHMEM_ACCESS

Requests shared memory access. This flag is required. 共有メモリへのアクセスを要求します。 このフラグは必須です。

BGWORKER_BACKEND_DATABASE_CONNECTION

<indexterm><primary>BGWORKER_BACKEND_&zwsp;DATABASE_CONNECTION</primary></indexterm> Requests the ability to establish a database connection through which it can later run transactions and queries. A background worker using <literal>BGWORKER_BACKEND_DATABASE_CONNECTION</literal> to connect to a database must also attach shared memory using <literal>BGWORKER_SHMEM_ACCESS</literal>, or worker start-up will fail. トランザクションやクエリの実行が出来るデータベース接続を要求します。 BGWORKER_BACKEND_DATABASE_CONNECTIONを使用してデータベースに接続するバックグラウンドワーカーはBGWORKER_SHMEM_ACCESSを使用して共有メモリにアタッチしなければなりません。さもなければ起動時に失敗します。

<structfield>bgw_start_time</structfield> is the server state during which <command>postgres</command> should start the process; it can be one of <literal>BgWorkerStart_PostmasterStart</literal> (start as soon as <command>postgres</command> itself has finished its own initialization; processes requesting this are not eligible for database connections), <literal>BgWorkerStart_ConsistentState</literal> (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 <literal>BgWorkerStart_RecoveryFinished</literal> (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_start_timeは、postgresがプロセスを起動するべきタイミングを指定します。 そのタイミングは、以下のうちの1つです。 BgWorkerStart_PostmasterStartpostgres自身が初期化を終えるとすぐに起動します。これを要求するプロセスはデータベース接続に望ましいものではありません)、 BgWorkerStart_ConsistentState(ホットスタンバイで一貫性のある状態に到達し、データベースに接続して参照のみのクエリが実行できるようになると起動します)、 BgWorkerStart_RecoveryFinished(システムが通常の参照/更新クエリを実行できるようになると起動します)。 最後の2つの値は、ホットスタンバイでないサーバでは同等であることに注意してください。 この設定はいつプロセスが起動されるかを示すだけであることに注意してください。 これらのプロセスは、違う状態になったときに停止するわけではありません。

<structfield>bgw_restart_time</structfield> is the interval, in seconds, that <command>postgres</command> should wait before restarting the process in the event that it crashes. It can be any positive value, or <literal>BGW_NEVER_RESTART</literal>, indicating not to restart the process in case of a crash. bgw_restart_timeは、万が一プロセスがクラッシュした場合にpostgresがそのプロセスを再起動するために待つ必要のある間隔を秒単位で指定します。 これは任意の正の値、またはクラッシュしても再起動させない場合にBGW_NEVER_RESTARTを指定します。

<structfield>bgw_library_name</structfield> is the name of a library in which the initial entry point for the background worker should be sought. The named library will be dynamically loaded by the worker process and <structfield>bgw_function_name</structfield> will be used to identify the function to be called. If calling a function in the core code, this must be set to <literal>"postgres"</literal>. bgw_library_nameは、バックグラウンドワーカーの初期エントリーポイントのためのライブラリ名です。 その指定されたライブラリがワーカープロセスによって動的にロードされます。呼び出すべき関数を特定するためにbgw_function_nameが使用されます。 コアコード内の関数を呼び出す場合、"postgres"を設定する必要があります。

<structfield>bgw_function_name</structfield> is the name of the function to use as the initial entry point for the new background worker. If this function is in a dynamically loaded library, it must be marked <literal>PGDLLEXPORT</literal> (and not <literal>static</literal>). bgw_function_nameは、新しいバックグラウンドワーカーの初期エントリポイントとして使用する関数の名前です。 この関数が動的にロードされたライブラリ内にある場合、PGDLLEXPORTstaticではない)とマークする必要があります。

<structfield>bgw_main_arg</structfield> is the <type>Datum</type> argument to the background worker main function. This main function should take a single argument of type <type>Datum</type> and return <type>void</type>. <structfield>bgw_main_arg</structfield> will be passed as the argument. In addition, the global variable <literal>MyBgworkerEntry</literal> points to a copy of the <structname>BackgroundWorker</structname> structure passed at registration time; the worker may find it helpful to examine this structure. bgw_main_argは、バックグラウンドワーカーのメイン関数のDatum引数です。 メイン関数は単一のDatum引数を取り、voidを返します。 bgw_main_argは引数として渡されます。 加えて、グローバル変数MyBgworkerEntryは、登録時に渡されたBackgroundWorker構造体のコピーを指しています。 ワーカーはこの構造を調べることがあり、役に立ちます。

On Windows (and anywhere else where <literal>EXEC_BACKEND</literal> is defined) or in dynamic background workers it is not safe to pass a <type>Datum</type> by reference, only by value. If an argument is required, it is safest to pass an int32 or other small value and use that as an index into an array allocated in shared memory. If a value like a <type>cstring</type> or <type>text</type> is passed then the pointer won't be valid from the new background worker process. Windowsの(どこか他の場所でEXEC_BACKENDが定義されている)場合、または動的バックグラウンドワーカーは、Datumを参照で渡すのは安全ではありません。値のみで渡してください。 引数が必要な場合は、int32型または他の小さな値を渡し、共有メモリに割り当てられた配列へのインデックスとしてそれを使用するのが最も安全です。 cstringtextのようなポインタを渡された場合は、新しいバックグラウンドワーカープロセスから有効になりません。

<structfield>bgw_extra</structfield> can contain extra data to be passed to the background worker. Unlike <structfield>bgw_main_arg</structfield>, this data is not passed as an argument to the worker's main function, but it can be accessed via <literal>MyBgworkerEntry</literal>, as discussed above. bgw_extraはバックグラウンドワーカーに渡す追加データを含めることが出来ます。 bgw_main_argとは異なり、このデータはワーカーのメイン関数の引数として渡されていませんが、上述したようにMyBgworkerEntryを介してアクセスすることが出来ます。

<structfield>bgw_notify_pid</structfield> is the PID of a PostgreSQL backend process to which the postmaster should send <literal>SIGUSR1</literal> when the process is started or exits. It should be 0 for workers registered at postmaster startup time, or when the backend registering the worker does not wish to wait for the worker to start up. Otherwise, it should be initialized to <literal>MyProcPid</literal>. bgw_notify_pidは、プロセスの開始時と終了時にpostmasterがSIGUSR1を送信するPostgreSQLバックエンドプロセスのPIDです。 それはpostmasterの起動時に登録されたワーカーの場合、またはワーカーを登録しているバックエンドがワーカーの起動を待ちたくない場合は0にする必要があります。 それ以外の場合は、MyProcPidで初期化する必要があります。

<para>Once running, the process can connect to a database by calling <function>BackgroundWorkerInitializeConnection(<parameter>char *dbname</parameter>, <parameter>char *username</parameter>, <parameter>uint32 flags</parameter>)</function> or <function>BackgroundWorkerInitializeConnectionByOid(<parameter>Oid dboid</parameter>, <parameter>Oid useroid</parameter>, <parameter>uint32 flags</parameter>)</function>. This allows the process to run transactions and queries using the <literal>SPI</literal> interface. If <varname>dbname</varname> is NULL or <varname>dboid</varname> is <literal>InvalidOid</literal>, the session is not connected to any particular database, but shared catalogs can be accessed. If <varname>username</varname> is NULL or <varname>useroid</varname> is <literal>InvalidOid</literal>, the process will run as the superuser created during <command>initdb</command>. If <literal>BGWORKER_BYPASS_ALLOWCONN</literal> is specified as <varname>flags</varname> it is possible to bypass the restriction to connect to databases not allowing user connections. A background worker can only call one of these two functions, and only once. It is not possible to switch databases. </para>

ひとたび実行すると、このプロセスはBackgroundWorkerInitializeConnection(char *dbname, char *username, uint32 flags)またはBackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)を呼び出すことによって、データベースに接続できます。 これはプロセスにSPIインタフェースを使用してのトランザクションとクエリの実行を許します。 もし、dbnameがNULLであった場合、またはdboidInvalidOidであった場合には、そのセッションは特定のデータベースに接続しません。しかし、共有カタログにはアクセス出来ます。 もし、usernameがNULLの場合、またはuseroidInvalidOidの場合には、そのプロセスはinitdb時に作成されたスーパーユーザとして実行されます。 flagsとしてBGWORKER_BYPASS_ALLOWCONNが設定されている場合、データベースへ接続する際のユーザ接続を許可しない制約を回避することが出来ます。 バックグラウンドワーカーはこれら2つの関数をどちらかを一度だけ呼ぶことが出来ます。 データベースを切り替えることができません。

Signals are initially blocked when control reaches the background worker's main function, and must be unblocked by it; this is to allow the process to customize its signal handlers, if necessary. Signals can be unblocked in the new process by calling <function>BackgroundWorkerUnblockSignals</function> and blocked by calling <function>BackgroundWorkerBlockSignals</function>. バックグラウンドワーカーのメイン関数に制御が達したとき、シグナルは最初にブロックされています。このブロックは解除されなければなりません。 これは、必要に応じてプロセスがシグナルハンドラをカスタマイズできるようにするためです。 シグナルは、新しいプロセスでBackgroundWorkerUnblockSignalsを呼び出すことにより解除でき、BackgroundWorkerBlockSignalsを呼び出すことでブロックできます。

If <structfield>bgw_restart_time</structfield> for a background worker is configured as <literal>BGW_NEVER_RESTART</literal>, or if it exits with an exit code of 0 or is terminated by <function>TerminateBackgroundWorker</function>, it will be automatically unregistered by the postmaster on exit. Otherwise, it will be restarted after the time period configured via <structfield>bgw_restart_time</structfield>, or immediately if the postmaster reinitializes the cluster due to a backend failure. Backends which need to suspend execution only temporarily should use an interruptible sleep rather than exiting; this can be achieved by calling <function>WaitLatch()</function>. Make sure the <literal>WL_POSTMASTER_DEATH</literal> flag is set when calling that function, and verify the return code for a prompt exit in the emergency case that <command>postgres</command> itself has terminated. バックグラウンドワーカーは、bgw_restart_timeBGW_NEVER_RESTARTに設定されている場合、または終了コード0で終了した場合、またはTerminateBackgroundWorkerによって終了した場合、postmasterに自動的に登録が解除されて終了します。 それ以外の場合、bgw_restart_timeで設定された時間の後に再起動します。または、バックエンドの障害のためにpostmasterがクラスタを再初期化した場合は、すぐに再起動します。 一時的に実行を中断するだけでよいバックエンドは、終了するのではなく、割り込み可能なスリープを使用する必要があります。 これはWaitLatch()を呼び出すことによって可能になります。 この関数を呼び出すときにはWL_POSTMASTER_DEATHフラグが設定されているか確認し、postgres自身が終了する緊急事態には、リターンコードを確認するようにしてください。

When a background worker is registered using the <function>RegisterDynamicBackgroundWorker</function> function, it is possible for the backend performing the registration to obtain information regarding the status of the worker. Backends wishing to do this should pass the address of a <type>BackgroundWorkerHandle *</type> as the second argument to <function>RegisterDynamicBackgroundWorker</function>. If the worker is successfully registered, this pointer will be initialized with an opaque handle that can subsequently be passed to <function>GetBackgroundWorkerPid(<parameter>BackgroundWorkerHandle *</parameter>, <parameter>pid_t *</parameter>)</function> or <function>TerminateBackgroundWorker(<parameter>BackgroundWorkerHandle *</parameter>)</function>. <function>GetBackgroundWorkerPid</function> can be used to poll the status of the worker: a return value of <literal>BGWH_NOT_YET_STARTED</literal> indicates that the worker has not yet been started by the postmaster; <literal>BGWH_STOPPED</literal> indicates that it has been started but is no longer running; and <literal>BGWH_STARTED</literal> indicates that it is currently running. In this last case, the PID will also be returned via the second argument. <function>TerminateBackgroundWorker</function> causes the postmaster to send <literal>SIGTERM</literal> to the worker if it is running, and to unregister it as soon as it is not. バックグラウンドワーカーをRegisterDynamicBackgroundWorker関数により登録している場合、登録を実行するバックエンドはワーカーの状態に関する情報を取得することが可能です。 取得したい場合はRegisterDynamicBackgroundWorkerに2番目の引数としてBackgroundWorkerHandle *のアドレスを渡す必要があります。 もし登録に成功した場合、このポインタは後でGetBackgroundWorkerPid(BackgroundWorkerHandle *,pid_t *)またはTerminateBackgroundWorker(BackgroundWorkerHandle *)に渡すことができるopaque(不透明)ハンドルで、初期化されます。 GetBackgroundWorkerPidはワーカーの状態を監視することができます。以下の返り値が得られます。 BGWH_NOT_YET_STARTEDワーカーはまだpostmasterにより開始されていない。 BGWH_STOPPED開始されたが、もはや実行されていない。 BGWH_STARTED実行中です。 この最後のケースでは、PIDは、2番目の引数を介して返されます。 TerminateBackgroundWorkerはワーカーが実行していた場合postmasterがワーカーにSIGTERMを送信し、実行が終了次第すぐに登録を解除します。

In some cases, a process which registers a background worker may wish to wait for the worker to start up. This can be accomplished by initializing <structfield>bgw_notify_pid</structfield> to <literal>MyProcPid</literal> and then passing the <type>BackgroundWorkerHandle *</type> obtained at registration time to <function>WaitForBackgroundWorkerStartup(<parameter>BackgroundWorkerHandle *handle</parameter>, <parameter>pid_t *</parameter>)</function> function. This function will block until the postmaster has attempted to start the background worker, or until the postmaster dies. If the background worker is running, the return value will be <literal>BGWH_STARTED</literal>, and the PID will be written to the provided address. Otherwise, the return value will be <literal>BGWH_STOPPED</literal> or <literal>BGWH_POSTMASTER_DIED</literal>. 場合によっては、バックグラウンドワーカーが起動するのを待ってから、ワーカーを登録したい場合もあるでしょう。 これは bgw_notify_pidMyProcPidで初期化し、登録時に得られたBackgroundWorkerHandle *を使用してWaitForBackgroundWorkerStartup(BackgroundWorkerHandle *handle,pid_t *)関数を呼び出すことで実現します。 postmasterがバックグラウンドワーカーを開始しようと試みたか、postmasterが死ぬまで、この関数はブロックします。 バックグラウンドワーカーが実行されている場合、戻り値はBGWH_STARTEDとなり、指定されたアドレスにPIDが書き込まれます。 そうでない場合、戻り値はBGWH_STOPPEDまたはBGWH_POSTMASTER_DIEDになります。

A process can also wait for a background worker to shut down, by using the <function>WaitForBackgroundWorkerShutdown(<parameter>BackgroundWorkerHandle *handle</parameter>)</function> function and passing the <type>BackgroundWorkerHandle *</type> obtained at registration. This function will block until the background worker exits, or postmaster dies. When the background worker exits, the return value is <literal>BGWH_STOPPED</literal>, if postmaster dies it will return <literal>BGWH_POSTMASTER_DIED</literal>. 登録時に得られたBackgroundWorkerHandle *を使用してWaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)関数を呼び出すことで、バックグラウンドワーカーがシャットダウンするのを待つこともできます。 バックグラウンドワーカーが終了するか、postmasterが死ぬまで、この関数はブロックします。 バックグラウンドワーカーが終了した場合の戻り値はBGWH_STOPPED、postmasterが死んだ場合の戻り値はBGWH_POSTMASTER_DIEDになります。

Background workers can send asynchronous notification messages, either by using the <command>NOTIFY</command> command via <acronym>SPI</acronym>, or directly via <function>Async_Notify()</function>. Such notifications will be sent at transaction commit. Background workers should not register to receive asynchronous notifications with the <command>LISTEN</command> command, as there is no infrastructure for a worker to consume such notifications. バックグラウンドワーカーは、SPI経由でNOTIFYコマンドを使用して、あるいはAsync_Notify()で直接、非同期通知メッセージを送ることができます。 そのような通知はトランザクションのコミット時に送信されます。 バックグラウンドワーカーは、LISTENコマンドによる非同期通知メッセージの受信登録をすべきではありません。 ワーカーがそのような通知を消費する基盤が存在しないからです。

The <filename>src/test/modules/worker_spi</filename> module contains a working example, which demonstrates some useful techniques. バックグラウンドワーカーの実例として、src/test/modules/worker_spiというモジュールがあります。 これはいくつかの有用な技術を示しています。

The maximum number of registered background workers is limited by <xref linkend="guc-max-worker-processes"/>. 登録できるバックグラウンドワーカーの最大数はmax_worker_processesによって制限されています。