Debian Codegraph @

test/core/transport/chttp2/graceful_shutdown_test.cc

raw
1 //
2 //
3 // Copyright 2022 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18
19 #include <grpc/support/port_platform.h>
20
21 #include <limits.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include <atomic>
27 #include <memory>
28 #include <string>
29 #include <thread>
30
31 #include "absl/base/thread_annotations.h"
32 #include "absl/status/status.h"
33 #include "absl/strings/match.h"
34 #include "absl/strings/str_cat.h"
35 #include "absl/strings/string_view.h"
36 #include "absl/time/clock.h"
37 #include "absl/time/time.h"
38 #include "gtest/gtest.h"
39
40 #include <grpc/grpc.h>
41 #include <grpc/slice.h>
42 #include <grpc/slice_buffer.h>
43 #include <grpc/status.h>
44 #include <grpc/support/log.h>
45
46 #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
47 #include "src/core/ext/transport/chttp2/transport/frame_goaway.h"
48 #include "src/core/ext/transport/chttp2/transport/frame_ping.h"
49 #include "src/core/lib/channel/channel_args.h"
50 #include "src/core/lib/channel/channelz.h"
51 #include "src/core/lib/gpr/useful.h"
52 #include "src/core/lib/gprpp/notification.h"
53 #include "src/core/lib/gprpp/sync.h"
54 #include "src/core/lib/iomgr/closure.h"
55 #include "src/core/lib/iomgr/endpoint.h"
56 #include "src/core/lib/iomgr/endpoint_pair.h"
57 #include "src/core/lib/iomgr/error.h"
58 #include "src/core/lib/iomgr/exec_ctx.h"
59 #include "src/core/lib/slice/slice.h"
60 #include "src/core/lib/slice/slice_internal.h"
61 #include "src/core/lib/surface/completion_queue.h"
62 #include "src/core/lib/surface/server.h"
63 #include "test/core/end2end/cq_verifier.h"
64 #include "test/core/util/test_config.h"
65
66 namespace grpc_core {
67 namespace {
68
69 void* Tag(intptr_t t) { return reinterpret_cast<void*>(t); }
70
71 class GracefulShutdownTest : public ::testing::Test {
72 protected:
73 GracefulShutdownTest() { SetupAndStart(); }
74
75 ~GracefulShutdownTest() override { ShutdownAndDestroy(); }
76
77 // Sets up the client and server
78 void SetupAndStart() {
79 ExecCtx exec_ctx;
80 cq_ = grpc_completion_queue_create_for_next(nullptr);
81 cqv_ = std::make_unique<CqVerifier>(cq_);
82 grpc_arg server_args[] = {
83 grpc_channel_arg_integer_create(
84 const_cast<char*>(GRPC_ARG_HTTP2_BDP_PROBE), 0),
85 grpc_channel_arg_integer_create(
86 const_cast<char*>(GRPC_ARG_KEEPALIVE_TIME_MS), INT_MAX)};
87 grpc_channel_args server_channel_args = {GPR_ARRAY_SIZE(server_args),
88 server_args};
89 // Create server
90 server_ = grpc_server_create(&server_channel_args, nullptr);
91 auto* core_server = Server::FromC(server_);
92 grpc_server_register_completion_queue(server_, cq_, nullptr);
93 grpc_server_start(server_);
94 fds_ = grpc_iomgr_create_endpoint_pair("fixture", nullptr);
95 auto* transport = grpc_create_chttp2_transport(core_server->channel_args(),
96 fds_.server, false);
97 grpc_endpoint_add_to_pollset(fds_.server, grpc_cq_pollset(cq_));
98 GPR_ASSERT(core_server->SetupTransport(transport, nullptr,
99 core_server->channel_args(),
100 nullptr) == absl::OkStatus());
101 grpc_chttp2_transport_start_reading(transport, nullptr, nullptr, nullptr);
102 // Start polling on the client
103 Notification client_poller_thread_started_notification;
104 client_poll_thread_ = std::make_unique<std::thread>(
105 [this, &client_poller_thread_started_notification]() {
106 grpc_completion_queue* client_cq =
107 grpc_completion_queue_create_for_next(nullptr);
108 {
109 ExecCtx exec_ctx;
110 grpc_endpoint_add_to_pollset(fds_.client,
111 grpc_cq_pollset(client_cq));
112 grpc_endpoint_add_to_pollset(fds_.server,
113 grpc_cq_pollset(client_cq));
114 }
115 client_poller_thread_started_notification.Notify();
116 while (!shutdown_) {
117 GPR_ASSERT(grpc_completion_queue_next(
118 client_cq, grpc_timeout_milliseconds_to_deadline(10),
119 nullptr)
120 .type == GRPC_QUEUE_TIMEOUT);
121 }
122 grpc_completion_queue_destroy(client_cq);
123 });
124 client_poller_thread_started_notification.WaitForNotification();
125 // Write connection prefix and settings frame
126 constexpr char kPrefix[] =
127 "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n\x00\x00\x00\x04\x00\x00\x00\x00\x00";
128 Write(absl::string_view(kPrefix, sizeof(kPrefix) - 1));
129 // Start reading on the client
130 grpc_slice_buffer_init(&read_buffer_);
131 GRPC_CLOSURE_INIT(&on_read_done_, OnReadDone, this, nullptr);
132 grpc_endpoint_read(fds_.client, &read_buffer_, &on_read_done_, false,
133 /*min_progress_size=*/1);
134 }
135
136 // Shuts down and destroys the client and server.
137 void ShutdownAndDestroy() {
138 shutdown_ = true;
139 ExecCtx exec_ctx;
140 grpc_endpoint_shutdown(fds_.client, GRPC_ERROR_CREATE("Client shutdown"));
141 ExecCtx::Get()->Flush();
142 client_poll_thread_->join();
143 GPR_ASSERT(read_end_notification_.WaitForNotificationWithTimeout(
144 absl::Seconds(5)));
145 grpc_endpoint_destroy(fds_.client);
146 ExecCtx::Get()->Flush();
147 // Shutdown and destroy server
148 grpc_server_shutdown_and_notify(server_, cq_, Tag(1000));
149 cqv_->Expect(Tag(1000), true);
150 cqv_->Verify();
151 grpc_server_destroy(server_);
152 cqv_.reset();
153 grpc_completion_queue_destroy(cq_);
154 }
155
156 static void OnReadDone(void* arg, grpc_error_handle error) {
157 GracefulShutdownTest* self = static_cast<GracefulShutdownTest*>(arg);
158 if (error.ok()) {
159 {
160 MutexLock lock(&self->mu_);
161 for (size_t i = 0; i < self->read_buffer_.count; ++i) {
162 absl::StrAppend(&self->read_bytes_,
163 StringViewFromSlice(self->read_buffer_.slices[i]));
164 }
165 self->read_cv_.SignalAll();
166 }
167 grpc_slice_buffer_reset_and_unref(&self->read_buffer_);
168 grpc_endpoint_read(self->fds_.client, &self->read_buffer_,
169 &self->on_read_done_, false, /*min_progress_size=*/1);
170 } else {
171 grpc_slice_buffer_destroy(&self->read_buffer_);
172 self->read_end_notification_.Notify();
173 }
174 }
175
176 // Waits for \a bytes to show up in read_bytes_
177 void WaitForReadBytes(absl::string_view bytes) {
178 std::atomic<bool> done{false};
179 auto start_time = absl::Now();
180 {
181 MutexLock lock(&mu_);
182 while (!absl::StrContains(read_bytes_, bytes)) {
183 ASSERT_LT(absl::Now() - start_time, absl::Seconds(60));
184 read_cv_.WaitWithTimeout(&mu_, absl::Seconds(5));
185 }
186 }
187 done = true;
188 }
189
190 void WaitForGoaway(uint32_t last_stream_id, uint32_t error_code = 0,
191 grpc_slice slice = grpc_empty_slice()) {
192 grpc_slice_buffer buffer;
193 grpc_slice_buffer_init(&buffer);
194 grpc_chttp2_goaway_append(last_stream_id, error_code, slice, &buffer);
195 std::string expected_bytes;
196 for (size_t i = 0; i < buffer.count; ++i) {
197 absl::StrAppend(&expected_bytes, StringViewFromSlice(buffer.slices[i]));
198 }
199 grpc_slice_buffer_destroy(&buffer);
200 WaitForReadBytes(expected_bytes);
201 }
202
203 void WaitForPing(uint64_t opaque_data) {
204 grpc_slice ping_slice = grpc_chttp2_ping_create(0, opaque_data);
205 WaitForReadBytes(StringViewFromSlice(ping_slice));
206 }
207
208 void SendPingAck(uint64_t opaque_data) {
209 grpc_slice ping_slice = grpc_chttp2_ping_create(1, opaque_data);
210 Write(StringViewFromSlice(ping_slice));
211 }
212
213 // This is a blocking call. It waits for the write callback to be invoked
214 // before returning. (In other words, do not call this from a thread that
215 // should not be blocked, for example, a polling thread.)
216 void Write(absl::string_view bytes) {
217 ExecCtx exec_ctx;
218 grpc_slice slice =
219 StaticSlice::FromStaticBuffer(bytes.data(), bytes.size()).TakeCSlice();
220 grpc_slice_buffer buffer;
221 grpc_slice_buffer_init(&buffer);
222 grpc_slice_buffer_add(&buffer, slice);
223 WriteBuffer(&buffer);
224 grpc_slice_buffer_destroy(&buffer);
225 }
226
227 void WriteBuffer(grpc_slice_buffer* buffer) {
228 Notification on_write_done_notification_;
229 GRPC_CLOSURE_INIT(&on_write_done_, OnWriteDone,
230 &on_write_done_notification_, nullptr);
231 grpc_endpoint_write(fds_.client, buffer, &on_write_done_, nullptr,
232 /*max_frame_size=*/INT_MAX);
233 ExecCtx::Get()->Flush();
234 GPR_ASSERT(on_write_done_notification_.WaitForNotificationWithTimeout(
235 absl::Seconds(5)));
236 }
237
238 static void OnWriteDone(void* arg, grpc_error_handle error) {
239 GPR_ASSERT(error.ok());
240 Notification* on_write_done_notification_ = static_cast<Notification*>(arg);
241 on_write_done_notification_->Notify();
242 }
243
244 grpc_endpoint_pair fds_;
245 grpc_server* server_ = nullptr;
246 grpc_completion_queue* cq_ = nullptr;
247 std::unique_ptr<CqVerifier> cqv_;
248 std::unique_ptr<std::thread> client_poll_thread_;
249 std::atomic<bool> shutdown_{false};
250 grpc_closure on_read_done_;
251 Mutex mu_;
252 CondVar read_cv_;
253 Notification read_end_notification_;
254 grpc_slice_buffer read_buffer_;
255 std::string read_bytes_ ABSL_GUARDED_BY(mu_);
256 grpc_closure on_write_done_;
257 };
258
259 TEST_F(GracefulShutdownTest, GracefulGoaway) {
260 // Initiate shutdown on the server
261 grpc_server_shutdown_and_notify(server_, cq_, Tag(1));
262 // Wait for first goaway
263 WaitForGoaway((1u << 31) - 1);
264 // Wait for the ping
265 WaitForPing(0);
266 // Reply to the ping
267 SendPingAck(0);
268 // Wait for final goaway
269 WaitForGoaway(0);
270 // The shutdown should successfully complete.
271 cqv_->Expect(Tag(1), true);
272 cqv_->Verify();
273 }
274
275 TEST_F(GracefulShutdownTest, RequestStartedBeforeFinalGoaway) {
276 grpc_call_error error;
277 grpc_call* s;
278 grpc_call_details call_details;
279 grpc_metadata_array request_metadata_recv;
280 grpc_call_details_init(&call_details);
281 grpc_metadata_array_init(&request_metadata_recv);
282 error = grpc_server_request_call(server_, &s, &call_details,
283 &request_metadata_recv, cq_, cq_, Tag(100));
284 GPR_ASSERT(GRPC_CALL_OK == error);
285 // Initiate shutdown on the server
286 grpc_server_shutdown_and_notify(server_, cq_, Tag(1));
287 // Wait for first goaway
288 WaitForGoaway((1u << 31) - 1);
289 // Wait for the ping
290 WaitForPing(0);
291 // Start a request
292 constexpr char kRequestFrame[] =
293 "\x00\x00\xbe\x01\x05\x00\x00\x00\x01"
294 "\x10\x05:path\x08/foo/bar"
295 "\x10\x07:scheme\x04http"
296 "\x10\x07:method\x04POST"
297 "\x10\x0a:authority\x09localhost"
298 "\x10\x0c"
299 "content-type\x10"
300 "application/grpc"
301 "\x10\x14grpc-accept-encoding\x15identity,deflate,gzip"
302 "\x10\x02te\x08trailers"
303 "\x10\x0auser-agent\x17grpc-c/0.12.0.0 (linux)";
304 Write(absl::string_view(kRequestFrame, sizeof(kRequestFrame) - 1));
305 // Reply to the ping
306 SendPingAck(0);
307 // Wait for final goaway with last stream ID 1 to show that the HTTP2
308 // transport accepted the stream.
309 WaitForGoaway(1);
310 // TODO(yashykt): The surface layer automatically cancels calls received after
311 // shutdown has been called. Once that is fixed, this should be a success.
312 cqv_->Expect(Tag(100), false);
313 // The shutdown should successfully complete.
314 cqv_->Expect(Tag(1), true);
315 cqv_->Verify();
316 grpc_metadata_array_destroy(&request_metadata_recv);
317 grpc_call_details_destroy(&call_details);
318 }
319
320 TEST_F(GracefulShutdownTest, RequestStartedAfterFinalGoawayIsIgnored) {
321 // Start a request before shutdown to make sure that the connection stays
322 // alive.
323 grpc_call_error error;
324 grpc_call* s;
325 grpc_call_details call_details;
326 grpc_metadata_array request_metadata_recv;
327 grpc_call_details_init(&call_details);
328 grpc_metadata_array_init(&request_metadata_recv);
329 error = grpc_server_request_call(server_, &s, &call_details,
330 &request_metadata_recv, cq_, cq_, Tag(100));
331 GPR_ASSERT(GRPC_CALL_OK == error);
332 // Send the request from the client.
333 constexpr char kRequestFrame[] =
334 "\x00\x00\xbe\x01\x05\x00\x00\x00\x01"
335 "\x10\x05:path\x08/foo/bar"
336 "\x10\x07:scheme\x04http"
337 "\x10\x07:method\x04POST"
338 "\x10\x0a:authority\x09localhost"
339 "\x10\x0c"
340 "content-type\x10"
341 "application/grpc"
342 "\x10\x14grpc-accept-encoding\x15identity,deflate,gzip"
343 "\x10\x02te\x08trailers"
344 "\x10\x0auser-agent\x17grpc-c/0.12.0.0 (linux)";
345 Write(absl::string_view(kRequestFrame, sizeof(kRequestFrame) - 1));
346 cqv_->Expect(Tag(100), true);
347 cqv_->Verify();
348
349 // Initiate shutdown on the server
350 grpc_server_shutdown_and_notify(server_, cq_, Tag(1));
351 // Wait for first goaway
352 WaitForGoaway((1u << 31) - 1);
353 // Wait for the ping
354 WaitForPing(0);
355 // Reply to the ping
356 SendPingAck(0);
357 // Wait for final goaway
358 WaitForGoaway(1);
359
360 // Send another request from the client which should be ignored.
361 constexpr char kNewRequestFrame[] =
362 "\x00\x00\xbe\x01\x05\x00\x00\x00\x03"
363 "\x10\x05:path\x08/foo/bar"
364 "\x10\x07:scheme\x04http"
365 "\x10\x07:method\x04POST"
366 "\x10\x0a:authority\x09localhost"
367 "\x10\x0c"
368 "content-type\x10"
369 "application/grpc"
370 "\x10\x14grpc-accept-encoding\x15identity,deflate,gzip"
371 "\x10\x02te\x08trailers"
372 "\x10\x0auser-agent\x17grpc-c/0.12.0.0 (linux)";
373 Write(absl::string_view(kNewRequestFrame, sizeof(kNewRequestFrame) - 1));
374
375 // Finish the accepted request.
376 grpc_op ops[3];
377 grpc_op* op;
378 memset(ops, 0, sizeof(ops));
379 op = ops;
380 op->op = GRPC_OP_SEND_INITIAL_METADATA;
381 op->data.send_initial_metadata.count = 0;
382 op->flags = 0;
383 op->reserved = nullptr;
384 op++;
385 op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;
386 op->data.send_status_from_server.trailing_metadata_count = 0;
387 op->data.send_status_from_server.status = GRPC_STATUS_UNIMPLEMENTED;
388 grpc_slice status_details = grpc_slice_from_static_string("xyz");
389 op->data.send_status_from_server.status_details = &status_details;
390 op->flags = 0;
391 op->reserved = nullptr;
392 op++;
393 op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;
394 int was_cancelled = 2;
395 op->data.recv_close_on_server.cancelled = &was_cancelled;
396 op->flags = 0;
397 op->reserved = nullptr;
398 op++;
399 error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), Tag(101),
400 nullptr);
401 GPR_ASSERT(GRPC_CALL_OK == error);
402 cqv_->Expect(Tag(101), true);
403 // The shutdown should successfully complete.
404 cqv_->Expect(Tag(1), true);
405 cqv_->Verify();
406 grpc_call_unref(s);
407 grpc_metadata_array_destroy(&request_metadata_recv);
408 grpc_call_details_destroy(&call_details);
409 }
410
411 // Make sure that the graceful goaway eventually makes progress even if a client
412 // does not respond to the ping.
413 TEST_F(GracefulShutdownTest, UnresponsiveClient) {
414 absl::Time initial_time = absl::Now();
415 // Initiate shutdown on the server
416 grpc_server_shutdown_and_notify(server_, cq_, Tag(1));
417 // Wait for first goaway
418 WaitForGoaway((1u << 31) - 1);
419 // Wait for the ping
420 WaitForPing(0);
421 // Wait for final goaway without sending a ping ACK.
422 WaitForGoaway(0);
423 EXPECT_GE(absl::Now() - initial_time,
424 absl::Seconds(20) -
425 absl::Seconds(
426 1) /* clock skew between threads due to time caching */);
427 // The shutdown should successfully complete.
428 cqv_->Expect(Tag(1), true);
429 cqv_->Verify();
430 }
431
432 // Test that servers send a GOAWAY with the last stream ID even when the
433 // transport is disconnected without letting Graceful GOAWAY complete
434 // successfully.
435 TEST_F(GracefulShutdownTest, GoawayReceivedOnServerDisconnect) {
436 // Initiate shutdown on the server and immediately disconnect.
437 grpc_server_shutdown_and_notify(server_, cq_, Tag(1));
438 grpc_server_cancel_all_calls(server_);
439 // Wait for final goaway.
440 WaitForGoaway(/*last_stream_id=*/0, /*error_code=*/2,
441 grpc_slice_from_static_string("Cancelling all calls"));
442 // The shutdown should successfully complete.
443 cqv_->Expect(Tag(1), true);
444 cqv_->Verify();
445 }
446
447 } // namespace
448 } // namespace grpc_core
449
450 int main(int argc, char** argv) {
451 ::testing::InitGoogleTest(&argc, argv);
452 grpc::testing::TestEnvironment env(&argc, argv);
453 grpc_init();
454 int result = RUN_ALL_TESTS();
455 grpc_shutdown();
456 return result;
457 }