_server.py 37 KB

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