1 /*
2  *
3  * Copyright 2015 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 "src/core/lib/surface/channel.h"
22 
23 #include <string.h>
24 
25 #include <grpc/support/alloc.h>
26 #include <grpc/support/log.h>
27 
28 #include "src/core/lib/surface/api_trace.h"
29 #include "src/core/lib/surface/completion_queue.h"
30 
31 struct ping_result {
32   grpc_closure closure;
33   void* tag;
34   grpc_completion_queue* cq;
35   grpc_cq_completion completion_storage;
36 };
ping_destroy(void * arg,grpc_cq_completion *)37 static void ping_destroy(void* arg, grpc_cq_completion* /*storage*/) {
38   gpr_free(arg);
39 }
40 
ping_done(void * arg,grpc_error * error)41 static void ping_done(void* arg, grpc_error* error) {
42   ping_result* pr = static_cast<ping_result*>(arg);
43   grpc_cq_end_op(pr->cq, pr->tag, GRPC_ERROR_REF(error), ping_destroy, pr,
44                  &pr->completion_storage);
45 }
46 
grpc_channel_ping(grpc_channel * channel,grpc_completion_queue * cq,void * tag,void * reserved)47 void grpc_channel_ping(grpc_channel* channel, grpc_completion_queue* cq,
48                        void* tag, void* reserved) {
49   GRPC_API_TRACE("grpc_channel_ping(channel=%p, cq=%p, tag=%p, reserved=%p)", 4,
50                  (channel, cq, tag, reserved));
51   grpc_transport_op* op = grpc_make_transport_op(nullptr);
52   ping_result* pr = static_cast<ping_result*>(gpr_malloc(sizeof(*pr)));
53   grpc_channel_element* top_elem =
54       grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0);
55   grpc_core::ExecCtx exec_ctx;
56   GPR_ASSERT(reserved == nullptr);
57   pr->tag = tag;
58   pr->cq = cq;
59   GRPC_CLOSURE_INIT(&pr->closure, ping_done, pr, grpc_schedule_on_exec_ctx);
60   op->send_ping.on_ack = &pr->closure;
61   op->bind_pollset = grpc_cq_pollset(cq);
62   GPR_ASSERT(grpc_cq_begin_op(cq, tag));
63   top_elem->filter->start_transport_op(top_elem, op);
64 }
65