Esempio n. 1
0
int main(int argc, char **argv) {
    grpc_closure destroyed;
    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    grpc_test_init(argc, argv);
    grpc_init();
    g_pollset = gpr_malloc(grpc_pollset_size());
    grpc_pollset_init(g_pollset, &g_mu);

    test_no_op();
    test_no_op_with_start();
    test_no_op_with_port();
    test_no_op_with_port_and_start();
    test_connect(1);
    test_connect(10);

    grpc_closure_init(&destroyed, destroy_pollset, g_pollset);
    grpc_pollset_shutdown(&exec_ctx, g_pollset, &destroyed);
    grpc_exec_ctx_finish(&exec_ctx);
    grpc_shutdown();
    gpr_free(g_pollset);
    return 0;
}
Esempio n. 2
0
int main(int argc, char **argv) {
  grpc_closure destroyed;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_test_init(argc, argv);
  grpc_init();
  g_pollset_set = grpc_pollset_set_create();
  g_pollset = gpr_malloc(grpc_pollset_size());
  grpc_pollset_init(g_pollset, &g_mu);
  grpc_pollset_set_add_pollset(&exec_ctx, g_pollset_set, g_pollset);
  grpc_exec_ctx_finish(&exec_ctx);
  test_succeeds();
  gpr_log(GPR_ERROR, "End of first test");
  test_fails();
  test_times_out();
  grpc_pollset_set_destroy(g_pollset_set);
  grpc_closure_init(&destroyed, destroy_pollset, g_pollset);
  grpc_pollset_shutdown(&exec_ctx, g_pollset, &destroyed);
  grpc_exec_ctx_finish(&exec_ctx);
  grpc_shutdown();
  gpr_free(g_pollset);
  return 0;
}
Esempio n. 3
0
static void free_port_using_server(char *server, int port) {
  grpc_httpcli_context context;
  grpc_httpcli_request req;
  freereq pr;
  char *path;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_closure shutdown_closure;

  grpc_init();

  memset(&pr, 0, sizeof(pr));
  memset(&req, 0, sizeof(req));
  grpc_pollset_init(&pr.pollset);
  grpc_closure_init(&shutdown_closure, destroy_pollset_and_shutdown,
                    &pr.pollset);

  req.host = server;
  gpr_asprintf(&path, "/drop/%d", port);
  req.path = path;

  grpc_httpcli_context_init(&context);
  grpc_httpcli_get(&exec_ctx, &context, &pr.pollset, &req,
                   GRPC_TIMEOUT_SECONDS_TO_DEADLINE(10), freed_port_from_server,
                   &pr);
  gpr_mu_lock(GRPC_POLLSET_MU(&pr.pollset));
  while (!pr.done) {
    grpc_pollset_worker worker;
    grpc_pollset_work(&exec_ctx, &pr.pollset, &worker,
                      gpr_now(GPR_CLOCK_MONOTONIC),
                      GRPC_TIMEOUT_SECONDS_TO_DEADLINE(1));
  }
  gpr_mu_unlock(GRPC_POLLSET_MU(&pr.pollset));

  grpc_httpcli_context_destroy(&context);
  grpc_exec_ctx_finish(&exec_ctx);
  grpc_pollset_shutdown(&exec_ctx, &pr.pollset, &shutdown_closure);
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_free(path);
}
int main(int argc, char **argv) {
  grpc_test_init(argc, argv);

  grpc_init();
  gpr_mu_init(&g_mu);
  g_combiner = grpc_combiner_create();
  grpc_resolve_address = my_resolve_address;
  grpc_dns_lookup_ares = my_dns_lookup_ares;
  grpc_channel_args *result = (grpc_channel_args *)1;

  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_resolver *resolver = create_resolver(&exec_ctx, "dns:test");
  gpr_event ev1;
  gpr_event_init(&ev1);
  call_resolver_next_after_locking(
      &exec_ctx, resolver, &result,
      GRPC_CLOSURE_CREATE(on_done, &ev1, grpc_schedule_on_exec_ctx));
  grpc_exec_ctx_flush(&exec_ctx);
  GPR_ASSERT(wait_loop(5, &ev1));
  GPR_ASSERT(result == NULL);

  gpr_event ev2;
  gpr_event_init(&ev2);
  call_resolver_next_after_locking(
      &exec_ctx, resolver, &result,
      GRPC_CLOSURE_CREATE(on_done, &ev2, grpc_schedule_on_exec_ctx));
  grpc_exec_ctx_flush(&exec_ctx);
  GPR_ASSERT(wait_loop(30, &ev2));
  GPR_ASSERT(result != NULL);

  grpc_channel_args_destroy(&exec_ctx, result);
  GRPC_RESOLVER_UNREF(&exec_ctx, resolver, "test");
  GRPC_COMBINER_UNREF(&exec_ctx, g_combiner, "test");
  grpc_exec_ctx_finish(&exec_ctx);

  grpc_shutdown();
  gpr_mu_destroy(&g_mu);
}
Esempio n. 5
0
int main(int argc, char **argv) {
  char *scope = NULL;
  char *json_key_file_path = NULL;
  char *service_url = NULL;
  grpc_init();
  gpr_cmdline *cl = gpr_cmdline_create("create_jwt");
  gpr_cmdline_add_string(cl, "json_key", "File path of the json key.",
                         &json_key_file_path);
  gpr_cmdline_add_string(cl, "scope",
                         "OPTIONAL Space delimited permissions. Mutually "
                         "exclusive with service_url",
                         &scope);
  gpr_cmdline_add_string(cl, "service_url",
                         "OPTIONAL service URL. Mutually exclusive with scope.",
                         &service_url);
  gpr_cmdline_parse(cl, argc, argv);

  if (json_key_file_path == NULL) {
    fprintf(stderr, "Missing --json_key option.\n");
    exit(1);
  }
  if (scope != NULL) {
    if (service_url != NULL) {
      fprintf(stderr,
              "Options --scope and --service_url are mutually exclusive.\n");
      exit(1);
    }
  } else if (service_url == NULL) {
    fprintf(stderr, "Need one of --service_url or --scope options.\n");
    exit(1);
  }

  create_jwt(json_key_file_path, service_url, scope);

  gpr_cmdline_destroy(cl);
  grpc_shutdown();
  return 0;
}
Esempio n. 6
0
int main(int argc, char **argv) {
  grpc_channel *chan;
  grpc_call *call;
  grpc_metadata md = {"a", "b", 1, {{NULL, NULL, NULL}}};
  grpc_completion_queue *cq;
  cq_verifier *cqv;

  grpc_test_init(argc, argv);
  grpc_init();

  chan = grpc_lame_client_channel_create();
  GPR_ASSERT(chan);
  call = grpc_channel_create_call_old(chan, "/Foo", "anywhere",
                                      GRPC_TIMEOUT_SECONDS_TO_DEADLINE(100));
  GPR_ASSERT(call);
  cq = grpc_completion_queue_create();
  cqv = cq_verifier_create(cq);

  /* we should be able to add metadata */
  GPR_ASSERT(GRPC_CALL_OK == grpc_call_add_metadata_old(call, &md, 0));

  /* and invoke the call */
  GPR_ASSERT(GRPC_CALL_OK == grpc_call_invoke_old(call, cq, tag(2), tag(3), 0));

  /* the call should immediately fail */
  cq_expect_client_metadata_read(cqv, tag(2), NULL);
  cq_expect_finished(cqv, tag(3), NULL);
  cq_verify(cqv);

  grpc_call_destroy(call);
  grpc_channel_destroy(chan);
  cq_verifier_destroy(cqv);
  grpc_completion_queue_destroy(cq);

  grpc_shutdown();

  return 0;
}
Esempio n. 7
0
int main(int argc, char **argv) {
  const char *poll_strategy = grpc_get_poll_strategy_name();
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_test_init(argc, argv);
  grpc_init();

  if (poll_strategy != NULL &&
      (strcmp(poll_strategy, "epoll") == 0 ||
       strcmp(poll_strategy, "epoll-threadpool") == 0)) {
    pollset_set_test_basic();
    pollset_set_test_dup_fds();
    pollset_set_test_empty_pollset();
  } else {
    gpr_log(GPR_INFO,
            "Skipping the test. The test is only relevant for 'epoll' "
            "strategy. and the current strategy is: '%s'",
            poll_strategy);
  }

  grpc_exec_ctx_finish(&exec_ctx);
  grpc_shutdown();
  return 0;
}
Esempio n. 8
0
static void test_slices_work(void) {
  /* ensure no memory leaks when switching representation from mdstr to slice */
  grpc_mdstr *str;
  gpr_slice slice;

  LOG_TEST("test_slices_work");

  grpc_init();

  str = grpc_mdstr_from_string(
      "123456789012345678901234567890123456789012345678901234567890");
  slice = gpr_slice_ref(str->slice);
  GRPC_MDSTR_UNREF(str);
  gpr_slice_unref(slice);

  str = grpc_mdstr_from_string(
      "123456789012345678901234567890123456789012345678901234567890");
  slice = gpr_slice_ref(str->slice);
  gpr_slice_unref(slice);
  GRPC_MDSTR_UNREF(str);

  grpc_shutdown();
}
Esempio n. 9
0
void Init_grpc() {
  grpc_init();
  ruby_vm_at_exit(grpc_rb_shutdown);
  grpc_rb_mGRPC = rb_define_module("GRPC");
  grpc_rb_mGrpcCore = rb_define_module_under(grpc_rb_mGRPC, "Core");
  grpc_rb_sNewServerRpc =
      rb_struct_define("NewServerRpc", "method", "host",
                       "deadline", "metadata", "call", NULL);
  grpc_rb_sStatus =
      rb_struct_define("Status", "code", "details", "metadata", NULL);
  sym_code = ID2SYM(rb_intern("code"));
  sym_details = ID2SYM(rb_intern("details"));
  sym_metadata = ID2SYM(rb_intern("metadata"));

  Init_grpc_channel();
  Init_grpc_completion_queue();
  Init_grpc_call();
  Init_grpc_credentials();
  Init_grpc_server();
  Init_grpc_server_credentials();
  Init_grpc_status_codes();
  Init_grpc_time_consts();
}
Esempio n. 10
0
int main(int argc, char **argv) {
  size_t i;
  FILE *roots_file;
  size_t roots_size = strlen(test_root_cert);
  char *roots_filename;

  grpc_test_init(argc, argv);
  grpc_end2end_tests_pre_init();

  /* Set the SSL roots env var. */
  roots_file =
      gpr_tmpfile("chttp2_simple_ssl_cert_fullstack_test", &roots_filename);
  GPR_ASSERT(roots_filename != NULL);
  GPR_ASSERT(roots_file != NULL);
  GPR_ASSERT(fwrite(test_root_cert, 1, roots_size, roots_file) == roots_size);
  fclose(roots_file);
  gpr_setenv(GRPC_DEFAULT_SSL_ROOTS_FILE_PATH_ENV_VAR, roots_filename);

  grpc_init();

  for (i = 0; i < sizeof(configs) / sizeof(*configs); i++) {
    grpc_end2end_test_fixture f =
        begin_test(configs[i].config, "SSL_CERT_tests", NULL, NULL);

    simple_request_body(f, configs[i].result);
    end_test(&f);
    configs[i].config.tear_down_data(&f);
  }

  grpc_shutdown();

  /* Cleanup. */
  remove(roots_filename);
  gpr_free(roots_filename);

  return 0;
}
Esempio n. 11
0
int main(int argc, char **argv) {
  synchronizer sync;
  grpc_jwt_verifier *verifier;
  gpr_cmdline *cl;
  char *jwt = NULL;
  char *aud = NULL;

  cl = gpr_cmdline_create("JWT verifier tool");
  gpr_cmdline_add_string(cl, "jwt", "JSON web token to verify", &jwt);
  gpr_cmdline_add_string(cl, "aud", "Audience for the JWT", &aud);
  gpr_cmdline_parse(cl, argc, argv);
  if (jwt == NULL || aud == NULL) {
    print_usage_and_exit(cl, argv[0]);
  }

  verifier = grpc_jwt_verifier_create(NULL, 0);

  grpc_init();

  grpc_pollset_init(&sync.pollset);
  sync.is_done = 0;

  grpc_jwt_verifier_verify(verifier, &sync.pollset, jwt, aud,
                           on_jwt_verification_done, &sync);

  gpr_mu_lock(GRPC_POLLSET_MU(&sync.pollset));
  while (!sync.is_done) {
    grpc_pollset_worker worker;
    grpc_pollset_work(&sync.pollset, &worker,
                      gpr_inf_future(GPR_CLOCK_MONOTONIC));
  }
  gpr_mu_unlock(GRPC_POLLSET_MU(&sync.pollset));

  grpc_jwt_verifier_destroy(verifier);
  gpr_cmdline_destroy(cl);
  return !sync.success;
}
Esempio n. 12
0
File: client.c Progetto: yugui/grpc
int main(int argc, char **argv) {
  grpc_memory_counters_init();
  grpc_slice slice = grpc_slice_from_copied_string("x");
  char *fake_argv[1];

  char *target = "localhost:443";
  gpr_cmdline *cl;
  grpc_event event;

  grpc_init();

  GPR_ASSERT(argc >= 1);
  fake_argv[0] = argv[0];
  grpc_test_init(1, fake_argv);

  int warmup_iterations = 100;
  int benchmark_iterations = 1000;

  cl = gpr_cmdline_create("memory profiling client");
  gpr_cmdline_add_string(cl, "target", "Target host:port", &target);
  gpr_cmdline_add_int(cl, "warmup", "Warmup iterations", &warmup_iterations);
  gpr_cmdline_add_int(cl, "benchmark", "Benchmark iterations",
                      &benchmark_iterations);
  gpr_cmdline_parse(cl, argc, argv);
  gpr_cmdline_destroy(cl);

  for (size_t k = 0; k < GPR_ARRAY_SIZE(calls); k++) {
    calls[k].details = grpc_empty_slice();
  }

  cq = grpc_completion_queue_create(NULL);

  struct grpc_memory_counters client_channel_start =
      grpc_memory_counters_snapshot();
  channel = grpc_insecure_channel_create(target, NULL, NULL);

  int call_idx = 0;

  struct grpc_memory_counters before_server_create = send_snapshot_request(
      0, grpc_slice_from_static_string("Reflector/GetBeforeSvrCreation"));
  struct grpc_memory_counters after_server_create = send_snapshot_request(
      0, grpc_slice_from_static_string("Reflector/GetAfterSvrCreation"));

  // warmup period
  for (call_idx = 0; call_idx < warmup_iterations; ++call_idx) {
    init_ping_pong_request(call_idx + 1);
  }

  struct grpc_memory_counters server_benchmark_calls_start =
      send_snapshot_request(
          0, grpc_slice_from_static_string("Reflector/SimpleSnapshot"));

  struct grpc_memory_counters client_benchmark_calls_start =
      grpc_memory_counters_snapshot();

  // benchmark period
  for (; call_idx < warmup_iterations + benchmark_iterations; ++call_idx) {
    init_ping_pong_request(call_idx + 1);
  }

  struct grpc_memory_counters client_calls_inflight =
      grpc_memory_counters_snapshot();

  struct grpc_memory_counters server_calls_inflight = send_snapshot_request(
      0, grpc_slice_from_static_string("Reflector/DestroyCalls"));

  do {
    event = grpc_completion_queue_next(
        cq, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
                         gpr_time_from_micros(10000, GPR_TIMESPAN)),
        NULL);
  } while (event.type != GRPC_QUEUE_TIMEOUT);

  // second step - recv status and destroy call
  for (call_idx = 0; call_idx < warmup_iterations + benchmark_iterations;
       ++call_idx) {
    finish_ping_pong_request(call_idx + 1);
  }

  struct grpc_memory_counters server_calls_end = send_snapshot_request(
      0, grpc_slice_from_static_string("Reflector/SimpleSnapshot"));

  struct grpc_memory_counters client_channel_end =
      grpc_memory_counters_snapshot();

  grpc_channel_destroy(channel);
  grpc_completion_queue_shutdown(cq);

  do {
    event = grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
                                       NULL);
  } while (event.type != GRPC_QUEUE_SHUTDOWN);
  grpc_slice_unref(slice);

  grpc_completion_queue_destroy(cq);
  grpc_shutdown();

  gpr_log(GPR_INFO, "---------client stats--------");
  gpr_log(GPR_INFO, "client call memory usage: %f bytes per call",
          (double)(client_calls_inflight.total_size_relative -
                   client_benchmark_calls_start.total_size_relative) /
              benchmark_iterations);
  gpr_log(GPR_INFO, "client channel memory usage %zi bytes",
          client_channel_end.total_size_relative -
              client_channel_start.total_size_relative);

  gpr_log(GPR_INFO, "---------server stats--------");
  gpr_log(GPR_INFO, "server create: %zi bytes",
          after_server_create.total_size_relative -
              before_server_create.total_size_relative);
  gpr_log(GPR_INFO, "server call memory usage: %f bytes per call",
          (double)(server_calls_inflight.total_size_relative -
                   server_benchmark_calls_start.total_size_relative) /
              benchmark_iterations);
  gpr_log(GPR_INFO, "server channel memory usage %zi bytes",
          server_calls_end.total_size_relative -
              after_server_create.total_size_relative);

  grpc_memory_counters_destroy();
  return 0;
}
Esempio n. 13
0
int main(int argc, char **argv) {
  grpc_channel *chan;
  grpc_call *call;
  grpc_completion_queue *cq;
  cq_verifier *cqv;
  grpc_op ops[6];
  grpc_op *op;
  grpc_metadata_array trailing_metadata_recv;
  grpc_status_code status;
  grpc_call_error error;
  char *details = NULL;
  size_t details_capacity = 0;

  grpc_test_init(argc, argv);
  grpc_init();

  grpc_metadata_array_init(&trailing_metadata_recv);

  chan = grpc_lame_client_channel_create(
      "lampoon:national", GRPC_STATUS_UNKNOWN, "Rpc sent on a lame channel.");
  GPR_ASSERT(chan);
  cq = grpc_completion_queue_create(NULL);
  call = grpc_channel_create_call(chan, NULL, GRPC_PROPAGATE_DEFAULTS, cq,
                                  "/Foo", "anywhere",
                                  GRPC_TIMEOUT_SECONDS_TO_DEADLINE(100), NULL);
  GPR_ASSERT(call);
  cqv = cq_verifier_create(cq);

  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
  op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
  op->data.recv_status_on_client.status = &status;
  op->data.recv_status_on_client.status_details = &details;
  op->data.recv_status_on_client.status_details_capacity = &details_capacity;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(call, ops, (size_t)(op - ops), tag(1), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  /* the call should immediately fail */
  cq_expect_completion(cqv, tag(1), 1);
  cq_verify(cqv);

  grpc_call_destroy(call);
  grpc_channel_destroy(chan);
  cq_verifier_destroy(cqv);
  grpc_completion_queue_destroy(cq);

  grpc_metadata_array_destroy(&trailing_metadata_recv);
  gpr_free(details);

  grpc_shutdown();

  return 0;
}
int main(int argc, char **argv) {
  grpc_test_init(argc, argv);
  grpc_init();
  int errors = 0;

  // tests with a minimal stack
  grpc_arg minimal_stack_arg = {.type = GRPC_ARG_INTEGER,
                                .key = GRPC_ARG_MINIMAL_STACK,
                                .value.integer = 1};
  grpc_channel_args minimal_stack_args = {.num_args = 1,
                                          .args = &minimal_stack_arg};
  errors += CHECK_STACK("unknown", &minimal_stack_args,
                        GRPC_CLIENT_DIRECT_CHANNEL, "connected", NULL);
  errors += CHECK_STACK("unknown", &minimal_stack_args, GRPC_CLIENT_SUBCHANNEL,
                        "connected", NULL);
  errors += CHECK_STACK("unknown", &minimal_stack_args, GRPC_SERVER_CHANNEL,
                        "server", "connected", NULL);
  errors +=
      CHECK_STACK("chttp2", &minimal_stack_args, GRPC_CLIENT_DIRECT_CHANNEL,
                  "http-client", "connected", NULL);
  errors += CHECK_STACK("chttp2", &minimal_stack_args, GRPC_CLIENT_SUBCHANNEL,
                        "http-client", "connected", NULL);
  errors += CHECK_STACK("chttp2", &minimal_stack_args, GRPC_SERVER_CHANNEL,
                        "server", "http-server", "connected", NULL);
  errors += CHECK_STACK(NULL, &minimal_stack_args, GRPC_CLIENT_CHANNEL,
                        "client-channel", NULL);

  // tests with a default stack
  errors += CHECK_STACK("unknown", NULL, GRPC_CLIENT_DIRECT_CHANNEL,
                        "message_size", "deadline", "connected", NULL);
  errors += CHECK_STACK("unknown", NULL, GRPC_CLIENT_SUBCHANNEL, "message_size",
                        "connected", NULL);
  errors += CHECK_STACK("unknown", NULL, GRPC_SERVER_CHANNEL, "server",
                        "message_size", "deadline", "connected", NULL);
  errors +=
      CHECK_STACK("chttp2", NULL, GRPC_CLIENT_DIRECT_CHANNEL, "message_size",
                  "deadline", "http-client", "compress", "connected", NULL);
  errors += CHECK_STACK("chttp2", NULL, GRPC_CLIENT_SUBCHANNEL, "message_size",
                        "http-client", "compress", "connected", NULL);
  errors +=
      CHECK_STACK("chttp2", NULL, GRPC_SERVER_CHANNEL, "server", "message_size",
                  "deadline", "http-server", "compress", "connected", NULL);
  errors +=
      CHECK_STACK(NULL, NULL, GRPC_CLIENT_CHANNEL, "client-channel", NULL);

  GPR_ASSERT(errors == 0);
  grpc_shutdown();
  return 0;
}

/*******************************************************************************
 * End of tests definitions, start of test infrastructure
 */

static int check_stack(const char *file, int line, const char *transport_name,
                       grpc_channel_args *init_args,
                       grpc_channel_stack_type channel_stack_type, ...) {
  // create dummy channel stack
  grpc_channel_stack_builder *builder = grpc_channel_stack_builder_create();
  grpc_transport_vtable fake_transport_vtable = {.name = transport_name};
  grpc_transport fake_transport = {.vtable = &fake_transport_vtable};
  grpc_channel_stack_builder_set_target(builder, "foo.test.google.fr");
  grpc_channel_args *channel_args = grpc_channel_args_copy(init_args);
  if (transport_name != NULL) {
    grpc_channel_stack_builder_set_transport(builder, &fake_transport);
  }
  {
    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    grpc_channel_stack_builder_set_channel_arguments(&exec_ctx, builder,
                                                     channel_args);
    GPR_ASSERT(
        grpc_channel_init_create_stack(&exec_ctx, builder, channel_stack_type));
    grpc_exec_ctx_finish(&exec_ctx);
  }

  // build up our expectation list
  gpr_strvec v;
  gpr_strvec_init(&v);
  va_list args;
  va_start(args, channel_stack_type);
  for (;;) {
    char *a = va_arg(args, char *);
    if (a == NULL) break;
    if (v.count != 0) gpr_strvec_add(&v, gpr_strdup(", "));
    gpr_strvec_add(&v, gpr_strdup(a));
  }
  va_end(args);
  char *expect = gpr_strvec_flatten(&v, NULL);
  gpr_strvec_destroy(&v);

  // build up our "got" list
  gpr_strvec_init(&v);
  grpc_channel_stack_builder_iterator *it =
      grpc_channel_stack_builder_create_iterator_at_first(builder);
  while (grpc_channel_stack_builder_move_next(it)) {
    const char *name = grpc_channel_stack_builder_iterator_filter_name(it);
    if (name == NULL) continue;
    if (v.count != 0) gpr_strvec_add(&v, gpr_strdup(", "));
    gpr_strvec_add(&v, gpr_strdup(name));
  }
  char *got = gpr_strvec_flatten(&v, NULL);
  gpr_strvec_destroy(&v);
  grpc_channel_stack_builder_iterator_destroy(it);

  // figure out result, log if there's an error
  int result = 0;
  if (0 != strcmp(got, expect)) {
    gpr_strvec_init(&v);
    gpr_strvec_add(&v, gpr_strdup("{"));
    for (size_t i = 0; i < channel_args->num_args; i++) {
      if (i > 0) gpr_strvec_add(&v, gpr_strdup(", "));
      gpr_strvec_add(&v, gpr_strdup(channel_args->args[i].key));
      gpr_strvec_add(&v, gpr_strdup("="));
      switch (channel_args->args[i].type) {
        case GRPC_ARG_INTEGER: {
          char *tmp;
          gpr_asprintf(&tmp, "%d", channel_args->args[i].value.integer);
          gpr_strvec_add(&v, tmp);
          break;
        }
        case GRPC_ARG_STRING:
          gpr_strvec_add(&v, gpr_strdup(channel_args->args[i].value.string));
          break;
        case GRPC_ARG_POINTER: {
          char *tmp;
          gpr_asprintf(&tmp, "%p", channel_args->args[i].value.pointer.p);
          gpr_strvec_add(&v, tmp);
          break;
        }
      }
    }
    gpr_strvec_add(&v, gpr_strdup("}"));
    char *args_str = gpr_strvec_flatten(&v, NULL);
    gpr_strvec_destroy(&v);

    gpr_log(file, line, GPR_LOG_SEVERITY_ERROR,
            "**************************************************");
    gpr_log(file, line, GPR_LOG_SEVERITY_ERROR,
            "FAILED transport=%s; stack_type=%s; channel_args=%s:",
            transport_name, grpc_channel_stack_type_string(channel_stack_type),
            args_str);
    gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "EXPECTED: %s", expect);
    gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "GOT:      %s", got);
    result = 1;

    gpr_free(args_str);
  }

  gpr_free(got);
  gpr_free(expect);

  {
    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    grpc_channel_stack_builder_destroy(&exec_ctx, builder);
    grpc_channel_args_destroy(&exec_ctx, channel_args);
    grpc_exec_ctx_finish(&exec_ctx);
  }

  return result;
}
Esempio n. 15
0
static void grpc_ruby_once_init() {
  grpc_init();
  atexit(grpc_rb_shutdown);
}
Esempio n. 16
0
int main(int argc, char **argv) {
  grpc_channel *chan;
  grpc_call *call;
  grpc_completion_queue *cq;
  cq_verifier *cqv;
  grpc_op ops[6];
  grpc_op *op;
  grpc_metadata_array initial_metadata_recv;
  grpc_metadata_array trailing_metadata_recv;
  grpc_status_code status;
  grpc_call_error error;
  grpc_slice details;
  char *peer;

  grpc_test_init(argc, argv);
  grpc_init();

  grpc_metadata_array_init(&initial_metadata_recv);
  grpc_metadata_array_init(&trailing_metadata_recv);

  chan = grpc_lame_client_channel_create(
      "lampoon:national", GRPC_STATUS_UNKNOWN, "Rpc sent on a lame channel.");
  GPR_ASSERT(chan);

  test_transport_op(chan);

  GPR_ASSERT(GRPC_CHANNEL_SHUTDOWN ==
             grpc_channel_check_connectivity_state(chan, 0));

  cq = grpc_completion_queue_create(NULL);

  grpc_slice host = grpc_slice_from_static_string("anywhere");
  call = grpc_channel_create_call(chan, NULL, GRPC_PROPAGATE_DEFAULTS, cq,
                                  grpc_slice_from_static_string("/Foo"), &host,
                                  grpc_timeout_seconds_to_deadline(100), NULL);
  GPR_ASSERT(call);
  cqv = cq_verifier_create(cq);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_INITIAL_METADATA;
  op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(call, ops, (size_t)(op - ops), tag(1), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  /* the call should immediately fail */
  CQ_EXPECT_COMPLETION(cqv, tag(1), 0);
  cq_verify(cqv);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
  op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
  op->data.recv_status_on_client.status = &status;
  op->data.recv_status_on_client.status_details = &details;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(call, ops, (size_t)(op - ops), tag(2), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  /* the call should immediately fail */
  CQ_EXPECT_COMPLETION(cqv, tag(2), 1);
  cq_verify(cqv);

  peer = grpc_call_get_peer(call);
  GPR_ASSERT(strcmp(peer, "lampoon:national") == 0);
  gpr_free(peer);

  grpc_call_destroy(call);
  grpc_channel_destroy(chan);
  cq_verifier_destroy(cqv);
  grpc_completion_queue_destroy(cq);

  grpc_metadata_array_destroy(&initial_metadata_recv);
  grpc_metadata_array_destroy(&trailing_metadata_recv);
  grpc_slice_unref(details);

  grpc_shutdown();

  return 0;
}
Esempio n. 17
0
int main(int argc, char **argv) {
  test_spec *spec;
  size_t i;
  const size_t NUM_ITERS = 10;
  const size_t NUM_SERVERS = 4;

  grpc_test_init(argc, argv);
  grpc_init();
  grpc_lb_round_robin_trace = 1;

  GPR_ASSERT(grpc_lb_policy_create("this-lb-policy-does-not-exist", NULL) ==
             NULL);
  GPR_ASSERT(grpc_lb_policy_create(NULL, NULL) == NULL);

  spec = test_spec_create(NUM_ITERS, NUM_SERVERS);
  /* everything is fine, all servers stay up the whole time and life's peachy */
  spec->verifier = verify_vanilla_round_robin;
  spec->description = "test_all_server_up";
  run_spec(spec);

  /* Kill all servers first thing in the morning */
  test_spec_reset(spec);
  spec->verifier = verify_total_carnage_round_robin;
  spec->description = "test_kill_all_server";
  for (i = 0; i < NUM_SERVERS; i++) {
    spec->kill_at[0][i] = 1;
  }
  run_spec(spec);

  /* at the start of the 2nd iteration, kill all but the first and last
   * servers.
   * This should knock down the server bound to be selected next */
  test_spec_reset(spec);
  spec->verifier = verify_vanishing_floor_round_robin;
  spec->description = "test_kill_all_server_at_2nd_iteration";
  for (i = 1; i < NUM_SERVERS - 1; i++) {
    spec->kill_at[1][i] = 1;
  }
  run_spec(spec);

  /* Midway, kill all servers. */
  test_spec_reset(spec);
  spec->verifier = verify_partial_carnage_round_robin;
  spec->description = "test_kill_all_server_midway";
  for (i = 0; i < NUM_SERVERS; i++) {
    spec->kill_at[spec->num_iters / 2][i] = 1;
  }
  run_spec(spec);

  /* After first iteration, kill all servers. On the third one, bring them all
   * back up. */
  test_spec_reset(spec);
  spec->verifier = verify_rebirth_round_robin;
  spec->description = "test_kill_all_server_after_1st_resurrect_at_3rd";
  for (i = 0; i < NUM_SERVERS; i++) {
    spec->kill_at[1][i] = 1;
    spec->revive_at[3][i] = 1;
  }
  run_spec(spec);
  test_spec_destroy(spec);

  test_pending_calls(4);
  test_ping();

  grpc_shutdown();
  return 0;
}
Esempio n. 18
0
void grpc_run_bad_client_test(const char *name, const char *client_payload,
                              size_t client_payload_length,
                              grpc_bad_client_server_side_validator validator) {
  grpc_endpoint_pair sfd;
  thd_args a;
  gpr_thd_id id;
  gpr_slice slice =
      gpr_slice_from_copied_buffer(client_payload, client_payload_length);

  /* Add a debug log */
  gpr_log(GPR_INFO, "TEST: %s", name);

  /* Init grpc */
  grpc_init();

  /* Create endpoints */
  sfd = grpc_iomgr_create_endpoint_pair(65536);

  /* Create server, completion events */
  a.server = grpc_server_create_from_filters(NULL, 0, NULL);
  a.cq = grpc_completion_queue_create();
  gpr_event_init(&a.done_thd);
  gpr_event_init(&a.done_write);
  a.validator = validator;
  grpc_server_register_completion_queue(a.server, a.cq);
  grpc_server_start(a.server);
  grpc_create_chttp2_transport(server_setup_transport, &a, NULL, sfd.server,
                               NULL, 0, grpc_mdctx_create(), 0);

  /* Bind everything into the same pollset */
  grpc_endpoint_add_to_pollset(sfd.client, grpc_cq_pollset(a.cq));
  grpc_endpoint_add_to_pollset(sfd.server, grpc_cq_pollset(a.cq));

  /* Check a ground truth */
  GPR_ASSERT(grpc_server_has_open_connections(a.server));

  /* Start validator */
  gpr_thd_new(&id, thd_func, &a, NULL);

  /* Write data */
  switch (grpc_endpoint_write(sfd.client, &slice, 1, done_write, &a)) {
    case GRPC_ENDPOINT_WRITE_DONE:
      done_write(&a, 1);
      break;
    case GRPC_ENDPOINT_WRITE_PENDING:
      break;
    case GRPC_ENDPOINT_WRITE_ERROR:
      done_write(&a, 0);
      break;
  }

  /* Await completion */
  GPR_ASSERT(
      gpr_event_wait(&a.done_write, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5)));
  GPR_ASSERT(gpr_event_wait(&a.done_thd, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5)));

  /* Shutdown */
  grpc_endpoint_destroy(sfd.client);
  grpc_server_destroy(a.server);
  grpc_completion_queue_destroy(a.cq);

  grpc_shutdown();
}
int run_concurrent_connectivity_test() {
  struct server_thread_args args;
  memset(&args, 0, sizeof(args));

  grpc_init();

  gpr_thd_id threads[NUM_THREADS];
  gpr_thd_id server;

  char *localhost = gpr_strdup("localhost:54321");
  gpr_thd_options options = gpr_thd_options_default();
  gpr_thd_options_set_joinable(&options);

  /* First round, no server */
  gpr_log(GPR_DEBUG, "Wave 1");
  for (size_t i = 0; i < NUM_THREADS; ++i) {
    gpr_thd_new(&threads[i], create_loop_destroy, localhost, &options);
  }
  for (size_t i = 0; i < NUM_THREADS; ++i) {
    gpr_thd_join(threads[i]);
  }
  gpr_free(localhost);

  /* Second round, actual grpc server */
  gpr_log(GPR_DEBUG, "Wave 2");
  int port = grpc_pick_unused_port_or_die();
  gpr_asprintf(&args.addr, "localhost:%d", port);
  args.server = grpc_server_create(NULL, NULL);
  grpc_server_add_insecure_http2_port(args.server, args.addr);
  args.cq = grpc_completion_queue_create_for_next(NULL);
  grpc_server_register_completion_queue(args.server, args.cq, NULL);
  grpc_server_start(args.server);
  gpr_thd_new(&server, server_thread, &args, &options);

  for (size_t i = 0; i < NUM_THREADS; ++i) {
    gpr_thd_new(&threads[i], create_loop_destroy, args.addr, &options);
  }
  for (size_t i = 0; i < NUM_THREADS; ++i) {
    gpr_thd_join(threads[i]);
  }
  grpc_server_shutdown_and_notify(args.server, args.cq, tag(0xd1e));

  gpr_thd_join(server);
  grpc_server_destroy(args.server);
  grpc_completion_queue_destroy(args.cq);
  gpr_free(args.addr);

  /* Third round, bogus tcp server */
  gpr_log(GPR_DEBUG, "Wave 3");
  args.pollset = gpr_zalloc(grpc_pollset_size());
  grpc_pollset_init(args.pollset, &args.mu);
  gpr_event_init(&args.ready);
  gpr_thd_new(&server, bad_server_thread, &args, &options);
  gpr_event_wait(&args.ready, gpr_inf_future(GPR_CLOCK_MONOTONIC));

  for (size_t i = 0; i < NUM_THREADS; ++i) {
    gpr_thd_new(&threads[i], create_loop_destroy, args.addr, &options);
  }
  for (size_t i = 0; i < NUM_THREADS; ++i) {
    gpr_thd_join(threads[i]);
  }

  gpr_atm_rel_store(&args.stop, 1);
  gpr_thd_join(server);
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_pollset_shutdown(&exec_ctx, args.pollset,
                        GRPC_CLOSURE_CREATE(done_pollset_shutdown, args.pollset,
                                            grpc_schedule_on_exec_ctx));
  grpc_exec_ctx_finish(&exec_ctx);

  grpc_shutdown();
  return 0;
}
Esempio n. 20
0
void grpc_run_bad_client_test(grpc_bad_client_server_side_validator validator,
                              const char *client_payload,
                              size_t client_payload_length, gpr_uint32 flags) {
  grpc_endpoint_pair sfd;
  thd_args a;
  gpr_thd_id id;
  char *hex;
  grpc_transport *transport;
  grpc_mdctx *mdctx = grpc_mdctx_create();
  gpr_slice slice =
      gpr_slice_from_copied_buffer(client_payload, client_payload_length);

  hex = gpr_dump(client_payload, client_payload_length,
                 GPR_DUMP_HEX | GPR_DUMP_ASCII);

  /* Add a debug log */
  gpr_log(GPR_INFO, "TEST: %s", hex);

  gpr_free(hex);

  /* Init grpc */
  grpc_init();

  /* Create endpoints */
  sfd = grpc_iomgr_create_endpoint_pair("fixture", 65536);

  /* Create server, completion events */
  a.server = grpc_server_create_from_filters(NULL, 0, NULL);
  a.cq = grpc_completion_queue_create(NULL);
  gpr_event_init(&a.done_thd);
  gpr_event_init(&a.done_write);
  a.validator = validator;
  grpc_server_register_completion_queue(a.server, a.cq, NULL);
  grpc_server_start(a.server);
  transport = grpc_create_chttp2_transport(NULL, sfd.server, mdctx, 0);
  server_setup_transport(&a, transport, mdctx);
  grpc_chttp2_transport_start_reading(transport, NULL, 0);

  /* Bind everything into the same pollset */
  grpc_endpoint_add_to_pollset(sfd.client, grpc_cq_pollset(a.cq));
  grpc_endpoint_add_to_pollset(sfd.server, grpc_cq_pollset(a.cq));

  /* Check a ground truth */
  GPR_ASSERT(grpc_server_has_open_connections(a.server));

  /* Start validator */
  gpr_thd_new(&id, thd_func, &a, NULL);

  /* Write data */
  switch (grpc_endpoint_write(sfd.client, &slice, 1, done_write, &a)) {
    case GRPC_ENDPOINT_WRITE_DONE:
      done_write(&a, 1);
      break;
    case GRPC_ENDPOINT_WRITE_PENDING:
      break;
    case GRPC_ENDPOINT_WRITE_ERROR:
      done_write(&a, 0);
      break;
  }

  /* Await completion */
  GPR_ASSERT(
      gpr_event_wait(&a.done_write, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5)));

  if (flags & GRPC_BAD_CLIENT_DISCONNECT) {
    grpc_endpoint_destroy(sfd.client);
    sfd.client = NULL;
  }

  GPR_ASSERT(gpr_event_wait(&a.done_thd, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5)));

  /* Shutdown */
  if (sfd.client) {
    grpc_endpoint_destroy(sfd.client);
  }
  grpc_server_shutdown_and_notify(a.server, a.cq, NULL);
  GPR_ASSERT(grpc_completion_queue_pluck(
                 a.cq, NULL, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(1), NULL)
                 .type == GRPC_OP_COMPLETE);
  grpc_server_destroy(a.server);
  grpc_completion_queue_destroy(a.cq);

  grpc_shutdown();
}
Esempio n. 21
0
static void run_test(bool wait_for_ready, bool use_service_config) {
  grpc_channel *chan;
  grpc_call *call;
  gpr_timespec deadline = GRPC_TIMEOUT_SECONDS_TO_DEADLINE(2);
  grpc_completion_queue *cq;
  cq_verifier *cqv;
  grpc_op ops[6];
  grpc_op *op;
  grpc_metadata_array trailing_metadata_recv;
  grpc_status_code status;
  char *details = NULL;
  size_t details_capacity = 0;

  gpr_log(GPR_INFO, "TEST: wait_for_ready=%d use_service_config=%d",
          wait_for_ready, use_service_config);

  grpc_init();

  grpc_metadata_array_init(&trailing_metadata_recv);

  cq = grpc_completion_queue_create(NULL);
  cqv = cq_verifier_create(cq);

  /* if using service config, create channel args */
  grpc_channel_args *args = NULL;
  if (use_service_config) {
    GPR_ASSERT(wait_for_ready);
    grpc_arg arg;
    arg.type = GRPC_ARG_STRING;
    arg.key = GRPC_ARG_SERVICE_CONFIG;
    arg.value.string =
        "{\n"
        "  \"methodConfig\": [ {\n"
        "    \"name\": [\n"
        "      { \"service\": \"service\", \"method\": \"method\" }\n"
        "    ],\n"
        "    \"waitForReady\": true\n"
        "  } ]\n"
        "}";
    args = grpc_channel_args_copy_and_add(args, &arg, 1);
  }

  /* create a call, channel to a port which will refuse connection */
  int port = grpc_pick_unused_port_or_die();
  char *addr;
  gpr_join_host_port(&addr, "127.0.0.1", port);
  gpr_log(GPR_INFO, "server: %s", addr);
  chan = grpc_insecure_channel_create(addr, args, NULL);
  call = grpc_channel_create_call(chan, NULL, GRPC_PROPAGATE_DEFAULTS, cq,
                                  "/service/method", "nonexistant", deadline,
                                  NULL);

  gpr_free(addr);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  op->flags = (wait_for_ready && !use_service_config)
                  ? GRPC_INITIAL_METADATA_WAIT_FOR_READY
                  : 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
  op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
  op->data.recv_status_on_client.status = &status;
  op->data.recv_status_on_client.status_details = &details;
  op->data.recv_status_on_client.status_details_capacity = &details_capacity;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(
                                 call, ops, (size_t)(op - ops), tag(1), NULL));
  /* verify that all tags get completed */
  CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
  cq_verify(cqv);

  if (wait_for_ready) {
    GPR_ASSERT(status == GRPC_STATUS_DEADLINE_EXCEEDED);
  } else {
    GPR_ASSERT(status == GRPC_STATUS_UNAVAILABLE);
  }

  grpc_completion_queue_shutdown(cq);
  while (
      grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME), NULL)
          .type != GRPC_QUEUE_SHUTDOWN)
    ;
  grpc_completion_queue_destroy(cq);
  grpc_call_destroy(call);
  grpc_channel_destroy(chan);
  cq_verifier_destroy(cqv);

  gpr_free(details);
  grpc_metadata_array_destroy(&trailing_metadata_recv);

  if (args != NULL) grpc_channel_args_destroy(args);

  grpc_shutdown();
}
Esempio n. 22
0
// This test launches a minimal TLS server on a separate thread and then
// establishes a TLS handshake via the core library to the server. The TLS
// server validates ALPN aspects of the handshake and supplies the protocol
// specified in the server_alpn_preferred argument to the client.
static bool client_ssl_test(char *server_alpn_preferred) {
  bool success = true;

  grpc_init();

  // Find a port we can bind to. Retries added to handle flakes in port server
  // and port picking.
  int port = -1;
  int server_socket = -1;
  int socket_retries = 10;
  while (server_socket == -1 && socket_retries-- > 0) {
    port = grpc_pick_unused_port_or_die();
    server_socket = create_socket(port);
    if (server_socket == -1) {
      sleep(1);
    }
  }
  GPR_ASSERT(server_socket > 0);

  // Launch the TLS server thread.
  gpr_thd_options thdopt = gpr_thd_options_default();
  gpr_thd_id thdid;
  gpr_thd_options_set_joinable(&thdopt);
  server_args args = {.socket = server_socket,
                      .alpn_preferred = server_alpn_preferred};
  GPR_ASSERT(gpr_thd_new(&thdid, server_thread, &args, &thdopt));

  // Load key pair and establish client SSL credentials.
  grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
  gpr_slice ca_slice, cert_slice, key_slice;
  GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
                               grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
  GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
                               grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
  GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
                               grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
  const char *ca_cert = (const char *)GPR_SLICE_START_PTR(ca_slice);
  pem_key_cert_pair.private_key = (const char *)GPR_SLICE_START_PTR(key_slice);
  pem_key_cert_pair.cert_chain = (const char *)GPR_SLICE_START_PTR(cert_slice);
  grpc_channel_credentials *ssl_creds =
      grpc_ssl_credentials_create(ca_cert, &pem_key_cert_pair, NULL);

  // Establish a channel pointing at the TLS server. Since the gRPC runtime is
  // lazy, this won't necessarily establish a connection yet.
  char *target;
  gpr_asprintf(&target, "127.0.0.1:%d", port);
  grpc_arg ssl_name_override = {GRPC_ARG_STRING,
                                GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
                                {"foo.test.google.fr"}};
  grpc_channel_args grpc_args;
  grpc_args.num_args = 1;
  grpc_args.args = &ssl_name_override;
  grpc_channel *channel =
      grpc_secure_channel_create(ssl_creds, target, &grpc_args, NULL);
  GPR_ASSERT(channel);
  gpr_free(target);

  // Initially the channel will be idle, the
  // grpc_channel_check_connectivity_state triggers an attempt to connect.
  GPR_ASSERT(grpc_channel_check_connectivity_state(
                 channel, 1 /* try_to_connect */) == GRPC_CHANNEL_IDLE);

  // Wait a bounded number of times for the channel to be ready. When the
  // channel is ready, the initial TLS handshake will have successfully
  // completed and we know that the client's ALPN list satisfied the server.
  int retries = 10;
  grpc_connectivity_state state = GRPC_CHANNEL_IDLE;
  grpc_completion_queue *cq = grpc_completion_queue_create(NULL);
  while (state != GRPC_CHANNEL_READY && retries-- > 0) {
    grpc_channel_watch_connectivity_state(
        channel, state, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(3), cq, NULL);
    gpr_timespec cq_deadline = GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5);
    grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, NULL);
    GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
    state =
        grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */);
  }
  grpc_completion_queue_destroy(cq);
  if (retries < 0) {
    success = false;
  }

  grpc_channel_destroy(channel);
  grpc_channel_credentials_release(ssl_creds);
  gpr_slice_unref(cert_slice);
  gpr_slice_unref(key_slice);
  gpr_slice_unref(ca_slice);

  gpr_thd_join(thdid);

  grpc_shutdown();

  return success;
}
Esempio n. 23
0
int main(int argc, char **argv) {
  int do_ipv6 = 1;

  grpc_test_init(argc, argv);
  grpc_init();

  if (!grpc_ipv6_loopback_available()) {
    gpr_log(GPR_INFO, "Can't bind to ::1.  Skipping IPv6 tests.");
    do_ipv6 = 0;
  }

  /* For coverage, test with and without dualstack sockets. */
  for (grpc_forbid_dualstack_sockets_for_testing = 0;
       grpc_forbid_dualstack_sockets_for_testing <= 1;
       grpc_forbid_dualstack_sockets_for_testing++) {
    /* :: and 0.0.0.0 are handled identically. */
    test_connect("::", "127.0.0.1", 0, 1);
    test_connect("::", "::ffff:127.0.0.1", 0, 1);
    test_connect("::", "ipv4:127.0.0.1", 0, 1);
    test_connect("::", "ipv6:[::ffff:127.0.0.1]", 0, 1);
    test_connect("::", "localhost", 0, 1);
    test_connect("0.0.0.0", "127.0.0.1", 0, 1);
    test_connect("0.0.0.0", "::ffff:127.0.0.1", 0, 1);
    test_connect("0.0.0.0", "ipv4:127.0.0.1", 0, 1);
    test_connect("0.0.0.0", "ipv4:127.0.0.1,127.0.0.2,127.0.0.3", 0, 1);
    test_connect("0.0.0.0", "ipv6:[::ffff:127.0.0.1],[::ffff:127.0.0.2]", 0, 1);
    test_connect("0.0.0.0", "localhost", 0, 1);
    if (do_ipv6) {
      test_connect("::", "::1", 0, 1);
      test_connect("0.0.0.0", "::1", 0, 1);
      test_connect("::", "ipv6:[::1]", 0, 1);
      test_connect("0.0.0.0", "ipv6:[::1]", 0, 1);
    }

    /* These only work when the families agree. */
    test_connect("127.0.0.1", "127.0.0.1", 0, 1);
    test_connect("127.0.0.1", "ipv4:127.0.0.1", 0, 1);
    if (do_ipv6) {
      test_connect("::1", "::1", 0, 1);
      test_connect("::1", "127.0.0.1", 0, 0);
      test_connect("127.0.0.1", "::1", 0, 0);
      test_connect("::1", "ipv6:[::1]", 0, 1);
      test_connect("::1", "ipv4:127.0.0.1", 0, 0);
      test_connect("127.0.0.1", "ipv6:[::1]", 0, 0);
    }

    if (!external_dns_works("loopback46.unittest.grpc.io")) {
      gpr_log(GPR_INFO, "Skipping tests that depend on *.unittest.grpc.io.");
    } else {
      test_connect("loopback46.unittest.grpc.io", "loopback4.unittest.grpc.io",
                   0, 1);
      test_connect("loopback4.unittest.grpc.io", "loopback46.unittest.grpc.io",
                   0, 1);
      if (do_ipv6) {
        test_connect("loopback46.unittest.grpc.io",
                     "loopback6.unittest.grpc.io", 0, 1);
        test_connect("loopback6.unittest.grpc.io",
                     "loopback46.unittest.grpc.io", 0, 1);
        test_connect("loopback4.unittest.grpc.io", "loopback6.unittest.grpc.io",
                     0, 0);
        test_connect("loopback6.unittest.grpc.io", "loopback4.unittest.grpc.io",
                     0, 0);
      }
    }
  }

  grpc_shutdown();

  return 0;
}
Esempio n. 24
0
int main(int argc, char **argv) {
  gpr_slice slice = gpr_slice_from_copied_string("x");
  double start, stop;
  unsigned i;

  char *fake_argv[1];

  int payload_size = 1;
  int secure = 0;
  char *target = "localhost:443";
  gpr_cmdline *cl;
  char *scenario_name = "ping-pong-request";
  scenario sc = {NULL, NULL, NULL};

  GPR_ASSERT(argc >= 1);
  fake_argv[0] = argv[0];
  grpc_test_init(1, fake_argv);

  grpc_init();

  cl = gpr_cmdline_create("fling client");
  gpr_cmdline_add_int(cl, "payload_size", "Size of the payload to send",
                      &payload_size);
  gpr_cmdline_add_string(cl, "target", "Target host:port", &target);
  gpr_cmdline_add_flag(cl, "secure", "Run with security?", &secure);
  gpr_cmdline_add_string(cl, "scenario", "Scenario", &scenario_name);
  gpr_cmdline_parse(cl, argc, argv);
  gpr_cmdline_destroy(cl);

  for (i = 0; i < GPR_ARRAY_SIZE(scenarios); i++) {
    if (0 == strcmp(scenarios[i].name, scenario_name)) {
      sc = scenarios[i];
    }
  }
  if (!sc.name) {
    fprintf(stderr, "unsupported scenario '%s'. Valid are:", scenario_name);
    for (i = 0; i < GPR_ARRAY_SIZE(scenarios); i++) {
      fprintf(stderr, " %s", scenarios[i].name);
    }
    return 1;
  }

  channel = grpc_channel_create(target, NULL);
  cq = grpc_completion_queue_create();
  the_buffer = grpc_raw_byte_buffer_create(&slice, payload_size);
  histogram = gpr_histogram_create(0.01, 60e9);

  sc.init();

  for (i = 0; i < 1000; i++) {
    sc.do_one_step();
  }

  gpr_log(GPR_INFO, "start profiling");
  grpc_profiler_start("client.prof");
  for (i = 0; i < 100000; i++) {
    start = now();
    sc.do_one_step();
    stop = now();
    gpr_histogram_add(histogram, stop - start);
  }
  grpc_profiler_stop();

  if (call) {
    grpc_call_destroy(call);
  }

  grpc_channel_destroy(channel);
  grpc_completion_queue_shutdown(cq);
  while (grpc_completion_queue_next(cq, gpr_inf_future).type !=
         GRPC_QUEUE_SHUTDOWN)
    ;
  grpc_completion_queue_destroy(cq);
  grpc_byte_buffer_destroy(the_buffer);
  gpr_slice_unref(slice);

  gpr_log(GPR_INFO, "latency (50/95/99/99.9): %f/%f/%f/%f",
          gpr_histogram_percentile(histogram, 50),
          gpr_histogram_percentile(histogram, 95),
          gpr_histogram_percentile(histogram, 99),
          gpr_histogram_percentile(histogram, 99.9));
  gpr_histogram_destroy(histogram);

  grpc_shutdown();

  return 0;
}
Esempio n. 25
0
GPR_EXPORT void GPR_CALLTYPE grpcsharp_init(void) { grpc_init(); }
Esempio n. 26
0
int main(int argc, char **argv) {
  grpc_event ev;
  call_state *s;
  char *addr_buf = NULL;
  gpr_cmdline *cl;
  int shutdown_started = 0;
  int shutdown_finished = 0;

  int secure = 0;
  char *addr = NULL;

  char *fake_argv[1];

  GPR_ASSERT(argc >= 1);
  fake_argv[0] = argv[0];
  grpc_test_init(1, fake_argv);

  grpc_init();
  srand(clock());

  cl = gpr_cmdline_create("fling server");
  gpr_cmdline_add_string(cl, "bind", "Bind host:port", &addr);
  gpr_cmdline_add_flag(cl, "secure", "Run with security?", &secure);
  gpr_cmdline_parse(cl, argc, argv);
  gpr_cmdline_destroy(cl);

  if (addr == NULL) {
    gpr_join_host_port(&addr_buf, "::", grpc_pick_unused_port_or_die());
    addr = addr_buf;
  }
  gpr_log(GPR_INFO, "creating server on: %s", addr);

  cq = grpc_completion_queue_create();
  if (secure) {
    grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {test_server1_key,
                                                    test_server1_cert};
    grpc_server_credentials *ssl_creds =
        grpc_ssl_server_credentials_create(NULL, &pem_key_cert_pair, 1, 0);
    server = grpc_server_create(NULL);
    GPR_ASSERT(grpc_server_add_secure_http2_port(server, addr, ssl_creds));
    grpc_server_credentials_release(ssl_creds);
  } else {
    server = grpc_server_create(NULL);
    GPR_ASSERT(grpc_server_add_insecure_http2_port(server, addr));
  }
  grpc_server_register_completion_queue(server, cq);
  grpc_server_start(server);

  gpr_free(addr_buf);
  addr = addr_buf = NULL;

  grpc_call_details_init(&call_details);

  request_call();

  grpc_profiler_start("server.prof");
  signal(SIGINT, sigint_handler);
  while (!shutdown_finished) {
    if (got_sigint && !shutdown_started) {
      gpr_log(GPR_INFO, "Shutting down due to SIGINT");
      grpc_server_shutdown_and_notify(server, cq, tag(1000));
      GPR_ASSERT(grpc_completion_queue_pluck(
                     cq, tag(1000), GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5))
                     .type == GRPC_OP_COMPLETE);
      grpc_completion_queue_shutdown(cq);
      shutdown_started = 1;
    }
    ev = grpc_completion_queue_next(
        cq, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
                         gpr_time_from_micros(1000000, GPR_TIMESPAN)));
    s = ev.tag;
    switch (ev.type) {
      case GRPC_OP_COMPLETE:
        switch ((gpr_intptr)s) {
          case FLING_SERVER_NEW_REQUEST:
            if (call != NULL) {
              if (0 ==
                  strcmp(call_details.method, "/Reflector/reflectStream")) {
                /* Received streaming call. Send metadata here. */
                start_read_op(FLING_SERVER_READ_FOR_STREAMING);
                send_initial_metadata();
              } else {
                /* Received unary call. Can do all ops in one batch. */
                start_read_op(FLING_SERVER_READ_FOR_UNARY);
              }
            } else {
              GPR_ASSERT(shutdown_started);
            }
            /*	    request_call();
             */
            break;
          case FLING_SERVER_READ_FOR_STREAMING:
            if (payload_buffer != NULL) {
              /* Received payload from client. */
              start_write_op();
            } else {
              /* Received end of stream from client. */
              start_send_status();
            }
            break;
          case FLING_SERVER_WRITE_FOR_STREAMING:
            /* Write completed at server  */
            grpc_byte_buffer_destroy(payload_buffer);
            payload_buffer = NULL;
            start_read_op(FLING_SERVER_READ_FOR_STREAMING);
            break;
          case FLING_SERVER_SEND_INIT_METADATA_FOR_STREAMING:
            /* Metadata send completed at server */
            break;
          case FLING_SERVER_SEND_STATUS_FOR_STREAMING:
            /* Send status and close completed at server */
            grpc_call_destroy(call);
            if (!shutdown_started) request_call();
            break;
          case FLING_SERVER_READ_FOR_UNARY:
            /* Finished payload read for unary. Start all reamaining
             *  unary ops in a batch.
             */
            handle_unary_method();
            break;
          case FLING_SERVER_BATCH_OPS_FOR_UNARY:
            /* Finished unary call. */
            grpc_byte_buffer_destroy(payload_buffer);
            payload_buffer = NULL;
            grpc_call_destroy(call);
            if (!shutdown_started) request_call();
            break;
        }
        break;
      case GRPC_QUEUE_SHUTDOWN:
        GPR_ASSERT(shutdown_started);
        shutdown_finished = 1;
        break;
      case GRPC_QUEUE_TIMEOUT:
        break;
    }
  }
  grpc_profiler_stop();
  grpc_call_details_destroy(&call_details);

  grpc_server_destroy(server);
  grpc_completion_queue_destroy(cq);
  grpc_shutdown();
  return 0;
}
Esempio n. 27
0
int main(int argc, char **argv) {
  grpc_call_credentials *creds = NULL;
  char *json_key_file_path = NULL;
  char *json_refresh_token_file_path = NULL;
  char *token = NULL;
  int use_gce = 0;
  char *scope = NULL;
  gpr_cmdline *cl = gpr_cmdline_create("fetch_oauth2");
  gpr_cmdline_add_string(cl, "json_refresh_token",
                         "File path of the json refresh token.",
                         &json_refresh_token_file_path);
  gpr_cmdline_add_flag(
      cl, "gce",
      "Get a token from the GCE metadata server (only works in GCE).",
      &use_gce);
  gpr_cmdline_parse(cl, argc, argv);

  grpc_init();

  if (json_key_file_path != NULL && json_refresh_token_file_path != NULL) {
    gpr_log(GPR_ERROR,
            "--json_key and --json_refresh_token are mutually exclusive.");
    exit(1);
  }

  if (use_gce) {
    if (json_key_file_path != NULL || scope != NULL) {
      gpr_log(GPR_INFO,
              "Ignoring json key and scope to get a token from the GCE "
              "metadata server.");
    }
    creds = grpc_google_compute_engine_credentials_create(NULL);
    if (creds == NULL) {
      gpr_log(GPR_ERROR, "Could not create gce credentials.");
      exit(1);
    }
  } else if (json_refresh_token_file_path != NULL) {
    creds = create_refresh_token_creds(json_refresh_token_file_path);
    if (creds == NULL) {
      gpr_log(GPR_ERROR,
              "Could not create refresh token creds. %s does probably not "
              "contain a valid json refresh token.",
              json_refresh_token_file_path);
      exit(1);
    }
  } else {
    gpr_log(GPR_ERROR, "Missing --gce or --json_refresh_token option.");
    exit(1);
  }
  GPR_ASSERT(creds != NULL);

  token = grpc_test_fetch_oauth2_token_with_credentials(creds);
  if (token != NULL) {
    printf("Got token: %s.\n", token);
    gpr_free(token);
  }
  grpc_call_credentials_release(creds);
  gpr_cmdline_destroy(cl);
  grpc_shutdown();
  return 0;
}
Esempio n. 28
0
File: _c.c Progetto: Abioy/kythe
static PyObject *init(PyObject *self) {
  grpc_init();
  Py_RETURN_NONE;
}
Esempio n. 29
0
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  grpc_test_only_set_metadata_hash_seed(0);
  struct grpc_memory_counters counters;
  if (squelch) gpr_set_log_function(dont_log);
  grpc_memory_counters_init();
  grpc_init();
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

  grpc_endpoint *mock_endpoint = grpc_mock_endpoint_create(discard_write);

  grpc_completion_queue *cq = grpc_completion_queue_create(NULL);
  grpc_transport *transport =
      grpc_create_chttp2_transport(&exec_ctx, NULL, mock_endpoint, 1);
  grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL, 0);

  grpc_channel *channel = grpc_channel_create(
      &exec_ctx, "test-target", NULL, GRPC_CLIENT_DIRECT_CHANNEL, transport);
  grpc_call *call =
      grpc_channel_create_call(channel, NULL, 0, cq, "/foo", "localhost",
                               gpr_inf_future(GPR_CLOCK_REALTIME), NULL);

  grpc_metadata_array initial_metadata_recv;
  grpc_metadata_array_init(&initial_metadata_recv);
  grpc_byte_buffer *response_payload_recv = NULL;
  grpc_metadata_array trailing_metadata_recv;
  grpc_metadata_array_init(&trailing_metadata_recv);
  grpc_status_code status;
  char *details = NULL;
  size_t details_capacity = 0;

  grpc_op ops[6];
  memset(ops, 0, sizeof(ops));
  grpc_op *op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_INITIAL_METADATA;
  op->data.recv_initial_metadata = &initial_metadata_recv;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_MESSAGE;
  op->data.recv_message = &response_payload_recv;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
  op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
  op->data.recv_status_on_client.status = &status;
  op->data.recv_status_on_client.status_details = &details;
  op->data.recv_status_on_client.status_details_capacity = &details_capacity;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  grpc_call_error error =
      grpc_call_start_batch(call, ops, (size_t)(op - ops), tag(1), NULL);
  int requested_calls = 1;
  GPR_ASSERT(GRPC_CALL_OK == error);

  grpc_mock_endpoint_put_read(
      &exec_ctx, mock_endpoint,
      gpr_slice_from_copied_buffer((const char *)data, size));

  grpc_event ev;
  while (1) {
    grpc_exec_ctx_flush(&exec_ctx);
    ev = grpc_completion_queue_next(cq, gpr_inf_past(GPR_CLOCK_REALTIME), NULL);
    switch (ev.type) {
      case GRPC_QUEUE_TIMEOUT:
        goto done;
      case GRPC_QUEUE_SHUTDOWN:
        break;
      case GRPC_OP_COMPLETE:
        requested_calls--;
        break;
    }
  }

