• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright 2018 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 "test/core/end2end/end2end_tests.h"
20 
21 #include <string.h>
22 
23 #include <grpc/support/alloc.h>
24 #include <grpc/support/log.h>
25 #include <grpc/support/sync.h>
26 
27 #include "src/core/ext/transport/inproc/inproc_transport.h"
28 #include "src/core/lib/surface/channel.h"
29 #include "src/core/lib/surface/completion_queue.h"
30 #include "src/core/lib/surface/server.h"
31 #include "test/core/util/port.h"
32 #include "test/core/util/test_config.h"
33 
34 typedef struct inproc_fixture_data {
35   bool dummy;  // reserved for future expansion. Struct can't be empty
36 } inproc_fixture_data;
37 
38 namespace {
39 template <typename F>
40 class CQDeletingCallback : public grpc_experimental_completion_queue_functor {
41  public:
CQDeletingCallback(F f)42   explicit CQDeletingCallback(F f) : func_(f) {
43     functor_run = &CQDeletingCallback::Run;
44     inlineable = false;
45   }
~CQDeletingCallback()46   ~CQDeletingCallback() {}
Run(grpc_experimental_completion_queue_functor * cb,int ok)47   static void Run(grpc_experimental_completion_queue_functor* cb, int ok) {
48     auto* callback = static_cast<CQDeletingCallback*>(cb);
49     callback->func_(static_cast<bool>(ok));
50     delete callback;
51   }
52 
53  private:
54   F func_;
55 };
56 
57 template <typename F>
NewDeletingCallback(F f)58 grpc_experimental_completion_queue_functor* NewDeletingCallback(F f) {
59   return new CQDeletingCallback<F>(f);
60 }
61 
62 class ShutdownCallback : public grpc_experimental_completion_queue_functor {
63  public:
ShutdownCallback()64   ShutdownCallback() : done_(false) {
65     functor_run = &ShutdownCallback::StaticRun;
66     inlineable = false;
67     gpr_mu_init(&mu_);
68     gpr_cv_init(&cv_);
69   }
~ShutdownCallback()70   ~ShutdownCallback() {
71     gpr_mu_destroy(&mu_);
72     gpr_cv_destroy(&cv_);
73   }
StaticRun(grpc_experimental_completion_queue_functor * cb,int ok)74   static void StaticRun(grpc_experimental_completion_queue_functor* cb,
75                         int ok) {
76     auto* callback = static_cast<ShutdownCallback*>(cb);
77     callback->Run(static_cast<bool>(ok));
78   }
Run(bool)79   void Run(bool /*ok*/) {
80     gpr_log(GPR_DEBUG, "CQ shutdown notification invoked");
81     gpr_mu_lock(&mu_);
82     done_ = true;
83     gpr_cv_broadcast(&cv_);
84     gpr_mu_unlock(&mu_);
85   }
86   // The Wait function waits for a specified amount of
87   // time for the completion of the shutdown and returns
88   // whether it was successfully shut down
Wait(gpr_timespec deadline)89   bool Wait(gpr_timespec deadline) {
90     gpr_mu_lock(&mu_);
91     while (!done_ && !gpr_cv_wait(&cv_, &mu_, deadline)) {
92     }
93     bool ret = done_;
94     gpr_mu_unlock(&mu_);
95     return ret;
96   }
97 
98  private:
99   bool done_;
100   gpr_mu mu_;
101   gpr_cv cv_;
102 };
103 
104 ShutdownCallback* g_shutdown_callback;
105 }  // namespace
106 
107 // The following global structure is the tag collection. It holds
108 // all information related to tags expected and tags received
109 // during the execution, with each callback setting a tag.
110 // The tag sets are implemented and checked using arrays and
111 // linear lookups (rather than maps) so that this test doesn't
112 // need the C++ standard library.
113 static gpr_mu tags_mu;
114 static gpr_cv tags_cv;
115 const size_t kAvailableTags = 4;
116 bool tags[kAvailableTags];
117 bool tags_valid[kAvailableTags];
118 bool tags_expected[kAvailableTags];
119 bool tags_needed[kAvailableTags];
120 
121 // Mark that a tag is expected; this function must be executed in the
122 // main thread only while there are no other threads altering the
123 // expectation set (e.g., by calling expect_tag or verify_tags)
expect_tag(intptr_t tag,bool ok)124 static void expect_tag(intptr_t tag, bool ok) {
125   size_t idx = static_cast<size_t>(tag);
126   GPR_ASSERT(idx < kAvailableTags);
127   tags_needed[idx] = true;
128   tags_expected[idx] = ok;
129 }
130 
131 // Check that the expected tags have reached, within a certain
132 // deadline. This must also be executed only on the main thread while
133 // there are no other threads altering the expectation set (e.g., by
134 // calling expect_tag or verify_tags). The tag verifier doesn't have
135 // to drive the CQ at all (unlike the next-based end2end tests)
136 // because the tags will get set when the callbacks are executed,
137 // which happens when a particular batch related to a callback is
138 // complete.
verify_tags(gpr_timespec deadline)139 static void verify_tags(gpr_timespec deadline) {
140   bool done = false;
141 
142   gpr_mu_lock(&tags_mu);
143   while (!done) {
144     done = gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), deadline) > 0;
145     for (size_t i = 0; i < kAvailableTags; i++) {
146       if (tags_needed[i]) {
147         if (tags_valid[i]) {
148           gpr_log(GPR_DEBUG, "Verifying tag %d", static_cast<int>(i));
149           if (tags[i] != tags_expected[i]) {
150             gpr_log(GPR_ERROR, "Got wrong result (%d instead of %d) for tag %d",
151                     tags[i], tags_expected[i], static_cast<int>(i));
152             GPR_ASSERT(false);
153           }
154           tags_valid[i] = false;
155           tags_needed[i] = false;
156         } else if (done) {
157           gpr_log(GPR_ERROR, "Didn't get tag %d", static_cast<int>(i));
158           GPR_ASSERT(false);
159         }
160       }
161     }
162     bool empty = true;
163     for (size_t i = 0; i < kAvailableTags; i++) {
164       if (tags_needed[i]) {
165         empty = false;
166       }
167     }
168     done = done || empty;
169     if (done) {
170       for (size_t i = 0; i < kAvailableTags; i++) {
171         if (tags_valid[i]) {
172           gpr_log(GPR_ERROR, "Got unexpected tag %d and result %d",
173                   static_cast<int>(i), tags[i]);
174           GPR_ASSERT(false);
175         }
176         tags_valid[i] = false;
177       }
178     } else {
179       gpr_cv_wait(&tags_cv, &tags_mu, deadline);
180     }
181   }
182   gpr_mu_unlock(&tags_mu);
183 }
184 
185 // This function creates a callback functor that emits the
186 // desired tag into the global tag set
tag(intptr_t t)187 static grpc_experimental_completion_queue_functor* tag(intptr_t t) {
188   auto func = [t](bool ok) {
189     gpr_mu_lock(&tags_mu);
190     gpr_log(GPR_DEBUG, "Completing operation %" PRIdPTR, t);
191     bool was_empty = true;
192     for (size_t i = 0; i < kAvailableTags; i++) {
193       if (tags_valid[i]) {
194         was_empty = false;
195       }
196     }
197     size_t idx = static_cast<size_t>(t);
198     tags[idx] = ok;
199     tags_valid[idx] = true;
200     if (was_empty) {
201       gpr_cv_signal(&tags_cv);
202     }
203     gpr_mu_unlock(&tags_mu);
204   };
205   auto cb = NewDeletingCallback(func);
206   return cb;
207 }
208 
inproc_create_fixture(grpc_channel_args *,grpc_channel_args *)209 static grpc_end2end_test_fixture inproc_create_fixture(
210     grpc_channel_args* /*client_args*/, grpc_channel_args* /*server_args*/) {
211   grpc_end2end_test_fixture f;
212   inproc_fixture_data* ffd = static_cast<inproc_fixture_data*>(
213       gpr_malloc(sizeof(inproc_fixture_data)));
214   memset(&f, 0, sizeof(f));
215 
216   f.fixture_data = ffd;
217   g_shutdown_callback = new ShutdownCallback();
218   f.cq =
219       grpc_completion_queue_create_for_callback(g_shutdown_callback, nullptr);
220   f.shutdown_cq = grpc_completion_queue_create_for_pluck(nullptr);
221 
222   return f;
223 }
224 
inproc_init_client(grpc_end2end_test_fixture * f,grpc_channel_args * client_args)225 void inproc_init_client(grpc_end2end_test_fixture* f,
226                         grpc_channel_args* client_args) {
227   f->client = grpc_inproc_channel_create(f->server, client_args, nullptr);
228   GPR_ASSERT(f->client);
229 }
230 
inproc_init_server(grpc_end2end_test_fixture * f,grpc_channel_args * server_args)231 void inproc_init_server(grpc_end2end_test_fixture* f,
232                         grpc_channel_args* server_args) {
233   if (f->server) {
234     grpc_server_destroy(f->server);
235   }
236   f->server = grpc_server_create(server_args, nullptr);
237   grpc_server_register_completion_queue(f->server, f->cq, nullptr);
238   grpc_server_start(f->server);
239 }
240 
inproc_tear_down(grpc_end2end_test_fixture * f)241 void inproc_tear_down(grpc_end2end_test_fixture* f) {
242   inproc_fixture_data* ffd = static_cast<inproc_fixture_data*>(f->fixture_data);
243   gpr_free(ffd);
244 }
245 
begin_test(grpc_end2end_test_config config,const char * test_name,grpc_channel_args * client_args,grpc_channel_args * server_args)246 static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,
247                                             const char* test_name,
248                                             grpc_channel_args* client_args,
249                                             grpc_channel_args* server_args) {
250   grpc_end2end_test_fixture f;
251   gpr_log(GPR_INFO, "Running test: %s/%s", test_name, config.name);
252   f = config.create_fixture(client_args, server_args);
253   config.init_server(&f, server_args);
254   config.init_client(&f, client_args);
255   return f;
256 }
257 
n_seconds_from_now(int n)258 static gpr_timespec n_seconds_from_now(int n) {
259   return grpc_timeout_seconds_to_deadline(n);
260 }
261 
five_seconds_from_now()262 static gpr_timespec five_seconds_from_now() { return n_seconds_from_now(5); }
263 
drain_cq(grpc_completion_queue *)264 static void drain_cq(grpc_completion_queue* /*cq*/) {
265   // Wait for the shutdown callback to arrive, or fail the test
266   GPR_ASSERT(g_shutdown_callback->Wait(five_seconds_from_now()));
267   gpr_log(GPR_DEBUG, "CQ shutdown wait complete");
268   delete g_shutdown_callback;
269 }
270 
shutdown_server(grpc_end2end_test_fixture * f)271 static void shutdown_server(grpc_end2end_test_fixture* f) {
272   if (!f->server) return;
273   grpc_server_shutdown_and_notify(
274       f->server, f->shutdown_cq,
275       reinterpret_cast<void*>(static_cast<intptr_t>(1000)));
276   GPR_ASSERT(
277       grpc_completion_queue_pluck(f->shutdown_cq, (void*)((intptr_t)1000),
278                                   grpc_timeout_seconds_to_deadline(5), nullptr)
279           .type == GRPC_OP_COMPLETE);
280   grpc_server_destroy(f->server);
281   f->server = nullptr;
282 }
283 
shutdown_client(grpc_end2end_test_fixture * f)284 static void shutdown_client(grpc_end2end_test_fixture* f) {
285   if (!f->client) return;
286   grpc_channel_destroy(f->client);
287   f->client = nullptr;
288 }
289 
end_test(grpc_end2end_test_fixture * f)290 static void end_test(grpc_end2end_test_fixture* f) {
291   shutdown_server(f);
292   shutdown_client(f);
293 
294   grpc_completion_queue_shutdown(f->cq);
295   drain_cq(f->cq);
296   grpc_completion_queue_destroy(f->cq);
297   grpc_completion_queue_destroy(f->shutdown_cq);
298 }
299 
simple_request_body(grpc_end2end_test_config config,grpc_end2end_test_fixture f)300 static void simple_request_body(grpc_end2end_test_config config,
301                                 grpc_end2end_test_fixture f) {
302   grpc_call* c;
303   grpc_call* s;
304   grpc_op ops[6];
305   grpc_op* op;
306   grpc_metadata_array initial_metadata_recv;
307   grpc_metadata_array trailing_metadata_recv;
308   grpc_metadata_array request_metadata_recv;
309   grpc_call_details call_details;
310   grpc_status_code status;
311   const char* error_string;
312   grpc_call_error error;
313   grpc_slice details;
314   int was_cancelled = 2;
315   char* peer;
316   gpr_timespec deadline = five_seconds_from_now();
317 
318   c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,
319                                grpc_slice_from_static_string("/foo"), nullptr,
320                                deadline, nullptr);
321   GPR_ASSERT(c);
322 
323   peer = grpc_call_get_peer(c);
324   GPR_ASSERT(peer != nullptr);
325   gpr_log(GPR_DEBUG, "client_peer_before_call=%s", peer);
326   gpr_free(peer);
327 
328   grpc_metadata_array_init(&initial_metadata_recv);
329   grpc_metadata_array_init(&trailing_metadata_recv);
330   grpc_metadata_array_init(&request_metadata_recv);
331   grpc_call_details_init(&call_details);
332 
333   // Create a basic client unary request batch (no payload)
334   memset(ops, 0, sizeof(ops));
335   op = ops;
336   op->op = GRPC_OP_SEND_INITIAL_METADATA;
337   op->data.send_initial_metadata.count = 0;
338   op->flags = 0;
339   op->reserved = nullptr;
340   op++;
341   op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
342   op->flags = 0;
343   op->reserved = nullptr;
344   op++;
345   op->op = GRPC_OP_RECV_INITIAL_METADATA;
346   op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
347   op->flags = 0;
348   op->reserved = nullptr;
349   op++;
350   op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
351   op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
352   op->data.recv_status_on_client.status = &status;
353   op->data.recv_status_on_client.status_details = &details;
354   op->data.recv_status_on_client.error_string = &error_string;
355   op->flags = 0;
356   op->reserved = nullptr;
357   op++;
358   error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1),
359                                 nullptr);
360   GPR_ASSERT(GRPC_CALL_OK == error);
361 
362   // Register a call at the server-side to match the incoming client call
363   error = grpc_server_request_call(f.server, &s, &call_details,
364                                    &request_metadata_recv, f.cq, f.cq, tag(2));
365   GPR_ASSERT(GRPC_CALL_OK == error);
366 
367   // We expect that the server call creation callback (and no others) will
368   // execute now since no other batch should be complete.
369   expect_tag(2, true);
370   verify_tags(deadline);
371 
372   peer = grpc_call_get_peer(s);
373   GPR_ASSERT(peer != nullptr);
374   gpr_log(GPR_DEBUG, "server_peer=%s", peer);
375   gpr_free(peer);
376   peer = grpc_call_get_peer(c);
377   GPR_ASSERT(peer != nullptr);
378   gpr_log(GPR_DEBUG, "client_peer=%s", peer);
379   gpr_free(peer);
380 
381   // Create the server response batch (no payload)
382   memset(ops, 0, sizeof(ops));
383   op = ops;
384   op->op = GRPC_OP_SEND_INITIAL_METADATA;
385   op->data.send_initial_metadata.count = 0;
386   op->flags = 0;
387   op->reserved = nullptr;
388   op++;
389   op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;
390   op->data.send_status_from_server.trailing_metadata_count = 0;
391   op->data.send_status_from_server.status = GRPC_STATUS_UNIMPLEMENTED;
392   grpc_slice status_details = grpc_slice_from_static_string("xyz");
393   op->data.send_status_from_server.status_details = &status_details;
394   op->flags = 0;
395   op->reserved = nullptr;
396   op++;
397   op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;
398   op->data.recv_close_on_server.cancelled = &was_cancelled;
399   op->flags = 0;
400   op->reserved = nullptr;
401   op++;
402   error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(3),
403                                 nullptr);
404   GPR_ASSERT(GRPC_CALL_OK == error);
405 
406   // Both the client request and server response batches should get complete
407   // now and we should see that their callbacks have been executed
408   expect_tag(3, true);
409   expect_tag(1, true);
410   verify_tags(deadline);
411 
412   GPR_ASSERT(status == GRPC_STATUS_UNIMPLEMENTED);
413   GPR_ASSERT(0 == grpc_slice_str_cmp(details, "xyz"));
414   // the following sanity check makes sure that the requested error string is
415   // correctly populated by the core. It looks for certain substrings that are
416   // not likely to change much. Some parts of the error, like time created,
417   // obviously are not checked.
418   GPR_ASSERT(nullptr != strstr(error_string, "xyz"));
419   GPR_ASSERT(nullptr != strstr(error_string, "description"));
420   GPR_ASSERT(nullptr != strstr(error_string, "Error received from peer"));
421   GPR_ASSERT(nullptr != strstr(error_string, "grpc_message"));
422   GPR_ASSERT(nullptr != strstr(error_string, "grpc_status"));
423   GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo"));
424   GPR_ASSERT(0 == call_details.flags);
425   GPR_ASSERT(was_cancelled == 0);
426 
427   grpc_slice_unref(details);
428   gpr_free(static_cast<void*>(const_cast<char*>(error_string)));
429   grpc_metadata_array_destroy(&initial_metadata_recv);
430   grpc_metadata_array_destroy(&trailing_metadata_recv);
431   grpc_metadata_array_destroy(&request_metadata_recv);
432   grpc_call_details_destroy(&call_details);
433 
434   grpc_call_unref(c);
435   grpc_call_unref(s);
436 
437   int expected_calls = 1;
438   if (config.feature_mask & FEATURE_MASK_SUPPORTS_REQUEST_PROXYING) {
439     expected_calls *= 2;
440   }
441 }
442 
test_invoke_simple_request(grpc_end2end_test_config config)443 static void test_invoke_simple_request(grpc_end2end_test_config config) {
444   grpc_end2end_test_fixture f;
445 
446   f = begin_test(config, "test_invoke_simple_request", nullptr, nullptr);
447   simple_request_body(config, f);
448   end_test(&f);
449   config.tear_down_data(&f);
450 }
451 
test_invoke_10_simple_requests(grpc_end2end_test_config config)452 static void test_invoke_10_simple_requests(grpc_end2end_test_config config) {
453   int i;
454   grpc_end2end_test_fixture f =
455       begin_test(config, "test_invoke_10_simple_requests", nullptr, nullptr);
456   for (i = 0; i < 10; i++) {
457     simple_request_body(config, f);
458     gpr_log(GPR_INFO, "Running test: Passed simple request %d", i);
459   }
460   end_test(&f);
461   config.tear_down_data(&f);
462 }
463 
test_invoke_many_simple_requests(grpc_end2end_test_config config)464 static void test_invoke_many_simple_requests(grpc_end2end_test_config config) {
465   int i;
466   const int many = 1000;
467   grpc_end2end_test_fixture f =
468       begin_test(config, "test_invoke_many_simple_requests", nullptr, nullptr);
469   gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
470   for (i = 0; i < many; i++) {
471     simple_request_body(config, f);
472   }
473   double us =
474       gpr_timespec_to_micros(gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), t1)) /
475       many;
476   gpr_log(GPR_INFO, "Time per ping %f us", us);
477   end_test(&f);
478   config.tear_down_data(&f);
479 }
480 
simple_request(grpc_end2end_test_config config)481 static void simple_request(grpc_end2end_test_config config) {
482   int i;
483   for (i = 0; i < 10; i++) {
484     test_invoke_simple_request(config);
485   }
486   test_invoke_10_simple_requests(config);
487   test_invoke_many_simple_requests(config);
488 }
489 
simple_request_pre_init()490 static void simple_request_pre_init() {
491   gpr_mu_init(&tags_mu);
492   gpr_cv_init(&tags_cv);
493 }
494 
495 /* All test configurations */
496 static grpc_end2end_test_config configs[] = {
497     {"inproc-callback", FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER, nullptr,
498      inproc_create_fixture, inproc_init_client, inproc_init_server,
499      inproc_tear_down},
500 };
501 
main(int argc,char ** argv)502 int main(int argc, char** argv) {
503   grpc::testing::TestEnvironment env(argc, argv);
504   grpc_init();
505 
506   simple_request_pre_init();
507   simple_request(configs[0]);
508 
509   grpc_shutdown();
510 
511   return 0;
512 }
513