Debian Codegraph @

src/core/lib/surface/server.h

raw
1 //
2 // Copyright 2015 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #ifndef GRPC_CORE_LIB_SURFACE_SERVER_H
18 #define GRPC_CORE_LIB_SURFACE_SERVER_H
19
20 #include <grpc/support/port_platform.h>
21
22 #include <stddef.h>
23 #include <stdint.h>
24
25 #include <atomic>
26 #include <functional>
27 #include <list>
28 #include <memory>
29 #include <string>
30 #include <utility>
31 #include <vector>
32
33 #include "absl/base/thread_annotations.h"
34 #include "absl/status/statusor.h"
35 #include "absl/types/optional.h"
36
37 #include <grpc/grpc.h>
38 #include <grpc/impl/codegen/gpr_types.h>
39 #include <grpc/impl/codegen/grpc_types.h>
40 #include <grpc/slice.h>
41 #include <grpc/support/log.h>
42
43 #include "src/core/lib/channel/channel_args.h"
44 #include "src/core/lib/channel/channel_fwd.h"
45 #include "src/core/lib/channel/channel_stack.h"
46 #include "src/core/lib/channel/channelz.h"
47 #include "src/core/lib/debug/trace.h"
48 #include "src/core/lib/gprpp/cpp_impl_of.h"
49 #include "src/core/lib/gprpp/dual_ref_counted.h"
50 #include "src/core/lib/gprpp/notification.h"
51 #include "src/core/lib/gprpp/orphanable.h"
52 #include "src/core/lib/gprpp/ref_counted_ptr.h"
53 #include "src/core/lib/gprpp/sync.h"
54 #include "src/core/lib/gprpp/time.h"
55 #include "src/core/lib/iomgr/call_combiner.h"
56 #include "src/core/lib/iomgr/closure.h"
57 #include "src/core/lib/iomgr/endpoint.h"
58 #include "src/core/lib/iomgr/error.h"
59 #include "src/core/lib/iomgr/iomgr_fwd.h"
60 #include "src/core/lib/slice/slice.h"
61 #include "src/core/lib/surface/channel.h"
62 #include "src/core/lib/surface/completion_queue.h"
63 #include "src/core/lib/transport/metadata_batch.h"
64 #include "src/core/lib/transport/transport.h"
65 #include "src/core/lib/transport/transport_fwd.h"
66
67 struct grpc_server_config_fetcher;
68
69 namespace grpc_core {
70
71 extern TraceFlag grpc_server_channel_trace;
72
73 class Server : public InternallyRefCounted<Server>,
74 public CppImplOf<Server, grpc_server> {
75 public:
76 // Filter vtable.
77 static const grpc_channel_filter kServerTopFilter;
78
79 // Opaque type used for registered methods.
80 struct RegisteredMethod;
81
82 // An object to represent the most relevant characteristics of a
83 // newly-allocated call object when using an AllocatingRequestMatcherBatch.
84 struct BatchCallAllocation {
85 void* tag;
86 grpc_call** call;
87 grpc_metadata_array* initial_metadata;
88 grpc_call_details* details;
89 grpc_completion_queue* cq;
90 };
91
92 // An object to represent the most relevant characteristics of a
93 // newly-allocated call object when using an
94 // AllocatingRequestMatcherRegistered.
95 struct RegisteredCallAllocation {
96 void* tag;
97 grpc_call** call;
98 grpc_metadata_array* initial_metadata;
99 gpr_timespec* deadline;
100 grpc_byte_buffer** optional_payload;
101 grpc_completion_queue* cq;
102 };
103
104 /// Interface for listeners.
105 /// Implementations must override the Orphan() method, which should stop
106 /// listening and initiate destruction of the listener.
107 class ListenerInterface : public Orphanable {
108 public:
109 ~ListenerInterface() override = default;
110
111 /// Starts listening. This listener may refer to the pollset object beyond
112 /// this call, so it is a pointer rather than a reference.
113 virtual void Start(Server* server,
114 const std::vector<grpc_pollset*>* pollsets) = 0;
115
116 /// Returns the channelz node for the listen socket, or null if not
117 /// supported.
118 virtual channelz::ListenSocketNode* channelz_listen_socket_node() const = 0;
119
120 /// Sets a closure to be invoked by the listener when its destruction
121 /// is complete.
122 virtual void SetOnDestroyDone(grpc_closure* on_destroy_done) = 0;
123 };
124
125 explicit Server(const ChannelArgs& args);
126 ~Server() override;
127
128 void Orphan() ABSL_LOCKS_EXCLUDED(mu_global_) override;
129
130 const ChannelArgs& channel_args() const { return channel_args_; }
131 channelz::ServerNode* channelz_node() const { return channelz_node_.get(); }
132
133 // Do not call this before Start(). Returns the pollsets. The
134 // vector itself is immutable, but the pollsets inside are mutable. The
135 // result is valid for the lifetime of the server.
136 const std::vector<grpc_pollset*>& pollsets() const { return pollsets_; }
137
138 grpc_server_config_fetcher* config_fetcher() const {
139 return config_fetcher_.get();
140 }
141
142 void set_config_fetcher(
143 std::unique_ptr<grpc_server_config_fetcher> config_fetcher) {
144 config_fetcher_ = std::move(config_fetcher);
145 }
146
147 bool HasOpenConnections() ABSL_LOCKS_EXCLUDED(mu_global_);
148
149 // Adds a listener to the server. When the server starts, it will call
150 // the listener's Start() method, and when it shuts down, it will orphan
151 // the listener.
152 void AddListener(OrphanablePtr<ListenerInterface> listener);
153
154 // Starts listening for connections.
155 void Start() ABSL_LOCKS_EXCLUDED(mu_global_);
156
157 // Sets up a transport. Creates a channel stack and binds the transport to
158 // the server. Called from the listener when a new connection is accepted.
159 // Takes ownership of a ref on resource_user from the caller.
160 grpc_error_handle SetupTransport(
161 grpc_transport* transport, grpc_pollset* accepting_pollset,
162 const ChannelArgs& args,
163 const RefCountedPtr<channelz::SocketNode>& socket_node);
164
165 void RegisterCompletionQueue(grpc_completion_queue* cq);
166
167 // Functions to specify that a specific registered method or the unregistered
168 // collection should use a specific allocator for request matching.
169 void SetRegisteredMethodAllocator(
170 grpc_completion_queue* cq, void* method_tag,
171 std::function<RegisteredCallAllocation()> allocator);
172 void SetBatchMethodAllocator(grpc_completion_queue* cq,
173 std::function<BatchCallAllocation()> allocator);
174
175 RegisteredMethod* RegisterMethod(
176 const char* method, const char* host,
177 grpc_server_register_method_payload_handling payload_handling,
178 uint32_t flags);
179
180 grpc_call_error RequestCall(grpc_call** call, grpc_call_details* details,
181 grpc_metadata_array* request_metadata,
182 grpc_completion_queue* cq_bound_to_call,
183 grpc_completion_queue* cq_for_notification,
184 void* tag);
185
186 grpc_call_error RequestRegisteredCall(
187 RegisteredMethod* rm, grpc_call** call, gpr_timespec* deadline,
188 grpc_metadata_array* request_metadata,
189 grpc_byte_buffer** optional_payload,
190 grpc_completion_queue* cq_bound_to_call,
191 grpc_completion_queue* cq_for_notification, void* tag_new);
192
193 void ShutdownAndNotify(grpc_completion_queue* cq, void* tag)
194 ABSL_LOCKS_EXCLUDED(mu_global_, mu_call_);
195
196 void StopListening();
197
198 void CancelAllCalls() ABSL_LOCKS_EXCLUDED(mu_global_);
199
200 void SendGoaways() ABSL_LOCKS_EXCLUDED(mu_global_, mu_call_);
201
202 private:
203 struct RequestedCall;
204
205 struct ChannelRegisteredMethod {
206 RegisteredMethod* server_registered_method = nullptr;
207 uint32_t flags;
208 bool has_host;
209 Slice method;
210 Slice host;
211 };
212
213 class RequestMatcherInterface;
214 class RealRequestMatcher;
215 class AllocatingRequestMatcherBase;
216 class AllocatingRequestMatcherBatch;
217 class AllocatingRequestMatcherRegistered;
218
219 class ChannelData {
220 public:
221 ChannelData() = default;
222 ~ChannelData();
223
224 void InitTransport(RefCountedPtr<Server> server,
225 RefCountedPtr<Channel> channel, size_t cq_idx,
226 grpc_transport* transport,
227 intptr_t channelz_socket_uuid);
228
229 RefCountedPtr<Server> server() const { return server_; }
230 Channel* channel() const { return channel_.get(); }
231 size_t cq_idx() const { return cq_idx_; }
232
233 ChannelRegisteredMethod* GetRegisteredMethod(const grpc_slice& host,
234 const grpc_slice& path);
235
236 // Filter vtable functions.
237 static grpc_error_handle InitChannelElement(
238 grpc_channel_element* elem, grpc_channel_element_args* args);
239 static void DestroyChannelElement(grpc_channel_element* elem);
240
241 private:
242 class ConnectivityWatcher;
243
244 static void AcceptStream(void* arg, grpc_transport* /*transport*/,
245 const void* transport_server_data);
246
247 void Destroy() ABSL_EXCLUSIVE_LOCKS_REQUIRED(server_->mu_global_);
248
249 static void FinishDestroy(void* arg, grpc_error_handle error);
250
251 RefCountedPtr<Server> server_;
252 RefCountedPtr<Channel> channel_;
253 // The index into Server::cqs_ of the CQ used as a starting point for
254 // where to publish new incoming calls.
255 size_t cq_idx_;
256 absl::optional<std::list<ChannelData*>::iterator> list_position_;
257 // A hash-table of the methods and hosts of the registered methods.
258 // TODO(vjpai): Convert this to an STL map type as opposed to a direct
259 // bucket implementation. (Consider performance impact, hash function to
260 // use, etc.)
261 std::unique_ptr<std::vector<ChannelRegisteredMethod>> registered_methods_;
262 uint32_t registered_method_max_probes_;
263 grpc_closure finish_destroy_channel_closure_;
264 intptr_t channelz_socket_uuid_;
265 };
266
267 class CallData {
268 public:
269 enum class CallState {
270 NOT_STARTED, // Waiting for metadata.
271 PENDING, // Initial metadata read, not flow controlled in yet.
272 ACTIVATED, // Flow controlled in, on completion queue.
273 ZOMBIED, // Cancelled before being queued.
274 };
275
276 CallData(grpc_call_element* elem, const grpc_call_element_args& args,
277 RefCountedPtr<Server> server);
278 ~CallData();
279
280 // Starts the recv_initial_metadata batch on the call.
281 // Invoked from ChannelData::AcceptStream().
282 void Start(grpc_call_element* elem);
283
284 void SetState(CallState state);
285
286 // Attempts to move from PENDING to ACTIVATED state. Returns true
287 // on success.
288 bool MaybeActivate();
289
290 // Publishes an incoming call to the application after it has been
291 // matched.
292 void Publish(size_t cq_idx, RequestedCall* rc);
293
294 void KillZombie();
295
296 void FailCallCreation();
297
298 // Filter vtable functions.
299 static grpc_error_handle InitCallElement(
300 grpc_call_element* elem, const grpc_call_element_args* args);
301 static void DestroyCallElement(grpc_call_element* elem,
302 const grpc_call_final_info* /*final_info*/,
303 grpc_closure* /*ignored*/);
304 static void StartTransportStreamOpBatch(
305 grpc_call_element* elem, grpc_transport_stream_op_batch* batch);
306
307 private:
308 // Helper functions for handling calls at the top of the call stack.
309 static void RecvInitialMetadataBatchComplete(void* arg,
310 grpc_error_handle error);
311 void StartNewRpc(grpc_call_element* elem);
312 static void PublishNewRpc(void* arg, grpc_error_handle error);
313
314 // Functions used inside the call stack.
315 void StartTransportStreamOpBatchImpl(grpc_call_element* elem,
316 grpc_transport_stream_op_batch* batch);
317 static void RecvInitialMetadataReady(void* arg, grpc_error_handle error);
318 static void RecvTrailingMetadataReady(void* arg, grpc_error_handle error);
319
320 RefCountedPtr<Server> server_;
321
322 grpc_call* call_;
323
324 std::atomic<CallState> state_{CallState::NOT_STARTED};
325
326 absl::optional<Slice> path_;
327 absl::optional<Slice> host_;
328 Timestamp deadline_ = Timestamp::InfFuture();
329
330 grpc_completion_queue* cq_new_ = nullptr;
331
332 RequestMatcherInterface* matcher_ = nullptr;
333 grpc_byte_buffer* payload_ = nullptr;
334
335 grpc_closure kill_zombie_closure_;
336
337 grpc_metadata_array initial_metadata_ =
338 grpc_metadata_array(); // Zero-initialize the C struct.
339 grpc_closure recv_initial_metadata_batch_complete_;
340
341 grpc_metadata_batch* recv_initial_metadata_ = nullptr;
342 grpc_closure recv_initial_metadata_ready_;
343 grpc_closure* original_recv_initial_metadata_ready_;
344 grpc_error_handle recv_initial_metadata_error_;
345
346 bool seen_recv_trailing_metadata_ready_ = false;
347 grpc_closure recv_trailing_metadata_ready_;
348 grpc_closure* original_recv_trailing_metadata_ready_;
349 grpc_error_handle recv_trailing_metadata_error_;
350
351 grpc_closure publish_;
352
353 CallCombiner* call_combiner_;
354 };
355
356 struct Listener {
357 explicit Listener(OrphanablePtr<ListenerInterface> l)
358 : listener(std::move(l)) {}
359 OrphanablePtr<ListenerInterface> listener;
360 grpc_closure destroy_done;
361 };
362
363 struct ShutdownTag {
364 ShutdownTag(void* tag_arg, grpc_completion_queue* cq_arg)
365 : tag(tag_arg), cq(cq_arg) {}
366 void* const tag;
367 grpc_completion_queue* const cq;
368 grpc_cq_completion completion;
369 };
370
371 static void ListenerDestroyDone(void* arg, grpc_error_handle error);
372
373 static void DoneShutdownEvent(void* server,
374 grpc_cq_completion* /*completion*/) {
375 static_cast<Server*>(server)->Unref();
376 }
377
378 static void DoneRequestEvent(void* req, grpc_cq_completion* completion);
379
380 void FailCall(size_t cq_idx, RequestedCall* rc, grpc_error_handle error);
381 grpc_call_error QueueRequestedCall(size_t cq_idx, RequestedCall* rc);
382
383 void MaybeFinishShutdown() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_global_)
384 ABSL_LOCKS_EXCLUDED(mu_call_);
385
386 void KillPendingWorkLocked(grpc_error_handle error)
387 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_call_);
388
389 static grpc_call_error ValidateServerRequest(
390 grpc_completion_queue* cq_for_notification, void* tag,
391 grpc_byte_buffer** optional_payload, RegisteredMethod* rm);
392 grpc_call_error ValidateServerRequestAndCq(
393 size_t* cq_idx, grpc_completion_queue* cq_for_notification, void* tag,
394 grpc_byte_buffer** optional_payload, RegisteredMethod* rm);
395
396 std::vector<RefCountedPtr<Channel>> GetChannelsLocked() const;
397
398 // Take a shutdown ref for a request (increment by 2) and return if shutdown
399 // has not been called.
400 bool ShutdownRefOnRequest() {
401 int old_value = shutdown_refs_.fetch_add(2, std::memory_order_acq_rel);
402 return (old_value & 1) != 0;
403 }
404
405 // Decrement the shutdown ref counter by either 1 (for shutdown call) or 2
406 // (for in-flight request) and possibly call MaybeFinishShutdown if
407 // appropriate.
408 void ShutdownUnrefOnRequest() ABSL_LOCKS_EXCLUDED(mu_global_) {
409 if (shutdown_refs_.fetch_sub(2, std::memory_order_acq_rel) == 2) {
410 MutexLock lock(&mu_global_);
411 MaybeFinishShutdown();
412 // The last request in-flight during shutdown is now complete.
413 if (requests_complete_ != nullptr) {
414 GPR_ASSERT(!requests_complete_->HasBeenNotified());
415 requests_complete_->Notify();
416 }
417 }
418 }
419 // Returns a notification pointer to wait on if there are requests in-flight,
420 // or null.
421 Notification* ShutdownUnrefOnShutdownCall()
422 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_global_) GRPC_MUST_USE_RESULT {
423 if (shutdown_refs_.fetch_sub(1, std::memory_order_acq_rel) == 1) {
424 // There is no request in-flight.
425 MaybeFinishShutdown();
426 return nullptr;
427 }
428 requests_complete_ = std::make_unique<Notification>();
429 return requests_complete_.get();
430 }
431
432 bool ShutdownCalled() const {
433 return (shutdown_refs_.load(std::memory_order_acquire) & 1) == 0;
434 }
435
436 // Returns whether there are no more shutdown refs, which means that shutdown
437 // has been called and all accepted requests have been published if using an
438 // AllocatingRequestMatcher.
439 bool ShutdownReady() const {
440 return shutdown_refs_.load(std::memory_order_acquire) == 0;
441 }
442
443 ChannelArgs const channel_args_;
444 RefCountedPtr<channelz::ServerNode> channelz_node_;
445 std::unique_ptr<grpc_server_config_fetcher> config_fetcher_;
446
447 std::vector<grpc_completion_queue*> cqs_;
448 std::vector<grpc_pollset*> pollsets_;
449 bool started_ = false;
450
451 // The two following mutexes control access to server-state.
452 // mu_global_ controls access to non-call-related state (e.g., channel state).
453 // mu_call_ controls access to call-related state (e.g., the call lists).
454 //
455 // If they are ever required to be nested, you must lock mu_global_
456 // before mu_call_. This is currently used in shutdown processing
457 // (ShutdownAndNotify() and MaybeFinishShutdown()).
458 Mutex mu_global_; // mutex for server and channel state
459 Mutex mu_call_; // mutex for call-specific state
460
461 // startup synchronization: flag, signals whether we are doing the listener
462 // start routine or not.
463 bool starting_ ABSL_GUARDED_BY(mu_global_) = false;
464 CondVar starting_cv_;
465
466 std::vector<std::unique_ptr<RegisteredMethod>> registered_methods_;
467
468 // Request matcher for unregistered methods.
469 std::unique_ptr<RequestMatcherInterface> unregistered_request_matcher_;
470
471 // The shutdown refs counter tracks whether or not shutdown has been called
472 // and whether there are any AllocatingRequestMatcher requests that have been
473 // accepted but not yet started (+2 on each one). If shutdown has been called,
474 // the lowest bit will be 0 (defaults to 1) and the counter will be even. The
475 // server should not notify on shutdown until the counter is 0 (shutdown is
476 // called and there are no requests that are accepted but not started).
477 std::atomic<int> shutdown_refs_{1};
478 bool shutdown_published_ ABSL_GUARDED_BY(mu_global_) = false;
479 std::vector<ShutdownTag> shutdown_tags_ ABSL_GUARDED_BY(mu_global_);
480 std::unique_ptr<Notification> requests_complete_ ABSL_GUARDED_BY(mu_global_);
481
482 std::list<ChannelData*> channels_;
483
484 std::list<Listener> listeners_;
485 size_t listeners_destroyed_ = 0;
486
487 // The last time we printed a shutdown progress message.
488 gpr_timespec last_shutdown_message_time_;
489 };
490
491 } // namespace grpc_core
492
493 struct grpc_server_config_fetcher {
494 public:
495 class ConnectionManager
496 : public grpc_core::DualRefCounted<ConnectionManager> {
497 public:
498 // Ownership of \a args is transfered.
499 virtual absl::StatusOr<grpc_core::ChannelArgs>
500 UpdateChannelArgsForConnection(const grpc_core::ChannelArgs& args,
501 grpc_endpoint* tcp) = 0;
502 };
503
504 class WatcherInterface {
505 public:
506 virtual ~WatcherInterface() = default;
507 // UpdateConnectionManager() is invoked by the config fetcher when a new
508 // config is available. Implementations should update the connection manager
509 // and start serving if not already serving.
510 virtual void UpdateConnectionManager(
511 grpc_core::RefCountedPtr<ConnectionManager> manager) = 0;
512 // Implementations should stop serving when this is called. Serving should
513 // only resume when UpdateConfig() is invoked.
514 virtual void StopServing() = 0;
515 };
516
517 virtual ~grpc_server_config_fetcher() = default;
518
519 virtual void StartWatch(std::string listening_address,
520 std::unique_ptr<WatcherInterface> watcher) = 0;
521 virtual void CancelWatch(WatcherInterface* watcher) = 0;
522 virtual grpc_pollset_set* interested_parties() = 0;
523 };
524
525 #endif /* GRPC_CORE_LIB_SURFACE_SERVER_H */