base_request.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # Copyright (C) 2013 Google Inc.
  2. #
  3. # This file is part of YouCompleteMe.
  4. #
  5. # YouCompleteMe is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # YouCompleteMe is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  17. from __future__ import unicode_literals
  18. from __future__ import print_function
  19. from __future__ import division
  20. from __future__ import absolute_import
  21. # Not installing aliases from python-future; it's unreliable and slow.
  22. from builtins import * # noqa
  23. import contextlib
  24. import logging
  25. import json
  26. from future.utils import native
  27. from base64 import b64decode, b64encode
  28. from ycm import vimsupport
  29. from ycmd.utils import ToBytes, urljoin, urlparse
  30. from ycmd.hmac_utils import CreateRequestHmac, CreateHmac, SecureBytesEqual
  31. from ycmd.responses import ServerError, UnknownExtraConf
  32. _HEADERS = {'content-type': 'application/json'}
  33. _CONNECT_TIMEOUT_SEC = 0.01
  34. # Setting this to None seems to screw up the Requests/urllib3 libs.
  35. _READ_TIMEOUT_SEC = 30
  36. _HMAC_HEADER = 'x-ycm-hmac'
  37. _logger = logging.getLogger( __name__ )
  38. class BaseRequest( object ):
  39. def __init__( self ):
  40. pass
  41. def Start( self ):
  42. pass
  43. def Done( self ):
  44. return True
  45. def Response( self ):
  46. return {}
  47. # This method blocks
  48. # |timeout| is num seconds to tolerate no response from server before giving
  49. # up; see Requests docs for details (we just pass the param along).
  50. @staticmethod
  51. def GetDataFromHandler( handler, timeout = _READ_TIMEOUT_SEC ):
  52. return JsonFromFuture( BaseRequest._TalkToHandlerAsync( '',
  53. handler,
  54. 'GET',
  55. timeout ) )
  56. # This is the blocking version of the method. See below for async.
  57. # |timeout| is num seconds to tolerate no response from server before giving
  58. # up; see Requests docs for details (we just pass the param along).
  59. @staticmethod
  60. def PostDataToHandler( data, handler, timeout = _READ_TIMEOUT_SEC ):
  61. return JsonFromFuture( BaseRequest.PostDataToHandlerAsync( data,
  62. handler,
  63. timeout ) )
  64. # This returns a future! Use JsonFromFuture to get the value.
  65. # |timeout| is num seconds to tolerate no response from server before giving
  66. # up; see Requests docs for details (we just pass the param along).
  67. @staticmethod
  68. def PostDataToHandlerAsync( data, handler, timeout = _READ_TIMEOUT_SEC ):
  69. return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout )
  70. # This returns a future! Use JsonFromFuture to get the value.
  71. # |method| is either 'POST' or 'GET'.
  72. # |timeout| is num seconds to tolerate no response from server before giving
  73. # up; see Requests docs for details (we just pass the param along).
  74. @staticmethod
  75. def _TalkToHandlerAsync( data,
  76. handler,
  77. method,
  78. timeout = _READ_TIMEOUT_SEC ):
  79. request_uri = _BuildUri( handler )
  80. if method == 'POST':
  81. sent_data = _ToUtf8Json( data )
  82. return BaseRequest.Session().post(
  83. request_uri,
  84. data = sent_data,
  85. headers = BaseRequest._ExtraHeaders( method,
  86. request_uri,
  87. sent_data ),
  88. timeout = ( _CONNECT_TIMEOUT_SEC, timeout ) )
  89. return BaseRequest.Session().get(
  90. request_uri,
  91. headers = BaseRequest._ExtraHeaders( method, request_uri ),
  92. timeout = ( _CONNECT_TIMEOUT_SEC, timeout ) )
  93. @staticmethod
  94. def _ExtraHeaders( method, request_uri, request_body = None ):
  95. if not request_body:
  96. request_body = bytes( b'' )
  97. headers = dict( _HEADERS )
  98. headers[ _HMAC_HEADER ] = b64encode(
  99. CreateRequestHmac( ToBytes( method ),
  100. ToBytes( urlparse( request_uri ).path ),
  101. request_body,
  102. BaseRequest.hmac_secret ) )
  103. return headers
  104. # These two methods exist to avoid importing the requests module at startup;
  105. # reducing loading time since this module is slow to import.
  106. @classmethod
  107. def Requests( cls ):
  108. try:
  109. return cls.requests
  110. except AttributeError:
  111. import requests
  112. cls.requests = requests
  113. return requests
  114. @classmethod
  115. def Session( cls ):
  116. try:
  117. return cls.session
  118. except AttributeError:
  119. from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor
  120. from requests_futures.sessions import FuturesSession
  121. executor = UnsafeThreadPoolExecutor( max_workers = 30 )
  122. cls.session = FuturesSession( executor = executor )
  123. return cls.session
  124. server_location = ''
  125. hmac_secret = ''
  126. def BuildRequestData( filepath = None ):
  127. """Build request for the current buffer or the buffer corresponding to
  128. |filepath| if specified."""
  129. current_filepath = vimsupport.GetCurrentBufferFilepath()
  130. if filepath and current_filepath != filepath:
  131. # Cursor position is irrelevant when filepath is not the current buffer.
  132. return {
  133. 'filepath': filepath,
  134. 'line_num': 1,
  135. 'column_num': 1,
  136. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( filepath )
  137. }
  138. line, column = vimsupport.CurrentLineAndColumn()
  139. return {
  140. 'filepath': current_filepath,
  141. 'line_num': line + 1,
  142. 'column_num': column + 1,
  143. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( current_filepath )
  144. }
  145. def JsonFromFuture( future ):
  146. response = future.result()
  147. _ValidateResponseObject( response )
  148. if response.status_code == BaseRequest.Requests().codes.server_error:
  149. raise MakeServerException( response.json() )
  150. # We let Requests handle the other status types, we only handle the 500
  151. # error code.
  152. response.raise_for_status()
  153. if response.text:
  154. return response.json()
  155. return None
  156. @contextlib.contextmanager
  157. def HandleServerException( display = True, truncate = False ):
  158. """Catch any exception raised through server communication. If it is raised
  159. because of a unknown .ycm_extra_conf.py file, load the file or ignore it after
  160. asking the user. Otherwise, log the exception and display its message to the
  161. user on the Vim status line. Unset the |display| parameter to hide the message
  162. from the user. Set the |truncate| parameter to avoid hit-enter prompts from
  163. this message.
  164. The GetDataFromHandler, PostDataToHandler, and JsonFromFuture functions should
  165. always be wrapped by this function to avoid Python exceptions bubbling up to
  166. the user.
  167. Example usage:
  168. with HandleServerException():
  169. response = BaseRequest.PostDataToHandler( ... )
  170. """
  171. try:
  172. try:
  173. yield
  174. except UnknownExtraConf as e:
  175. if vimsupport.Confirm( str( e ) ):
  176. _LoadExtraConfFile( e.extra_conf_file )
  177. else:
  178. _IgnoreExtraConfFile( e.extra_conf_file )
  179. except BaseRequest.Requests().exceptions.ConnectionError:
  180. # We don't display this exception to the user since it is likely to happen
  181. # for each subsequent request (typically if the server crashed) and we
  182. # don't want to spam the user with it.
  183. _logger.exception( 'Unable to connect to server' )
  184. except Exception as e:
  185. _logger.exception( 'Error while handling server response' )
  186. if display:
  187. DisplayServerException( e, truncate )
  188. def _LoadExtraConfFile( filepath ):
  189. BaseRequest.PostDataToHandler( { 'filepath': filepath },
  190. 'load_extra_conf_file' )
  191. def _IgnoreExtraConfFile( filepath ):
  192. BaseRequest.PostDataToHandler( { 'filepath': filepath },
  193. 'ignore_extra_conf_file' )
  194. def DisplayServerException( exception, truncate = False ):
  195. serialized_exception = str( exception )
  196. # We ignore the exception about the file already being parsed since it comes
  197. # up often and isn't something that's actionable by the user.
  198. if 'already being parsed' in serialized_exception:
  199. return
  200. vimsupport.PostVimMessage( serialized_exception, truncate = truncate )
  201. def _ToUtf8Json( data ):
  202. return ToBytes( json.dumps( data ) if data else None )
  203. def _ValidateResponseObject( response ):
  204. our_hmac = CreateHmac( response.content, BaseRequest.hmac_secret )
  205. their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )
  206. if not SecureBytesEqual( our_hmac, their_hmac ):
  207. raise RuntimeError( 'Received invalid HMAC for response!' )
  208. return True
  209. def _BuildUri( handler ):
  210. return native( ToBytes( urljoin( BaseRequest.server_location, handler ) ) )
  211. def MakeServerException( data ):
  212. if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__:
  213. return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] )
  214. return ServerError( '{0}: {1}'.format( data[ 'exception' ][ 'TYPE' ],
  215. data[ 'message' ] ) )