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

19.4. カーネルリソースの管理 #

<title>Managing Kernel Resources</title>

<productname>PostgreSQL</productname> can sometimes exhaust various operating system resource limits, especially when multiple copies of the server are running on the same system, or in very large installations. This section explains the kernel resources used by <productname>PostgreSQL</productname> and the steps you can take to resolve problems related to kernel resource consumption. PostgreSQLは、特に同一システム上で複数のサーバコピーを実行している場合や非常に大規模なインストレーションでは、オペレーティングシステムの様々なリソース制限を超えてしまうことがあります。 本節では、PostgreSQLで使用されるカーネルリソース、およびカーネルリソース消費に関連した問題を解消する時に取ることができる手順について説明します。

19.4.1. 共有メモリとセマフォ #

<title>Shared Memory and Semaphores</title>

<productname>PostgreSQL</productname> requires the operating system to provide inter-process communication (<acronym>IPC</acronym>) features, specifically shared memory and semaphores. Unix-derived systems typically provide <quote><systemitem class="osname">System V</systemitem></quote> <acronym>IPC</acronym>, <quote><systemitem class="osname">POSIX</systemitem></quote> <acronym>IPC</acronym>, or both. <systemitem class="osname">Windows</systemitem> has its own implementation of these features and is not discussed here. PostgreSQLはオペレーティングシステムが、プロセス間通信(IPC)特に共有メモリとセマフォ機能を提供することを要求します。 Unix(派生)システムでは、System V IPCや、POSIX IPC、またはその両方を提供します。 Windowsは、これらの機能を独自で実装しているため、ここでは説明しません。

By default, <productname>PostgreSQL</productname> allocates a very small amount of System V shared memory, as well as a much larger amount of anonymous <function>mmap</function> shared memory. Alternatively, a single large System V shared memory region can be used (see <xref linkend="guc-shared-memory-type"/>). In addition a significant number of semaphores, which can be either System V or POSIX style, are created at server startup. Currently, POSIX semaphores are used on Linux and FreeBSD systems while other platforms use System V semaphores. デフォルトではPostgreSQLは通常、非常に少量のSystem V共有メモリと、もっと大量の無名mmap共有メモリを割り当てます。 代替方法として、単一の大きなSystem Vメモリリージョンも利用できます (shared_memory_type参照)。 さらに、System V又はPOSIXスタイルのどちらかのセマフォがサーバの起動時に作成されます。 現在、LinuxとFreeBSDシステムではPOSIXセマフォが使用され、それ以外のプラットフォームではSystem Vセマフォが使用されます。

System V <acronym>IPC</acronym> features are typically constrained by system-wide allocation limits. When <productname>PostgreSQL</productname> exceeds one of these limits, the server will refuse to start and should leave an instructive error message describing the problem and what to do about it. (See also <xref linkend="server-start-failures"/>.) The relevant kernel parameters are named consistently across different systems; <xref linkend="sysvipc-parameters"/> gives an overview. The methods to set them, however, vary. Suggestions for some platforms are given below. System V IPC機能は、通常システム全体の割り当て制限に制約されます。 PostgreSQLがこれらの制限のいずれかを超えると、サーバは起動を拒否し、問題および何をすべきかを説明するエラーメッセージを残します。 (19.3.1 も参照してください。) 関係するカーネルパラメータは別々のシステム上でも統一して名付けられています。 表 19.1で概略がわかります。 しかしこれらを設定するための方法は異なります。 以下に、いくつかのプラットフォームへの提案を挙げます。

表19.1 System V IPCパラメータ

<title><systemitem class="osname">System V</systemitem> <acronym>IPC</acronym> Parameters</title>
名前説明一つのPostgreSQLインスタンスに必要な値
SHMMAX共有メモリセグメントの最大サイズ(バイト)最小でも1キロバイト(ただしデフォルトはもっと多くなっています)
SHMMIN共有メモリセグメントの最小サイズ(バイト)1
SHMALL使用可能な共有メモリの総量(バイトまたはページ)バイト指定の場合はSHMMAXと同じ。ページ指定の場合はceil(SHMMAX/PAGE_SIZE)。 + 他のアプリケーション用の空間
SHMSEGプロセスごとの共有メモリセグメントの最大数必要なのは1セグメントのみ(ただしデフォルトはもっと多くなっています)
SHMMNIシステム全体の共有メモリセグメントの最大数SHMSEGと同様 + 他のアプリケーション用の空間
SEMMNIセマフォ識別子の最大数(つまりセット)最低ceil((max_connections + autovacuum_max_workers + max_worker_processes + 5) / 16) + 他のアプリケーション用の空間
SEMMNSシステム全体のセマフォの最大数ceil((max_connections + autovacuum_max_workers + max_worker_processes + 5) / 16) * 17 + 他のアプリケーション用の空間
SEMMSLセットごとのセマフォの最大数最低17
SEMMAPセマフォマップの中の項目の数本文を参照
SEMVMXセマフォの最大値最低1000(デフォルトはしばしば32767ですが、必要がなければ変更しないでください)

<productname>PostgreSQL</productname> requires a few bytes of System V shared memory (typically 48 bytes, on 64-bit platforms) for each copy of the server. On most modern operating systems, this amount can easily be allocated. However, if you are running many copies of the server or you explicitly configure the server to use large amounts of System V shared memory (see <xref linkend="guc-shared-memory-type"/> and <xref linkend="guc-dynamic-shared-memory-type"/>), it may be necessary to increase <varname>SHMALL</varname>, which is the total amount of System V shared memory system-wide. Note that <varname>SHMALL</varname> is measured in pages rather than bytes on many systems. PostgreSQLは、サーバのコピー毎にSystem V共有メモリの数バイト(64ビットプラットフォームでは通常48バイト)を必要とします。 最近のほとんどのオペレーティングシステムでは、このくらいの量は簡単に割り当てられます。 しかし複数のサーバのコピーを実行している場合やSystem V共有メモリを使用する他のアプリケーションを実行している場合(shared_memory_typeおよびdynamic_shared_memory_typeを参照)は、システム全体のSystem V共有メモリであるSHMALLを増加させる必要があるかもしれません。 多くのシステムではSHMALLをバイト単位ではなくページ単位で測ることに注意してください。

