Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ctrl+C in terminal broken on windows #1972

Open
davidefortunatotecnos opened this issue May 8, 2023 · 13 comments · May be fixed by #2059
Open

Ctrl+C in terminal broken on windows #1972

davidefortunatotecnos opened this issue May 8, 2023 · 13 comments · May be fixed by #2059

Comments

@davidefortunatotecnos
Copy link

davidefortunatotecnos commented May 8, 2023

With last release of Uvicorn 0.22.0 doing CTRL+C in a windows terminal doesn't work anymore.
Everything is frozen and it is impossible to stop it. In addition the command --reload is broken too, because it doesn't restart anymore, probably because of the same issue.

Tried on Windows 11 and Powershell 7.3.4.

Downgrading to version 0.21.1 makes it works again.

Important

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@lzcmian
Copy link

lzcmian commented May 9, 2023

same question

@UF-code
Copy link

UF-code commented May 10, 2023

when you launch without testing properly that will happen, also same here, in addition to that issue with "--reload" parameter over time it stucks and doesn't update api endpoints

@AshminJayson
Copy link

Also the issue of the everything being frozen is generally triggered right after watchfiles tries restarting the server/detected a change, also killing the process manually using the port number doesn't fully terminate it and does not allow for the port to be reused without a full system reboot.

@humrochagf humrochagf linked a pull request Jul 25, 2023 that will close this issue
3 tasks
@JinglingB
Copy link

Crude monkey-patching hack to use SetConsoleCtrlHandler, which actually has its handlers called unlike signal.signal's. Don't add this to anything serious:

import sys

if __name__ == "__main__":
    if sys.platform == "win32":
        # Based on Eryk Sun's code: https://stackoverflow.com/a/43095532
        import ctypes

        from signal import SIGINT, CTRL_C_EVENT

        _console_ctrl_handlers = {} # must be global / kept alive to avoid GC

        kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)

        PHANDLER_ROUTINE = ctypes.WINFUNCTYPE(
            ctypes.wintypes.BOOL,
            ctypes.wintypes.DWORD)

        def _errcheck_bool(result, func, args):
            if not result:
                raise ctypes.WinError(ctypes.get_last_error())
            return args

        kernel32.SetConsoleCtrlHandler.errcheck = _errcheck_bool
        kernel32.SetConsoleCtrlHandler.argtypes = (
            PHANDLER_ROUTINE,
            ctypes.wintypes.BOOL)

        from uvicorn.supervisors.multiprocess import Multiprocess
        uvicorn_multiprocess_startup_orig = Multiprocess.startup
        def uvicorn_multiprocess_startup(self, *args, **kwargs):
            ret = uvicorn_multiprocess_startup_orig(self, *args, **kwargs)

            def win_ctrl_handler(dwCtrlType):
                if (dwCtrlType == CTRL_C_EVENT and
                    not self.should_exit.is_set()):
                    kernel32.SetConsoleCtrlHandler(_console_ctrl_handlers[win_ctrl_handler], False)
                    self.signal_handler(SIGINT, None)
                    del _console_ctrl_handlers[win_ctrl_handler]
                    return True
                return False

            if win_ctrl_handler not in _console_ctrl_handlers:
                h = PHANDLER_ROUTINE(win_ctrl_handler)
                kernel32.SetConsoleCtrlHandler(h, True)
                _console_ctrl_handlers[win_ctrl_handler] = h

            return ret
        Multiprocess.startup = uvicorn_multiprocess_startup

    uvicorn.run("app", workers=4)

@AshminJayson
Copy link

Also the issue of the everything being frozen is generally triggered right after watchfiles tries restarting the server/detected a change, also killing the process manually using the port number doesn't fully terminate it and does not allow for the port to be reused without a full system reboot.

The current workaround which works for this is to run uvicorn from the main function of the app rather than having to run it directly as a command line command.

This ensures that the port is freed and also terminates the program correctly.

if __name__ == '__main__':
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

@olafrv
Copy link

olafrv commented Oct 28, 2023

Does not works for me @AshminJayson .
I switched to hypercorn in the meantime.

if __name__ == '__main__':
    # https://github.com/encode/uvicorn/issues/1972
    asyncio.run(serve(app, Config()))

Sample:

