1
0

base_request.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. # Copyright (C) 2013-2018 YouCompleteMe contributors
  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 logging
  24. import json
  25. import vim
  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, GetCurrentDirectory
  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. self._should_resend = False
  41. def Start( self ):
  42. pass
  43. def Done( self ):
  44. return True
  45. def Response( self ):
  46. return {}
  47. def ShouldResend( self ):
  48. return self._should_resend
  49. def HandleFuture( self,
  50. future,
  51. display_message = True,
  52. truncate_message = False ):
  53. """Get the server response from a |future| object and catch any exception
  54. while doing so. If an exception is raised because of a unknown
  55. .ycm_extra_conf.py file, load the file or ignore it after asking the user.
  56. An identical request should be sent again to the server. For other
  57. exceptions, log the exception and display its message to the user on the Vim
  58. status line. Unset the |display_message| parameter to hide the message from
  59. the user. Set the |truncate_message| parameter to avoid hit-enter prompts
  60. from this message."""
  61. try:
  62. try:
  63. return _JsonFromFuture( future )
  64. except UnknownExtraConf as e:
  65. if vimsupport.Confirm( str( e ) ):
  66. _LoadExtraConfFile( e.extra_conf_file )
  67. else:
  68. _IgnoreExtraConfFile( e.extra_conf_file )
  69. self._should_resend = True
  70. except BaseRequest.Requests().exceptions.ConnectionError as e:
  71. # We don't display this exception to the user since it is likely to happen
  72. # for each subsequent request (typically if the server crashed) and we
  73. # don't want to spam the user with it.
  74. _logger.error( e )
  75. except Exception as e:
  76. _logger.exception( 'Error while handling server response' )
  77. if display_message:
  78. DisplayServerException( e, truncate_message )
  79. return None
  80. # This method blocks
  81. # |timeout| is num seconds to tolerate no response from server before giving
  82. # up; see Requests docs for details (we just pass the param along).
  83. # See the HandleFuture method for the |display_message| and |truncate_message|
  84. # parameters.
  85. def GetDataFromHandler( self,
  86. handler,
  87. timeout = _READ_TIMEOUT_SEC,
  88. display_message = True,
  89. truncate_message = False ):
  90. return self.HandleFuture(
  91. BaseRequest._TalkToHandlerAsync( '', handler, 'GET', timeout ),
  92. display_message,
  93. truncate_message )
  94. # This is the blocking version of the method. See below for async.
  95. # |timeout| is num seconds to tolerate no response from server before giving
  96. # up; see Requests docs for details (we just pass the param along).
  97. # See the HandleFuture method for the |display_message| and |truncate_message|
  98. # parameters.
  99. def PostDataToHandler( self,
  100. data,
  101. handler,
  102. timeout = _READ_TIMEOUT_SEC,
  103. display_message = True,
  104. truncate_message = False ):
  105. return self.HandleFuture(
  106. BaseRequest.PostDataToHandlerAsync( data, handler, timeout ),
  107. display_message,
  108. truncate_message )
  109. # This returns a future! Use HandleFuture to get the value.
  110. # |timeout| is num seconds to tolerate no response from server before giving
  111. # up; see Requests docs for details (we just pass the param along).
  112. @staticmethod
  113. def PostDataToHandlerAsync( data, handler, timeout = _READ_TIMEOUT_SEC ):
  114. return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout )
  115. # This returns a future! Use HandleFuture to get the value.
  116. # |method| is either 'POST' or 'GET'.
  117. # |timeout| is num seconds to tolerate no response from server before giving
  118. # up; see Requests docs for details (we just pass the param along).
  119. @staticmethod
  120. def _TalkToHandlerAsync( data,
  121. handler,
  122. method,
  123. timeout = _READ_TIMEOUT_SEC ):
  124. request_uri = _BuildUri( handler )
  125. if method == 'POST':
  126. sent_data = _ToUtf8Json( data )
  127. return BaseRequest.Session().post(
  128. request_uri,
  129. data = sent_data,
  130. headers = BaseRequest._ExtraHeaders( method,
  131. request_uri,
  132. sent_data ),
  133. timeout = ( _CONNECT_TIMEOUT_SEC, timeout ) )
  134. return BaseRequest.Session().get(
  135. request_uri,
  136. headers = BaseRequest._ExtraHeaders( method, request_uri ),
  137. timeout = ( _CONNECT_TIMEOUT_SEC, timeout ) )
  138. @staticmethod
  139. def _ExtraHeaders( method, request_uri, request_body = None ):
  140. if not request_body:
  141. request_body = bytes( b'' )
  142. headers = dict( _HEADERS )
  143. headers[ _HMAC_HEADER ] = b64encode(
  144. CreateRequestHmac( ToBytes( method ),
  145. ToBytes( urlparse( request_uri ).path ),
  146. request_body,
  147. BaseRequest.hmac_secret ) )
  148. return headers
  149. # These two methods exist to avoid importing the requests module at startup;
  150. # reducing loading time since this module is slow to import.
  151. @classmethod
  152. def Requests( cls ):
  153. try:
  154. return cls.requests
  155. except AttributeError:
  156. import requests
  157. cls.requests = requests
  158. return requests
  159. @classmethod
  160. def Session( cls ):
  161. try:
  162. return cls.session
  163. except AttributeError:
  164. from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor
  165. from requests_futures.sessions import FuturesSession
  166. executor = UnsafeThreadPoolExecutor( max_workers = 30 )
  167. cls.session = FuturesSession( executor = executor )
  168. return cls.session
  169. server_location = ''
  170. hmac_secret = ''
  171. def BuildRequestData( buffer_number = None ):
  172. """Build request for the current buffer or the buffer with number
  173. |buffer_number| if specified."""
  174. working_dir = GetCurrentDirectory()
  175. current_buffer = vim.current.buffer
  176. if buffer_number and current_buffer.number != buffer_number:
  177. # Cursor position is irrelevant when filepath is not the current buffer.
  178. buffer_object = vim.buffers[ buffer_number ]
  179. filepath = vimsupport.GetBufferFilepath( buffer_object )
  180. return {
  181. 'filepath': filepath,
  182. 'line_num': 1,
  183. 'column_num': 1,
  184. 'working_dir': working_dir,
  185. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( buffer_object,
  186. filepath )
  187. }
  188. current_filepath = vimsupport.GetBufferFilepath( current_buffer )
  189. line, column = vimsupport.CurrentLineAndColumn()
  190. return {
  191. 'filepath': current_filepath,
  192. 'line_num': line + 1,
  193. 'column_num': column + 1,
  194. 'working_dir': working_dir,
  195. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( current_buffer,
  196. current_filepath )
  197. }
  198. def _JsonFromFuture( future ):
  199. response = future.result()
  200. _ValidateResponseObject( response )
  201. if response.status_code == BaseRequest.Requests().codes.server_error:
  202. raise MakeServerException( response.json() )
  203. # We let Requests handle the other status types, we only handle the 500
  204. # error code.
  205. response.raise_for_status()
  206. if response.text:
  207. return response.json()
  208. return None
  209. def _LoadExtraConfFile( filepath ):
  210. BaseRequest().PostDataToHandler( { 'filepath': filepath },
  211. 'load_extra_conf_file' )
  212. def _IgnoreExtraConfFile( filepath ):
  213. BaseRequest().PostDataToHandler( { 'filepath': filepath },
  214. 'ignore_extra_conf_file' )
  215. def DisplayServerException( exception, truncate_message = False ):
  216. serialized_exception = str( exception )
  217. # We ignore the exception about the file already being parsed since it comes
  218. # up often and isn't something that's actionable by the user.
  219. if 'already being parsed' in serialized_exception:
  220. return
  221. vimsupport.PostVimMessage( serialized_exception, truncate = truncate_message )
  222. def _ToUtf8Json( data ):
  223. return ToBytes( json.dumps( data ) if data else None )
  224. def _ValidateResponseObject( response ):
  225. our_hmac = CreateHmac( response.content, BaseRequest.hmac_secret )
  226. their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )
  227. if not SecureBytesEqual( our_hmac, their_hmac ):
  228. raise RuntimeError( 'Received invalid HMAC for response!' )
  229. return True
  230. def _BuildUri( handler ):
  231. return native( ToBytes( urljoin( BaseRequest.server_location, handler ) ) )
  232. def MakeServerException( data ):
  233. if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__:
  234. return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] )
  235. return ServerError( '{0}: {1}'.format( data[ 'exception' ][ 'TYPE' ],
  236. data[ 'message' ] ) )