Less likely to cause problems is the minimum size for shared memory segments (<varname>SHMMIN</varname>), which should be at most approximately 32 bytes for <productname>PostgreSQL</productname> (it is usually just 1). The maximum number of segments system-wide (<varname>SHMMNI</varname>) or per-process (<varname>SHMSEG</varname>) are unlikely to cause a problem unless your system has them set to zero. 問題が少ないのは共有メモリセグメントの最小サイズ(SHMMIN)で、PostgreSQLでは最大でもおよそ32バイトのはずです(通常では1です)。 システム全体のセグメントの最大数(SHMMNI)もしくはプロセスごとのセグメントの最大数(SHMSEG)に関して、使用しているシステムで0に設定されていない限り、問題が起きることはほぼありません。

When using System V semaphores, <productname>PostgreSQL</productname> uses one semaphore per allowed connection (<xref linkend="guc-max-connections"/>), allowed autovacuum worker process (<xref linkend="guc-autovacuum-max-workers"/>) and allowed background process (<xref linkend="guc-max-worker-processes"/>), in sets of 16. Each such set will also contain a 17th semaphore which contains a <quote>magic number</quote>, to detect collision with semaphore sets used by other applications. The maximum number of semaphores in the system is set by <varname>SEMMNS</varname>, which consequently must be at least as high as <varname>max_connections</varname> plus <varname>autovacuum_max_workers</varname> plus <varname>max_wal_senders</varname>, plus <varname>max_worker_processes</varname>, plus one extra for each 16 allowed connections plus workers (see the formula in <xref linkend="sysvipc-parameters"/>). The parameter <varname>SEMMNI</varname> determines the limit on the number of semaphore sets that can exist on the system at one time. Hence this parameter must be at least <literal>ceil((max_connections + autovacuum_max_workers + max_wal_senders + max_worker_processes + 5) / 16)</literal>. Lowering the number of allowed connections is a temporary workaround for failures, which are usually confusingly worded <quote>No space left on device</quote>, from the function <function>semget</function>. System V セマフォを使用している場合、PostgreSQLは、許可した接続(max_connections)、許可したオートバキュームワーカープロセス(autovacuum_max_workers)、許可したバックエンドプロセス(max_worker_processes)ごとに1つのセマフォを使用し、16個のセマフォをセットとして扱います。 それぞれそのようなセットは、他のアプリケーションに使われているセマフォセットとの衝突を検出するためのマジックナンバーが含まれている17個目のセマフォを持っています。 システム内のセマフォの最大数はSEMMNSによって設定され、その結果としてその値は少なくともmax_connectionsautovacuum_max_workersmax_wal_sendersmax_worker_processesと同じ、ただし、許可された接続とワーカー16個ごとに余分な1個を加えた値以上はなければいけません(表 19.1の公式を参照してください)。 SEMMNIパラメータはシステム上に同時に存在できるセマフォ集合の数の上限を決定します。 ですから、このパラメータは少なくともceil((max_connections + autovacuum_max_workers + max_wal_senders + max_worker_processes + 5) / 16)以上はなくてはいけません。 一時的な失敗の回避策としては許可される接続の数を下げることができますが、No space left on deviceという紛らわしい言葉がsemget関数から表示されます。

In some cases it might also be necessary to increase <varname>SEMMAP</varname> to be at least on the order of <varname>SEMMNS</varname>. If the system has this parameter (many do not), it defines the size of the semaphore resource map, in which each contiguous block of available semaphores needs an entry. When a semaphore set is freed it is either added to an existing entry that is adjacent to the freed block or it is registered under a new map entry. If the map is full, the freed semaphores get lost (until reboot). Fragmentation of the semaphore space could over time lead to fewer available semaphores than there should be. 場合によってはSEMMAPを少なくともSEMMNSと同程度に増やすことが必要になる場合があるかもしれません。 システムにこのパラメータがあるなら(ないかもしれません)、このパラメータはセマフォリソースマップのサイズを定義し、その中では有効なセマフォのそれぞれの隣接したブロックの項目が必要です。 セマフォ集合が解放されると、解放されたブロックに隣接する既に存在する項目に追加されるか、もしくは新しいマップの項目の下に登録されます。 もしマップが一杯だった場合、解放されたセマフォは(再起動するまで)失われます。 セマフォ空間の断片化により時間が経つごとに、有効なセマフォがあるべき量よりも少なくなる可能性があります。

Various other settings related to <quote>semaphore undo</quote>, such as <varname>SEMMNU</varname> and <varname>SEMUME</varname>, do not affect <productname>PostgreSQL</productname>. SEMMNUSEMUMEのような、その他の様々なsemaphore undoに関する設定はPostgreSQLには影響を与えません。

