Gunicorn: OSError:[Errno9]不正なファイル記述子

作成日 2018年09月10日  ·  19コメント  ·  ソース: benoitc/gunicorn

ラズビアンイメージでこの問題が発生しています

[2018-09-10 20:40:11 +0800] [21421] [クリティカル]ワーカータイムアウト(pid:21699)
[2018-09-10 20:40:11 +0800] [21699] [ERROR]ソケットエラー処理要求。
トレースバック(最後の最後の呼び出し):
ファイル「/usr/lib/python3/dist-packages/gunicorn/workers/async.py」、62行目、ハンドル
six.reraise(* sys.exc_info())
ファイル "/usr/lib/python3/dist-packages/gunicorn/six.py"、行625、リレイズ
価値を上げる
ファイル「/usr/lib/python3/dist-packages/gunicorn/workers/async.py」、35行目、ハンドル
listener_name = listener.getsockname()
OSError:[Errno9]不正なファイル記述子

Feedback Requested Investigation

最も参考になるコメント

  1. gunicornuvicornだけの設定で、このログエラーを再現できます。 このエラーメッセージは、以前のバージョンの0.11.3 (OSxとLinuxコンテナの両方)ではなく、 uvicorn==0.11.4発生し始めます。 これは、報告されたバージョンが常に0.11.4より大きいuvicornを使用した上記のレポートと一致しています。 最後の証拠
  2. このエラーの責任をコミットこれである1 。 問題は、今述べたコミットのこれらの数行にあります。 コミットは、コードの2つのブロックの順序のみを変更します。 その順序の変更を元に戻すと、 uvicornテストスイートに合格したまま、ログエラーが消えます。
  3. 上記のように、スタックgunicorn+uvicorn最上位でstarlettefastapiを使用すると、同じログエラーが発生します。 - 0.11.4代わりに最新のuvicornバージョン12.X 0.11.4ます; -1つ以上のuvicornワーカーでgunicornします

証拠。 osxの新しいフォルダで、添付のスクリプトtest.sh実行します(osxでテスト済み)。 Linuxコンテナーでテストするには、スクリプトとDockerfileの両方を保存してから、Dockerfileのヘッダーを読み取ります。 スクリプトのログも添付します。

@benoitc 、バグを導入しているように見えるuvicornでのこのコミットについてどう思いますか? 問題はgunicornuvicorn間のインターフェースにあるようです。 上記のuvicornのコミットで変更された2ブロックのコードの順序についてコメントできますか? これは、他のケースでもこれが発生する理由を見つけるのに役立つ場合があります。 これまでのところ、これはaiohttpgeventFlask-SocketIO sanicでも報告されています。 簡単にするために、スクリプトのログも添付します。

log_test.log

ファイル_test.sh_

#!/bin/bash
python3 -m venv venv
source venv/bin/activate
pip install gunicorn==20.0.04 uvicorn==0.11.4
# create simple uvicorn app
printf "async def app(scope, receive, send):\n    await send()\n" > example.py
# spin up gunicorn with 1 uvicorn worker, and then send TERM signal to gunicorn
gunicorn example:app -w 1 -k uvicorn.workers.UvicornWorker &
sleep 5 && pkill -f gunicorn
sleep 1
# you will see 1 log entry like this one:
# [XX] [YY] [INFO] Error while closing socket [Errno 9] Bad file descriptor

printf "\n\n[INFO] if you instead bump down uvicorn's version from 11.4 to 11.3 [Errno 9] goes away:\n\n"
pip install uvicorn==0.11.3
gunicorn example:app -w 1 -k uvicorn.workers.UvicornWorker &
sleep 5 && pkill -f gunicorn

ファイル_Dockerfile_

# run with:
# docker run -it $(docker build -q .)
FROM python:3.8
COPY test.sh .
RUN chmod +x /test.sh
CMD /test.sh

全てのコメント19件

@ leond08チケットありがとうございます!

それがどのように起こっているかを理解するために、もう少し情報を提供できますか?

  • Gunicornのどのバージョンをテストしていますか
  • どのワーカーを使用していますか
  • これはいつ起こりますか?

gunicorn3最新バージョンを使用しています
これにはeventletとgeventを使用しています
フラスコアプリケーションを実行しています-Flask-SocketIO

ユーザーがボタンをクリックした後、バックグラウンドタスクを開始します
私のバックグラウンドタスク機能は、イベントをリッスンすることです。
[完了]ボタンをクリックした後、バックグラウンドタスクを停止する必要があります
次に、すべてのユーザーに送信メッセージを送信します

