3 * Copyright 2015 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <grpcpp/impl/codegen/server_context.h>
24 #include <grpc/compression.h>
25 #include <grpc/grpc.h>
26 #include <grpc/load_reporting.h>
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/log.h>
29 #include <grpcpp/impl/call.h>
30 #include <grpcpp/impl/codegen/completion_queue.h>
31 #include <grpcpp/support/server_callback.h>
32 #include <grpcpp/support/time.h>
34 #include "src/core/lib/gprpp/ref_counted.h"
35 #include "src/core/lib/gprpp/sync.h"
36 #include "src/core/lib/surface/call.h"
42 class ServerContextBase::CompletionOp final
43 : public internal::CallOpSetInterface {
45 // initial refs: one in the server context, one in the cq
46 // must ref the call before calling constructor and after deleting this
47 CompletionOp(internal::Call* call,
48 ::grpc::internal::ServerCallbackCall* callback_controller)
50 callback_controller_(callback_controller),
57 done_intercepting_(false) {}
59 // CompletionOp isn't copyable or movable
60 CompletionOp(const CompletionOp&) = delete;
61 CompletionOp& operator=(const CompletionOp&) = delete;
62 CompletionOp(CompletionOp&&) = delete;
63 CompletionOp& operator=(CompletionOp&&) = delete;
65 ~CompletionOp() override {
66 if (call_.server_rpc_info()) {
67 call_.server_rpc_info()->Unref();
71 void FillOps(internal::Call* call) override;
73 // This should always be arena allocated in the call, so override delete.
74 // But this class is not trivially destructible, so must actually call delete
75 // before allowing the arena to be freed
76 static void operator delete(void* /*ptr*/, std::size_t size) {
77 // Use size to avoid unused-parameter warning since assert seems to be
78 // compiled out and treated as unused in some gcc optimized versions.
80 assert(size == sizeof(CompletionOp));
83 // This operator should never be called as the memory should be freed as part
84 // of the arena destruction. It only exists to provide a matching operator
85 // delete to the operator new so that some compilers will not complain (see
86 // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
87 // there are no tests catching the compiler warning.
88 static void operator delete(void*, void*) { assert(0); }
90 bool FinalizeResult(void** tag, bool* status) override;
92 bool CheckCancelled(CompletionQueue* cq) {
94 return CheckCancelledNoPluck();
96 bool CheckCancelledAsync() { return CheckCancelledNoPluck(); }
98 void set_tag(void* tag) {
103 void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; }
105 void* core_cq_tag() override { return core_cq_tag_; }
109 // This will be called while interceptors are run if the RPC is a hijacked
110 // RPC. This should set hijacking state for each of the ops.
111 void SetHijackingState() override {
112 /* Servers don't allow hijacking */
116 /* Should be called after interceptors are done running */
117 void ContinueFillOpsAfterInterception() override {}
119 /* Should be called after interceptors are done running on the finalize result
121 void ContinueFinalizeResultAfterInterception() override {
122 done_intercepting_ = true;
124 /* We don't have a tag to return. */
128 /* Start a dummy op so that we can return the tag */
129 GPR_ASSERT(grpc_call_start_batch(call_.call(), nullptr, 0, core_cq_tag_,
130 nullptr) == GRPC_CALL_OK);
134 bool CheckCancelledNoPluck() {
135 grpc_core::MutexLock lock(&mu_);
136 return finalized_ ? (cancelled_ != 0) : false;
139 internal::Call call_;
140 ::grpc::internal::ServerCallbackCall* const callback_controller_;
144 grpc_core::RefCount refs_;
145 grpc_core::Mutex mu_;
147 int cancelled_; // This is an int (not bool) because it is passed to core
148 bool done_intercepting_;
149 internal::InterceptorBatchMethodsImpl interceptor_methods_;
152 void ServerContextBase::CompletionOp::Unref() {
154 grpc_call* call = call_.call();
156 grpc_call_unref(call);
160 void ServerContextBase::CompletionOp::FillOps(internal::Call* call) {
162 ops.op = GRPC_OP_RECV_CLOSE_ON_SERVER;
163 ops.data.recv_close_on_server.cancelled = &cancelled_;
165 ops.reserved = nullptr;
166 interceptor_methods_.SetCall(&call_);
167 interceptor_methods_.SetReverse();
168 interceptor_methods_.SetCallOpSetInterface(this);
169 // The following call_start_batch is internally-generated so no need for an
170 // explanatory log on failure.
171 GPR_ASSERT(grpc_call_start_batch(call->call(), &ops, 1, core_cq_tag_,
172 nullptr) == GRPC_CALL_OK);
173 /* No interceptors to run here */
176 bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) {
177 // Decide whether to call the cancel callback within the lock
181 grpc_core::MutexLock lock(&mu_);
182 if (done_intercepting_) {
183 // We are done intercepting.
184 bool has_tag = has_tag_;
193 // If for some reason the incoming status is false, mark that as a
195 // TODO(vjpai): does this ever happen?
200 call_cancel = (cancelled_ != 0);
201 // Release the lock since we may call a callback and interceptors.
204 if (call_cancel && callback_controller_ != nullptr) {
205 callback_controller_->MaybeCallOnCancel();
207 /* Add interception point and run through interceptors */
208 interceptor_methods_.AddInterceptionHookPoint(
209 experimental::InterceptionHookPoints::POST_RECV_CLOSE);
210 if (interceptor_methods_.RunInterceptors()) {
211 // No interceptors were run
212 bool has_tag = has_tag_;
219 // There are interceptors to be run. Return false for now.
223 // ServerContextBase body
225 ServerContextBase::ServerContextBase()
226 : deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)) {}
228 ServerContextBase::ServerContextBase(gpr_timespec deadline,
229 grpc_metadata_array* arr)
230 : deadline_(deadline) {
231 std::swap(*client_metadata_.arr(), *arr);
234 void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline,
235 grpc_metadata_array* arr) {
236 deadline_ = deadline;
237 std::swap(*client_metadata_.arr(), *arr);
240 ServerContextBase::~ServerContextBase() {
241 if (completion_op_) {
242 completion_op_->Unref();
247 if (default_reactor_used_.load(std::memory_order_relaxed)) {
248 reinterpret_cast<Reactor*>(&default_reactor_)->~Reactor();
252 ServerContextBase::CallWrapper::~CallWrapper() {
254 // If the ServerContext is part of the call's arena, this could free the
256 grpc_call_unref(call);
260 void ServerContextBase::BeginCompletionOp(
261 internal::Call* call, std::function<void(bool)> callback,
262 ::grpc::internal::ServerCallbackCall* callback_controller) {
263 GPR_ASSERT(!completion_op_);
267 grpc_call_ref(call->call());
269 new (grpc_call_arena_alloc(call->call(), sizeof(CompletionOp)))
270 CompletionOp(call, callback_controller);
271 if (callback_controller != nullptr) {
272 completion_tag_.Set(call->call(), std::move(callback), completion_op_,
274 completion_op_->set_core_cq_tag(&completion_tag_);
275 completion_op_->set_tag(completion_op_);
276 } else if (has_notify_when_done_tag_) {
277 completion_op_->set_tag(async_notify_when_done_tag_);
279 call->PerformOps(completion_op_);
282 internal::CompletionQueueTag* ServerContextBase::GetCompletionOpTag() {
283 return static_cast<internal::CompletionQueueTag*>(completion_op_);
286 void ServerContextBase::AddInitialMetadata(const std::string& key,
287 const std::string& value) {
288 initial_metadata_.insert(std::make_pair(key, value));
291 void ServerContextBase::AddTrailingMetadata(const std::string& key,
292 const std::string& value) {
293 trailing_metadata_.insert(std::make_pair(key, value));
296 void ServerContextBase::TryCancel() const {
297 internal::CancelInterceptorBatchMethods cancel_methods;
299 for (size_t i = 0; i < rpc_info_->interceptors_.size(); i++) {
300 rpc_info_->RunInterceptor(&cancel_methods, i);
303 grpc_call_error err =
304 grpc_call_cancel_with_status(call_.call, GRPC_STATUS_CANCELLED,
305 "Cancelled on the server side", nullptr);
306 if (err != GRPC_CALL_OK) {
307 gpr_log(GPR_ERROR, "TryCancel failed with: %d", err);
311 bool ServerContextBase::IsCancelled() const {
312 if (completion_tag_) {
313 // When using callback API, this result is always valid.
314 return completion_op_->CheckCancelledAsync();
315 } else if (has_notify_when_done_tag_) {
316 // When using async API, the result is only valid
317 // if the tag has already been delivered at the completion queue
318 return completion_op_ && completion_op_->CheckCancelledAsync();
320 // when using sync API, the result is always valid
321 return completion_op_ && completion_op_->CheckCancelled(cq_);
325 void ServerContextBase::set_compression_algorithm(
326 grpc_compression_algorithm algorithm) {
327 compression_algorithm_ = algorithm;
328 const char* algorithm_name = nullptr;
329 if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) {
330 gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.",
334 GPR_ASSERT(algorithm_name != nullptr);
335 AddInitialMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name);
338 std::string ServerContextBase::peer() const {
341 char* c_peer = grpc_call_get_peer(call_.call);
348 const struct census_context* ServerContextBase::census_context() const {
349 return call_.call == nullptr ? nullptr
350 : grpc_census_call_get_context(call_.call);
353 void ServerContextBase::SetLoadReportingCosts(
354 const std::vector<std::string>& cost_data) {
355 if (call_.call == nullptr) return;
356 for (const auto& cost_datum : cost_data) {
357 AddTrailingMetadata(GRPC_LB_COST_MD_KEY, cost_datum);