When using POSIX semaphores, the number of semaphores needed is the same as for System V, that is one semaphore per allowed connection (<xref linkend="guc-max-connections"/>), allowed autovacuum worker process (<xref linkend="guc-autovacuum-max-workers"/>) and allowed background process (<xref linkend="guc-max-worker-processes"/>). On the platforms where this option is preferred, there is no specific kernel limit on the number of POSIX semaphores. POSIXセマフォを使用している場合、System Vと同じ数のセマフォを必要とします。 つまり、許可した接続(max_connections)、許可したオートバキュームワーカープロセス(autovacuum_max_workers)、許可したバックエンドプロセス(max_worker_processes)ごとに1つのセマフォを使用します。 このオプションが優先されるプラットフォームでは、POSIXセマフォの数に特定のカーネル制限はありません。

AIX

It should not be necessary to do any special configuration for such parameters as <varname>SHMMAX</varname>, as it appears this is configured to allow all memory to be used as shared memory. That is the sort of configuration commonly used for other databases such as <application>DB/2</application>.</para> SHMMAXなどのパラメータに対して特別な設定は必要ありません。 これは、すべてのメモリを共有メモリとして使用できるように設定されているためです。 これはDB/2などの他のデータベースでも使用される、一般的な設定方法です。

<para> It might, however, be necessary to modify the global <command>ulimit</command> information in <filename>/etc/security/limits</filename>, as the default hard limits for file sizes (<varname>fsize</varname>) and numbers of files (<varname>nofiles</varname>) might be too low.

しかし、/etc/security/limits内の大域的なulimit情報は変更しなければならないかもしれません。 デフォルトのファイルサイズ(fsize)とファイル数(nofiles)用のハードリミットは低過ぎるかもしれないためです。

FreeBSD

The default shared memory settings are usually good enough, unless you have set <literal>shared_memory_type</literal> to <literal>sysv</literal>. System V semaphores are not used on this platform. shared_memory_typesysvに設定していない限り、通常はデフォルトの共有メモリ設定で十分です。 System V セマフォはこのプラットフォームでは使用しません。

The default IPC settings can be changed using the <command>sysctl</command> or <command>loader</command> interfaces. The following parameters can be set using <command>sysctl</command>: デフォルトのIPC設定はsysctlまたはloaderインタフェースを使用して変更を行うことができます。 以下ではsysctlを使用してパラメータを変更しています。

# sysctl kern.ipc.shmall=32768
# sysctl kern.ipc.shmmax=134217728

To make these settings persist over reboots, modify <filename>/etc/sysctl.conf</filename>. これらの設定を再起動しても永続化するには、/etc/sysctl.confを変更します。

If you have set <literal>shared_memory_type</literal> to <literal>sysv</literal>, you might also want to configure your kernel to lock System V shared memory into RAM and prevent it from being paged out to swap. This can be accomplished using the <command>sysctl</command> setting <literal>kern.ipc.shm_use_phys</literal>. shared_memory_typesysvに設定している場合は、System V共有メモリをRAM上に固定して、スワップによってページアウトされるのを避けるために、カーネルを設定することもできます。 これはsysctlを使用してkern.ipc.shm_use_physを設定することで実現できます。

