|
1 | 1 | # -*- coding: utf-8 -*- |
2 | 2 | import logging |
3 | | -import socket |
| 3 | +import os |
4 | 4 |
|
5 | | -from elasticapm.conf import defaults |
6 | | -from elasticapm.contrib.async_worker import AsyncWorker |
7 | | -from elasticapm.transport.base import (AsyncTransport, Transport, |
8 | | - TransportException) |
9 | | -from elasticapm.utils.compat import HTTPError |
10 | | - |
11 | | -try: |
12 | | - from urllib2 import Request, urlopen |
13 | | -except ImportError: |
14 | | - from urllib.request import Request, urlopen |
| 5 | +import certifi |
| 6 | +import urllib3 |
| 7 | +from urllib3.exceptions import MaxRetryError, TimeoutError |
15 | 8 |
|
| 9 | +from elasticapm.conf import defaults |
| 10 | +from elasticapm.transport.base import TransportException |
| 11 | +from elasticapm.transport.http_base import (AsyncHTTPTransportBase, |
| 12 | + HTTPTransportBase) |
| 13 | +from elasticapm.utils import compat |
16 | 14 |
|
17 | | -logger = logging.getLogger('elasticapm') |
| 15 | +logger = logging.getLogger(__name__) |
18 | 16 |
|
19 | 17 |
|
20 | | -class HTTPTransport(Transport): |
| 18 | +class Transport(HTTPTransportBase): |
21 | 19 |
|
22 | 20 | scheme = ['http', 'https'] |
23 | 21 |
|
24 | 22 | def __init__(self, parsed_url): |
25 | | - self.check_scheme(parsed_url) |
26 | | - |
27 | | - self._parsed_url = parsed_url |
28 | | - self._url = parsed_url.geturl() |
| 23 | + kwargs = { |
| 24 | + 'cert_reqs': 'CERT_REQUIRED', |
| 25 | + 'ca_certs': certifi.where(), |
| 26 | + 'block': True, |
| 27 | + } |
| 28 | + proxy_url = os.environ.get('HTTPS_PROXY', os.environ.get('HTTP_PROXY')) |
| 29 | + if proxy_url: |
| 30 | + self.http = urllib3.ProxyManager(proxy_url, **kwargs) |
| 31 | + else: |
| 32 | + self.http = urllib3.PoolManager(**kwargs) |
| 33 | + super(Transport, self).__init__(parsed_url) |
29 | 34 |
|
30 | 35 | def send(self, data, headers, timeout=None): |
31 | | - """ |
32 | | - Sends a request to a remote webserver using HTTP POST. |
33 | | -
|
34 | | - Returns the shortcut URL of the recorded error on Elastic APM |
35 | | - """ |
36 | | - req = Request(self._url, headers=headers) |
37 | 36 | if timeout is None: |
38 | 37 | timeout = defaults.TIMEOUT |
39 | 38 | response = None |
| 39 | + |
| 40 | + # ensure headers are byte strings |
| 41 | + headers = {k.encode('ascii') if isinstance(k, compat.text_type) else k: |
| 42 | + v.encode('ascii') if isinstance(v, compat.text_type) else v |
| 43 | + for k, v in headers.items()} |
| 44 | + if compat.PY2 and isinstance(self._url, compat.text_type): |
| 45 | + url = self._url.encode('utf-8') |
| 46 | + else: |
| 47 | + url = self._url |
40 | 48 | try: |
41 | 49 | try: |
42 | | - response = urlopen(req, data, timeout) |
43 | | - except TypeError: |
44 | | - response = urlopen(req, data) |
45 | | - except Exception as e: |
46 | | - print_trace = True |
47 | | - if isinstance(e, socket.timeout): |
48 | | - message = ( |
49 | | - "Connection to APM Server timed out " |
50 | | - "(url: %s, timeout: %d seconds)" % (self._url, timeout) |
| 50 | + response = self.http.urlopen( |
| 51 | + 'POST', url, body=data, headers=headers, timeout=timeout, preload_content=False |
51 | 52 | ) |
52 | | - elif isinstance(e, HTTPError): |
53 | | - body = e.read() |
54 | | - if e.code == 429: # rate-limited |
| 53 | + logger.info('Sent request, url=%s size=%.2fkb status=%s', url, len(data) / 1024.0, response.status) |
| 54 | + except Exception as e: |
| 55 | + print_trace = True |
| 56 | + if isinstance(e, MaxRetryError) and isinstance(e.reason, TimeoutError): |
| 57 | + message = ( |
| 58 | + "Connection to APM Server timed out " |
| 59 | + "(url: %s, timeout: %d seconds)" % (self._url, timeout) |
| 60 | + ) |
| 61 | + print_trace = False |
| 62 | + else: |
| 63 | + message = 'Unable to reach APM Server: %s (url: %s)' % ( |
| 64 | + e, self._url |
| 65 | + ) |
| 66 | + raise TransportException(message, data, print_trace=print_trace) |
| 67 | + body = response.read() |
| 68 | + if response.status >= 400: |
| 69 | + if response.status == 429: # rate-limited |
55 | 70 | message = 'Temporarily rate limited: ' |
56 | 71 | print_trace = False |
57 | 72 | else: |
58 | | - message = 'Unable to reach APM Server: ' |
59 | | - message += '%s (url: %s, body: %s)' % (e, self._url, body) |
60 | | - else: |
61 | | - message = 'Unable to reach APM Server: %s (url: %s)' % ( |
62 | | - e, self._url |
63 | | - ) |
64 | | - raise TransportException(message, data, print_trace=print_trace) |
| 73 | + message = 'HTTP %s: ' % response.status |
| 74 | + print_trace = True |
| 75 | + message += body.decode('utf8') |
| 76 | + raise TransportException(message, data, print_trace=print_trace) |
| 77 | + return response.getheader('Location') |
65 | 78 | finally: |
66 | 79 | if response: |
67 | 80 | response.close() |
68 | 81 |
|
69 | | - return response.info().get('Location') |
70 | 82 |
|
71 | | - |
72 | | -class AsyncHTTPTransport(AsyncTransport, HTTPTransport): |
| 83 | +class AsyncTransport(AsyncHTTPTransportBase, Transport): |
73 | 84 | scheme = ['http', 'https'] |
74 | 85 | async_mode = True |
75 | | - |
76 | | - def __init__(self, parsed_url): |
77 | | - super(AsyncHTTPTransport, self).__init__(parsed_url) |
78 | | - if self._url.startswith('async+'): |
79 | | - self._url = self._url[6:] |
80 | | - self._worker = None |
81 | | - |
82 | | - @property |
83 | | - def worker(self): |
84 | | - if not self._worker or not self._worker.is_alive(): |
85 | | - self._worker = AsyncWorker() |
86 | | - return self._worker |
87 | | - |
88 | | - def send_sync(self, data=None, headers=None, success_callback=None, |
89 | | - fail_callback=None): |
90 | | - try: |
91 | | - url = HTTPTransport.send(self, data, headers) |
92 | | - if callable(success_callback): |
93 | | - success_callback(url=url) |
94 | | - except Exception as e: |
95 | | - if callable(fail_callback): |
96 | | - fail_callback(exception=e) |
97 | | - |
98 | | - def send_async(self, data, headers, success_callback=None, |
99 | | - fail_callback=None): |
100 | | - kwargs = { |
101 | | - 'data': data, |
102 | | - 'headers': headers, |
103 | | - 'success_callback': success_callback, |
104 | | - 'fail_callback': fail_callback, |
105 | | - } |
106 | | - self.worker.queue(self.send_sync, kwargs) |
107 | | - |
108 | | - def close(self): |
109 | | - if self._worker: |
110 | | - self._worker.main_thread_terminated() |
| 86 | + sync_transport = Transport |
0 commit comments