done:
  if (requested_calls) {
    grpc_call_cancel(call, NULL);
  }
  for (int i = 0; i < requested_calls; i++) {
    ev = grpc_completion_queue_next(cq, gpr_inf_past(GPR_CLOCK_REALTIME), NULL);
    GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
  }
  grpc_completion_queue_shutdown(cq);
  for (int i = 0; i < requested_calls; i++) {
    ev = grpc_completion_queue_next(cq, gpr_inf_past(GPR_CLOCK_REALTIME), NULL);
    GPR_ASSERT(ev.type == GRPC_QUEUE_SHUTDOWN);
  }
  grpc_call_destroy(call);
  grpc_completion_queue_destroy(cq);
  grpc_metadata_array_destroy(&initial_metadata_recv);
  grpc_metadata_array_destroy(&trailing_metadata_recv);
  gpr_free(details);
  grpc_channel_destroy(channel);
  if (response_payload_recv != NULL) {
    grpc_byte_buffer_destroy(response_payload_recv);
  }
  grpc_shutdown();
  counters = grpc_memory_counters_snapshot();
  grpc_memory_counters_destroy();
  GPR_ASSERT(counters.total_size_relative == 0);
  return 0;
}
Esempio n. 30
0
// Cython doesn't have Py_AtExit bindings, so we call the C_API directly
int pygrpc_initialize_core(void) {
  grpc_init();
  return Py_AtExit(grpc_shutdown) < 0 ? 0 : 1;
}