If running in a FreeBSD jail, you should set its <literal>sysvshm</literal> parameter to <literal>new</literal>, so that it has its own separate System V shared memory namespace. (Before FreeBSD 11.0, it was necessary to enable shared access to the host's IPC namespace from jails, and take measures to avoid collisions.) FreeBSD jailを実行している場合、sysvshmパラメータをnewに設定して、独自のSystem V共有メモリ名前空間を有するようにする必要があります。 (FreeBSD 11.0以前は、jailからIPC名前空間への共有アクセスを可能にし、衝突を避けるための対策を講じる必要がありました。)

NetBSD

The default shared memory settings are usually good enough, unless you have set <literal>shared_memory_type</literal> to <literal>sysv</literal>. You will usually want to increase <literal>kern.ipc.semmni</literal> and <literal>kern.ipc.semmns</literal>, as <systemitem class="osname">NetBSD</systemitem>'s default settings for these are uncomfortably small. shared_memory_typesysvに設定していない限り、通常はデフォルトの共有メモリ設定で十分です。 通常は、kern.ipc.semmnikern.ipc.semmnsを増やす必要があります。これは、NetBSDのデフォルト設定は不適切に小さいためです。

IPC parameters can be adjusted using <command>sysctl</command>, for example: 以下の例のようにIPCパラメータをsysctlを用いて調整することができます。

# sysctl -w kern.ipc.semmni=100

To make these settings persist over reboots, modify <filename>/etc/sysctl.conf</filename>. これらの設定を再起動しても永続化するには、/etc/sysctl.confを変更します。

If you have set <literal>shared_memory_type</literal> to <literal>sysv</literal>, you might also want to configure your kernel to lock System V shared memory into RAM and prevent it from being paged out to swap. This can be accomplished using the <command>sysctl</command> setting <literal>kern.ipc.shm_use_phys</literal>. shared_memory_typesysvに設定している場合は、System V共有メモリをRAM上に固定して、スワップによってページアウトされるのを避けるために、カーネルを設定することもできます。 これはsysctlを使用してkern.ipc.shm_use_physを設定することで実現できます。

OpenBSD

The default shared memory settings are usually good enough, unless you have set <literal>shared_memory_type</literal> to <literal>sysv</literal>. You will usually want to increase <literal>kern.seminfo.semmni</literal> and <literal>kern.seminfo.semmns</literal>, as <systemitem class="osname">OpenBSD</systemitem>'s default settings for these are uncomfortably small. shared_memory_typesysvに設定していない限り、通常はデフォルトの共有メモリ設定で十分です。 通常は、kern.seminfo.semmnikern.seminfo.semmnsを増やす必要があります。これは、OpenBSDのデフォルト設定は不適切に小さいためです。

IPC parameters can be adjusted using <command>sysctl</command>, for example: 以下の例のようにIPCパラメータをsysctlを用いて調整することができます。

# sysctl kern.seminfo.semmni=100

To make these settings persist over reboots, modify <filename>/etc/sysctl.conf</filename>. これらの設定を再起動しても永続化するには、/etc/sysctl.confを変更します。

Linux

The default shared memory settings are usually good enough, unless you have set <literal>shared_memory_type</literal> to <literal>sysv</literal>, and even then only on older kernel versions that shipped with low defaults. System V semaphores are not used on this platform. shared_memory_typesysvに設定していて、低いデフォルトで出荷されたより古いカーネルバージョンでない限り、通常はデフォルトの共有メモリ設定で十分です。 System V セマフォはこのプラットフォームでは使用しません。

The shared memory size settings can be changed via the <command>sysctl</command> interface. For example, to allow 16 GB: 共有メモリサイズの設定はsysctlインタフェースを使用して変更可能です。 例えば16ギガバイトまで許すには以下のようにします。

$ sysctl -w kernel.shmmax=17179869184
$ sysctl -w kernel.shmall=4194304

To make these settings persist over reboots, see <filename>/etc/sysctl.conf</filename>. これらの設定を再起動しても永続化するには、/etc/sysctl.confを参照してください。

macOS

The default shared memory and semaphore settings are usually good enough, unless you have set <literal>shared_memory_type</literal> to <literal>sysv</literal>. shared_memory_typesysvに設定していない限り、通常はデフォルトの共有メモリとセマフォ設定で十分です。

The recommended method for configuring shared memory in macOS is to create a file named <filename>/etc/sysctl.conf</filename>, containing variable assignments such as: macOSにおける共有メモリの推奨設定方法は、以下のような変数代入文からなる/etc/sysctl.confという名称のファイルを作成することです。

kern.sysv.shmmax=4194304
kern.sysv.shmmin=1
kern.sysv.shmmni=32
kern.sysv.shmseg=8
kern.sysv.shmall=1024

Note that in some macOS versions, <emphasis>all five</emphasis> shared-memory parameters must be set in <filename>/etc/sysctl.conf</filename>, else the values will be ignored. 一部のバージョンのmacOSでは/etc/sysctl.conf内に共有メモリパラメータ5つすべてを設定しなければならないという点に注意してください。 さもなくば値が無視されます。

<varname>SHMMAX</varname> can only be set to a multiple of 4096. SHMMAXは4096の倍数のみ設定できます。

<varname>SHMALL</varname> is measured in 4 kB pages on this platform. このプラットフォームではSHMALLは4キロバイトページ単位です。

It is possible to change all but <varname>SHMMNI</varname> on the fly, using <application>sysctl</application>. But it's still best to set up your preferred values via <filename>/etc/sysctl.conf</filename>, so that the values will be kept across reboots. SHMMNI以外の変更は、sysctlを用いることにより、その場でおこなうことができます。 しかしいずれにせよ/etc/sysctl.conf経由で望む値に設定することが最善です。 再起動を行っても値が保持されるからです。

Solaris
illumos

The default shared memory and semaphore settings are usually good enough for most <productname>PostgreSQL</productname> applications. Solaris defaults to a <varname>SHMMAX</varname> of one-quarter of system <acronym>RAM</acronym>. To further adjust this setting, use a project setting associated with the <literal>postgres</literal> user. For example, run the following as <literal>root</literal>: 大抵のPostgreSQLアプリケーションではデフォルトの共有メモリとセマフォ設定で十分です。 SolarisのデフォルトのSHMMAXはシステムのRAMの1/4になりました。 さらにこの設定を調整するためには、postgresユーザに関するプロジェクト設定を使用しなければなりません。 例えば以下をroot権限で実行してください。

projadd -c "PostgreSQL DB User" -K "project.max-shm-memory=(privileged,8GB,deny)" -U postgres -G postgres user.postgres

This command adds the <literal>user.postgres</literal> project and sets the shared memory maximum for the <literal>postgres</literal> user to 8GB, and takes effect the next time that user logs in, or when you restart <productname>PostgreSQL</productname> (not reload). The above assumes that <productname>PostgreSQL</productname> is run by the <literal>postgres</literal> user in the <literal>postgres</literal> group. No server reboot is required. このコマンドはuser.postgresプロジェクトを追加し、postgresユーザの共有メモリの最大サイズを8GBに設定します。 この影響は次にこのユーザがログインした時、またはPostgreSQLを再起動した時(再読み込み時ではありません)に有効になります。 上ではPostgreSQLpostgresグループに属するpostgresユーザにより実行されていることを前提としています。 サーバの再起動は不要です。

Other recommended kernel setting changes for database servers which will have a large number of connections are: 多くの接続を受け付けるデータベースサーバにおいて推奨するカーネル設定にはこの他に以下があります。

project.max-shm-ids=(priv,32768,deny)
project.max-sem-ids=(priv,4096,deny)
project.max-msg-ids=(priv,4096,deny)

Additionally, if you are running <productname>PostgreSQL</productname> inside a zone, you may need to raise the zone resource usage limits as well. See "Chapter2: Projects and Tasks" in the <citetitle>System Administrator's Guide</citetitle> for more information on <literal>projects</literal> and <command>prctl</command>. さらに、ゾーン内でPostgreSQLを実行している場合、ゾーンのリソース使用上限も上げる必要があるかもしれません。 projectsprctlについてはSystem Administrator's Guideの第2章 プロジェクトとタスクを参照してください。

19.4.2. systemd RemoveIPC #

If <productname>systemd</productname> is in use, some care must be taken that IPC resources (including shared memory) are not prematurely removed by the operating system. This is especially of concern when installing PostgreSQL from source. Users of distribution packages of PostgreSQL are less likely to be affected, as the <literal>postgres</literal> user is then normally created as a system user. systemdが使用されている場合、(共有メモリを含む)IPCリソースがオペレーティングシステムによって時期尚早に削除されないように注意する必要があります。 これはPostgreSQLをソースからインストールした場合に特に重要です。 PostgreSQLのディストリビューションパッケージのユーザーは、通常postgresユーザーがシステムユーザーで作成されるため、影響を受けにくいでしょう。

The setting <literal>RemoveIPC</literal> in <filename>logind.conf</filename> controls whether IPC objects are removed when a user fully logs out. System users are exempt. This setting defaults to on in stock <productname>systemd</productname>, but some operating system distributions default it to off. logind.confRemoveIPCの設定はユーザが完全にログアウトしたときにIPCオブジェクトを削除するかどうかを制御します。 システムユーザは免除されます。 この設定のデフォルトはsystemdですが、いくつかのオペレーティングシステムではデフォルトでオフになっています。

A typical observed effect when this setting is on is that shared memory objects used for parallel query execution are removed at apparently random times, leading to errors and warnings while attempting to open and remove them, like この設定が有効になっている時の典型的な影響は、並列問い合わせの実行で使われる共有メモリオブジェクトが見かけ上ランダムな時間に削除され、共有メモリオブジェクトをオープンしようとしたり、削除しようとしたりした時に以下のようなエラーや警告が出ることです。

WARNING:  could not remove shared memory segment "/PostgreSQL.1450751626": No such file or directory

Different types of IPC objects (shared memory vs. semaphores, System V vs. POSIX) are treated slightly differently by <productname>systemd</productname>, so one might observe that some IPC resources are not removed in the same way as others. But it is not advisable to rely on these subtle differences. IPCオブジェクトの違い(共有メモリ vs. セマフォ、System V vs. POSIX)はsystemdによって若干扱いが異なるため一部のIPCは他のものと違って削除されないことがあります。 しかし、これらの微妙な違いに依存することはお勧めできません。

A <quote>user logging out</quote> might happen as part of a maintenance job or manually when an administrator logs in as the <literal>postgres</literal> user or something similar, so it is hard to prevent in general. ユーザーログアウトは、メンテナンスジョブの一環として、又は手動で、管理者がpostgresユーザーや類似のユーザでログインする可能性があるため、一般的に防止することは困難です。

What is a <quote>system user</quote> is determined at <productname>systemd</productname> compile time from the <symbol>SYS_UID_MAX</symbol> setting in <filename>/etc/login.defs</filename>. システムユーザーは、/etc/login.defsSYS_UID_MAXの設定によりsystemdのコンパイル時に決定されます。

Packaging and deployment scripts should be careful to create the <literal>postgres</literal> user as a system user by using <literal>useradd -r</literal>, <literal>adduser &#45;-system</literal>, or equivalent. パッケージとデプロイスクリプトは、useradd -r, adduser --system又は同等のコマンドを使用してpostgresユーザを作成するように注意する必要があります。

Alternatively, if the user account was created incorrectly or cannot be changed, it is recommended to set また、ユーザアカウントが誤って作成されて変更出来ないような場合は、以下を設定することを推奨します。

RemoveIPC=no

in <filename>/etc/systemd/logind.conf</filename> or another appropriate configuration file. /etc/systemd/logind.conf又はその他の設定ファイルで上記を入れます。

注意

At least one of these two things has to be ensured, or the PostgreSQL server will be very unreliable. これらの2つのうち少なくとも1つが保証されてないとなりません。そうでないとPostgreSQLサーバは非常に信頼性が低くなります。

19.4.3. リソースの制限 #

<title>Resource Limits</title>

Unix-like operating systems enforce various kinds of resource limits that might interfere with the operation of your <productname>PostgreSQL</productname> server. Of particular importance are limits on the number of processes per user, the number of open files per process, and the amount of memory available to each process. Each of these have a <quote>hard</quote> and a <quote>soft</quote> limit. The soft limit is what actually counts but it can be changed by the user up to the hard limit. The hard limit can only be changed by the root user. The system call <function>setrlimit</function> is responsible for setting these parameters. The shell's built-in command <command>ulimit</command> (Bourne shells) or <command>limit</command> (<application>csh</application>) is used to control the resource limits from the command line. On BSD-derived systems the file <filename>/etc/login.conf</filename> controls the various resource limits set during login. See the operating system documentation for details. The relevant parameters are <varname>maxproc</varname>, <varname>openfiles</varname>, and <varname>datasize</varname>. For example: UnixライクなオペレーティングシステムではPostgreSQLサーバの操作と関係する可能性のある様々な種類のリソース制限があります。 特に重要なのは、ユーザごとのプロセス数の制限、プロセスごとのオープンファイルの数、プロセスごとの利用可能なメモリの量です。 これらのそれぞれがハードソフトの2つの制限を持っています。 ソフト制限が実際に有効な制限ですが、ユーザによってハード制限まで変えることが可能です。 ハード制限はrootユーザによってのみ変えることができます。 setrlimitシステムコールがこれらのパラメータの設定を行います。 シェルの組み込みコマンドulimit(Bourne シェル)もしくはlimitcsh)は、コマンドラインからリソース制限を制御するために使われます。 BSD派生システム上では/etc/login.confファイルが、ログイン時に設定される様々なリソース制限を制御します。 詳細はオペレーティングシステムの文書を参照してください。 関連するパラメータはmaxprocopenfilesdatasizeです。 以下に例を示します。

default:\
...
        :datasize-cur=256M:\
        :maxproc-cur=256:\
        :openfiles-cur=256:\
...

(<literal>-cur</literal> is the soft limit. Append <literal>-max</literal> to set the hard limit.) -curはソフト制限です。 ハード制限を設定するためには-maxを付けてください。)