PS C:\Users\olafr\test> python .\server.py
[2023-10-28 02:19:19 +0200] [13228] [INFO] Running on http://127.0.0.1:8000 (CTRL + C to quit)
2023-10-28 02:19:19,472 loglevel=INFO   logger=hypercorn.error info() L106  Running on http://127.0.0.1:8000 (CTRL + C to quit)
PS C:\Users\olafr\test>

@humrochagf
Copy link
Contributor

@olafrv can you check if the changes that are in this MR works on your side?

#2059

@olafrv
Copy link

olafrv commented Oct 28, 2023

@humrochagf , tested, nothing changes, but thanks to your PR I nailed down the problem.

I'm on latests Windows 11 23H2 builtin Poweshell, VSCode 1.83.1, Python 3.12.0 (tags/v3.12.0:0fb18b0).

The signal is indeed received (CTRL+C), since the shutdown starts, both in 0.23.2 and your #2059 .

However, the shutdown process hangs forever, giving the impression of not working, you only see:
INFO: Shutting down

It does not matter if you pass or not the --reload and/or --reload-delay, so you end up doing:
taskkill /f /im "uvicorn.exe"

I found that the server.wait_closed() never returns (or timeouts after minutes):

I guess the socket.close() is never closed until timeout?:

sock.close()

My dirty workaround:

      for server in self.servers:
            # await server.wait_closed()
            pass

I also saw Python has an open asyncio.Server.wait_closed() appears to hang indefinitely in 3.12.0a7 but I didn't check how it is related to the server.py logic in depth.

So you can merge #2059 but won't solve the(my) problem.

It is reproducible even with this helloworld.py but it gets more evident on more complex apps:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@humrochagf
Copy link
Contributor

Alright, thanks for taking a look at it, I'll run some tests in python 3.12 to see if I can reproduce it 🙂

@jcheng5
Copy link
Contributor

jcheng5 commented Oct 30, 2023

There's a discussion on this issue here, along with a proposed fix: #2122

@tonnydourado
Copy link

tonnydourado commented Nov 30, 2023

By the way, I'm having the same problem for a while, on Windows 10, both Python 3.9 and 3.11. Don't remember the version I was using with 3.9, but with 3.11 is 0.24.0.post1.

Downgrading to 0.21.1 seems to improve the reload behavior, but CTRL+C still doesn't work, with or without reload.

By the way, this is somewhat intermittent. It's broken most of the time, but sometimes it just works normally, just often enough to make me doubt my sanity, competence, and the nature of reality itself.

@frankhuurman
Copy link

frankhuurman commented Dec 11, 2023

Not entirely sure if this is the same issue but on Windows 10 I'm also having issues since a python 3.12 upgrade with the NiceGUI framework(that uses uvicorn under the hood for filewatching/serving).

Any time I edit & save a file while uvicorn is running, it seems to shut down some process and not properly pick up on file changes plus it's impossible to Ctrl+C out of the application unless I close the browser tab.

zauberzeug/nicegui#2138

Python 3.11.x works fine, Python 3.12+ seems to break the filewatcher(unsure if the actual bug is in Uvicorn or in the asyncio/python 3.12/Windows combo).
On Mac OS/Linux it works fine with Py 3.12, it's just Windows that's seemingly picky.

@Mason-Chou
Copy link

I've been using this project for on Windows for quite a while and finally decided to spend some time tonight to look into why this annoying issue is happening.

There has been some great discussions over possible fixes to this issue, but it seems like it comes down to the parent process, supervisors.multiprocess.Multiprocess, being unable to receive any signals from pressing Ctrl+C.

Why is it the case? The Server subprocesses is able to receive the signals fine. Seems to be an open bug with CPython threading.Event.wait() on Windows.

@humrochagf seems to be on the right path with #2059 by changing the behavior to use a timeout to unblock the parent process and have it receive all the handled signals. Seems to be buggy still though.

The fix I've done was replacing the self.should_exit.wait() with a simple time.sleep() loop in supervisors.multiprocess.Multiprocess

    def run(self) -> None:
        self.startup()
        while not self.should_exit.is_set():
            time.sleep(.1)
        self.shutdown()

Seems to work with my build:

  • Windows 11
  • Python 3.12
  • uvicorn master branch

I'm sure it'll work for older versions. --reload works for me but still has some annoying CancelledError.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.