複数の Worker を起動するアプリケーションにおいて、各 Worker に一意な連番を割り振りたい場面があったのでメモ。
設定ファイルのServer Hooks
を使えばワーカーの起動時に呼ばれる処理を定義できるため、ここでワーカープロセス毎に環境変数を設定する。
実装
FastAPI + gunicorn の例
pre_fork
イベントを利用する
gunicorn.config.py
import os
workers = 4
def pre_fork(server, worker):
print('## called pre_fork')
os.environ['WORKER_ID'] = str(server.worker_age - 1)
main.py
import os
from fastapi import FastAPI
app = FastAPI()
worker_id = os.getenv('WORKER_ID')
print('## WORKER_ID:', worker_id)
@app.get('/')
def index():
return {'msg': 'hello!'}
起動コマンドと出力
$ gunicorn main:app -c gunicorn.config.py
[2020-11-25 21:07:32 +0900] [18136] [INFO] Starting gunicorn 20.0.4
[2020-11-25 21:07:32 +0900] [18136] [INFO] Listening at: http://127.0.0.1:8000 (18136)
[2020-11-25 21:07:32 +0900] [18136] [INFO] Using worker: sync
## called pre_fork
[2020-11-25 21:07:32 +0900] [18139] [INFO] Booting worker with pid: 18139
## called pre_fork
[2020-11-25 21:07:32 +0900] [18140] [INFO] Booting worker with pid: 18140
## called pre_fork
## WORKER_ID: 0
[2020-11-25 21:07:32 +0900] [18141] [INFO] Booting worker with pid: 18141
## WORKER_ID: 1
## called pre_fork
[2020-11-25 21:07:32 +0900] [18142] [INFO] Booting worker with pid: 18142
## WORKER_ID: 2
## WORKER_ID: 3
pre_fork
が4回呼び出され、ワーカー毎に0~3の番号が環境変数にセットされた