Kernels can also have system-wide limits on some resources. カーネルはいくつかのリソースに対して、システム全体の制限も持つことができます。

  • On <productname>Linux</productname> the kernel parameter <varname>fs.file-max</varname> determines the maximum number of open files that the kernel will support. It can be changed with <literal>sysctl -w fs.file-max=<replaceable>N</replaceable></literal>. To make the setting persist across reboots, add an assignment in <filename>/etc/sysctl.conf</filename>. The maximum limit of files per process is fixed at the time the kernel is compiled; see <filename>/usr/src/linux/Documentation/proc.txt</filename> for more information. Linuxカーネルパラメータfs.file-maxは、カーネルがサポートするオープンファイルの最大数を決定します。 これはsysctl-w fs.file-max=Nで変更できます。 再起動後もこの設定を保持するには、/etc/sysctl.confに割り当てを追加します。 プロセスあたりのファイル数の上限は、カーネルのコンパイル時に固定されます。 詳細は/usr/src/linux/Documentation/proc.txtを参照してください。

The <productname>PostgreSQL</productname> server uses one process per connection so you should provide for at least as many processes as allowed connections, in addition to what you need for the rest of your system. This is usually not a problem but if you run several servers on one machine things might get tight. PostgreSQLサーバは接続ごとに1つのプロセスを使うので、少なくとも許可された接続の数だけのプロセスに残りのシステムで必要な分を追加したものが必要になります。 通常はこれは問題ではありませんが、1つのマシン上でいくつかのサーバを起動している場合は厳しい状況になるかもしれません。

