Repository navigation
TcpProxy: proxy half-closes - #2386
Conversation
Added optional half-close semantics to Connection. This is disabled by default to avoid making all code deal with half-close semantics when they don't need it. Signed-off-by: Greg Greenway <[email protected]>
mattklein123
left a comment
There was a problem hiding this comment.
Quick skim seems reasonable. 1 question. @alyssawilk can you take a look?
| ENVOY_CONN_LOG(debug, "new tcp proxy session", read_callbacks_->connection()); | ||
|
|
||
| read_callbacks_->connection().addConnectionCallbacks(downstream_callbacks_); | ||
| read_callbacks_->connection().enableHalfClose(true); |
There was a problem hiding this comment.
I'm not convinced we want this to be the default without any option. I'm wondering if this should be an opt-in option on the filter? WDYT?
There was a problem hiding this comment.
I think properly proxying half-closes should at least be the default. Is there any concrete use-case where this behavior causes problems? In general, if either the client or the server can't deal with half-close semantics, they'll signal that (via a RST), so the proxy shouldn't need to modify TCP behavior.
There was a problem hiding this comment.
I don't know. I'm mainly concerned that this is not the current behavior and something will break.
There was a problem hiding this comment.
I thought about it, and I agree it sounds reasonable to just do half-close processing for TCP proxy by default.
There was a problem hiding this comment.
Definitely warrants a release note so don't forget your TODO :-)
Signed-off-by: Greg Greenway <[email protected]>
alyssawilk
left a comment
There was a problem hiding this comment.
Fantastic! I'm really glad both that we're getting this support for Envoy and that someone else tackled it before I did ;-)
| ENVOY_CONN_LOG(debug, "new tcp proxy session", read_callbacks_->connection()); | ||
|
|
||
| read_callbacks_->connection().addConnectionCallbacks(downstream_callbacks_); | ||
| read_callbacks_->connection().enableHalfClose(true); |
There was a problem hiding this comment.
Definitely warrants a release note so don't forget your TODO :-)
| /** | ||
| * Half-closes the transport socket. For TCP, this sends a FIN. | ||
| */ | ||
| virtual void halfCloseSocket() PURE; |
There was a problem hiding this comment.
Looking at the documentation I'd think that this should be done by closeSocket. Looking at closeSocket I'm less sure.
I'd like to do half close and close in the same manner, so either do both in closeSocket, or rename closeSocket to prepareForClose (doing transport-specific stuff) and then do the half close where we actually currently close.
@lizan can you weigh in on this one?
There was a problem hiding this comment.
I started with including it in closeSocket(), but gave up because it shared no code with the other close paths, and the parameter type was wrong. It would have required adding a new enum value to ConnectionEvent that only made sense in this context, not in raising events to filters.
There was a problem hiding this comment.
It might be possible to merge those two methods. I don't think the parameter of closeSocket is actually used.
| FlushWrite, // Flush pending write data before raising ConnectionEvent::LocalClose | ||
| NoFlush // Do not flush any pending data and immediately raise ConnectionEvent::LocalClose | ||
| NoFlush, // Do not flush any pending data and immediately raise ConnectionEvent::LocalClose | ||
| HalfClose, // Send a half-close after flushing any pending data. If we have already received |
There was a problem hiding this comment.
This is a bit weird because it leads to a bunch of close(HalfClose) where close then doesn't really close.
Just to sanity check, plumbing this way was cleaner/easier than doing an H2 style last_data / fin boolean to the write call?
There was a problem hiding this comment.
I hadn't looked at the h2 style stuff. That's another option. But it might be weird because we'll always end up writing either (data, false), or (empty, true) because receiving the half-close is a connection-event, not included with onData(). But I suppose the half-close-rx could be included with onData() if we wanted.
Thinking about this, that actually may be more correct due to the following case:
- some data is read, a network filter in the chain before tcp_proxy gets onData() and returns StopIteration
- connection receives half-close, sends onEvent(half-close) to all filters
- tcp_proxy sends half-close to peer filter
- the other network filter unblocks the data, and now tcp_proxy gets some data that it can't proxy because it has already half-closed.
So would it make sense then to have the half-close signaling always go with the data (both tx and rx)?
There was a problem hiding this comment.
Yeah, we definitely need to make sure everything is drained before the half close. I suspect your way of doing things is cleaner from an API perspective but I don't know if there's a way to solve close getting ahead of data with it. I'm totally open to either if you find a way :-)
If you go the data/fin route you can totally "combine" data with the FIN for efficiency.
| // Attempt to send a shutdown before closing the socket. It's possible this won't go out if | ||
| // there is no room on the socket. We can extend the state machine to handle this at some point | ||
| // if needed. | ||
| int rc = SSL_shutdown(ssl_.get()); |
There was a problem hiding this comment.
hm, I think this cleans up TLS state but I'm not convinced it forwards the FIN on. I'd think we'd want to wait until SSL_shutdown succeeds and then send on the FIN. Alternately we can claim SSL_shutdown is best effort (which svaldez@google tells me is is generally OK) and FIN after.
@PiotrSikora any preference on this one?
There was a problem hiding this comment.
When you say "then send the FIN" do you mean a TCP-level FIN or a TLS-level FIN (logical FIN)?
Either way, I'm going to add an integration test that has tcp-proxy with TLS on one side and raw TCP on the other and test that half-close gets proxied correctly.
There was a problem hiding this comment.
TCP FIN :-)
Prior to this PR I hadn't realized TLS logical FIN was a thing, but I know all about proxying TCP FINs :-)
There was a problem hiding this comment.
In the case of TLS, because it operates as the transport layer, we don't send a TCP FIN at all; boringssl can do that if it wants to.
When the TLS connection is half-closed (at the TLS layer), I'm pretty sure the TCP connection still needs to be bi-directional in case any keys need to be renegotiated or renewed, because the connection could be in this state for an arbitrarily long amount of time. So calling SSL_shutdown() is all we're supposed to do on a TLS connection to consider it half-closed.
At least that's my understanding of it. Someone please correct me if I'm wrong.
There was a problem hiding this comment.
I'd prefer to do the full close_notify dance, or at the very least to make sure that we sent close_notify before tearing down the connection.
There was a problem hiding this comment.
According to https://wiki.openssl.org/index.php/Manual:SSL_shutdown(3), SSL_shutdown() sends a close-notify. But I'm not very familiar with this part of TLS or boring/openssl. Is there more that should be done to gracefully close the connection?
There was a problem hiding this comment.
SSL_shutdown() is the correct function, but it can fail (rc == -1) or might need to be retried (rc == -1 && (SSL_get_error() == SSL_ERROR_WANT_READ || SSL_get_error() == SSL_ERROR_WANT_WRITE)).
rc == 1 once close_notify has been both sent and received.
If we don't want to do that, then we should at least set SSL_set_quiet_shutdown() before calling SSL_shutdown(), otherwise we might end up in a weird state.
| if (data_to_write == 0 || type == ConnectionCloseType::NoFlush || | ||
| !transport_socket_->canFlushClose()) { | ||
| if (type == ConnectionCloseType::HalfClose) { | ||
| local_half_closed_ = true; |
There was a problem hiding this comment.
Can you verify a corner case for me? Let's assume we get a giant read with a FIN. So we set local_half_closed_ true but the write results in backup. When does the fin actually get sent?
I'd think you need something akin to close_with_flush_ where we'd mark should_send_fin_ here and then local_half_closed_ or sent_fin_ once we've flushed the write.
| fake_upstream_connection->waitForData(5); | ||
|
|
||
| fake_upstream_connection->close(); | ||
| fake_upstream_connection->halfClose(); |
There was a problem hiding this comment.
Now that we have half close, can we modify these so we
half close upstream->downstream path
wait for half close to propogate
write on downstream->upstream path (verify the connection is still open)
fully close
and vice versa?
There was a problem hiding this comment.
Yep, it's on my TODO list. There's a whole bunch of tests that need to be written for this PR still.
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
| enum class PostIoAction { | ||
| // Close the connection. | ||
| // Remote side sent a half-close. | ||
| HalfClose, |
There was a problem hiding this comment.
HalfClose shouldn't be in PostIoAction since it is not telling the connection what to do after I/O. The remote sent half-close should be a flag in IoResult.
There was a problem hiding this comment.
Yes, I agree. In thinking this through today from the other feedback, this makes sense.
|
I just spent some time with this and I think my current feeling at the filter leave is we should have:
and
and
Then I think we can basically keep the existing close and event semantics at the interface level. Close would basically just be a full close as it is today. This is a larger change, but I think it handles the filtering case a bunch better. I still think we would have the option to turn half close processing on at the connection level, which would control:
@ggreenway @alyssawilk @lizan WDYT? |
|
@mattklein123 That's pretty much what I was thinking too. I think that's the best interface. The ugliness will be in the filter manager to track the end_stream bit along with data, but it should be manageable and contained. |
Yeah, I think it won't be too bad. Also, unlike HTTP, the filter manager is already split out which makes it much easier to test. |
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
|
@mattklein123 @alyssawilk Can you take another look? Mostly looking for feedback on the interface and any high-level design issues. This still needs a bunch of work on tests. |
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
|
@ggreenway will take a look in the morning. While I'm going through and auditing coverage, can you take a look at the missing coverage in TCP proxy? Both of the missing cases seem like it would be good to cover. Thank you. |
|
@mattklein123 The first of those I'd like to delete; I want to make the config be required, so then there won't be an else case at all. Right now, that uncovered code is only hit for websockets. For the second one, I'll have to think about the right way to test that. That code is supposed to run if envoy is exiting with open connections, which is tricky to test. I could probably write a unit test for it, but it wouldn't tell us much, because really we want to know that it works correctly at the stage of shutdown it is called from. I'll see what I can do on that. I think when I wrote that code, you said it wasn't worth the effort to come up with a test for it. |
Agreed, we should just have a config in all cases to unify the logic.
Sorry I think I meant not an integration test. A unit test does have follow because it will usually catch issues with delayed deletion logic (via ASAN, etc.). It's not a huge deal but not a bad idea to add if you have time. |
mattklein123
left a comment
There was a problem hiding this comment.
Interface looks great to me. I didn't fully review the code, but left one question.
| * are installed. | ||
| */ | ||
| virtual void write(Buffer::Instance& data) PURE; | ||
| virtual void write(Buffer::Instance& data, bool last_byte) PURE; |
There was a problem hiding this comment.
nit: I might consider actually calling this end_stream vs. last_byte like we do up in HTTP land, just to match the concepts. But I admit this is bikeshedding and I don't feel strongly about it.
There was a problem hiding this comment.
I'll change it to keep things consistent.
| IoResult RawBufferSocket::doRead(Buffer::Instance& buffer) { | ||
| PostIoAction action = PostIoAction::KeepOpen; | ||
| uint64_t bytes_read = 0; | ||
| bool last_byte = false; |
There was a problem hiding this comment.
This is not a fully formed comment, just a question: Do we have problems since we are using EV_CLOSED (FileReadyType::Closed)? Is there a case during flow control in which we might get EOF but not actually read all the data and do we now have to handle that? I know we had some issues with this in the past and don't enable EV_CLOSED in all cases, but I think it might cause problems.
There was a problem hiding this comment.
I actually suspect that if we are handling half close semantics we should never set EV_CLOSED?
There was a problem hiding this comment.
Yes, I think we will want to disable EV_CLOSED in this case.
There was a problem hiding this comment.
I think I just need to call detectEarlyCloseWhenReadDisabled(true) on both the upstream and downstream connections. @alyssawilk does that seem correct?
There was a problem hiding this comment.
Yes I think that is correct. Basically if half close semantics are enabled never detect early close.
alyssawilk
left a comment
There was a problem hiding this comment.
This looks fantastic! I think it was definitely worth the rewrite.
I did a more thorough review than you asked for, since I think the APIs look fine, and this way I don't have to do a full pass on the source come next upload. Hopefully the flood of nits is OK :-) Ignored the tests for now, but I'll take a look next round.
| */ | ||
| enum class PostIoAction { | ||
| // Close the connection. | ||
| // Connection is forcibly closed. |
There was a problem hiding this comment.
I think the previous comment makes more sense given the context "This is the action that should occur"
| * True if an end-of-stream was read from a connection. This | ||
| * can only be true for read operations. | ||
| */ | ||
| bool last_byte_read_; |
There was a problem hiding this comment.
not seeing this initialized. Do we need last_byte_read_{};?
There was a problem hiding this comment.
This struct is the return value from doRead() and doWrite(), and is always constructed/initialized via {val1, val2, val3};
| @@ -111,7 +118,7 @@ class TransportSocket { | |||
| * @param buffer supplies the buffer to write from | |||
| * @return IoResult the result of the write action. | |||
|
|
||
| // Network::ReadFilter | ||
| Network::FilterStatus onData(Buffer::Instance& data) override; | ||
| Network::FilterStatus onData(Buffer::Instance& data, bool last_byte) override; |
There was a problem hiding this comment.
What's the policy for an unused param in the class definition (with non-inline function definition)? We omit the name in the function definition, but what about in the declaration?
| cluster->resourceManager(Upstream::ResourcePriority::Default).connections().inc(); | ||
| upstream_connection_->addReadFilter(upstream_callbacks_); | ||
| upstream_connection_->addConnectionCallbacks(*upstream_callbacks_); | ||
| upstream_connection_->enableHalfClose(true); |
There was a problem hiding this comment.
Sanity check: if a fin were received prior to this, it would be treated as full close and the connection would never have been assigned to the proxy session right?
There was a problem hiding this comment.
The call to upstream_connection_->connect() is a few lines down, so this is happening before there is a kernel-connection.
There was a problem hiding this comment.
Ahh, I forgot. I keep thinking we have prefetching for tcp proxying connections already :-)
| case SSL_ERROR_WANT_READ: | ||
| break; | ||
| case SSL_ERROR_ZERO_RETURN: | ||
| last_byte = true; |
There was a problem hiding this comment.
same as raw transport socket I think it's worth latching this and asserting on further reads, just for sanity checks.
| } | ||
|
|
||
| IoResult RawBufferSocket::doWrite(Buffer::Instance& buffer) { | ||
| IoResult RawBufferSocket::doWrite(Buffer::Instance& buffer, bool last_byte) { |
There was a problem hiding this comment.
can we add an assert that it's not already shut down?
| } | ||
|
|
||
| Network::IoResult SslSocket::doWrite(Buffer::Instance& write_buffer) { | ||
| Network::IoResult SslSocket::doWrite(Buffer::Instance& write_buffer, bool last_byte) { |
| void SslSocket::onConnected() { ASSERT(!handshake_complete_); } | ||
|
|
||
| void SslSocket::shutdownSsl() { | ||
| if (!shutdown_sent_ && handshake_complete_ && |
There was a problem hiding this comment.
Please comment why we defer until the handshake is complete. If SSL is shut down and the handshake is incomplete, can it ever complete? should we flush shutdown when it is?
Edit: oh hey this was moved from prior close. Well still worth answering IMO :-P
There was a problem hiding this comment.
Yeah, this is a bit strange, in that connection_impl actually calls close(fd), not the transport, so it's not clear what's happening. I think this is roughly what is happening (spread across multiple files), but I'm not 100% sure:
if (can send ssl shutdown) {
SSL_shutdown(ssl);
}
close(fd);```
| private: | ||
| Network::PostIoAction doHandshake(); | ||
| void drainErrorQueue(); | ||
| void shutdownSsl(); |
There was a problem hiding this comment.
maybeShutdownSsl? Or at least comment when it does and doesn't happen.
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
|
Our connection tests used to use raw underlying connections until @lizan's recent refactor which mocked them out. I think it's a bad plan to just not have unit tests of real TCP/TLS socket code going forward but @mattklein123 can override me here. If the TLS side is a pain I don't mind if we wrapper it in a connection which uses a real tls transport socket iff that makes things easier. I think you can just socket_pair for the raw socket test so that should be pretty straight-forward. |
I admit I didn't fully track what @lizan did in the tests. It seems like all of our connection_impl_tests should use real sockets. I thought he actually did do that? Where are we using mocks now? |
|
OK, this is at least partially my hurried reading of code. There are at least some tests with a mocked out transport socket but there's plenty more with createClientConnection( Network::Test::createRawBufferSocket()) and the ConnectionImplTests added seem to use that. So we're good there. Still trying to track down where/if we have TLS coverage of the new half-close |
|
OK, that's ssl_socket_test which you're touching but doesn't seem to have half-close unit tests. So let's do that one? |
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
|
@alyssawilk @mattklein123 I added a test in ssl_socket_test to cover this case, and a similar one for connection_impl_test (because, for better or for worse, that's where the coverage of raw_buffer_socket ends up). I think I've finished everything requested so far; ready for more review. |
alyssawilk
left a comment
There was a problem hiding this comment.
I think you have all the tests written - yay great coverage! Just a few questions on final cleanup
Also can you update your comment in the PR description - I think you're good on tests so you should be fine to remove it.
TODO(alyssawilk): look closer at ssl socket test, look at tls integration test if it's not refactored.
| connection_->addWriteFilter(write_filter2); | ||
|
|
||
| // EXPECT_CALL(*write_filter1, onNewConnection()).WillOnce(Return(FilterStatus::Continue)); | ||
| // EXPECT_CALL(*write_filter2, onNewConnection()).WillOnce(Return(FilterStatus::Continue)); |
| manager.onWrite(); | ||
| } | ||
|
|
||
| TEST_F(NetworkFilterManagerTest, EndStream) { |
There was a problem hiding this comment.
You did such a great job commenting all your other tests, mind doing this one too?
| } | ||
| }; | ||
|
|
||
| class TcpProxySslIntegrationTest : public TcpProxyIntegrationTest { |
There was a problem hiding this comment.
Would it make more sense to have tls be an argument to initialize_ and call most/all tests with a TEST_P? Or generalize the tests in the base class as we do in http_integration.cc and call them from TEST_F(Tls...) TEST_F(Raw) like we do for H2/HTTP/H2Upstream?
There was a problem hiding this comment.
I like going in the direction of making TEST_P's for the tests. However, the TLS tests end up being written slightly differently: they require a bunch of calls to dispatcher_->run(), I think because of the behavior of the ssl library. I'm not entirely sure why that is needed, and I'd rather not sort out that knot in this PR. It's already big enough.
There was a problem hiding this comment.
Fair enough - you've gone great testing so I'll only ask you do so much rewriting :-P I'll keep it on my list for test framework improvements then!
Signed-off-by: Greg Greenway <[email protected]>
alyssawilk
left a comment
There was a problem hiding this comment.
Yay! I'm super excited for this feature to land.
@mattklein123 any final comments on your end?
Will look through today. |
mattklein123
left a comment
There was a problem hiding this comment.
Epic change! Just a few comments/questions.
| * are installed. | ||
| * @param data Supplies the data to write to the connection. | ||
| * @param end_stream If true, this indicates that this is the last write to the connection. If | ||
| * end_stream is true, the connection is half-closed. This may only be called if |
There was a problem hiding this comment.
nit: "This may only be called" is a bit misleading. "May only be set to true" ?
| if (read_end_stream_) { | ||
| if (read_end_stream_raised_) { | ||
| // No further data can be delivered after end_stream | ||
| ASSERT(read_buffer_size == 0); |
There was a problem hiding this comment.
Out of curiosity when does this happen? Might be worth some more comments on why this occurs (I can't think of it off the top of my head).
There was a problem hiding this comment.
But why do we keep calling read()? Are there cases in which ready ready keeps getting set?
There was a problem hiding this comment.
Neither @alyssawilk nor myself could convince ourselves that it couldn't happen, and we wanted to make a guarantee to filters that they wouldn't see duplicates.
There was a problem hiding this comment.
OK fair enough. Do you mind expanding the comment a bit more to say that we don't think this should happen but this is an extra paranoid guard? (Or something to that effect).
|
|
||
| if (write_end_stream_) { | ||
| // It is an API violation to write more data after writing end_stream, | ||
| // but a duplicate end_stream with no data is ok. |
There was a problem hiding this comment.
When does this happen? (Duplicate end_stream with no data). More comments?
There was a problem hiding this comment.
I don't think it does happen. But duplicate end_stream without data should be harmless, so I didn't think it was worth asserting. But with data, we know that data will get dropped, so I thought that was worth an assert.
Want me to expand on the comment?
There was a problem hiding this comment.
Sure I would just expand a bit and say that it shouldn't happen but is a guard just in case.
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Signed-off-by: Greg Greenway <[email protected]>
Automatic merge from submit-queue. Update envoy to e2117cb **What this PR does / why we need it**: Update Envoy to envoyproxy/envoy@e2117cb Align with envoyproxy/envoy#2386 **Release note**: ```release-note None ```
Co-authored-by: jpsim <[email protected]> Signed-off-by: GitHub Action <[email protected]> Signed-off-by: JP Simard <[email protected]>
Co-authored-by: jpsim <[email protected]> Signed-off-by: GitHub Action <[email protected]> Signed-off-by: JP Simard <[email protected]>
Added optional half-close semantics to Connection. This is disabled by default
to avoid making all code deal with half-close semantics when they don't need it.
Risk Level: Medium-high
Testing: Existing tests pass, new unit and integration tests
Docs Changes: N/A
Release Notes: Added
Fixes #2067