httpclient.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import json
  2. import logging
  3. import re
  4. import uuid
  5. from base64 import b64encode
  6. from typing import Optional, Dict, Any, Sequence, Union, List, Callable, Generator, BinaryIO
  7. from urllib.parse import urlencode
  8. from urllib3 import Timeout
  9. from urllib3.exceptions import HTTPError
  10. from urllib3.poolmanager import PoolManager
  11. from urllib3.response import HTTPResponse
  12. from clickhouse_connect import common
  13. from clickhouse_connect.datatypes import registry
  14. from clickhouse_connect.datatypes.base import ClickHouseType
  15. from clickhouse_connect.driver.ctypes import RespBuffCls
  16. from clickhouse_connect.driver.client import Client
  17. from clickhouse_connect.driver.common import dict_copy, coerce_bool, coerce_int
  18. from clickhouse_connect.driver.compression import available_compression
  19. from clickhouse_connect.driver.exceptions import DatabaseError, OperationalError, ProgrammingError
  20. from clickhouse_connect.driver.external import ExternalData
  21. from clickhouse_connect.driver.httputil import ResponseSource, get_pool_manager, get_response_data, \
  22. default_pool_manager, get_proxy_manager, all_managers, check_env_proxy, check_conn_reset
  23. from clickhouse_connect.driver.insert import InsertContext
  24. from clickhouse_connect.driver.summary import QuerySummary
  25. from clickhouse_connect.driver.query import QueryResult, QueryContext, quote_identifier, bind_query
  26. from clickhouse_connect.driver.transform import NativeTransform
  27. logger = logging.getLogger(__name__)
  28. columns_only_re = re.compile(r'LIMIT 0\s*$', re.IGNORECASE)
  29. # pylint: disable=too-many-instance-attributes
  30. class HttpClient(Client):
  31. params = {}
  32. valid_transport_settings = {'database', 'buffer_size', 'session_id',
  33. 'compress', 'decompress', 'session_timeout',
  34. 'session_check', 'query_id', 'quota_key',
  35. 'wait_end_of_query', 'client_protocol_version'}
  36. optional_transport_settings = {'send_progress_in_http_headers',
  37. 'http_headers_progress_interval_ms',
  38. 'enable_http_compression'}
  39. _owns_pool_manager = False
  40. # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements,unused-argument
  41. def __init__(self,
  42. interface: str,
  43. host: str,
  44. port: int,
  45. username: str,
  46. password: str,
  47. database: str,
  48. compress: Union[bool, str] = True,
  49. query_limit: int = 0,
  50. query_retries: int = 2,
  51. connect_timeout: int = 10,
  52. send_receive_timeout: int = 300,
  53. client_name: Optional[str] = None,
  54. verify: bool = True,
  55. ca_cert: Optional[str] = None,
  56. client_cert: Optional[str] = None,
  57. client_cert_key: Optional[str] = None,
  58. session_id: Optional[str] = None,
  59. settings: Optional[Dict[str, Any]] = None,
  60. pool_mgr: Optional[PoolManager] = None,
  61. http_proxy: Optional[str] = None,
  62. https_proxy: Optional[str] = None,
  63. server_host_name: Optional[str] = None,
  64. apply_server_timezone: Optional[Union[str, bool]] = True):
  65. """
  66. Create an HTTP ClickHouse Connect client
  67. See clickhouse_connect.get_client for parameters
  68. """
  69. self.url = f'{interface}://{host}:{port}'
  70. self.headers = {}
  71. ch_settings = dict_copy(settings, self.params)
  72. self.http = pool_mgr
  73. if interface == 'https':
  74. if not https_proxy:
  75. https_proxy = check_env_proxy('https', host, port)
  76. if client_cert:
  77. if not username:
  78. raise ProgrammingError('username parameter is required for Mutual TLS authentication')
  79. self.headers['X-ClickHouse-User'] = username
  80. self.headers['X-ClickHouse-SSL-Certificate-Auth'] = 'on'
  81. verify = coerce_bool(verify)
  82. # pylint: disable=too-many-boolean-expressions
  83. if not self.http and (server_host_name or ca_cert or client_cert or not verify or https_proxy):
  84. options = {
  85. 'ca_cert': ca_cert,
  86. 'client_cert': client_cert,
  87. 'verify': verify,
  88. 'client_cert_key': client_cert_key
  89. }
  90. if server_host_name:
  91. if verify:
  92. options['assert_hostname'] = server_host_name
  93. options['server_hostname'] = server_host_name
  94. self.http = get_pool_manager(https_proxy=https_proxy, **options)
  95. self._owns_pool_manager = True
  96. if not self.http:
  97. if not http_proxy:
  98. http_proxy = check_env_proxy('http', host, port)
  99. if http_proxy:
  100. self.http = get_proxy_manager(host, http_proxy)
  101. else:
  102. self.http = default_pool_manager()
  103. if not client_cert and username:
  104. self.headers['Authorization'] = 'Basic ' + b64encode(f'{username}:{password}'.encode()).decode()
  105. self.headers['User-Agent'] = common.build_client_name(client_name)
  106. self._read_format = self._write_format = 'Native'
  107. self._transform = NativeTransform()
  108. # There is use cases when client need to disable timeouts.
  109. if connect_timeout is not None:
  110. connect_timeout = coerce_int(connect_timeout)
  111. if send_receive_timeout is not None:
  112. send_receive_timeout = coerce_int(send_receive_timeout)
  113. self.timeout = Timeout(connect=connect_timeout, read=send_receive_timeout)
  114. self.http_retries = 1
  115. self._send_progress = None
  116. self._send_comp_setting = False
  117. self._progress_interval = None
  118. self._active_session = None
  119. if session_id:
  120. ch_settings['session_id'] = session_id
  121. elif 'session_id' not in ch_settings and common.get_setting('autogenerate_session_id'):
  122. ch_settings['session_id'] = str(uuid.uuid4())
  123. if coerce_bool(compress):
  124. compression = ','.join(available_compression)
  125. self.write_compression = available_compression[0]
  126. elif compress and compress not in ('False', 'false', '0'):
  127. if compress not in available_compression:
  128. raise ProgrammingError(f'Unsupported compression method {compress}')
  129. compression = compress
  130. self.write_compression = compress
  131. else:
  132. compression = None
  133. super().__init__(database=database,
  134. uri=self.url,
  135. query_limit=query_limit,
  136. query_retries=query_retries,
  137. server_host_name=server_host_name,
  138. apply_server_timezone=apply_server_timezone)
  139. self.params = self._validate_settings(ch_settings)
  140. comp_setting = self._setting_status('enable_http_compression')
  141. self._send_comp_setting = not comp_setting.is_set and comp_setting.is_writable
  142. if comp_setting.is_set or comp_setting.is_writable:
  143. self.compression = compression
  144. send_setting = self._setting_status('send_progress_in_http_headers')
  145. self._send_progress = not send_setting.is_set and send_setting.is_writable
  146. if (send_setting.is_set or send_setting.is_writable) and \
  147. self._setting_status('http_headers_progress_interval_ms').is_writable:
  148. self._progress_interval = str(min(120000, max(10000, (send_receive_timeout - 5) * 1000)))
  149. def set_client_setting(self, key, value):
  150. str_value = self._validate_setting(key, value, common.get_setting('invalid_setting_action'))
  151. if str_value is not None:
  152. self.params[key] = str_value
  153. def get_client_setting(self, key) -> Optional[str]:
  154. values = self.params.get(key)
  155. return values[0] if values else None
  156. def _prep_query(self, context: QueryContext):
  157. final_query = super()._prep_query(context)
  158. if context.is_insert:
  159. return final_query
  160. return f'{final_query}\n FORMAT {self._read_format}'
  161. def _query_with_context(self, context: QueryContext) -> QueryResult:
  162. headers = {}
  163. params = {}
  164. if self.database:
  165. params['database'] = self.database
  166. if self.protocol_version:
  167. params['client_protocol_version'] = self.protocol_version
  168. context.block_info = True
  169. params.update(context.bind_params)
  170. params.update(self._validate_settings(context.settings))
  171. if columns_only_re.search(context.uncommented_query):
  172. response = self._raw_request(f'{context.final_query}\n FORMAT JSON',
  173. params, headers, retries=self.query_retries)
  174. json_result = json.loads(response.data)
  175. # ClickHouse will respond with a JSON object of meta, data, and some other objects
  176. # We just grab the column names and column types from the metadata sub object
  177. names: List[str] = []
  178. types: List[ClickHouseType] = []
  179. for col in json_result['meta']:
  180. names.append(col['name'])
  181. types.append(registry.get_from_name(col['type']))
  182. return QueryResult([], None, tuple(names), tuple(types))
  183. if self.compression:
  184. headers['Accept-Encoding'] = self.compression
  185. if self._send_comp_setting:
  186. params['enable_http_compression'] = '1'
  187. final_query = self._prep_query(context)
  188. if context.external_data:
  189. body = bytes()
  190. params['query'] = final_query
  191. params.update(context.external_data.query_params)
  192. fields = context.external_data.form_data
  193. else:
  194. body = final_query
  195. fields = None
  196. headers['Content-Type'] = 'text/plain; charset=utf-8'
  197. response = self._raw_request(body,
  198. params,
  199. headers,
  200. stream=True,
  201. retries=self.query_retries,
  202. fields=fields,
  203. server_wait=not context.streaming)
  204. byte_source = RespBuffCls(ResponseSource(response)) # pylint: disable=not-callable
  205. context.set_response_tz(self._check_tz_change(response.headers.get('X-ClickHouse-Timezone')))
  206. query_result = self._transform.parse_response(byte_source, context)
  207. query_result.summary = self._summary(response)
  208. return query_result
  209. def data_insert(self, context: InsertContext) -> QuerySummary:
  210. """
  211. See BaseClient doc_string for this method
  212. """
  213. if context.empty:
  214. logger.debug('No data included in insert, skipping')
  215. return QuerySummary()
  216. def error_handler(resp: HTTPResponse):
  217. # If we actually had a local exception when building the insert, throw that instead
  218. if context.insert_exception:
  219. ex = context.insert_exception
  220. context.insert_exception = None
  221. raise ex
  222. self._error_handler(resp)
  223. headers = {'Content-Type': 'application/octet-stream'}
  224. if context.compression is None:
  225. context.compression = self.write_compression
  226. if context.compression:
  227. headers['Content-Encoding'] = context.compression
  228. block_gen = self._transform.build_insert(context)
  229. params = {}
  230. if self.database:
  231. params['database'] = self.database
  232. params.update(self._validate_settings(context.settings))
  233. response = self._raw_request(block_gen, params, headers, error_handler=error_handler, server_wait=False)
  234. logger.debug('Context insert response code: %d, content: %s', response.status, response.data)
  235. context.data = None
  236. return QuerySummary(self._summary(response))
  237. def raw_insert(self, table: str = None,
  238. column_names: Optional[Sequence[str]] = None,
  239. insert_block: Union[str, bytes, Generator[bytes, None, None], BinaryIO] = None,
  240. settings: Optional[Dict] = None,
  241. fmt: Optional[str] = None,
  242. compression: Optional[str] = None) -> QuerySummary:
  243. """
  244. See BaseClient doc_string for this method
  245. """
  246. params = {}
  247. headers = {'Content-Type': 'application/octet-stream'}
  248. if compression:
  249. headers['Content-Encoding'] = compression
  250. if table:
  251. cols = f" ({', '.join([quote_identifier(x) for x in column_names])})" if column_names is not None else ''
  252. query = f'INSERT INTO {table}{cols} FORMAT {fmt if fmt else self._write_format}'
  253. if not compression and isinstance(insert_block, str):
  254. insert_block = query + '\n' + insert_block
  255. elif not compression and isinstance(insert_block, (bytes, bytearray, BinaryIO)):
  256. insert_block = (query + '\n').encode() + insert_block
  257. else:
  258. params['query'] = query
  259. if self.database:
  260. params['database'] = self.database
  261. params.update(self._validate_settings(settings or {}))
  262. response = self._raw_request(insert_block, params, headers, server_wait=False)
  263. logger.debug('Raw insert response code: %d, content: %s', response.status, response.data)
  264. return QuerySummary(self._summary(response))
  265. @staticmethod
  266. def _summary(response: HTTPResponse):
  267. summary = {}
  268. if 'X-ClickHouse-Summary' in response.headers:
  269. try:
  270. summary = json.loads(response.headers['X-ClickHouse-Summary'])
  271. except json.JSONDecodeError:
  272. pass
  273. summary['query_id'] = response.headers.get('X-ClickHouse-Query-Id', '')
  274. return summary
  275. def command(self,
  276. cmd,
  277. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  278. data: Union[str, bytes] = None,
  279. settings: Optional[Dict] = None,
  280. use_database: int = True,
  281. external_data: Optional[ExternalData] = None) -> Union[str, int, Sequence[str], QuerySummary]:
  282. """
  283. See BaseClient doc_string for this method
  284. """
  285. cmd, params = bind_query(cmd, parameters, self.server_tz)
  286. headers = {}
  287. payload = None
  288. fields = None
  289. if external_data:
  290. if data:
  291. raise ProgrammingError('Cannot combine command data with external data') from None
  292. fields = external_data.form_data
  293. params.update(external_data.query_params)
  294. elif isinstance(data, str):
  295. headers['Content-Type'] = 'text/plain; charset=utf-8'
  296. payload = data.encode()
  297. elif isinstance(data, bytes):
  298. headers['Content-Type'] = 'application/octet-stream'
  299. payload = data
  300. if payload is None and not cmd:
  301. raise ProgrammingError('Command sent without query or recognized data') from None
  302. if payload or fields:
  303. params['query'] = cmd
  304. else:
  305. payload = cmd
  306. if use_database and self.database:
  307. params['database'] = self.database
  308. params.update(self._validate_settings(settings or {}))
  309. method = 'POST' if payload or fields else 'GET'
  310. response = self._raw_request(payload, params, headers, method, fields=fields)
  311. if response.data:
  312. try:
  313. result = response.data.decode()[:-1].split('\t')
  314. if len(result) == 1:
  315. try:
  316. return int(result[0])
  317. except ValueError:
  318. return result[0]
  319. return result
  320. except UnicodeDecodeError:
  321. return str(response.data)
  322. return QuerySummary(self._summary(response))
  323. def _error_handler(self, response: HTTPResponse, retried: bool = False) -> None:
  324. err_str = f'HTTPDriver for {self.url} returned response code {response.status})'
  325. try:
  326. err_content = get_response_data(response)
  327. except Exception: # pylint: disable=broad-except
  328. err_content = None
  329. finally:
  330. response.close()
  331. if err_content:
  332. err_msg = common.format_error(err_content.decode(errors='backslashreplace'))
  333. err_str = f':{err_str}\n {err_msg}'
  334. raise OperationalError(err_str) if retried else DatabaseError(err_str) from None
  335. def _raw_request(self,
  336. data,
  337. params: Dict[str, str],
  338. headers: Optional[Dict[str, Any]] = None,
  339. method: str = 'POST',
  340. retries: int = 0,
  341. stream: bool = False,
  342. server_wait: bool = True,
  343. fields: Optional[Dict[str, tuple]] = None,
  344. error_handler: Callable = None) -> HTTPResponse:
  345. if isinstance(data, str):
  346. data = data.encode()
  347. headers = dict_copy(self.headers, headers)
  348. attempts = 0
  349. if server_wait:
  350. params['wait_end_of_query'] = '1'
  351. # We can't actually read the progress headers, but we enable them so ClickHouse sends something
  352. # to keep the connection alive when waiting for long-running queries and (2) to get summary information
  353. # if not streaming
  354. if self._send_progress:
  355. params['send_progress_in_http_headers'] = '1'
  356. if self._progress_interval:
  357. params['http_headers_progress_interval_ms'] = self._progress_interval
  358. final_params = dict_copy(self.params, params)
  359. url = f'{self.url}?{urlencode(final_params)}'
  360. kwargs = {
  361. 'headers': headers,
  362. 'timeout': self.timeout,
  363. 'retries': self.http_retries,
  364. 'preload_content': not stream
  365. }
  366. if self.server_host_name:
  367. kwargs['assert_same_host'] = False
  368. kwargs['headers'].update({'Host': self.server_host_name})
  369. if fields:
  370. kwargs['fields'] = fields
  371. else:
  372. kwargs['body'] = data
  373. check_conn_reset(self.http)
  374. query_session = final_params.get('session_id')
  375. while True:
  376. attempts += 1
  377. if query_session:
  378. if query_session == self._active_session:
  379. raise ProgrammingError('Attempt to execute concurrent queries within the same session.' +
  380. 'Please use a separate client instance per thread/process.')
  381. # There is a race condition here when using multiprocessing -- in that case the server will
  382. # throw an error instead, but in most cases this more helpful error will be thrown first
  383. self._active_session = query_session
  384. try:
  385. response = self.http.request(method, url, **kwargs)
  386. except HTTPError as ex:
  387. if isinstance(ex.__context__, ConnectionResetError):
  388. # The server closed the connection, probably because the Keep Alive has expired
  389. # We should be safe to retry, as ClickHouse should not have processed anything on a connection
  390. # that it killed. We also only retry this once, as multiple disconnects are unlikely to be
  391. # related to the Keep Alive settings
  392. if attempts == 1:
  393. logger.debug('Retrying remotely closed connection')
  394. continue
  395. logger.warning('Unexpected Http Driver Exception')
  396. raise OperationalError(f'Error {ex} executing HTTP request attempt {attempts} {self.url}') from ex
  397. finally:
  398. if query_session:
  399. self._active_session = None # Make sure we always clear this
  400. if 200 <= response.status < 300:
  401. return response
  402. if response.status in (429, 503, 504):
  403. if attempts > retries:
  404. self._error_handler(response, True)
  405. logger.debug('Retrying requests with status code %d', response.status)
  406. elif error_handler:
  407. error_handler(response)
  408. else:
  409. self._error_handler(response)
  410. def ping(self):
  411. """
  412. See BaseClient doc_string for this method
  413. """
  414. try:
  415. response = self.http.request('GET', f'{self.url}/ping', timeout=3)
  416. return 200 <= response.status < 300
  417. except HTTPError:
  418. logger.debug('ping failed', exc_info=True)
  419. return False
  420. def raw_query(self, query: str,
  421. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  422. settings: Optional[Dict[str, Any]] = None, fmt: str = None,
  423. use_database: bool = True, external_data: Optional[ExternalData] = None) -> bytes:
  424. """
  425. See BaseClient doc_string for this method
  426. """
  427. final_query, bind_params = bind_query(query, parameters, self.server_tz)
  428. if fmt:
  429. final_query += f'\n FORMAT {fmt}'
  430. params = self._validate_settings(settings or {})
  431. if use_database and self.database:
  432. params['database'] = self.database
  433. params.update(bind_params)
  434. if external_data:
  435. body = bytes()
  436. params['query'] = final_query
  437. params.update(external_data.query_params)
  438. fields = external_data.form_data
  439. else:
  440. body = final_query
  441. fields = None
  442. return self._raw_request(body, params, fields=fields).data
  443. def close(self):
  444. if self._owns_pool_manager:
  445. self.http.clear()
  446. all_managers.pop(self.http, None)