The factory default limit on open files is often set to <quote>socially friendly</quote> values that allow many users to coexist on a machine without using an inappropriate fraction of the system resources. If you run many servers on a machine this is perhaps what you want, but on dedicated servers you might want to raise this limit. オープンファイルの制限の出荷時のデフォルトは、しばしば大多数のユーザはマシン上でシステムリソースの不正使用をしないという前堤に立った社会的に友好的な値を設定してしまいます。 もし1つのマシン上で複数のサーバを起動する場合はそれが必要でしょうが、専用サーバではこの制限を上げたいかもしれません。

On the other side of the coin, some systems allow individual processes to open large numbers of files; if more than a few processes do so then the system-wide limit can easily be exceeded. If you find this happening, and you do not want to alter the system-wide limit, you can set <productname>PostgreSQL</productname>'s <xref linkend="guc-max-files-per-process"/> configuration parameter to limit the consumption of open files. 反対に、個々のプロセスが多数のファイルをオープンすることを許可するシステムもあります。 そのようなプロセスが数個以上あれば、システム全体の制限は簡単に超えてしまいます。 この発生を検知し、システム全体の制限の変更を望まない場合は、PostgreSQLmax_files_per_process設定パラメータを設定し、オープンファイルの消費を制限することができます。

Another kernel limit that may be of concern when supporting large numbers of client connections is the maximum socket connection queue length. If more than that many connection requests arrive within a very short period, some may get rejected before the <productname>PostgreSQL</productname> server can service the requests, with those clients receiving unhelpful connection failure errors such as <quote>Resource temporarily unavailable</quote> or <quote>Connection refused</quote>. The default queue length limit is 128 on many platforms. To raise it, adjust the appropriate kernel parameter via <application>sysctl</application>, then restart the <productname>PostgreSQL</productname> server. The parameter is variously named <varname>net.core.somaxconn</varname> on Linux, <varname>kern.ipc.soacceptqueue</varname> on newer FreeBSD, and <varname>kern.ipc.somaxconn</varname> on macOS and other BSD variants. 多数のクライアント接続をサポートする場合に懸念されるもう1つのカーネル制限は、ソケット接続キューの最大長です。 非常に短い時間内にそれ以上の数の接続要求が到着すると、PostgreSQLサーバが要求を処理する前に一部が拒否される可能性があります。 これらのクライアントはResource temporarily unavailableConnection refusedなどの役に立たない接続失敗エラーを受け取ります。 多くのプラットフォームでデフォルトのキュー長制限は128です。 これを上げるにはsysctlで適切なカーネルパラメータを調整し、PostgreSQLサーバを再起動します。 このパラメータはLinuxではnet.core.somaxconn、新しいFreeBSDではkern.ipc.soacceptqueue、macOSや他のBSD系ではkern.ipc.somaxconnと様々な名前が付けられています。

19.4.4. Linuxのメモリオーバーコミット #

<title>Linux Memory Overcommit</title>

The default virtual memory behavior on Linux is not optimal for <productname>PostgreSQL</productname>. Because of the way that the kernel implements memory overcommit, the kernel might terminate the <productname>PostgreSQL</productname> postmaster (the supervisor server process) if the memory demands of either <productname>PostgreSQL</productname> or another process cause the system to run out of virtual memory. Linuxでのデフォルトの仮想メモリの動作はPostgreSQLには最適ではありません。 カーネルがメモリオーバーコミットを実装する方法のため、カーネルは、PostgreSQLや他のプロセスのメモリ要求がシステムの仮想メモリを枯渇させた場合、PostgreSQL postmaster (スーパーバイザーサーバプロセス)を終了させる可能性があります。

If this happens, you will see a kernel message that looks like this (consult your system documentation and configuration on where to look for such a message): これが発生した場合、以下のようなカーネルメッセージが現れます (こうしたメッセージを検索する場所についてはシステム文書と設定を参照してください)。

Out of Memory: Killed process 12345 (postgres).

