PostgreSQL/解析

はじめに

PostgreSQLを動かしていると「sorry, too many clients already」のようなメッセージを見ることがあるかもしれない。これは、接続するクライアント数がPostgreSQLの制限を超えてしまった場合に表示される。ソースコードから、メッセージの出力箇所を探して見ると、メッセージが記述されている箇所が複数存在することに気づく。では、一体どういった時にこのメッセージが出力されるのだろうか?

ここでは、ソースコードを参照しながら動作内容を確認する。

メッセージの出力箇所

postmasterプロセスは、クライアントの接続のaccept後にバックエンドプロセスの最大数をチェックしてforkしているかと思うが、実際にはそうではない。postmasterプロセスは、クライアント接続を受けるとバックエンドプロセスをforkする。その後、forkで生成されたバックエンドプロセスは、自身の初期化プロセスの中で資源の割り当てが可能かを確認し、空きがない場合は、エラーレベルFATALで「sorry, too many clients already」をを出力して終了する流れとなっている。

メッセージが出力されうる箇所は、バックエンドプロセスの処理フローで示すと下図の赤色箇所に該当する。

too-many-clients-already.png

メッセージが出る状況

ProcessStartupPacket

この関数は、クライアントからのStartupPacketを読む。キャンセルリクエストであった場合は、当該バックエンドプロセスのキャンセル(SIGINTシグナル)を行なう。この時点では、エラー(ERRCODE_TOO_MANY_CONNECTIONS)の制限には引っかからない(つまりacceptが成功すれば、キャンセルリクエストは正常に処理されると言える)。そして、クライアント接続数の制限チェックは、この関数の末尾で実行されている。

参考 postmaster/postmaster.c#ProcessStartupPacket

  1. static int
  2. ProcessStartupPacket(Port *port, bool SSLdone)
  3. {
  4. // .... 省略、キャンセルリクエストの場合はキャンセル(SIGINT)を送るので、エラー(ERRCODE_TOO_MANY_CONNECTIONS)には引っかからない。
  5.  
  6. /*
  7. * If we're going to reject the connection due to database state, say so
  8. * now instead of wasting cycles on an authentication exchange. (This also
  9. * allows a pg_ping utility to be written.)
  10. */
  11. switch (port->canAcceptConnections)
  12. {
  13. case CAC_STARTUP:
  14. ereport(FATAL,
  15. (errcode(ERRCODE_CANNOT_CONNECT_NOW),
  16. errmsg("the database system is starting up")));
  17. break;
  18. case CAC_SHUTDOWN:
  19. ereport(FATAL,
  20. (errcode(ERRCODE_CANNOT_CONNECT_NOW),
  21. errmsg("the database system is shutting down")));
  22. break;
  23. case CAC_RECOVERY:
  24. ereport(FATAL,
  25. (errcode(ERRCODE_CANNOT_CONNECT_NOW),
  26. errmsg("the database system is in recovery mode")));
  27. break;
  28. case CAC_TOOMANY:  // 制限を超えていた場合、ここでFATALで終了する
  29. ereport(FATAL,
  30. (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
  31. errmsg("sorry, too many clients already")));
  32. break;
  33. case CAC_WAITBACKUP:
  34. /* OK for now, will check in InitPostgres */
  35. break;
  36. case CAC_OK:
  37. break;
  38. }
  39. }

なお、このport->canAcceptConnectionsに、CAC_TOOMANYフラグが設定されているのは、以下の箇所のようである。

参考 postmaster/postmaster.c#canAcceptConnections

  1. static CAC_state
  2. canAcceptConnections(void)
  3. {
  4. CAC_state result = CAC_OK;
  5.  
  6. ... 省略
  7.  
  8. /*
  9. * Don't start too many children.
  10. *
  11. * We allow more connections than we can have backends here because some
  12. * might still be authenticating; they might fail auth, or some existing
  13. * backend might exit before the auth cycle is completed. The exact
  14. * MaxBackends limit is enforced when a new backend tries to join the
  15. * shared-inval backend array.
  16. *
  17. * The limit here must match the sizes of the per-child-process arrays;
  18. * see comments for MaxLivePostmasterChildren().
  19. */
  20. if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren())
  21. result = CAC_TOOMANY;
  22.  
  23. return result;
  24. }

ここでは、CountChildrenMaxLivePostmasterChildrenという二つの関数による返り値の比較が実行されている。これらの関数の内部を見てみる。

参考 postmaster/postmaster.c#MaxLivePostmasterChildren

