diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b94a409b..77c79905 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -30,6 +30,9 @@ jobs: - name: Run FPC router lifetime regression run: sh tests/fpc-router-lifetime/run-router-lifetime-test.sh + - name: Run FPC HTTPApplication graceful shutdown regression + run: sh tests/fpc-graceful-shutdown/run-graceful-shutdown-test.sh + - name: Run FPC URL decoding regression run: sh tests/fpc-url-decoding/run-url-decoding-test.sh diff --git a/doc/graceful-shutdown.md b/doc/graceful-shutdown.md index c768b058..fd0d14ac 100644 --- a/doc/graceful-shutdown.md +++ b/doc/graceful-shutdown.md @@ -61,6 +61,7 @@ The graceful shutdown protocol and drain loop are natively implemented in the fo * **Daemon Provider** (`Horse.Provider.Daemon`) * **Lazarus/LCL Provider** (`Horse.Provider.FPC.LCL`) * **Lazarus Daemon Provider** (`Horse.Provider.FPC.Daemon`) +* **FPC HTTPApplication Provider** (`Horse.Provider.FPC.HTTPApplication`) * **IOCP Provider** (`Horse.Provider.IOCP`) * **HTTP.sys Provider** (`Horse.Provider.HttpSys`) diff --git a/doc/graceful-shutdown.pt-BR.md b/doc/graceful-shutdown.pt-BR.md index 559bb814..69227bd0 100644 --- a/doc/graceful-shutdown.pt-BR.md +++ b/doc/graceful-shutdown.pt-BR.md @@ -61,6 +61,7 @@ O protocolo de desligamento suave e o ciclo de escoamento de requisições ativa * **Daemon Provider** (`Horse.Provider.Daemon`) * **Lazarus/LCL Provider** (`Horse.Provider.FPC.LCL`) * **Lazarus Daemon Provider** (`Horse.Provider.FPC.Daemon`) +* **FPC HTTPApplication Provider** (`Horse.Provider.FPC.HTTPApplication`) * **IOCP Provider** (`Horse.Provider.IOCP`) * **HTTP.sys Provider** (`Horse.Provider.HttpSys`) diff --git a/src/Horse.Provider.FPC.HTTPApplication.pas b/src/Horse.Provider.FPC.HTTPApplication.pas index 5a432fa7..948e23e6 100644 --- a/src/Horse.Provider.FPC.HTTPApplication.pas +++ b/src/Horse.Provider.FPC.HTTPApplication.pas @@ -28,6 +28,8 @@ THorseProvider = class(THorseProviderAbstract) class var FRunning: Boolean; class var FListenQueue: Integer; class var FHTTPApplication: THTTPApplication; + class var FStopRequested: LongInt; + class var FStopFinished: LongInt; class function GetDefaultHTTPApplication: THTTPApplication; class function HTTPApplicationIsNil: Boolean; class procedure SetListenQueue(const AValue: Integer); static; @@ -40,6 +42,9 @@ THorseProvider = class(THorseProviderAbstract) class function GetHost: string; static; class procedure InternalListen; virtual; class procedure DoGetModule(Sender: TObject; ARequest: TRequest; var ModuleClass: TCustomHTTPModuleClass); + class procedure DoAcceptIdle(Sender: TObject); + class function StopIsRequested: Boolean; + class procedure StopAccepting(const AApplication: THTTPApplication); {$IF FPC_FULLVERSION >= 30301} class procedure EnableServerKeepAlive(const AApplication: THTTPApplication); class procedure ConfigureServerTransport(const AApplication: THTTPApplication); @@ -61,6 +66,8 @@ THorseProvider = class(THorseProviderAbstract) // PATCH-FPCHTTP-1 class procedure ListenWithConfig(const APort: Integer; const AConfig: THorseCrossSocketConfig); override; + class procedure StopListen; override; + class procedure StopListenGraceful(const ATimeoutMS: Integer); override; class function IsRunning: Boolean; end; {$ENDIF} @@ -71,11 +78,24 @@ implementation uses Horse.WebModule, + Horse.Core, Horse.Response {$IF FPC_FULLVERSION >= 30301}, custhttpapp, fphttpserver, ssockets{$ENDIF} {$IF DEFINED(FPC) AND DEFINED(UNIX)}, Sockets{$ENDIF} {$IF DEFINED(FPC) AND DEFINED(MSWINDOWS)}, WinSock2{$ENDIF}; +const + { The accept loop wakes up this often while idle, so a stop + requested before Run starts accepting (Terminate cannot break an accept loop + that has not started yet) is still honoured on the next idle tick. } + STOP_ACCEPT_IDLE_MS = 100; + STOP_DRAIN_POLL_MS = 50; + { Listen polls the end of the drain instead of waiting on an OS event: an + event created at unit initialization would break programs that never + stop the server and run without a thread manager (no cthreads). } + STOP_FINISHED_POLL_MS = 10; + DEFAULT_STOP_TIMEOUT_MS = 5000; + {$IF FPC_FULLVERSION >= 30301} const { Per-request keep-alive lifetime handed to the embedded fphttpserver so its @@ -292,9 +312,100 @@ class procedure THorseProvider.InternalListen; EnableServerKeepAlive(LHTTPApplication); ConfigureServerTransport(LHTTPApplication); {$ENDIF} + { With a positive idle timeout the accept loop polls + DoAcceptIdle, which stops accepting once a stop was requested. } + LHTTPApplication.AcceptIdleTimeout := STOP_ACCEPT_IDLE_MS; + LHTTPApplication.OnAcceptIdle := DoAcceptIdle; FRunning := True; DoOnListen; - LHTTPApplication.Run; + try + if not StopIsRequested then + LHTTPApplication.Run; + + { Run returns as soon as the accept loop ends; Listen only returns after + StopListenGraceful finished draining, so callers that exit right after + Listen do not race the drain. } + if StopIsRequested then + while InterlockedCompareExchange(FStopFinished, 0, 0) = 0 do + Sleep(STOP_FINISHED_POLL_MS); + finally + FRunning := False; + InterlockedExchange(FStopFinished, 0); + InterlockedExchange(FStopRequested, 0); + end; +end; + +class function THorseProvider.StopIsRequested: Boolean; +begin + Result := InterlockedCompareExchange(FStopRequested, 0, 0) <> 0; +end; + +class procedure THorseProvider.DoAcceptIdle(Sender: TObject); +begin + if StopIsRequested then + StopAccepting(GetDefaultHTTPApplication); +end; + +class procedure THorseProvider.StopAccepting(const AApplication: THTTPApplication); +{$IF FPC_FULLVERSION >= 30301} +var + LHandler: TFPHTTPServerHandler; + LServer: TEmbeddedHttpServer; +{$ENDIF} +begin + { Terminate marks the application so Run leaves its loop. It reaches the + handler (and the server) only the first time, so a call made before Run + starts accepting would be lost: the embedded server is also switched off + directly, which is what the idle guard relies on. } + AApplication.Terminate; + {$IF FPC_FULLVERSION >= 30301} + LHandler := AApplication.HTTPHandler; + if LHandler <> nil then + begin + LServer := THorseHTTPServerHandlerAccess(LHandler).HTTPServer; + if LServer <> nil then + begin + { Idle keep-alive connections re-read KeepConnections on every loop and + leave within the idle poll instead of holding the stop for the whole + keep-alive window; requests in flight are not cut. } + THorseEmbeddedServerAccess(LServer).KeepConnections := False; + LServer.Active := False; + end; + end; + {$ENDIF} +end; + +class procedure THorseProvider.StopListen; +begin + StopListenGraceful(DEFAULT_STOP_TIMEOUT_MS); +end; + +class procedure THorseProvider.StopListenGraceful(const ATimeoutMS: Integer); +var + LStart: QWord; +begin + { Documented order (doc/graceful-shutdown.md): mark the + shutdown, stop listening, drain the active requests up to ATimeoutMS, then + release Listen. A stop requested before Listen reaches Run makes Listen + return without serving; a second call is a no-op. } + if InterlockedExchange(FStopRequested, 1) <> 0 then + Exit; + + TriggerBeforeStop; + THorseCore.SetIsShuttingDown(True); + try + if not HTTPApplicationIsNil then + StopAccepting(GetDefaultHTTPApplication); + + LStart := GetTickCount64; + while (GetDrainActiveRequests > 0) and (GetTickCount64 - LStart < QWord(ATimeoutMS)) do + Sleep(STOP_DRAIN_POLL_MS); + + DoOnStopListen; + finally + THorseCore.SetIsShuttingDown(False); + InterlockedExchange(FStopFinished, 1); + end; end; class procedure THorseProvider.DoGetModule(Sender: TObject; ARequest: TRequest; var ModuleClass: TCustomHTTPModuleClass); diff --git a/tests/fpc-graceful-shutdown/GracefulShutdownCheck.dpr b/tests/fpc-graceful-shutdown/GracefulShutdownCheck.dpr new file mode 100644 index 00000000..edee0ca2 --- /dev/null +++ b/tests/fpc-graceful-shutdown/GracefulShutdownCheck.dpr @@ -0,0 +1,229 @@ +program GracefulShutdownCheck; + +{ Graceful shutdown of the FPC HTTPApplication provider. + + Usage: GracefulShutdownCheck [drain|in-onlisten] + + drain (default): a worker waits for the server, opens an idle keep-alive + connection, starts a slow request (1.5 s) and calls StopListenGraceful. + The check passes when: + - the slow request in flight answers 200; + - the idle keep-alive connection sees EOF in under 1 s, while the slow + request is still draining; + - StopListenGraceful returns before Listen does; + - Listen returns at all. + + in-onlisten: StopListenGraceful is called inside the Listen callback, the + earliest point; Listen must return without serving. + + Exit code 0 means pass. Before this change the provider inherited the + abstract StopListen, which raises "StopListen not implemented", and Listen + never returned. } + +{$MODE DELPHI}{$H+} + +uses + {$IFDEF UNIX} + cthreads, + {$ENDIF} + Classes, + SysUtils, + SyncObjs, + ssockets, + fphttpclient, + Horse; + +const + SLOW_MS = 1500; + IDLE_EOF_LIMIT_MS = 1000; + READY_TIMEOUT_MS = 10000; + STOP_TIMEOUT_MS = 5000; + +var + GPort: Integer; + GStopReturned: LongInt; + GListenReturnedFirst: LongInt; + GSlowStatus: Integer; + GIdleEofMs: Int64; + GFailure: string; + +procedure Slow(Req: THorseRequest; Res: THorseResponse); +begin + Sleep(SLOW_MS); + Res.Send('slow-ok'); +end; + +procedure Ping(Req: THorseRequest; Res: THorseResponse); +begin + Res.Send('pong'); +end; + +procedure StopFromThread; +begin + THorse.StopListenGraceful(STOP_TIMEOUT_MS); + InterlockedExchange(GStopReturned, 1); +end; + +procedure StopInOnListen; +begin + THorse.StopListenGraceful(STOP_TIMEOUT_MS); +end; + +function Url(const APath: string): string; +begin + Result := Format('http://127.0.0.1:%d%s', [GPort, APath]); +end; + +function ServerAnswers: Boolean; +var + LClient: TFPHTTPClient; +begin + LClient := TFPHTTPClient.Create(nil); + try + LClient.KeepConnection := False; + LClient.IOTimeout := 500; + try + Result := Trim(LClient.Get(Url('/ping'))) = 'pong'; + except + Result := False; + end; + finally + LClient.Free; + end; +end; + +type + TSlowRequest = class(TThread) + protected + procedure Execute; override; + end; + + TDrainWorker = class(TThread) + protected + procedure Execute; override; + end; + +procedure TSlowRequest.Execute; +var + LClient: TFPHTTPClient; +begin + LClient := TFPHTTPClient.Create(nil); + try + LClient.KeepConnection := False; + LClient.IOTimeout := 10000; + try + LClient.Get(Url('/slow')); + GSlowStatus := LClient.ResponseStatusCode; + except + GSlowStatus := -1; + end; + finally + LClient.Free; + end; +end; + +function OpenIdleKeepAlive: TInetSocket; +const + REQUEST = 'GET /ping HTTP/1.1'#13#10'Host: 127.0.0.1'#13#10'Connection: keep-alive'#13#10#13#10; +var + LRequest: AnsiString; + LBuffer: array[0..1023] of Byte; + LRead: Integer; + LReceived: AnsiString; +begin + Result := TInetSocket.Create('127.0.0.1', GPort); + Result.IOTimeout := 3000; + LRequest := REQUEST; + Result.WriteBuffer(LRequest[1], Length(LRequest)); + LReceived := ''; + repeat + LRead := Result.Read(LBuffer, SizeOf(LBuffer)); + if LRead > 0 then + LReceived := LReceived + Copy(PAnsiChar(@LBuffer[0]), 1, LRead); + until (LRead <= 0) or (Pos('pong', LReceived) > 0); + if Pos('pong', LReceived) = 0 then + raise Exception.Create('keep-alive connection did not get its response'); +end; + +function WaitEof(const ASocket: TInetSocket): Int64; +var + LBuffer: array[0..255] of Byte; + LStart: QWord; +begin + LStart := GetTickCount64; + ASocket.IOTimeout := 5000; + while ASocket.Read(LBuffer, SizeOf(LBuffer)) > 0 do; + Result := GetTickCount64 - LStart; +end; + +procedure TDrainWorker.Execute; +var + LDeadline: QWord; + LIdle: TInetSocket; + LSlow: TSlowRequest; +begin + try + LDeadline := GetTickCount64 + READY_TIMEOUT_MS; + while not ServerAnswers do + begin + if GetTickCount64 > LDeadline then + raise Exception.Create('server did not answer'); + Sleep(50); + end; + + LIdle := OpenIdleKeepAlive; + try + LSlow := TSlowRequest.Create(False); + try + Sleep(200); + TThread.CreateAnonymousThread(StopFromThread).Start; + GIdleEofMs := WaitEof(LIdle); + LSlow.WaitFor; + finally + LSlow.Free; + end; + finally + LIdle.Free; + end; + except + on E: Exception do + GFailure := E.ClassName + ': ' + E.Message; + end; +end; + +var + LMode: string; + LWorker: TDrainWorker; +begin + GPort := StrToInt(ParamStr(1)); + LMode := ParamStr(2); + THorse.Get('/ping', Ping); + THorse.Get('/slow', Slow); + + if LMode = 'in-onlisten' then + begin + THorse.Listen(GPort, StopInOnListen); + WriteLn('in-onlisten: Listen returned'); + Halt(0); + end; + + LWorker := TDrainWorker.Create(False); + THorse.Listen(GPort); + if InterlockedCompareExchange(GStopReturned, 0, 0) = 0 then + GListenReturnedFirst := 1; + LWorker.WaitFor; + LWorker.Free; + + WriteLn(Format('slow=%d idle-eof=%dms listen-before-stop=%d failure=%s', + [GSlowStatus, GIdleEofMs, GListenReturnedFirst, GFailure])); + + if GFailure <> '' then + Halt(1); + if GSlowStatus <> 200 then + Halt(2); + if GIdleEofMs >= IDLE_EOF_LIMIT_MS then + Halt(3); + if GListenReturnedFirst <> 0 then + Halt(4); + WriteLn('drain: passed'); +end. diff --git a/tests/fpc-graceful-shutdown/README.md b/tests/fpc-graceful-shutdown/README.md new file mode 100644 index 00000000..8de7811c --- /dev/null +++ b/tests/fpc-graceful-shutdown/README.md @@ -0,0 +1,25 @@ +# FPC HTTPApplication graceful shutdown regression + +`GracefulShutdownCheck.dpr` drives `THorse.StopListenGraceful` on the FPC +HTTPApplication provider (the default provider for FPC console applications). +Before this change, the provider did not override `StopListen`: it inherited +the abstract one, which raises `StopListen not implemented`, although +`doc/deployment.md` stops this shape with `THorse.StopListen`. + +Two modes, each must exit with code 0: + +- `drain`: with a slow request in flight and an idle keep-alive connection + open, `StopListenGraceful` stops accepting, lets the slow request answer + 200, makes the idle connection see EOF in under 1 s (keep-alive is switched + off instead of waiting for its 15 s window) and returns before `Listen` + does. +- `in-onlisten`: `StopListenGraceful` called inside the `Listen` callback, the + earliest point; `Listen` returns without serving. The accept loop runs with + an idle timeout, so a stop requested before `Run` starts accepting is still + honoured. + +On Linux, run `sh tests/fpc-graceful-shutdown/run-graceful-shutdown-test.sh` +from the repository root. The same command is registered in the tests +workflow. Against the provider without this change, `drain` hangs (the +script fails on its timeout) and `in-onlisten` exits with +`StopListen not implemented`. diff --git a/tests/fpc-graceful-shutdown/run-graceful-shutdown-test.sh b/tests/fpc-graceful-shutdown/run-graceful-shutdown-test.sh new file mode 100644 index 00000000..71698ff5 --- /dev/null +++ b/tests/fpc-graceful-shutdown/run-graceful-shutdown-test.sh @@ -0,0 +1,27 @@ +#!/bin/sh +set -eu + +test_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +output_dir=$(mktemp -d /tmp/horse-graceful-shutdown.XXXXXX) +port=${HORSE_GRACEFUL_PORT:-9911} + +cd "$test_dir" +fpc -B -Mdelphi -Sh -gl \ + -Fu../../src \ + -FU"$output_dir" -FE"$output_dir" \ + GracefulShutdownCheck.dpr + +# Without this change, StopListen raised "not implemented" and Listen never +# returned: the timeout turns that hang into a failure. +for mode in drain in-onlisten; do + set +e + timeout 30 "$output_dir/GracefulShutdownCheck" "$port" "$mode" + status=$? + set -e + if [ "$status" -ne 0 ]; then + echo "Graceful shutdown regression ($mode): exit status $status." >&2 + exit 1 + fi +done + +echo 'Graceful shutdown regression passed: drain, idle keep-alive, Listen order and stop inside OnListen.'