Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

HTTP2: Rework shutdown handling - #39638

Merged
geoffkizer merged 7 commits into
dotnet:masterfrom
geoffkizer:streamshutdownfixes4
Jul 24, 2019
Merged

geoffkizer merged 7 commits into
dotnet:masterfrom
geoffkizer:streamshutdownfixes4

Conversation

@geoffkizer

@geoffkizer geoffkizer commented Jul 20, 2019 •

Copy link
Copy Markdown

Fixes #39630
Fixes #39624
Incomplete attempt to fix #39586
Fixes #39461
Fixes #39460
Fixes #39458
Fixes #39459
Fixes #39404

Rework shutdown handling to be reliable and consistent, for both streams and connections.

Each Http2Stream has to complete both request and response before shutting down, at which time it will remove itself from the stream dictionary and clean up associated state.

The request body and response body can each be cancelled, and these are now cancelled at appropriate times (e.g. Dispose on response stream before reading to end).

The behavior of early non-success status codes is changed to not cancel the request body. This matches HTTP/1.1 behavior.

The connection is now shut down only when all streams are removed from the dictionary. Receiving EndStream or RST_STREAM does not automatically remove the stream; instead we let the stream manage its own shutdown and then remove it from the dictionary.

Add relevant tests, fix up some existing tests, and remove one bogus test.

I haven't run stress tests on this yet -- I wanted to get the review out first. Will report when I have stress results.

cc @stephentoub @dotnet/ncl

@geoffkizer
geoffkizer requested review from a team and stephentoub July 20, 2019 02:23
@geoffkizer geoffkizer added this to the 3.0 milestone Jul 20, 2019
waiter.TrySetException(abortException != null ? (Exception)
new IOException(SR.net_http_request_aborted, abortException) :
CreateObjectDisposedException(forActiveWaiter: true));
waiter.TrySetException(CreateObjectDisposedException(forActiveWaiter: true));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've not yet read most of the PR yet, but... is this revert a mistake, or is it no longer needed because we now expect there never to be a waiter present when a CreditManager is disposed? If the latter, seems there should be a Debug.Fail inside the waiters != null block.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We now expect there never to be a waiter present.

Re Debug.Fail, where do you want this?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re Debug.Fail, where do you want this?

As the first line inside if (_waiters != null) block.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, yeah. Sure, I can make that change.

if (NetEventSource.IsEnabled) Trace($"{nameof(ProcessIncomingFramesAsync)}: {e.Message}");

if (!_disposed)
if (_abortException == null)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just always call Abort and let its logic figure out what to do?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems reasonable. I will make the change and see what happens.

The main point of the change here is to not skip this just because _disposed is set; this could mean we don't abort streams properly -- see my comment on _disposed at the top of the file.

FWIW, there's some weirdness here in that if the connection fails, we could end up throwing in both the read path and the write path, and racing to determine which exception is actually stored. That seems bad; better to have consistent behavior here. We should always fail in the read path, because we are constantly reading from the connection. We could also fail a write, and if that happens, that's when the race occurs. I thought about changing this so that we only actually abort when the read fails, but then what do we do if a write fails? Just keep trying to write and assume that the read will fail too, causing an abort? Seems a bit odd. Thoughts?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really related, but anyway: We're also going to throw here when the server shuts down the connection and we receive EOF. We throw some exception about "expected 9 bytes to read" (frame header size). This is slightly annoying for two reasons: One is, we should avoid throwing in non-error situations, which this could be, if it the server has previously sent a GOAWAY and we've finished processing all streams. Two is, the actual exception text is not super helpful. Possibly we should make some changes here. We do need to still go through the abort path in this case because we need to abort any requests that the server didn't complete. Thoughts?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could end up throwing in both the read path and the write path, and racing to determine which exception is actually stored.

I think it's ok, or at least that the alternatives are worse. But this is why we have _abortException, user an interlocked to set it, and when it's set propagate it, in order to try to always surface the same exception, even when there's a race.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One is, we should avoid throwing in non-error situations, which this could be, if it the server has previously sent a GOAWAY and we've finished processing all streams.

Doesn't seem particularly hard. We could just TryReadFrame or whatever, and then if it was false and there were active streams, we could abort them with a better exception.