aiohttp + gunicornで同じ問題が発生した場合は、ctrl + cのたびに同じメッセージを確認してください。

[INFO]ソケットを閉じるときにエラーが発生しました[Errno9]ファイル記述子が正しくありません

私はそれを再現しません。 アプリケーションが上記の問題を引き起こすいくつかのfdsを閉じていると思われます。

同じ問題が発生しています。唯一の問題は、DockerSwarmで実行されている8つのコンテナーのうち1つでのみ発生していることです。

9つのコンテナのうち1つで同じ問題が発生しました。これは、dockerとpython3およびgeventに関連しているようです。

gunicorn 20.0.4 + aiohttp 3.6.2

Gunicornは開発サーバーとして実行されています:

gunicorn --reload app:make_app --bind localhost:5000 --worker-class aiohttp.GunicornWebWorker --workers 2 --access-logfile -

ほとんどすべてのCtrl + Cはで終わります

^C[2020-05-23 21:49:50 +0200] [38524] [INFO] Handling signal: int
Exception ignored when trying to write to the signal wakeup fd:
Exception ignored when trying to write to the signal wakeup fd:
Traceback (most recent call last):
  File "/usr/lib/python3.8/asyncio/unix_events.py", line 42, in _sighandler_noop
Traceback (most recent call last):
  File "/usr/lib/python3.8/asyncio/unix_events.py", line 42, in _sighandler_noop
    def _sighandler_noop(signum, frame):
    def _sighandler_noop(signum, frame):
OSError: [Errno 9] Bad file descriptor
OSError: [Errno 9] Bad file descriptor
[2020-05-23 21:49:50 +0200] [38526] [INFO] Worker exiting (pid: 38526)
[2020-05-23 21:49:50 +0200] [38528] [INFO] Worker exiting (pid: 38528)
[2020-05-23 21:49:50 +0200] [38524] [INFO] Shutting down: Master

アプリケーションがリクエストを処理したかどうかは関係ありません。

Sanic 20.3.0の場合:

^C[2020-05-26 13:24:55 +0200] [27706] [INFO] Handling signal: int
[2020-05-26 13:24:55 +0200] [27769] [INFO] Stopping server: 27769, connections: 0
[2020-05-26 13:24:55 +0200] [27769] [INFO] Error while closing socket [Errno 9] Bad file descriptor
[2020-05-26 13:24:55 +0200] [27769] [INFO] Worker exiting (pid: 27769)
[2020-05-26 13:24:55 +0200] [27771] [INFO] Stopping server: 27771, connections: 0
[2020-05-26 13:24:55 +0200] [27771] [INFO] Error while closing socket [Errno 9] Bad file descriptor
[2020-05-26 13:24:55 +0200] [27771] [INFO] Worker exiting (pid: 27771)
[2020-05-26 13:24:55 +0200] [27706] [INFO] Shutting down: Master

ここでも、すべてのCtrl + CでGunicorn20.0.4 + Uvicorn0.11.5ワーカークラスを使用します。

INFO:     [12621] [gunicorn.error] Handling signal: int
INFO:     [12635] [gunicorn.error] Error while closing socket [Errno 9] Bad file descriptor
INFO:     [12634] [gunicorn.error] Error while closing socket [Errno 9] Bad file descriptor
INFO:     [12635] [gunicorn.error] Worker exiting (pid: 12635)
INFO:     [12634] [gunicorn.error] Worker exiting (pid: 12634)
INFO:     [12621] [gunicorn.error] Shutting down: Master

アプリケーションの例はありますか? また、Pythonのどのバージョンについて話しているのですか?

Ubuntu 20.04、システムはvirtualenvでPython3.8.2を提供しました

アプリケーションの例: httpshttps://github.com/zgoda/newsloop-server/tree/b2a8a7f09fa9848d0384b51a3f6c0bb 私の以前のコメントでの正確なgunicornの呼び出し。

aiohttpとSanicの出力の違いにより、ワーカーに何か問題があるのではないかと疑っています。

同じ問題、python 3.8.0
サニック19.12.2
gunicorn 20.0.4

編集:これは、Macでローカルに実行しているときに発生しますが、LinuxDocker内で実行しているときは発生しません。

こんにちは、
この問題https://github.com/benoitc/gunicorn/issues/2064にも同じ理由があると思い
問題とほぼ同じエラーが発生しますが、gunicorn-19.9.0を使用します

