Debian Codegraph @

test/core/iomgr/stranded_event_test.cc

raw
1 /*
2 *
3 * Copyright 2020 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 <stdlib.h>
22 #include <string.h>
23
24 #include <functional>
25 #include <set>
26 #include <thread>
27
28 #include <gmock/gmock.h>
29
30 #include "absl/strings/str_cat.h"
31 #include "absl/strings/str_format.h"
32 #include "absl/types/optional.h"
33
34 #include <grpc/grpc.h>
35 #include <grpc/grpc_security.h>
36 #include <grpc/impl/codegen/grpc_types.h>
37 #include <grpc/slice.h>
38 #include <grpc/support/alloc.h>
39 #include <grpc/support/log.h>
40 #include <grpc/support/string_util.h>
41 #include <grpc/support/time.h>
42
43 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
44 #include "src/core/lib/address_utils/parse_address.h"
45 #include "src/core/lib/gpr/useful.h"
46 #include "src/core/lib/gprpp/host_port.h"
47 #include "src/core/lib/gprpp/thd.h"
48 #include "src/core/lib/iomgr/error.h"
49 #include "src/core/lib/security/credentials/alts/alts_credentials.h"
50 #include "src/core/lib/security/credentials/credentials.h"
51 #include "src/core/lib/security/security_connector/alts/alts_security_connector.h"
52 #include "src/core/lib/slice/slice_string_helpers.h"
53 #include "src/core/lib/uri/uri_parser.h"
54 #include "test/core/end2end/cq_verifier.h"
55 #include "test/core/util/port.h"
56 #include "test/core/util/test_config.h"
57
58 namespace {
59
60 const int kNumMessagePingPongsPerCall = 4000;
61
62 struct TestCall {
63 explicit TestCall(grpc_channel* channel, grpc_call* call,
64 grpc_completion_queue* cq)
65 : channel(channel), call(call), cq(cq) {}
66
67 TestCall(const TestCall& other) = delete;
68 TestCall& operator=(const TestCall& other) = delete;
69
70 ~TestCall() {
71 grpc_call_cancel(call, nullptr);
72 grpc_call_unref(call);
73 grpc_channel_destroy(channel);
74 grpc_completion_queue_shutdown(cq);
75 while (grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
76 nullptr)
77 .type != GRPC_QUEUE_SHUTDOWN) {
78 }
79 grpc_completion_queue_destroy(cq);
80 }
81
82 grpc_channel* channel;
83 grpc_call* call;
84 grpc_completion_queue* cq;
85 absl::optional<grpc_status_code>
86 status; // filled in when the call is finished
87 };
88
89 void StartCall(TestCall* test_call) {
90 grpc_op ops[6];
91 grpc_op* op;
92 memset(ops, 0, sizeof(ops));
93 op = ops;
94 op->op = GRPC_OP_SEND_INITIAL_METADATA;
95 op->data.send_initial_metadata.count = 0;
96 op->flags = GRPC_INITIAL_METADATA_WAIT_FOR_READY;
97 op->reserved = nullptr;
98 op++;
99 void* tag = test_call;
100 grpc_call_error error = grpc_call_start_batch(
101 test_call->call, ops, static_cast<size_t>(op - ops), tag, nullptr);
102 GPR_ASSERT(GRPC_CALL_OK == error);
103 grpc_core::CqVerifier cqv(test_call->cq);
104 cqv.Expect(tag, true);
105 cqv.Verify();
106 }
107
108 void SendMessage(grpc_call* call, grpc_completion_queue* cq) {
109 grpc_slice request_payload_slice = grpc_slice_from_copied_string("a");
110 grpc_byte_buffer* request_payload =
111 grpc_raw_byte_buffer_create(&request_payload_slice, 1);
112 grpc_op ops[6];
113 grpc_op* op;
114 memset(ops, 0, sizeof(ops));
115 op = ops;
116 op->op = GRPC_OP_SEND_MESSAGE;
117 op->data.send_message.send_message = request_payload;
118 op->reserved = nullptr;
119 op++;
120 void* tag = call;
121 grpc_call_error error = grpc_call_start_batch(
122 call, ops, static_cast<size_t>(op - ops), tag, nullptr);
123 GPR_ASSERT(GRPC_CALL_OK == error);
124 grpc_core::CqVerifier cqv(cq);
125 cqv.Expect(tag, true);
126 cqv.Verify();
127 grpc_byte_buffer_destroy(request_payload);
128 }
129
130 void ReceiveMessage(grpc_call* call, grpc_completion_queue* cq) {
131 grpc_byte_buffer* request_payload = nullptr;
132 grpc_op ops[6];
133 grpc_op* op;
134 memset(ops, 0, sizeof(ops));
135 op = ops;
136 op->op = GRPC_OP_RECV_MESSAGE;
137 op->data.recv_message.recv_message = &request_payload;
138 op->reserved = nullptr;
139 op++;
140 void* tag = call;
141 grpc_call_error error = grpc_call_start_batch(
142 call, ops, static_cast<size_t>(op - ops), tag, nullptr);
143 GPR_ASSERT(GRPC_CALL_OK == error);
144 grpc_core::CqVerifier cqv(cq);
145 cqv.Expect(tag, true);
146 cqv.Verify();
147 grpc_byte_buffer_destroy(request_payload);
148 }
149
150 void ReceiveInitialMetadata(TestCall* test_call, gpr_timespec deadline) {
151 grpc_metadata_array initial_metadata_recv;
152 grpc_metadata_array_init(&initial_metadata_recv);
153 grpc_op ops[6];
154 grpc_op* op;
155 memset(ops, 0, sizeof(ops));
156 op = ops;
157 op->op = GRPC_OP_RECV_INITIAL_METADATA;
158 op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
159 op->reserved = nullptr;
160 op++;
161 void* tag = test_call;
162 grpc_call_error error = grpc_call_start_batch(
163 test_call->call, ops, static_cast<size_t>(op - ops), tag, nullptr);
164 GPR_ASSERT(GRPC_CALL_OK == error);
165 grpc_event event =
166 grpc_completion_queue_next(test_call->cq, deadline, nullptr);
167 if (event.type != GRPC_OP_COMPLETE || !event.success) {
168 gpr_log(GPR_ERROR,
169 "Wanted op complete with success, got op type:%d success:%d",
170 event.type, event.success);
171 GPR_ASSERT(0);
172 }
173 GPR_ASSERT(event.tag == tag);
174 grpc_metadata_array_destroy(&initial_metadata_recv);
175 }
176
177 void FinishCall(TestCall* test_call) {
178 grpc_op ops[6];
179 grpc_op* op;
180 grpc_metadata_array trailing_metadata_recv;
181 grpc_status_code status;
182 grpc_slice details;
183 grpc_metadata_array_init(&trailing_metadata_recv);
184 memset(ops, 0, sizeof(ops));
185 op = ops;
186 op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
187 op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
188 op->data.recv_status_on_client.status = &status;
189 op->data.recv_status_on_client.status_details = &details;
190 op->flags = 0;
191 op->reserved = nullptr;
192 op++;
193 void* tag = test_call;
194 grpc_call_error error = grpc_call_start_batch(
195 test_call->call, ops, static_cast<size_t>(op - ops), tag, nullptr);
196 GPR_ASSERT(GRPC_CALL_OK == error);
197 grpc_event event = grpc_completion_queue_next(
198 test_call->cq, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr);
199 GPR_ASSERT(event.type == GRPC_OP_COMPLETE);
200 GPR_ASSERT(event.success);
201 GPR_ASSERT(event.tag == tag);
202 test_call->status = status;
203 grpc_metadata_array_destroy(&trailing_metadata_recv);
204 grpc_slice_unref(details);
205 }
206
207 class TestServer {
208 public:
209 explicit TestServer() {
210 cq_ = grpc_completion_queue_create_for_next(nullptr);
211 server_ = grpc_server_create(nullptr, nullptr);
212 address_ =
213 grpc_core::JoinHostPort("127.0.0.1", grpc_pick_unused_port_or_die());
214 grpc_server_register_completion_queue(server_, cq_, nullptr);
215 grpc_server_credentials* server_creds =
216 grpc_insecure_server_credentials_create();
217 GPR_ASSERT(
218 grpc_server_add_http2_port(server_, address_.c_str(), server_creds));
219 grpc_server_credentials_release(server_creds);
220 grpc_server_start(server_);
221 thread_ = std::thread(std::bind(&TestServer::AcceptThread, this));
222 }
223
224 ~TestServer() {
225 thread_.join();
226 void* shutdown_and_notify_tag = this;
227 grpc_server_shutdown_and_notify(server_, cq_, shutdown_and_notify_tag);
228 grpc_event event = grpc_completion_queue_next(
229 cq_, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr);
230 GPR_ASSERT(event.type == GRPC_OP_COMPLETE);
231 GPR_ASSERT(event.tag == shutdown_and_notify_tag);
232 GPR_ASSERT(event.success);
233 grpc_server_destroy(server_);
234 grpc_completion_queue_shutdown(cq_);
235 while (grpc_completion_queue_next(cq_, gpr_inf_future(GPR_CLOCK_REALTIME),
236 nullptr)
237 .type != GRPC_QUEUE_SHUTDOWN) {
238 }
239 grpc_completion_queue_destroy(cq_);
240 }
241
242 std::string address() const { return address_; }
243
244 private:
245 void AcceptThread() {
246 grpc_call_details call_details;
247 grpc_call_details_init(&call_details);
248 grpc_metadata_array request_metadata_recv;
249 grpc_metadata_array_init(&request_metadata_recv);
250 void* tag = &call_details;
251 grpc_call* call;
252 grpc_call_error error = grpc_server_request_call(
253 server_, &call, &call_details, &request_metadata_recv, cq_, cq_, tag);
254 GPR_ASSERT(error == GRPC_CALL_OK);
255 grpc_event event = grpc_completion_queue_next(
256 cq_, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr);
257 GPR_ASSERT(event.type == GRPC_OP_COMPLETE);
258 GPR_ASSERT(event.success);
259 GPR_ASSERT(event.tag == tag);
260 grpc_op ops[6];
261 grpc_op* op;
262 memset(ops, 0, sizeof(ops));
263 op = ops;
264 op->op = GRPC_OP_SEND_INITIAL_METADATA;
265 op->data.send_initial_metadata.count = 0;
266 op->reserved = nullptr;
267 op++;
268 error = grpc_call_start_batch(call, ops, static_cast<size_t>(op - ops), tag,
269 nullptr);
270 GPR_ASSERT(GRPC_CALL_OK == error);
271 event = grpc_completion_queue_next(cq_, gpr_inf_future(GPR_CLOCK_REALTIME),
272 nullptr);
273 GPR_ASSERT(event.type == GRPC_OP_COMPLETE);
274 GPR_ASSERT(event.success);
275 GPR_ASSERT(event.tag == tag);
276 for (int i = 0; i < kNumMessagePingPongsPerCall; i++) {
277 ReceiveMessage(call, cq_);
278 SendMessage(call, cq_);
279 }
280 grpc_call_cancel_with_status(call, GRPC_STATUS_PERMISSION_DENIED,
281 "test status", nullptr);
282 grpc_metadata_array_destroy(&request_metadata_recv);
283 grpc_call_details_destroy(&call_details);
284 grpc_call_unref(call);
285 }
286
287 grpc_server* server_;
288 grpc_completion_queue* cq_;
289 std::string address_;
290 std::thread thread_;
291 };
292
293 grpc_core::Resolver::Result BuildResolverResponse(
294 const std::vector<std::string>& addresses) {
295 grpc_core::Resolver::Result result;
296 result.addresses = grpc_core::ServerAddressList();
297 for (const auto& address_str : addresses) {
298 absl::StatusOr<grpc_core::URI> uri = grpc_core::URI::Parse(address_str);
299 if (!uri.ok()) {
300 gpr_log(GPR_ERROR, "Failed to parse. Error: %s",
301 uri.status().ToString().c_str());
302 GPR_ASSERT(uri.ok());
303 }
304 grpc_resolved_address address;
305 GPR_ASSERT(grpc_parse_uri(*uri, &address));
306 result.addresses->emplace_back(address.addr, address.len,
307 grpc_core::ChannelArgs());
308 }
309 return result;
310 }
311
312 // Perform a simple RPC where the server cancels the request with
313 // grpc_call_cancel_with_status
314 TEST(Pollers, TestReadabilityNotificationsDontGetStrandedOnOneCq) {
315 gpr_log(GPR_DEBUG, "test thread");
316 /* 64 is a somewhat arbitary number, the important thing is that it
317 * exceeds the value of MAX_EPOLL_EVENTS_HANDLED_EACH_POLL_CALL (16), which
318 * is enough to repro a bug at time of writing. */
319 const int kNumCalls = 32;
320 size_t ping_pong_round = 0;
321 size_t ping_pongs_done = 0;
322 grpc_core::Mutex ping_pong_round_mu;
323 grpc_core::CondVar ping_pong_round_cv;
324 const std::string kSharedUnconnectableAddress =
325 grpc_core::JoinHostPort("127.0.0.1", grpc_pick_unused_port_or_die());
326 gpr_log(GPR_DEBUG, "created unconnectable address:%s",
327 kSharedUnconnectableAddress.c_str());
328 std::vector<std::thread> threads;
329 threads.reserve(kNumCalls);
330 std::vector<std::unique_ptr<TestServer>> test_servers;
331 // Instantiate servers inline here, so that we get port allocation out of the
332 // way and don't depend on it during the actual test. It can sometimes take
333 // time to allocate kNumCalls ports from the port server, and we don't want to
334 // hit test timeouts because of that.
335 test_servers.reserve(kNumCalls);
336 for (int i = 0; i < kNumCalls; i++) {
337 test_servers.push_back(std::make_unique<TestServer>());
338 }
339 for (int i = 0; i < kNumCalls; i++) {
340 auto test_server = test_servers[i].get();
341 threads.push_back(std::thread([kSharedUnconnectableAddress,
342 &ping_pong_round, &ping_pongs_done,
343 &ping_pong_round_mu, &ping_pong_round_cv,
344 test_server]() {
345 gpr_log(GPR_DEBUG, "using test_server with address:%s",
346 test_server->address().c_str());
347 std::vector<grpc_arg> args;
348 grpc_arg service_config_arg;
349 service_config_arg.type = GRPC_ARG_STRING;
350 service_config_arg.key = const_cast<char*>(GRPC_ARG_SERVICE_CONFIG);
351 service_config_arg.value.string =
352 const_cast<char*>("{\"loadBalancingConfig\":[{\"round_robin\":{}}]}");
353 args.push_back(service_config_arg);
354 auto fake_resolver_response_generator =
355 grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
356 {
357 grpc_core::ExecCtx exec_ctx;
358 fake_resolver_response_generator->SetResponse(BuildResolverResponse(
359 {absl::StrCat("ipv4:", kSharedUnconnectableAddress),
360 absl::StrCat("ipv4:", test_server->address())}));
361 }
362 args.push_back(grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
363 fake_resolver_response_generator.get()));
364 grpc_channel_args* channel_args =
365 grpc_channel_args_copy_and_add(nullptr, args.data(), args.size());
366 grpc_channel_credentials* creds = grpc_insecure_credentials_create();
367 grpc_channel* channel =
368 grpc_channel_create("fake:///test.server.com", creds, channel_args);
369 grpc_channel_credentials_release(creds);
370 grpc_channel_args_destroy(channel_args);
371 grpc_completion_queue* cq =
372 grpc_completion_queue_create_for_next(nullptr);
373 grpc_call* call = grpc_channel_create_call(
374 channel, nullptr, GRPC_PROPAGATE_DEFAULTS, cq,
375 grpc_slice_from_static_string("/foo"), nullptr,
376 gpr_inf_future(GPR_CLOCK_REALTIME), nullptr);
377 auto test_call = std::make_unique<TestCall>(channel, call, cq);
378 // Start a call, and ensure that round_robin load balancing is configured
379 StartCall(test_call.get());
380 // Make sure the test is doing what it's meant to be doing
381 grpc_channel_info channel_info;
382 memset(&channel_info, 0, sizeof(channel_info));
383 char* lb_policy_name = nullptr;
384 channel_info.lb_policy_name = &lb_policy_name;
385 grpc_channel_get_info(channel, &channel_info);
386 EXPECT_EQ(std::string(lb_policy_name), "round_robin")
387 << "not using round robin; this test has a low chance of hitting the "
388 "bug that it's meant to try to hit";
389 gpr_free(lb_policy_name);
390 // Receive initial metadata
391 gpr_log(GPR_DEBUG,
392 "now receive initial metadata on call with server address:%s",
393 test_server->address().c_str());
394 ReceiveInitialMetadata(test_call.get(),
395 grpc_timeout_seconds_to_deadline(30));
396 for (int i = 1; i <= kNumMessagePingPongsPerCall; i++) {
397 {
398 grpc_core::MutexLock lock(&ping_pong_round_mu);
399 ping_pong_round_cv.SignalAll();
400 while (int(ping_pong_round) != i) {
401 ping_pong_round_cv.Wait(&ping_pong_round_mu);
402 }
403 }
404 SendMessage(test_call->call, test_call->cq);
405 ReceiveMessage(test_call->call, test_call->cq);
406 {
407 grpc_core::MutexLock lock(&ping_pong_round_mu);
408 ping_pongs_done++;
409 ping_pong_round_cv.SignalAll();
410 }
411 }
412 gpr_log(GPR_DEBUG, "now receive status on call with server address:%s",
413 test_server->address().c_str());
414 FinishCall(test_call.get());
415 GPR_ASSERT(test_call->status.has_value());
416 GPR_ASSERT(test_call->status.value() == GRPC_STATUS_PERMISSION_DENIED);
417 {
418 grpc_core::ExecCtx exec_ctx;
419 fake_resolver_response_generator.reset();
420 }
421 }));
422 }
423 for (size_t i = 1; i <= kNumMessagePingPongsPerCall; i++) {
424 {
425 grpc_core::MutexLock lock(&ping_pong_round_mu);
426 while (ping_pongs_done < ping_pong_round * kNumCalls) {
427 ping_pong_round_cv.Wait(&ping_pong_round_mu);
428 }
429 ping_pong_round++;
430 ping_pong_round_cv.SignalAll();
431 gpr_log(GPR_DEBUG, "initiate ping pong round: %ld", ping_pong_round);
432 }
433 }
434 for (auto& thread : threads) {
435 thread.join();
436 }
437 gpr_log(GPR_DEBUG, "All RPCs completed!");
438 }
439
440 } // namespace
441
442 int main(int argc, char** argv) {
443 ::testing::InitGoogleTest(&argc, argv);
444 grpc::testing::TestEnvironment env(&argc, argv);
445 grpc_init();
446 auto result = RUN_ALL_TESTS();
447 grpc_shutdown();
448 return result;
449 }