This indicates that the <filename>postgres</filename> process has been terminated due to memory pressure. Although existing database connections will continue to function normally, no new connections will be accepted. To recover, <productname>PostgreSQL</productname> will need to be restarted. これは、postgresプロセスがメモリ不足のために終了してしまったことを示します。 起動中のデータベース接続は正常に動作しますが、新しい接続は受け付けられません。 復旧するには、PostgreSQLを再起動しなければなりません。

One way to avoid this problem is to run <productname>PostgreSQL</productname> on a machine where you can be sure that other processes will not run the machine out of memory. If memory is tight, increasing the swap space of the operating system can help avoid the problem, because the out-of-memory (OOM) killer is invoked only when physical memory and swap space are exhausted. この問題を防止する1つの方法として、PostgreSQLを他のプロセスがそのマシンのメモリを枯渇させないことが確実なマシンで起動するというものがあります。 物理メモリとスワップ領域が消費尽くされた時のみにメモリ不足(OOM)killerが発生するため、メモリが不足する場合、オペレーティングシステムのスワップ領域を増やすことが問題解決の役にたちます。

If <productname>PostgreSQL</productname> itself is the cause of the system running out of memory, you can avoid the problem by changing your configuration. In some cases, it may help to lower memory-related configuration parameters, particularly <link linkend="guc-shared-buffers"><varname>shared_buffers</varname></link>, <link linkend="guc-work-mem"><varname>work_mem</varname></link>, and <link linkend="guc-hash-mem-multiplier"><varname>hash_mem_multiplier</varname></link>. In other cases, the problem may be caused by allowing too many connections to the database server itself. In many cases, it may be better to reduce <link linkend="guc-max-connections"><varname>max_connections</varname></link> and instead make use of external connection-pooling software. PostgreSQL自体が実行中のシステムのメモリ不足を引き起こした場合、設定を変更することで問題を防止することができます。 場合によっては、メモリ関連の設定パラメータ、shared_bufferswork_memおよびhash_mem_multiplierを低くすることで回避できる場合もあります。 この他にもデータベースサーバ自体への接続を多く許可しすぎることで問題が引き起こされる場合もあります。 多くの場合、max_connectionsを減らし、外部のコネクションプールソフトウェアを使用することで改善されます。

It is possible to modify the kernel's behavior so that it will not <quote>overcommit</quote> memory. Although this setting will not prevent the <ulink url="https://lwn.net/Articles/104179/">OOM killer</ulink> from being invoked altogether, it will lower the chances significantly and will therefore lead to more robust system behavior. This is done by selecting strict overcommit mode via <command>sysctl</command>: メモリをオーバーコミットさせないようにカーネルの動作を変更することができます。 この設定は完全にOOM killerの発生を防ぐことはできませんが、その発生頻度をかなり軽減しますので、システム動作の堅牢性をより高めます。 これは、以下のようにsysctlを使用して厳密なオーバーコミットモードを選択するこで実施されます。

sysctl -w vm.overcommit_memory=2

or placing an equivalent entry in <filename>/etc/sysctl.conf</filename>. You might also wish to modify the related setting <varname>vm.overcommit_ratio</varname>. For details see the kernel documentation file <ulink url="https://www.kernel.org/doc/Documentation/vm/overcommit-accounting"></ulink>. または/etc/sysctl.confに同等のエントリを配置します。 また、関連するvm.overcommit_ratio設定を変更した方が良いでしょう。 詳細はカーネル文書ファイルhttps://www.kernel.org/doc/Documentation/vm/overcommit-accountingを参照してください。

Another approach, which can be used with or without altering <varname>vm.overcommit_memory</varname>, is to set the process-specific <firstterm>OOM score adjustment</firstterm> value for the postmaster process to <literal>-1000</literal>, thereby guaranteeing it will not be targeted by the OOM killer. The simplest way to do this is to execute vm.overcommit_memoryの変更と関係なく使用できるその他の方法は、プロセス固有のOOMスコア調整値をpostmasterプロセス向けに-1000に設定することです。 これによりOOM killerの対象とならないことが保証されます。 このための最も簡単な方法は以下をPostgreSQLの起動スクリプト内でpostgresを実行する直前に実行することです。

echo -1000 > /proc/self/oom_score_adj

in the <productname>PostgreSQL</productname> startup script just before invoking <filename>postgres</filename>. Note that this action must be done as root, or it will have no effect; so a root-owned startup script is the easiest place to do it. If you do this, you should also set these environment variables in the startup script before invoking <filename>postgres</filename>: この作業をrootで実行しなければならないことに注意して下さい。 さもないと効果がありません。 このためrootが所有する起動スクリプトが、これを行うための最も簡単な場所です。 その場合には、起動スクリプトのpostgresの起動前に以下の環境変数を設定することも推奨します。

export PG_OOM_ADJUST_FILE=/proc/self/oom_score_adj
export PG_OOM_ADJUST_VALUE=0

These settings will cause postmaster child processes to run with the normal OOM score adjustment of zero, so that the OOM killer can still target them at need. You could use some other value for <envar>PG_OOM_ADJUST_VALUE</envar> if you want the child processes to run with some other OOM score adjustment. (<envar>PG_OOM_ADJUST_VALUE</envar> can also be omitted, in which case it defaults to zero.) If you do not set <envar>PG_OOM_ADJUST_FILE</envar>, the child processes will run with the same OOM score adjustment as the postmaster, which is unwise since the whole point is to ensure that the postmaster has a preferential setting. これらの設定は、いざという時にpostmasterの子プロセスをOOM killerのターゲットに出来るようにOOMスコア調整を通常のゼロで実行します。 子プロセスを他のOOMスコア調整で実行したい場合には、PG_OOM_ADJUST_VALUEにより別の値にすることが出来ます。 (PG_OOM_ADJUST_VALUEは省略することが出来て、その場合はデフォルトのゼロになります。) PG_OOM_ADJUST_FILEを設定しない場合、子プロセスはpostmasterと同じOOMスコア調整で実行されますが、postmasterが優先される設定にすることが肝心なので、それは賢明とは言えません。