私もこれを経験しています。FastAPI+ Python3.8.5を使用する最新のGunicornおよびuvicornワーカー

uvicornの使用をやめるとすぐに(つまり、gunicornの設定からこの行を削除します):

worker_class = "uvicorn.workers.UvicornWorker"

エラーは消えます。

上記のように、これはCtrl + CでGunicornを停止するか、PIDに正常なkillシグナルを送信するときに発生します。

[2020-09-12 11:56:37 +1000] [100390] [INFO] Starting gunicorn 20.0.4
[2020-09-12 11:56:37 +1000] [100390] [INFO] Listening at: http://0.0.0.0:6000 (100390)
[2020-09-12 11:56:37 +1000] [100390] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2020-09-12 11:56:37 +1000] [100392] [INFO] Booting worker with pid: 100392
[2020-09-12 11:56:38 +1000] [100392] [INFO] Started server process [100392]
[2020-09-12 11:56:38 +1000] [100392] [INFO] Waiting for application startup.
[2020-09-12 11:56:38 +1000] [100392] [INFO] Application startup complete.
[2020-09-12 11:56:48 +1000] [100390] [INFO] Handling signal: term
[2020-09-12 11:56:48 +1000] [100392] [INFO] Shutting down
[2020-09-12 11:56:48 +1000] [100392] [INFO] Error while closing socket [Errno 9] Bad file descriptor
[2020-09-12 11:56:48 +1000] [100392] [INFO] Waiting for application shutdown.
[2020-09-12 11:56:48 +1000] [100392] [INFO] Application shutdown complete.
[2020-09-12 11:56:48 +1000] [100392] [INFO] Finished server process [100392]
[2020-09-12 11:56:48 +1000] [100392] [INFO] Worker exiting (pid: 100392)
[2020-09-12 11:56:48 +1000] [100390] [INFO] Shutting down: Master

問題の正確な複製は次のとおりです。

[fots<strong i="6">@workstation</strong> testing]$ python3.8 -V
Python 3.8.5
[fots<strong i="7">@workstation</strong> testing]$ python3.8 -m venv ~/.virtualenv/testing
[fots<strong i="8">@workstation</strong> testing]$ source ~/.virtualenv/testing/bin/activate
(testing) [fots<strong i="9">@workstation</strong> testing]$ pip install fastapi gunicorn uvicorn
Collecting fastapi
  Using cached fastapi-0.61.1-py3-none-any.whl (48 kB)
Collecting gunicorn
  Using cached gunicorn-20.0.4-py2.py3-none-any.whl (77 kB)
Collecting uvicorn
  Using cached uvicorn-0.11.8-py3-none-any.whl (43 kB)
Collecting pydantic<2.0.0,>=1.0.0
  Using cached pydantic-1.6.1-cp38-cp38-manylinux2014_x86_64.whl (11.5 MB)
Collecting starlette==0.13.6
  Using cached starlette-0.13.6-py3-none-any.whl (59 kB)
Requirement already satisfied: setuptools>=3.0 in /home/fots/.virtualenv/testing/lib/python3.8/site-packages (from gunicorn) (47.1.0)
Collecting h11<0.10,>=0.8
  Using cached h11-0.9.0-py2.py3-none-any.whl (53 kB)
Collecting websockets==8.*
  Using cached websockets-8.1-cp38-cp38-manylinux2010_x86_64.whl (78 kB)
Collecting httptools==0.1.*; sys_platform != "win32" and sys_platform != "cygwin" and platform_python_implementation != "PyPy"
  Using cached httptools-0.1.1-cp38-cp38-manylinux1_x86_64.whl (227 kB)
Collecting uvloop>=0.14.0; sys_platform != "win32" and sys_platform != "cygwin" and platform_python_implementation != "PyPy"
  Using cached uvloop-0.14.0-cp38-cp38-manylinux2010_x86_64.whl (4.7 MB)
Collecting click==7.*
  Using cached click-7.1.2-py2.py3-none-any.whl (82 kB)