ここでは、MaxBackendsの2倍の値を返すようになっている。

  1. /*
  2.  * MaxLivePostmasterChildren
  3.  *
  4.  * This reports the number of entries needed in per-child-process arrays
  5.  * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
  6.  * These arrays include regular backends, autovac workers, walsenders
  7.  * and background workers, but not special children nor dead_end children.
  8.  * This allows the arrays to have a fixed maximum size, to wit the same
  9.  * too-many-children limit enforced by canAcceptConnections().  The exact value
  10.  * isn't too critical as long as it's more than MaxBackends.
  11.  */
  12. int
  13. MaxLivePostmasterChildren(void)
  14. {
  15. return 2 * (MaxConnections + autovacuum_max_workers + 1 +
  16. max_worker_processes);
  17. }

参考 postmaster/postmaster.c#CountChildren

関数の引数は、BACKEND_TYPE_ALLなので、Backendでdead_endフラグがたっていない場合にカウントされる。

  1. /*
  2.  * Count up number of child processes of specified types (dead_end children
  3.  * are always excluded).
  4.  */
  5. static int
  6. CountChildren(int target)
  7. {
  8. dlist_iter iter;
  9. int cnt = 0;
  10.  
  11. dlist_foreach(iter, &BackendList)
  12. {
  13. Backend    *bp = dlist_container(Backend, elem, iter.cur);
  14.  
  15. if (bp->dead_end)
  16. continue;
  17.  
  18. /*
  19. * Since target == BACKEND_TYPE_ALL is the most common case, we test
  20. * it first and avoid touching shared memory for every child.
  21. */
  22. if (target != BACKEND_TYPE_ALL)
  23. {
  24. /*
  25. * Assign bkend_type for any recently announced WAL Sender
  26. * processes.
  27. */
  28. if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
  29. IsPostmasterChildWalSender(bp->child_slot))
  30. bp->bkend_type = BACKEND_TYPE_WALSND;
  31.  
  32. if (!(target & bp->bkend_type))
  33. continue;
  34. }
  35.  
  36. cnt++;
  37. }
  38. return cnt;
  39. }

dead_endtrueになるのは、調べる限り以下の箇所しか見当たらなかった。canAcceptConnectionsが、CAC_OKでもCAC_WAITBACKUPでもない時である。postmasterの状態がPM_RUNの時は、通常CAC_OKとなるので、forkで生成されたバックエンドプロセスはカウント対象であろう。

  1. static int
  2. BackendStartup(Port *port)
  3. {
  4. Backend    *bn; /* for backend cleanup */
  5. pid_t pid;
  6.  
  7. /*
  8. * Create backend data structure.  Better before the fork() so we can
  9. * handle failure cleanly.
  10. */
  11. bn = (Backend *) malloc(sizeof(Backend));
  12. if (!bn)
  13. {
  14. ereport(LOG,
  15. (errcode(ERRCODE_OUT_OF_MEMORY),
  16. errmsg("out of memory")));
  17. return STATUS_ERROR;
  18. }
  19.  
  20. /*
  21. * Compute the cancel key that will be assigned to this backend. The
  22. * backend will have its own copy in the forked-off process' value of
  23. * MyCancelKey, so that it can transmit the key to the frontend.
  24. */
  25. if (!RandomCancelKey(&MyCancelKey))
  26. {
  27. free(bn);
  28. ereport(LOG,
  29. (errcode(ERRCODE_INTERNAL_ERROR),
  30. errmsg("could not generate random cancel key")));
  31. return STATUS_ERROR;
  32. }
  33.  
  34. bn->cancel_key = MyCancelKey;
  35.  
  36. /* Pass down canAcceptConnections state */
  37. port->canAcceptConnections = canAcceptConnections();
  38. bn->dead_end = (port->canAcceptConnections != CAC_OK &&
  39. port->canAcceptConnections != CAC_WAITBACKUP);
  40.  
  41. /*
  42. * Unless it's a dead_end child, assign it a child slot number
  43. */
  44. if (!bn->dead_end)
  45. bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
  46. else
  47. bn->child_slot = 0;
  48.  
  49. /* Hasn't asked to be notified about any bgworkers yet */
  50. bn->bgworker_notify = false;
  51.  
  52. #ifdef EXEC_BACKEND
  53. pid = backend_forkexec(port);
  54. #else /* !EXEC_BACKEND */
  55. pid = fork_process();
  56. if (pid == 0) /* child */
  57. {
  58. free(bn);
  59.  
  60. /* Detangle from postmaster */
  61. InitPostmasterChild();
  62.  
  63. /* Close the postmaster's sockets */
  64. ClosePostmasterPorts(false);
  65.  
  66. /* Perform additional initialization and collect startup packet */
  67. BackendInitialize(port);
  68.  
  69. /* And run the backend */
  70. BackendRun(port);
  71. }
  72. #endif /* EXEC_BACKEND */
  73.  
  74. ... 省略
  75. }

実験