{
http2Stream.OnAbort(new Http2StreamException(protocolError));
http2Stream.OnReset(new Http2StreamException(protocolError));
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about just:

http2Stream.OnReset(
    new Http2StreamException(protocolError),
    canRetry: protocolError == Http2ProtocolErrorCode.RefusedStream);

?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure


// On cancel, we get TaskCanceledException here instead of OperationCanceledException.
// For consistency, try to ensure we get OperationCanceledException when the cancellationToken has fired.
cancellationToken.ThrowIfCancellationRequested();

@stephentoub stephentoub Jul 20, 2019 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For consistency, try to ensure we get OperationCanceledException when the cancellationToken has fired.

We have a bunch of places that actually try to do the opposite.

internal static Exception CreateOperationCanceledException(Exception innerException, CancellationToken cancellationToken) =>
new TaskCanceledException(s_cancellationMessage, innerException, cancellationToken); // TCE for compatibility with other handlers that use TaskCompletionSource.TrySetCanceled()

I would remove this ThrowIfCancellationRequested. TCE derives from OCE; it's fine to let the former propagate.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, will do. I changed it because some test was explicitly checking for OCE; I'll fix the test.

WriteHeaders(request);

Http2Stream http2Stream = AddStream(request);
int streamId = http2Stream.StreamId;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If something fails between here and the return, such as StartWriteAsync getting canceled, what removes the newly added stream?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, there's a problem here. I changed this as I was changing all the RemoveStream stuff. But I think it ended up wrong.

I'm a little worried there are some error paths in this method that aren't handled properly. I'll go through it and try to ensure all cases are handled.


lock (SyncObject)
{
if (NetEventSource.IsEnabled) Trace($"{nameof(abortException)}={abortException}");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be moved to the beginning of the method, prior to the InvalidateHttp2Connection call? I don't remember why we felt it was important to call it under the lock, but it seems misleading here for someone reading the trace.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do

{
replacementException = new OperationCanceledException(oce.Message, oce, cancellationToken);
}
throw new HttpRequestException(SR.net_http_client_execution_error, e);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it ok to remove the _abortException ?? here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the exception that propagates from failure above should be the correct exception to give to the user.

It's possible that there's some weird timing issues where (a) an exception happens above, and starts to propagate; (b) OnReset is called, and sets _resetException; (c) this causes the original exception to get overwritten. If the code above is failing for the same reason OnReset is being called -- i.e. connection failure or whatever -- then the same exception should get propagated both ways.

}

// We run out of IDs or we have race condition between receiving GOAWAY and processing requests.
// We ran out of stream IDs or we raced condition between acquiring the connection from the pool and shutting down.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: "or we raced condition"... strange phrasing

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will fix

// Stream can be removed from background ProcessIncomingFramesAsync() when endOfStream is set
// or when we hit various error conditions in SendAsync() call.
// Skip logic below if stream was already removed.
Debug.Assert(false, "Stream not found in dictionary during RemoveStream???");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Debug.Assert(false, => Debug.Fail(

_responseProtocolState = ResponseProtocolState.ExpectingStatus;

_disposed = false;
_request = request;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: move this to be the very first line, so that the first three lines map to assigning the first three arguments to fields?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do

{
using (Http2WriteStream writeStream = new Http2WriteStream(this))
if (NetEventSource.IsEnabled)
Trace($"{_request.Content}");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: one line

catch (Exception e)
{
if (NetEventSource.IsEnabled) Trace($"Failed to send request body: {e}");
await _connection.SendEndStreamAsync(_streamId);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.ConfigureAwait(false)

if (_requestBodyCancellationSource != null)
{
_requestBodyCancellationSource.Dispose();
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: _requestBodyCancellationSource?.Dispose();

{
var thisRef = (Http2Stream)s;
if (NetEventSource.IsEnabled)
thisRef.Trace($"100-Continue timer expired.");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: one line

}
else

if (NetEventSource.IsEnabled) Trace($"Stream complete.");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit:

if (NetEventSource.IsEnabled) Trace($"Stream complete. Request={_requestCompletionState}, Response={_responseCompletionState}.");

?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do

{
return;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Debug.Assert(_requestBodyCancellationSource != null);?


if (endStream)
{
Debug.Assert(_responseCompletionState == StreamCompletionState.InProgress, $"Response already completed with state={_responseCompletionState}");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we assert this safely? i.e. what if the server sent erroneous data... could it trigger this assert?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we process the first endStream, we should set _responseProtocolState (NOT _responseCompletionState) to Completed. Then any subsequent frames received should throw a protocol error when they check the state. So we shouldn't get here.

That said, some of the state logic around _responseProtocolState above and elsewhere is a little messy, so I can't say 100% we catch all of these. We have tests for this, but we could be missing something. I've tried not to mess with _responseProtocolState too much here because I didn't want to break anything here, but perhaps I should review all this and clean it up a bit.

_waitSource.SetResult(true);
}
CancelRequestBody();
CancelResponseBody();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CancelResponseBody calls CancelRequestBody. Do we need both here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've been thinking I may combine these into one routine anyway, just Cancel(). As you point out, CancelResponseBody calls CancelRequestBody anyway. And we only call CancelRequestBody without calling CancelResponseBody in cases where the response body is already completed (I think -- will verify), so in that case cancelling the response body is a no-op anyway. Will look at this further.

@geoffkizer
geoffkizer force-pushed the streamshutdownfixes4 branch from b2899ee to 29328b7 Compare July 23, 2019 20:19
@geoffkizer

Copy link
Copy Markdown
Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 4 pipeline(s).

// We can't validate that we hold the semaphore, but we can at least validate that someone is holding it.
Debug.Assert(_writerLock.CurrentCount == 0);

EndWrite(false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: EndWrite(forceFlush: false);

FrameFlags flags =
(remaining.Length == 0 ? FrameFlags.EndHeaders : FrameFlags.None) |
(request.Content == null ? FrameFlags.EndStream : FrameFlags.None);
// Client-initiated streams are always odd-numbered, so increase by 2.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth adding an assert that _nextStream is odd?

@geoffkizer

Copy link
Copy Markdown
Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 4 pipeline(s).

@geoffkizer

Copy link
Copy Markdown
Author

Failures are unrelated

@geoffkizer
geoffkizer merged commit ca3fe67 into dotnet:master Jul 24, 2019
@Tratcher

Copy link
Copy Markdown
Member

The behavior of early non-success status codes is changed to not cancel the request body. This matches HTTP/1.1 behavior.

Are you sure about this one? HTTP/1.1 has to do this in order to maintain the connection protocol (e.g. content-length many bytes MUST be sent or you have to close the connection). HTTP/2 is more flexible, it can reset the stream without disrupting the connection. Once you have a final non-success status code the request body is no longer needed. The server is likely to reset the stream anyways if the client keeps sending unwanted request data.

@geoffkizer

Copy link
Copy Markdown
Author

@Tratcher I agree, it would be good to stop sending the request body in this case. We were trying to do this previously, but the logic wasn't correct in some cases.

Given the 3.0 timeframe, and given how HTTP/1.1 works, it seems best to just match 1.1 behavior here. We can revisit in the future.

@JamesNK

JamesNK commented Jul 25, 2019

Copy link
Copy Markdown
Member

Is this being included with 3.0? I downloaded the latest nightly SDK and gRPC functional tests are still broken. Is that because the nightly SDK doesn't include this PR yet or because it hasn't been applied to the 3.0 branch?

@geoffkizer

Copy link
Copy Markdown
Author

It's not in the 3.0 branch yet. Should be in today.

@geoffkizer

geoffkizer commented Jul 25, 2019 •

Copy link
Copy Markdown
Author

This is now in the 3.0 branch -- see PR #39775

@karelz

karelz commented Aug 3, 2019 •

Copy link
Copy Markdown
Member

@geoffkizer please link the PRs (ideally also all issues) in future, it is not clear which PR ported it to 3.0 :(
Update: 3.0 PR is #39775

@karelz

karelz commented Aug 3, 2019

Copy link
Copy Markdown
Member

@geoffkizer it seems one of the issues linked in top post is incorrect (I crossed it). Do you know which was the right number?

@geoffkizer

Copy link
Copy Markdown
Author

It should be #39458, not #39548.

@karelz

karelz commented Aug 3, 2019

Copy link
Copy Markdown
Member

Great, top post updated, thanks!

@karelz karelz modified the milestones: 3.0, 5.0 Aug 3, 2019
@karelz

karelz commented Aug 3, 2019

Copy link
Copy Markdown
Member

This PR went into master - fixing milestone to 5.0.
It was later ported into release/3.0 branch in PR #39775.

picenka21 pushed a commit to picenka21/runtime that referenced this pull request Feb 18, 2022
…fixes4

HTTP2: Rework shutdown handling

Commit migrated from dotnet/corefx@ca3fe67
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.