Installing collected packages: pydantic, starlette, fastapi, gunicorn, h11, websockets, httptools, uvloop, click, uvicorn
Successfully installed click-7.1.2 fastapi-0.61.1 gunicorn-20.0.4 h11-0.9.0 httptools-0.1.1 pydantic-1.6.1 starlette-0.13.6 uvicorn-0.11.8 uvloop-0.14.0 websockets-8.1
WARNING: You are using pip version 20.1.1; however, version 20.2.3 is available.
You should consider upgrading via the '/home/fots/.virtualenv/testing/bin/python3.8 -m pip install --upgrade pip' command.
(testing) [fots<strong i="10">@workstation</strong> testing]$ ls -l
total 4
-rw-rw-r-- 1 fots fots 117 Sep 12 12:13 main.py
(testing) [fots<strong i="11">@workstation</strong> testing]$ cat main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}
(testing) [fots<strong i="12">@workstation</strong> testing]$ gunicorn -k uvicorn.workers.UvicornWorker main:app
[2020-09-12 12:19:05 +1000] [105788] [INFO] Starting gunicorn 20.0.4
[2020-09-12 12:19:05 +1000] [105788] [INFO] Listening at: http://127.0.0.1:8000 (105788)
[2020-09-12 12:19:05 +1000] [105788] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2020-09-12 12:19:05 +1000] [105790] [INFO] Booting worker with pid: 105790
[2020-09-12 12:19:05 +1000] [105790] [INFO] Started server process [105790]
[2020-09-12 12:19:05 +1000] [105790] [INFO] Waiting for application startup.
[2020-09-12 12:19:05 +1000] [105790] [INFO] Application startup complete.
^C[2020-09-12 12:19:06 +1000] [105788] [INFO] Handling signal: int
[2020-09-12 12:19:06 +1000] [105790] [INFO] Shutting down
[2020-09-12 12:19:06 +1000] [105790] [INFO] Error while closing socket [Errno 9] Bad file descriptor
[2020-09-12 12:19:06 +1000] [105790] [INFO] Waiting for application shutdown.
[2020-09-12 12:19:06 +1000] [105790] [INFO] Application shutdown complete.
[2020-09-12 12:19:06 +1000] [105790] [INFO] Finished server process [105790]
[2020-09-12 12:19:06 +1000] [105790] [INFO] Worker exiting (pid: 105790)
[2020-09-12 12:19:07 +1000] [105788] [INFO] Shutting down: Master

そして、これがpip freeze出力です。

click==7.1.2
fastapi==0.61.1
gunicorn==20.0.4
h11==0.9.0
httptools==0.1.1
pydantic==1.6.1
starlette==0.13.6
uvicorn==0.11.8
uvloop==0.14.0
websockets==8.1

GitHub(マスターブランチ)からuvicornとgunicornをインストールして、最新の修正を確実に取得しようとしましたが、問題は解決しませんでした。

お役に立てれば
Fotis

  1. gunicornuvicornだけの設定で、このログエラーを再現できます。 このエラーメッセージは、以前のバージョンの0.11.3 (OSxとLinuxコンテナの両方)ではなく、 uvicorn==0.11.4発生し始めます。 これは、報告されたバージョンが常に0.11.4より大きいuvicornを使用した上記のレポートと一致しています。 最後の証拠
  2. このエラーの責任をコミットこれである1 。 問題は、今述べたコミットのこれらの数行にあります。 コミットは、コードの2つのブロックの順序のみを変更します。 その順序の変更を元に戻すと、 uvicornテストスイートに合格したまま、ログエラーが消えます。
  3. 上記のように、スタックgunicorn+uvicorn最上位でstarlettefastapiを使用すると、同じログエラーが発生します。 - 0.11.4代わりに最新のuvicornバージョン12.X 0.11.4ます; -1つ以上のuvicornワーカーでgunicornします

証拠。 osxの新しいフォルダで、添付のスクリプトtest.sh実行します(osxでテスト済み)。 Linuxコンテナーでテストするには、スクリプトとDockerfileの両方を保存してから、Dockerfileのヘッダーを読み取ります。 スクリプトのログも添付します。

@benoitc 、バグを導入しているように見えるuvicornでのこのコミットについてどう思いますか? 問題はgunicornuvicorn間のインターフェースにあるようです。 上記のuvicornのコミットで変更された2ブロックのコードの順序についてコメントできますか? これは、他のケースでもこれが発生する理由を見つけるのに役立つ場合があります。 これまでのところ、これはaiohttpgeventFlask-SocketIO sanicでも報告されています。 簡単にするために、スクリプトのログも添付します。

log_test.log

ファイル_test.sh_