InitProcessの途中にsleepで停止させ、psqlでクライアント接続を行なった。以下のような感じである。

  1. void
  2. InitProcess(void)
  3. {
  4. PGPROC   *volatile *procgloballist;
  5.  
  6. wait_if_exists("InitProcess"); // InitProcessというファイルを見つけたら一定秒sleepを繰り返させる。
  7.  
  8.         ...

結果、接続数がMaxLivePostmasterChildren()で返される値に達した時、以下のメッセージを確認することができた。

psql: FATAL:  sorry, too many clients already

参考

InitProcess

通常、エラーERRCODE_TOO_MANY_CONNECTIONSに引っかかるのはこの箇所であろう。バックエンドプロセスは、PGPROCという構造体で表現される。このPGPROC構造体は、max_connectionsautovacuum_max_workersmax_worker_processesなどのパラメータで指定されたサイズ分、共有メモリ上に確保され配置される(詳しくは下図およびソースリンクを参照のこと)。バックエンドプロセスのPGPROCのフリーリストは、ProcGlobal構造体で管理されており、通常のバックエンドプロセスのフリーリストの先頭はfreeProcsメンバ変数が指している。バックエンドプロセスが起動する度に、フリーリストからPGPROC構造体が割り当てられ、クライアント接続数がmax_connectionsに達すると、割り当てられるPGPROCがないため、「sorry, too many clients already」でエラーとなる。

pgproc.png

参考

ProcArrayAdd

この関数は、PGPROC構造体を引数で受け取り、共有メモリ上のProc配列にprocnoを追加する。バックエンドプロセスは、アクティブなバックエンドとして管理される。

ProcArrayAddのエラーになる箇所を参照すると、「ここでERRCODE_TOO_MANY_CONNECTIONSエラーことはないはずである」と書かれている。通常は、先のPGPROC構造体の割り当て時にfreeProcsがないためにエラーになるはずである。

  1. void
  2. ProcArrayAdd(PGPROC *proc)
  3. {
  4. ProcArrayStruct *arrayP = procArray;
  5. int index;
  6.  
  7. LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
  8.  
  9. if (arrayP->numProcs >= arrayP->maxProcs)
  10. {
  11. /*
  12. * Oops, no room.  (This really shouldn't happen, since there is a
  13. * fixed supply of PGPROC structs too, and so we should have failed
  14. * earlier.)
  15. */
  16. LWLockRelease(ProcArrayLock);
  17. ereport(FATAL,
  18. (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
  19. errmsg("sorry, too many clients already")));
  20. }
  21.  
  22.         ... 省略
  23. }

SharedInvalBackendInit

Shared Invalidation Cacheとは、バックエンドプロセス間でシステムカタログなどのキャッシュが無効化されたことを通知する仕組みの事である。

バックエンドごとにProcState構造体が割り当てられる。SharedInvalBackendInit関数では、その初期化が行われているが、このProcState構造体がMaxBackendsを超えた場合にエラーERRCODE_TOO_MANY_CONNECTIONSとなる(ただし、maxBackendsは、MaxBackendsで設定されており、通常この値を超えることはない?と思われる)。

  1. void
  2. SharedInvalBackendInit(bool sendOnly)
  3. {
  4. int index;
  5. ProcState  *stateP = NULL;
  6. SISeg   *segP = shmInvalBuffer;
  7.  
  8. /*
  9. * This can run in parallel with read operations, but not with write
  10. * operations, since SIInsertDataEntries relies on lastBackend to set
  11. * hasMessages appropriately.
  12. */
  13. LWLockAcquire(SInvalWriteLock, LW_EXCLUSIVE);
  14.  
  15. /* Look for a free entry in the procState array */
  16. for (index = 0; index < segP->lastBackend; index++)
  17. {
  18. if (segP->procState[index].procPid == 0) /* inactive slot? */
  19. {
  20. stateP = &segP->procState[index];
  21. break;
  22. }
  23. }
  24.  
  25. if (stateP == NULL)
  26. {
  27. if (segP->lastBackend < segP->maxBackends)
  28. {
  29. stateP = &segP->procState[segP->lastBackend];
  30. Assert(stateP->procPid == 0);
  31. segP->lastBackend++;
  32. }
  33. else
  34. {
  35. /*
  36. * out of procState slots: MaxBackends exceeded -- report normally
  37. */
  38. MyBackendId = InvalidBackendId;
  39. LWLockRelease(SInvalWriteLock);
  40. ereport(FATAL,
  41. (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
  42. errmsg("sorry, too many clients already")));
  43. }
  44. }
  45.  
  46.         ... 省略
shinvalbuffer.png

参考

参考リンク


添付ファイル: filepgproc.png 323件 [詳細] fileshinvalbuffer.png 312件 [詳細] filetoo-many-clients-already.png 352件 [詳細]

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
目次
ダブルクリックで閉じるTOP | 閉じる
GO TO TOP