19.4.5. LinuxのHugePages #

<title>Linux Huge Pages</title>

Using huge pages reduces overhead when using large contiguous chunks of memory, as <productname>PostgreSQL</productname> does, particularly when using large values of <xref linkend="guc-shared-buffers"/>. To use this feature in <productname>PostgreSQL</productname> you need a kernel with <varname>CONFIG_HUGETLBFS=y</varname> and <varname>CONFIG_HUGETLB_PAGE=y</varname>. You will also have to configure the operating system to provide enough huge pages of the desired size. To determine the number of huge pages needed, use the <command>postgres</command> command to see the value of <xref linkend="guc-shared-memory-size-in-huge-pages"/>. Note that the server must be shut down to view this runtime-computed parameter. This might look like: PostgreSQLのように、メモリの大きな連続チャンクを使用するとき、特にshared_buffersの値が大きい場合に、huge pagesを使用するとオーバーヘッドが減少します。 PostgreSQLでこの機能を有効にするには、CONFIG_HUGETLBFS=yおよびCONFIG_HUGETLB_PAGE=yとしたカーネルが必要です。 また、要求される十分な量だけhuge pagesを提供するようにオペレーティングシステムを調整する必要があるでしょう。 必要なhuge pages数を決定するには、postgresコマンドを起動してshared_memory_size_in_huge_pagesの値を調べます。 実行時に計算されたこのパラメータを見るためには、サーバを停止しなければならないことに注意してください。 これは以下のような感じになるでしょう。

$ postgres -D $PGDATA -C shared_memory_size_in_huge_pages
3170
$ grep ^Hugepagesize /proc/meminfo
Hugepagesize:       2048 kB
$ ls /sys/kernel/mm/hugepages
hugepages-1048576kB  hugepages-2048kB

In this example the default is 2MB, but you can also explicitly request either 2MB or 1GB with <xref linkend="guc-huge-page-size"/> to adapt the number of pages calculated by <varname>shared_memory_size_in_huge_pages</varname>. この例ではデフォルトは2MBですが、明示的に2MBまたは1GBをhuge_page_sizeで要求して、shared_memory_size_in_huge_pagesで計算されたページ数を調整することもできます。 While we need at least <literal>3170</literal> huge pages in this example, a larger setting would be appropriate if other programs on the machine also need huge pages. We can set this with: この例では少なくとも3170のhuge pageが必要ですが、マシン上の他のプログラムもhuge pageを必要とする場合には、より大きな設定が適切です。 これは以下のように設定できます。

# sysctl -w vm.nr_hugepages=3170

Don't forget to add this setting to <filename>/etc/sysctl.conf</filename> so that it is reapplied after reboots. For non-default huge page sizes, we can instead use: 再起動後にこの設定が行われるように、/etc/sysctl.confにこの設定を追加するのを忘れないようにしましょう。 非標準のhuge pageサイズなら、代わりに以下のようにできます。

# echo 3170 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages

It is also possible to provide these settings at boot time using kernel parameters such as <literal>hugepagesz=2M hugepages=3170</literal>. hugepagesz=2M hugepages=3170のようにして、起動時にカーネルパラメータとしてこれらの設定を与えることもできます。

Sometimes the kernel is not able to allocate the desired number of huge pages immediately due to fragmentation, so it might be necessary to repeat the command or to reboot. (Immediately after a reboot, most of the machine's memory should be available to convert into huge pages.) To verify the huge page allocation situation for a given size, use: 時には、断片化のためにカーネルは求められた数のhuge pagesを直ちには割り当てることができないことがあるので、そのコマンドを繰り返すか、再起動する必要があるかもしれません。 (再起動の直後は、マシンのメモリの大部分はhuge pagesへの変更が可能なはずです。) 指定サイズに対するhuge pagesの割り当ての状況を確認するには、次のようにします。

$ cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages

It may also be necessary to give the database server's operating system user permission to use huge pages by setting <varname>vm.hugetlb_shm_group</varname> via <application>sysctl</application>, and/or give permission to lock memory with <command>ulimit -l</command>. sysctlを使ってvm.hugetlb_shm_groupを設定する、あるいはulimit -lでメモリをロックする権限を与えることで、データベースサーバのOSユーザにhuge pagesを使用する権限を与える必要もあるかもしれません。

The default behavior for huge pages in <productname>PostgreSQL</productname> is to use them when possible, with the system's default huge page size, and to fall back to normal pages on failure. To enforce the use of huge pages, you can set <xref linkend="guc-huge-pages"/> to <literal>on</literal> in <filename>postgresql.conf</filename>. Note that with this setting <productname>PostgreSQL</productname> will fail to start if not enough huge pages are available. PostgreSQLのhuge pagesのデフォルトの動作は、可能な場合はシステムのデフォルトサイズのhuge pagesを使用し、失敗した場合は通常のページを使用します。 postgresql.confhuge_pagesonに設定することで、huge pagesの使用を強制することができます。 この設定の場合、十分なhuge pagesが確保できなければ、PostgreSQLの起動に失敗することに注意してください。

For a detailed description of the <productname>Linux</productname> huge pages feature have a look at <ulink url="https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt"></ulink>. Linuxのhuge pages機能の詳細はhttps://www.kernel.org/doc/Documentation/vm/hugetlbpage.txtを参照してください。