#!/bin/bash
python3 -m venv venv
source venv/bin/activate
pip install gunicorn==20.0.04 uvicorn==0.11.4
# create simple uvicorn app
printf "async def app(scope, receive, send):\n    await send()\n" > example.py
# spin up gunicorn with 1 uvicorn worker, and then send TERM signal to gunicorn
gunicorn example:app -w 1 -k uvicorn.workers.UvicornWorker &
sleep 5 && pkill -f gunicorn
sleep 1
# you will see 1 log entry like this one:
# [XX] [YY] [INFO] Error while closing socket [Errno 9] Bad file descriptor

printf "\n\n[INFO] if you instead bump down uvicorn's version from 11.4 to 11.3 [Errno 9] goes away:\n\n"
pip install uvicorn==0.11.3
gunicorn example:app -w 1 -k uvicorn.workers.UvicornWorker &
sleep 5 && pkill -f gunicorn

ファイル_Dockerfile_

# run with:
# docker run -it $(docker build -q .)
FROM python:3.8
COPY test.sh .
RUN chmod +x /test.sh
CMD /test.sh

私はまったく同じ問題を抱えていました。 これが私の場合です。

簡単な説明:gunicornを使用してDjangodwebsocketのテストアプリケーションを確立しようとしています。 websocket_clientを使用して結果をテストしようとすると、websocketを閉じた後、このエラーが毎回発生します。

環境 :
Dockerイメージ: python:3.7
Pythonバージョン:python3.7.6
gunicorn:バージョン= 20.0.4、work = gevent
Djangoバージョン:Django == 2.2
dwebsocketバージョン:0.5.12

コード:

view.py

from dwebsocket import accept_websocket

<strong i="16">@accept_websocket</strong>
def my_ws(request):
    if request.is_websocket():
        ws = request.websocket
        while True:
            msg = ws.wait(timeout=15)
            if msg is None:
                print('get None message')
                break
            else:
                msg = b'echo :' + msg
                ws.send(msg)
                print('send ws seccess')
        print('websocket close')

urls.py

from websocketInfo.views import  my_ws
from django.conf.urls import url

urlpatterns = [
    url(r'my_ws/$', my_ws, name='my_ws')
]

websocket_client

from websocket import create_connection
ws = create_connection("ws://127.0.0.1:8080/my_ws/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Receiving...")
result = ws.recv()
print(result)
ws.close()
print('ws close')

gunicornサーバーを実行するためのコンマ

gunicorn MyWebsocket.wsgi -b 0.0.0.0:8000 -w 3 -k gevent

エラー出力

send ws seccess
get None message
websocket close
[2021-01-13 02:43:56 +0000] [101] [ERROR] Socket error processing request.
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 65, in handle
    util.reraise(*sys.exc_info())
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 625, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 55, in handle
    self.handle_request(listener_name, req, client, addr)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/ggevent.py", line 143, in handle_request
    super().handle_request(listener_name, req, sock, addr)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 128, in handle_request
    util.reraise(*sys.exc_info())
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 625, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 114, in handle_request
    resp.write(item)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/http/wsgi.py", line 326, in write
    self.send_headers()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/http/wsgi.py", line 322, in send_headers
    util.write(self.sock, util.to_bytestring(header_str, "latin-1"))
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 286, in write
    sock.sendall(data)
  File "/usr/local/lib/python3.7/site-packages/gevent/_socket3.py", line 523, in sendall
    return _socketcommon._sendall(self, data_memory, flags)
  File "/usr/local/lib/python3.7/site-packages/gevent/_socketcommon.py", line 367, in _sendall
    chunk_size = max(socket.getsockopt(SOL_SOCKET, SO_SNDBUF), 1024 * 1024)
  File "/usr/local/lib/python3.7/site-packages/gevent/_socket3.py", line 156, in __getattr__
    return getattr(self._sock, name)
  File "/usr/local/lib/python3.7/site-packages/gevent/_socket3.py", line 66, in _dummy
    raise OSError(EBADF, 'Bad file descriptor')
OSError: [Errno 9] Bad file descriptor

@ChrisXiaoShu投稿したスタックトレースは、この特定のソケットオブジェクトがPythonレベルで明示的に閉じられていることを示しています(geventがその_dummyを使用して、オペレーティングシステムと同じ例外を生成する場合)。 これは、アプリケーションスタックの一部が、応答を返す前にソケットを閉じて、gunicornに処理させることを意味します。 エラーが発生した時点では、gunicornはまだHTTP応答ヘッダーを送信していませんでした。

私の場合も同じような問題ですが、このエラーは何もせずに発生するという違いがあります。 時には5分後、時には2時間後...

このページは役に立ちましたか?
0 / 5 - 0 評価