1
0

base_request.py 9.7 KB

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