Debian Codegraph @

src/python/grpcio/grpc/_server.py

raw
1 # Copyright 2016 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Service-side implementation of gRPC Python."""
15
16 import collections
17 from concurrent import futures
18 import enum
19 import logging
20 import threading
21 import time
22
23 import grpc
24 from grpc import _common
25 from grpc import _compression
26 from grpc import _interceptor
27 from grpc._cython import cygrpc
28
29 _LOGGER = logging.getLogger(__name__)
30
31 _SHUTDOWN_TAG = 'shutdown'
32 _REQUEST_CALL_TAG = 'request_call'
33
34 _RECEIVE_CLOSE_ON_SERVER_TOKEN = 'receive_close_on_server'
35 _SEND_INITIAL_METADATA_TOKEN = 'send_initial_metadata'
36 _RECEIVE_MESSAGE_TOKEN = 'receive_message'
37 _SEND_MESSAGE_TOKEN = 'send_message'
38 _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN = (
39 'send_initial_metadata * send_message')
40 _SEND_STATUS_FROM_SERVER_TOKEN = 'send_status_from_server'
41 _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN = (
42 'send_initial_metadata * send_status_from_server')
43
44 _OPEN = 'open'
45 _CLOSED = 'closed'
46 _CANCELLED = 'cancelled'
47
48 _EMPTY_FLAGS = 0
49
50 _DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0
51 _INF_TIMEOUT = 1e9
52
53
54 def _serialized_request(request_event):
55 return request_event.batch_operations[0].message()
56
57
58 def _application_code(code):
59 cygrpc_code = _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE.get(code)
60 return cygrpc.StatusCode.unknown if cygrpc_code is None else cygrpc_code
61
62
63 def _completion_code(state):
64 if state.code is None:
65 return cygrpc.StatusCode.ok
66 else:
67 return _application_code(state.code)
68
69
70 def _abortion_code(state, code):
71 if state.code is None:
72 return code
73 else:
74 return _application_code(state.code)
75
76
77 def _details(state):
78 return b'' if state.details is None else state.details
79
80
81 class _HandlerCallDetails(
82 collections.namedtuple('_HandlerCallDetails', (
83 'method',
84 'invocation_metadata',
85 )), grpc.HandlerCallDetails):
86 pass
87
88
89 class _RPCState(object):
90
91 def __init__(self):
92 self.condition = threading.Condition()
93 self.due = set()
94 self.request = None
95 self.client = _OPEN
96 self.initial_metadata_allowed = True
97 self.compression_algorithm = None
98 self.disable_next_compression = False
99 self.trailing_metadata = None
100 self.code = None
101 self.details = None
102 self.statused = False
103 self.rpc_errors = []
104 self.callbacks = []
105 self.aborted = False
106
107
108 def _raise_rpc_error(state):
109 rpc_error = grpc.RpcError()
110 state.rpc_errors.append(rpc_error)
111 raise rpc_error
112
113
114 def _possibly_finish_call(state, token):
115 state.due.remove(token)
116 if not _is_rpc_state_active(state) and not state.due:
117 callbacks = state.callbacks
118 state.callbacks = None
119 return state, callbacks
120 else:
121 return None, ()
122
123
124 def _send_status_from_server(state, token):
125
126 def send_status_from_server(unused_send_status_from_server_event):
127 with state.condition:
128 return _possibly_finish_call(state, token)
129
130 return send_status_from_server
131
132
133 def _get_initial_metadata(state, metadata):
134 with state.condition:
135 if state.compression_algorithm:
136 compression_metadata = (
137 _compression.compression_algorithm_to_metadata(
138 state.compression_algorithm),)
139 if metadata is None:
140 return compression_metadata
141 else:
142 return compression_metadata + tuple(metadata)
143 else:
144 return metadata
145
146
147 def _get_initial_metadata_operation(state, metadata):
148 operation = cygrpc.SendInitialMetadataOperation(
149 _get_initial_metadata(state, metadata), _EMPTY_FLAGS)
150 return operation
151
152
153 def _abort(state, call, code, details):
154 if state.client is not _CANCELLED:
155 effective_code = _abortion_code(state, code)
156 effective_details = details if state.details is None else state.details
157 if state.initial_metadata_allowed:
158 operations = (
159 _get_initial_metadata_operation(state, None),
160 cygrpc.SendStatusFromServerOperation(state.trailing_metadata,
161 effective_code,
162 effective_details,
163 _EMPTY_FLAGS),
164 )
165 token = _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN
166 else:
167 operations = (cygrpc.SendStatusFromServerOperation(
168 state.trailing_metadata, effective_code, effective_details,
169 _EMPTY_FLAGS),)
170 token = _SEND_STATUS_FROM_SERVER_TOKEN
171 call.start_server_batch(operations,
172 _send_status_from_server(state, token))
173 state.statused = True
174 state.due.add(token)
175
176
177 def _receive_close_on_server(state):
178
179 def receive_close_on_server(receive_close_on_server_event):
180 with state.condition:
181 if receive_close_on_server_event.batch_operations[0].cancelled():
182 state.client = _CANCELLED
183 elif state.client is _OPEN:
184 state.client = _CLOSED
185 state.condition.notify_all()
186 return _possibly_finish_call(state, _RECEIVE_CLOSE_ON_SERVER_TOKEN)
187
188 return receive_close_on_server
189
190
191 def _receive_message(state, call, request_deserializer):
192
193 def receive_message(receive_message_event):
194 serialized_request = _serialized_request(receive_message_event)
195 if serialized_request is None:
196 with state.condition:
197 if state.client is _OPEN:
198 state.client = _CLOSED
199 state.condition.notify_all()
200 return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
201 else:
202 request = _common.deserialize(serialized_request,
203 request_deserializer)
204 with state.condition:
205 if request is None:
206 _abort(state, call, cygrpc.StatusCode.internal,
207 b'Exception deserializing request!')
208 else:
209 state.request = request
210 state.condition.notify_all()
211 return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
212
213 return receive_message
214
215
216 def _send_initial_metadata(state):
217
218 def send_initial_metadata(unused_send_initial_metadata_event):
219 with state.condition:
220 return _possibly_finish_call(state, _SEND_INITIAL_METADATA_TOKEN)
221
222 return send_initial_metadata
223
224
225 def _send_message(state, token):
226
227 def send_message(unused_send_message_event):
228 with state.condition:
229 state.condition.notify_all()
230 return _possibly_finish_call(state, token)
231
232 return send_message
233
234
235 class _Context(grpc.ServicerContext):
236
237 def __init__(self, rpc_event, state, request_deserializer):
238 self._rpc_event = rpc_event
239 self._state = state
240 self._request_deserializer = request_deserializer
241
242 def is_active(self):
243 with self._state.condition:
244 return _is_rpc_state_active(self._state)
245
246 def time_remaining(self):
247 return max(self._rpc_event.call_details.deadline - time.time(), 0)
248
249 def cancel(self):
250 self._rpc_event.call.cancel()
251
252 def add_callback(self, callback):
253 with self._state.condition:
254 if self._state.callbacks is None:
255 return False
256 else:
257 self._state.callbacks.append(callback)
258 return True
259
260 def disable_next_message_compression(self):
261 with self._state.condition:
262 self._state.disable_next_compression = True
263
264 def invocation_metadata(self):
265 return self._rpc_event.invocation_metadata
266
267 def peer(self):
268 return _common.decode(self._rpc_event.call.peer())
269
270 def peer_identities(self):
271 return cygrpc.peer_identities(self._rpc_event.call)
272
273 def peer_identity_key(self):
274 id_key = cygrpc.peer_identity_key(self._rpc_event.call)
275 return id_key if id_key is None else _common.decode(id_key)
276
277 def auth_context(self):
278 auth_context = cygrpc.auth_context(self._rpc_event.call)
279 auth_context_dict = {} if auth_context is None else auth_context
280 return {
281 _common.decode(key): value
282 for key, value in auth_context_dict.items()
283 }
284
285 def set_compression(self, compression):
286 with self._state.condition:
287 self._state.compression_algorithm = compression
288
289 def send_initial_metadata(self, initial_metadata):
290 with self._state.condition:
291 if self._state.client is _CANCELLED:
292 _raise_rpc_error(self._state)
293 else:
294 if self._state.initial_metadata_allowed:
295 operation = _get_initial_metadata_operation(
296 self._state, initial_metadata)
297 self._rpc_event.call.start_server_batch(
298 (operation,), _send_initial_metadata(self._state))
299 self._state.initial_metadata_allowed = False
300 self._state.due.add(_SEND_INITIAL_METADATA_TOKEN)
301 else:
302 raise ValueError('Initial metadata no longer allowed!')
303
304 def set_trailing_metadata(self, trailing_metadata):
305 with self._state.condition:
306 self._state.trailing_metadata = trailing_metadata
307
308 def trailing_metadata(self):
309 return self._state.trailing_metadata
310
311 def abort(self, code, details):
312 # treat OK like other invalid arguments: fail the RPC
313 if code == grpc.StatusCode.OK:
314 _LOGGER.error(
315 'abort() called with StatusCode.OK; returning UNKNOWN')
316 code = grpc.StatusCode.UNKNOWN
317 details = ''
318 with self._state.condition:
319 self._state.code = code
320 self._state.details = _common.encode(details)
321 self._state.aborted = True
322 raise Exception()
323
324 def abort_with_status(self, status):
325 self._state.trailing_metadata = status.trailing_metadata
326 self.abort(status.code, status.details)
327
328 def set_code(self, code):
329 with self._state.condition:
330 self._state.code = code
331
332 def code(self):
333 return self._state.code
334
335 def set_details(self, details):
336 with self._state.condition:
337 self._state.details = _common.encode(details)
338
339 def details(self):
340 return self._state.details
341
342 def _finalize_state(self):
343 pass
344
345
346 class _RequestIterator(object):
347
348 def __init__(self, state, call, request_deserializer):
349 self._state = state
350 self._call = call
351 self._request_deserializer = request_deserializer
352
353 def _raise_or_start_receive_message(self):
354 if self._state.client is _CANCELLED:
355 _raise_rpc_error(self._state)
356 elif not _is_rpc_state_active(self._state):
357 raise StopIteration()
358 else:
359 self._call.start_server_batch(
360 (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
361 _receive_message(self._state, self._call,
362 self._request_deserializer))
363 self._state.due.add(_RECEIVE_MESSAGE_TOKEN)
364
365 def _look_for_request(self):
366 if self._state.client is _CANCELLED:
367 _raise_rpc_error(self._state)
368 elif (self._state.request is None and
369 _RECEIVE_MESSAGE_TOKEN not in self._state.due):
370 raise StopIteration()
371 else:
372 request = self._state.request
373 self._state.request = None
374 return request
375
376 raise AssertionError() # should never run
377
378 def _next(self):
379 with self._state.condition:
380 self._raise_or_start_receive_message()
381 while True:
382 self._state.condition.wait()
383 request = self._look_for_request()
384 if request is not None:
385 return request
386
387 def __iter__(self):
388 return self
389
390 def __next__(self):
391 return self._next()
392
393 def next(self):
394 return self._next()
395
396
397 def _unary_request(rpc_event, state, request_deserializer):
398
399 def unary_request():
400 with state.condition:
401 if not _is_rpc_state_active(state):
402 return None
403 else:
404 rpc_event.call.start_server_batch(
405 (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
406 _receive_message(state, rpc_event.call,
407 request_deserializer))
408 state.due.add(_RECEIVE_MESSAGE_TOKEN)
409 while True:
410 state.condition.wait()
411 if state.request is None:
412 if state.client is _CLOSED:
413 details = '"{}" requires exactly one request message.'.format(
414 rpc_event.call_details.method)
415 _abort(state, rpc_event.call,
416 cygrpc.StatusCode.unimplemented,
417 _common.encode(details))
418 return None
419 elif state.client is _CANCELLED:
420 return None
421 else:
422 request = state.request
423 state.request = None
424 return request
425
426 return unary_request
427
428
429 def _call_behavior(rpc_event,
430 state,
431 behavior,
432 argument,
433 request_deserializer,
434 send_response_callback=None):
435 from grpc import _create_servicer_context
436 with _create_servicer_context(rpc_event, state,
437 request_deserializer) as context:
438 try:
439 response_or_iterator = None
440 if send_response_callback is not None:
441 response_or_iterator = behavior(argument, context,
442 send_response_callback)
443 else:
444 response_or_iterator = behavior(argument, context)
445 return response_or_iterator, True
446 except Exception as exception: # pylint: disable=broad-except
447 with state.condition:
448 if state.aborted:
449 _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
450 b'RPC Aborted')
451 elif exception not in state.rpc_errors:
452 details = 'Exception calling application: {}'.format(
453 exception)
454 _LOGGER.exception(details)
455 _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
456 _common.encode(details))
457 return None, False
458
459
460 def _take_response_from_response_iterator(rpc_event, state, response_iterator):
461 try:
462 return next(response_iterator), True
463 except StopIteration:
464 return None, True
465 except Exception as exception: # pylint: disable=broad-except
466 with state.condition:
467 if state.aborted:
468 _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
469 b'RPC Aborted')
470 elif exception not in state.rpc_errors:
471 details = 'Exception iterating responses: {}'.format(exception)
472 _LOGGER.exception(details)
473 _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
474 _common.encode(details))
475 return None, False
476
477
478 def _serialize_response(rpc_event, state, response, response_serializer):
479 serialized_response = _common.serialize(response, response_serializer)
480 if serialized_response is None:
481 with state.condition:
482 _abort(state, rpc_event.call, cygrpc.StatusCode.internal,
483 b'Failed to serialize response!')
484 return None
485 else:
486 return serialized_response
487
488
489 def _get_send_message_op_flags_from_state(state):
490 if state.disable_next_compression:
491 return cygrpc.WriteFlag.no_compress
492 else:
493 return _EMPTY_FLAGS
494
495
496 def _reset_per_message_state(state):
497 with state.condition:
498 state.disable_next_compression = False
499
500
501 def _send_response(rpc_event, state, serialized_response):
502 with state.condition:
503 if not _is_rpc_state_active(state):
504 return False
505 else:
506 if state.initial_metadata_allowed:
507 operations = (
508 _get_initial_metadata_operation(state, None),
509 cygrpc.SendMessageOperation(
510 serialized_response,
511 _get_send_message_op_flags_from_state(state)),
512 )
513 state.initial_metadata_allowed = False
514 token = _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN
515 else:
516 operations = (cygrpc.SendMessageOperation(
517 serialized_response,
518 _get_send_message_op_flags_from_state(state)),)
519 token = _SEND_MESSAGE_TOKEN
520 rpc_event.call.start_server_batch(operations,
521 _send_message(state, token))
522 state.due.add(token)
523 _reset_per_message_state(state)
524 while True:
525 state.condition.wait()
526 if token not in state.due:
527 return _is_rpc_state_active(state)
528
529
530 def _status(rpc_event, state, serialized_response):
531 with state.condition:
532 if state.client is not _CANCELLED:
533 code = _completion_code(state)
534 details = _details(state)
535 operations = [
536 cygrpc.SendStatusFromServerOperation(state.trailing_metadata,
537 code, details,
538 _EMPTY_FLAGS),
539 ]
540 if state.initial_metadata_allowed:
541 operations.append(_get_initial_metadata_operation(state, None))
542 if serialized_response is not None:
543 operations.append(
544 cygrpc.SendMessageOperation(
545 serialized_response,
546 _get_send_message_op_flags_from_state(state)))
547 rpc_event.call.start_server_batch(
548 operations,
549 _send_status_from_server(state, _SEND_STATUS_FROM_SERVER_TOKEN))
550 state.statused = True
551 _reset_per_message_state(state)
552 state.due.add(_SEND_STATUS_FROM_SERVER_TOKEN)
553
554
555 def _unary_response_in_pool(rpc_event, state, behavior, argument_thunk,
556 request_deserializer, response_serializer):
557 cygrpc.install_context_from_request_call_event(rpc_event)
558 try:
559 argument = argument_thunk()
560 if argument is not None:
561 response, proceed = _call_behavior(rpc_event, state, behavior,
562 argument, request_deserializer)
563 if proceed:
564 serialized_response = _serialize_response(
565 rpc_event, state, response, response_serializer)
566 if serialized_response is not None:
567 _status(rpc_event, state, serialized_response)
568 finally:
569 cygrpc.uninstall_context()
570
571
572 def _stream_response_in_pool(rpc_event, state, behavior, argument_thunk,
573 request_deserializer, response_serializer):
574 cygrpc.install_context_from_request_call_event(rpc_event)
575
576 def send_response(response):
577 if response is None:
578 _status(rpc_event, state, None)
579 else:
580 serialized_response = _serialize_response(rpc_event, state,
581 response,
582 response_serializer)
583 if serialized_response is not None:
584 _send_response(rpc_event, state, serialized_response)
585
586 try:
587 argument = argument_thunk()
588 if argument is not None:
589 if hasattr(behavior, 'experimental_non_blocking'
590 ) and behavior.experimental_non_blocking:
591 _call_behavior(rpc_event,
592 state,
593 behavior,
594 argument,
595 request_deserializer,
596 send_response_callback=send_response)
597 else:
598 response_iterator, proceed = _call_behavior(
599 rpc_event, state, behavior, argument, request_deserializer)
600 if proceed:
601 _send_message_callback_to_blocking_iterator_adapter(
602 rpc_event, state, send_response, response_iterator)
603 finally:
604 cygrpc.uninstall_context()
605
606
607 def _is_rpc_state_active(state):
608 return state.client is not _CANCELLED and not state.statused
609
610
611 def _send_message_callback_to_blocking_iterator_adapter(rpc_event, state,
612 send_response_callback,
613 response_iterator):
614 while True:
615 response, proceed = _take_response_from_response_iterator(
616 rpc_event, state, response_iterator)
617 if proceed:
618 send_response_callback(response)
619 if not _is_rpc_state_active(state):
620 break
621 else:
622 break
623
624
625 def _select_thread_pool_for_behavior(behavior, default_thread_pool):
626 if hasattr(behavior, 'experimental_thread_pool') and isinstance(
627 behavior.experimental_thread_pool, futures.ThreadPoolExecutor):
628 return behavior.experimental_thread_pool
629 else:
630 return default_thread_pool
631
632
633 def _handle_unary_unary(rpc_event, state, method_handler, default_thread_pool):
634 unary_request = _unary_request(rpc_event, state,
635 method_handler.request_deserializer)
636 thread_pool = _select_thread_pool_for_behavior(method_handler.unary_unary,
637 default_thread_pool)
638 return thread_pool.submit(_unary_response_in_pool, rpc_event, state,
639 method_handler.unary_unary, unary_request,
640 method_handler.request_deserializer,
641 method_handler.response_serializer)
642
643
644 def _handle_unary_stream(rpc_event, state, method_handler, default_thread_pool):
645 unary_request = _unary_request(rpc_event, state,
646 method_handler.request_deserializer)
647 thread_pool = _select_thread_pool_for_behavior(method_handler.unary_stream,
648 default_thread_pool)
649 return thread_pool.submit(_stream_response_in_pool, rpc_event, state,
650 method_handler.unary_stream, unary_request,
651 method_handler.request_deserializer,
652 method_handler.response_serializer)
653
654
655 def _handle_stream_unary(rpc_event, state, method_handler, default_thread_pool):
656 request_iterator = _RequestIterator(state, rpc_event.call,
657 method_handler.request_deserializer)
658 thread_pool = _select_thread_pool_for_behavior(method_handler.stream_unary,
659 default_thread_pool)
660 return thread_pool.submit(_unary_response_in_pool, rpc_event, state,
661 method_handler.stream_unary,
662 lambda: request_iterator,
663 method_handler.request_deserializer,
664 method_handler.response_serializer)
665
666
667 def _handle_stream_stream(rpc_event, state, method_handler,
668 default_thread_pool):
669 request_iterator = _RequestIterator(state, rpc_event.call,
670 method_handler.request_deserializer)
671 thread_pool = _select_thread_pool_for_behavior(method_handler.stream_stream,
672 default_thread_pool)
673 return thread_pool.submit(_stream_response_in_pool, rpc_event, state,
674 method_handler.stream_stream,
675 lambda: request_iterator,
676 method_handler.request_deserializer,
677 method_handler.response_serializer)
678
679
680 def _find_method_handler(rpc_event, generic_handlers, interceptor_pipeline):
681
682 def query_handlers(handler_call_details):
683 for generic_handler in generic_handlers:
684 method_handler = generic_handler.service(handler_call_details)
685 if method_handler is not None:
686 return method_handler
687 return None
688
689 handler_call_details = _HandlerCallDetails(
690 _common.decode(rpc_event.call_details.method),
691 rpc_event.invocation_metadata)
692
693 if interceptor_pipeline is not None:
694 return interceptor_pipeline.execute(query_handlers,
695 handler_call_details)
696 else:
697 return query_handlers(handler_call_details)
698
699
700 def _reject_rpc(rpc_event, status, details):
701 rpc_state = _RPCState()
702 operations = (
703 _get_initial_metadata_operation(rpc_state, None),
704 cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
705 cygrpc.SendStatusFromServerOperation(None, status, details,
706 _EMPTY_FLAGS),
707 )
708 rpc_event.call.start_server_batch(operations, lambda ignored_event: (
709 rpc_state,
710 (),
711 ))
712 return rpc_state
713
714
715 def _handle_with_method_handler(rpc_event, method_handler, thread_pool):
716 state = _RPCState()
717 with state.condition:
718 rpc_event.call.start_server_batch(
719 (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
720 _receive_close_on_server(state))
721 state.due.add(_RECEIVE_CLOSE_ON_SERVER_TOKEN)
722 if method_handler.request_streaming:
723 if method_handler.response_streaming:
724 return state, _handle_stream_stream(rpc_event, state,
725 method_handler, thread_pool)
726 else:
727 return state, _handle_stream_unary(rpc_event, state,
728 method_handler, thread_pool)
729 else:
730 if method_handler.response_streaming:
731 return state, _handle_unary_stream(rpc_event, state,
732 method_handler, thread_pool)
733 else:
734 return state, _handle_unary_unary(rpc_event, state,
735 method_handler, thread_pool)
736
737
738 def _handle_call(rpc_event, generic_handlers, interceptor_pipeline, thread_pool,
739 concurrency_exceeded):
740 if not rpc_event.success:
741 return None, None
742 if rpc_event.call_details.method is not None:
743 try:
744 method_handler = _find_method_handler(rpc_event, generic_handlers,
745 interceptor_pipeline)
746 except Exception as exception: # pylint: disable=broad-except
747 details = 'Exception servicing handler: {}'.format(exception)
748 _LOGGER.exception(details)
749 return _reject_rpc(rpc_event, cygrpc.StatusCode.unknown,
750 b'Error in service handler!'), None
751 if method_handler is None:
752 return _reject_rpc(rpc_event, cygrpc.StatusCode.unimplemented,
753 b'Method not found!'), None
754 elif concurrency_exceeded:
755 return _reject_rpc(rpc_event, cygrpc.StatusCode.resource_exhausted,
756 b'Concurrent RPC limit exceeded!'), None
757 else:
758 return _handle_with_method_handler(rpc_event, method_handler,
759 thread_pool)
760 else:
761 return None, None
762
763
764 @enum.unique
765 class _ServerStage(enum.Enum):
766 STOPPED = 'stopped'
767 STARTED = 'started'
768 GRACE = 'grace'
769
770
771 class _ServerState(object):
772
773 # pylint: disable=too-many-arguments
774 def __init__(self, completion_queue, server, generic_handlers,
775 interceptor_pipeline, thread_pool, maximum_concurrent_rpcs):
776 self.lock = threading.RLock()
777 self.completion_queue = completion_queue
778 self.server = server
779 self.generic_handlers = list(generic_handlers)
780 self.interceptor_pipeline = interceptor_pipeline
781 self.thread_pool = thread_pool
782 self.stage = _ServerStage.STOPPED
783 self.termination_event = threading.Event()
784 self.shutdown_events = [self.termination_event]
785 self.maximum_concurrent_rpcs = maximum_concurrent_rpcs
786 self.active_rpc_count = 0
787
788 # TODO(https://github.com/grpc/grpc/issues/6597): eliminate these fields.
789 self.rpc_states = set()
790 self.due = set()
791
792 # A "volatile" flag to interrupt the daemon serving thread
793 self.server_deallocated = False
794
795
796 def _add_generic_handlers(state, generic_handlers):
797 with state.lock:
798 state.generic_handlers.extend(generic_handlers)
799
800
801 def _add_insecure_port(state, address):
802 with state.lock:
803 return state.server.add_http2_port(address)
804
805
806 def _add_secure_port(state, address, server_credentials):
807 with state.lock:
808 return state.server.add_http2_port(address,
809 server_credentials._credentials)
810
811
812 def _request_call(state):
813 state.server.request_call(state.completion_queue, state.completion_queue,
814 _REQUEST_CALL_TAG)
815 state.due.add(_REQUEST_CALL_TAG)
816
817
818 # TODO(https://github.com/grpc/grpc/issues/6597): delete this function.
819 def _stop_serving(state):
820 if not state.rpc_states and not state.due:
821 state.server.destroy()
822 for shutdown_event in state.shutdown_events:
823 shutdown_event.set()
824 state.stage = _ServerStage.STOPPED
825 return True
826 else:
827 return False
828
829
830 def _on_call_completed(state):
831 with state.lock:
832 state.active_rpc_count -= 1
833
834
835 def _process_event_and_continue(state, event):
836 should_continue = True
837 if event.tag is _SHUTDOWN_TAG:
838 with state.lock:
839 state.due.remove(_SHUTDOWN_TAG)
840 if _stop_serving(state):
841 should_continue = False
842 elif event.tag is _REQUEST_CALL_TAG:
843 with state.lock:
844 state.due.remove(_REQUEST_CALL_TAG)
845 concurrency_exceeded = (
846 state.maximum_concurrent_rpcs is not None and
847 state.active_rpc_count >= state.maximum_concurrent_rpcs)
848 rpc_state, rpc_future = _handle_call(event, state.generic_handlers,
849 state.interceptor_pipeline,
850 state.thread_pool,
851 concurrency_exceeded)
852 if rpc_state is not None:
853 state.rpc_states.add(rpc_state)
854 if rpc_future is not None:
855 state.active_rpc_count += 1
856 rpc_future.add_done_callback(
857 lambda unused_future: _on_call_completed(state))
858 if state.stage is _ServerStage.STARTED:
859 _request_call(state)
860 elif _stop_serving(state):
861 should_continue = False
862 else:
863 rpc_state, callbacks = event.tag(event)
864 for callback in callbacks:
865 try:
866 callback()
867 except Exception: # pylint: disable=broad-except
868 _LOGGER.exception('Exception calling callback!')
869 if rpc_state is not None:
870 with state.lock:
871 state.rpc_states.remove(rpc_state)
872 if _stop_serving(state):
873 should_continue = False
874 return should_continue
875
876
877 def _serve(state):
878 while True:
879 timeout = time.time() + _DEALLOCATED_SERVER_CHECK_PERIOD_S
880 event = state.completion_queue.poll(timeout)
881 if state.server_deallocated:
882 _begin_shutdown_once(state)
883 if event.completion_type != cygrpc.CompletionType.queue_timeout:
884 if not _process_event_and_continue(state, event):
885 return
886 # We want to force the deletion of the previous event
887 # ~before~ we poll again; if the event has a reference
888 # to a shutdown Call object, this can induce spinlock.
889 event = None
890
891
892 def _begin_shutdown_once(state):
893 with state.lock:
894 if state.stage is _ServerStage.STARTED:
895 state.server.shutdown(state.completion_queue, _SHUTDOWN_TAG)
896 state.stage = _ServerStage.GRACE
897 state.due.add(_SHUTDOWN_TAG)
898
899
900 def _stop(state, grace):
901 with state.lock:
902 if state.stage is _ServerStage.STOPPED:
903 shutdown_event = threading.Event()
904 shutdown_event.set()
905 return shutdown_event
906 else:
907 _begin_shutdown_once(state)
908 shutdown_event = threading.Event()
909 state.shutdown_events.append(shutdown_event)
910 if grace is None:
911 state.server.cancel_all_calls()
912 else:
913
914 def cancel_all_calls_after_grace():
915 shutdown_event.wait(timeout=grace)
916 with state.lock:
917 state.server.cancel_all_calls()
918
919 thread = threading.Thread(target=cancel_all_calls_after_grace)
920 thread.start()
921 return shutdown_event
922 shutdown_event.wait()
923 return shutdown_event
924
925
926 def _start(state):
927 with state.lock:
928 if state.stage is not _ServerStage.STOPPED:
929 raise ValueError('Cannot start already-started server!')
930 state.server.start()
931 state.stage = _ServerStage.STARTED
932 _request_call(state)
933
934 thread = threading.Thread(target=_serve, args=(state,))
935 thread.daemon = True
936 thread.start()
937
938
939 def _validate_generic_rpc_handlers(generic_rpc_handlers):
940 for generic_rpc_handler in generic_rpc_handlers:
941 service_attribute = getattr(generic_rpc_handler, 'service', None)
942 if service_attribute is None:
943 raise AttributeError(
944 '"{}" must conform to grpc.GenericRpcHandler type but does '
945 'not have "service" method!'.format(generic_rpc_handler))
946
947
948 def _augment_options(base_options, compression):
949 compression_option = _compression.create_channel_option(compression)
950 return tuple(base_options) + compression_option
951
952
953 class _Server(grpc.Server):
954
955 # pylint: disable=too-many-arguments
956 def __init__(self, thread_pool, generic_handlers, interceptors, options,
957 maximum_concurrent_rpcs, compression, xds):
958 completion_queue = cygrpc.CompletionQueue()
959 server = cygrpc.Server(_augment_options(options, compression), xds)
960 server.register_completion_queue(completion_queue)
961 self._state = _ServerState(completion_queue, server, generic_handlers,
962 _interceptor.service_pipeline(interceptors),
963 thread_pool, maximum_concurrent_rpcs)
964
965 def add_generic_rpc_handlers(self, generic_rpc_handlers):
966 _validate_generic_rpc_handlers(generic_rpc_handlers)
967 _add_generic_handlers(self._state, generic_rpc_handlers)
968
969 def add_insecure_port(self, address):
970 return _common.validate_port_binding_result(
971 address, _add_insecure_port(self._state, _common.encode(address)))
972
973 def add_secure_port(self, address, server_credentials):
974 return _common.validate_port_binding_result(
975 address,
976 _add_secure_port(self._state, _common.encode(address),
977 server_credentials))
978
979 def start(self):
980 _start(self._state)
981
982 def wait_for_termination(self, timeout=None):
983 # NOTE(https://bugs.python.org/issue35935)
984 # Remove this workaround once threading.Event.wait() is working with
985 # CTRL+C across platforms.
986 return _common.wait(self._state.termination_event.wait,
987 self._state.termination_event.is_set,
988 timeout=timeout)
989
990 def stop(self, grace):
991 return _stop(self._state, grace)
992
993 def __del__(self):
994 if hasattr(self, '_state'):
995 # We can not grab a lock in __del__(), so set a flag to signal the
996 # serving daemon thread (if it exists) to initiate shutdown.
997 self._state.server_deallocated = True
998
999
1000 def create_server(thread_pool, generic_rpc_handlers, interceptors, options,
1001 maximum_concurrent_rpcs, compression, xds):
1002 _validate_generic_rpc_handlers(generic_rpc_handlers)
1003 return _Server(thread_pool, generic_rpc_handlers, interceptors, options,
1004 maximum_concurrent_rpcs, compression, xds)