| {"repo": "emlid/ntripbrowser", "pull_number": 11, "instance_id": "emlid__ntripbrowser-11", "issue_numbers": "", "base_commit": "f4eab93ae9f246ca0d5ec35dce14a026118e0433", "patch": "diff --git a/ntripbrowser/__init__.py b/ntripbrowser/__init__.py\n--- a/ntripbrowser/__init__.py\n+++ b/ntripbrowser/__init__.py\n@@ -1,8 +1,8 @@\n from .ntripbrowser import NtripBrowser\n-from .exceptions import (NtripbrowserError, ExceededTimeoutError, NoDataFoundOnPage,\n- NoDataReceivedFromCaster, UnableToConnect, HandshakeFiledError)\n+from .exceptions import (NtripbrowserError, ExceededTimeoutError, NoDataReceivedFromCaster,\n+ UnableToConnect)\n from .constants import STR_HEADERS, NET_HEADERS, CAS_HEADERS\n \n __all__ = ['NtripBrowser', 'NtripbrowserError', 'ExceededTimeoutError',\n- 'NoDataFoundOnPage', 'NoDataReceivedFromCaster', 'UnableToConnect', 'HandshakeFiledError',\n+ 'NoDataReceivedFromCaster', 'UnableToConnect',\n 'STR_HEADERS', 'NET_HEADERS', 'CAS_HEADERS']\ndiff --git a/ntripbrowser/browser.py b/ntripbrowser/browser.py\n--- a/ntripbrowser/browser.py\n+++ b/ntripbrowser/browser.py\n@@ -5,7 +5,7 @@\n from texttable import Texttable\n \n from ntripbrowser import NtripBrowser\n-from ntripbrowser import ExceededTimeoutError, UnableToConnect, NoDataReceivedFromCaster, HandshakeFiledError\n+from ntripbrowser import ExceededTimeoutError, UnableToConnect, NoDataReceivedFromCaster\n from ntripbrowser import CAS_HEADERS, STR_HEADERS, NET_HEADERS\n \n \n@@ -80,7 +80,5 @@ def main():\n print('Unable to connect to NTRIP caster')\n except NoDataReceivedFromCaster:\n print('No data received from NTRIP caster')\n- except HandshakeFiledError:\n- print('Unable to connect to NTRIP caster, handshake error')\n else:\n display_ntrip_table(ntrip_table)\ndiff --git a/ntripbrowser/constants.py b/ntripbrowser/constants.py\n--- a/ntripbrowser/constants.py\n+++ b/ntripbrowser/constants.py\n@@ -14,3 +14,5 @@\n PYCURL_CONNECTION_FAILED_ERRNO = 7\n PYCURL_TIMEOUT_ERRNO = 28\n PYCURL_HANDSHAKE_ERRNO = 35\n+\n+MULTICURL_SELECT_TIMEOUT = 0.5\ndiff --git a/ntripbrowser/exceptions.py b/ntripbrowser/exceptions.py\n--- a/ntripbrowser/exceptions.py\n+++ b/ntripbrowser/exceptions.py\n@@ -10,13 +10,5 @@ class ExceededTimeoutError(NtripbrowserError):\n pass\n \n \n-class NoDataFoundOnPage(NtripbrowserError):\n- pass\n-\n-\n-class HandshakeFiledError(NtripbrowserError):\n- pass\n-\n-\n class NoDataReceivedFromCaster(NtripbrowserError):\n pass\ndiff --git a/ntripbrowser/ntripbrowser.py b/ntripbrowser/ntripbrowser.py\n--- a/ntripbrowser/ntripbrowser.py\n+++ b/ntripbrowser/ntripbrowser.py\n@@ -32,8 +32,8 @@\n import logging\n from geopy.distance import geodesic\n \n-import chardet\n import pycurl\n+import cchardet\n \n try:\n from io import BytesIO # Python 3\n@@ -41,15 +41,140 @@\n from StringIO import StringIO as BytesIO # Python 2\n \n from .constants import (CAS_HEADERS, STR_HEADERS, NET_HEADERS, PYCURL_TIMEOUT_ERRNO,\n- PYCURL_COULD_NOT_RESOLVE_HOST_ERRNO, PYCURL_CONNECTION_FAILED_ERRNO,\n- PYCURL_HANDSHAKE_ERRNO)\n-from .exceptions import (ExceededTimeoutError, UnableToConnect, NoDataFoundOnPage,\n- NoDataReceivedFromCaster, HandshakeFiledError)\n+ MULTICURL_SELECT_TIMEOUT)\n+from .exceptions import (ExceededTimeoutError, UnableToConnect, NoDataReceivedFromCaster)\n \n \n logger = logging.getLogger(__name__)\n \n \n+class DataFetcher(object):\n+ \"\"\"Fetch data from specified urls, execute custom callback on results.\n+\n+ Parameters\n+ ----------\n+ urls : [str, str, ...]\n+ URL's to fetch data from.\n+ timeout : int\n+ parser_method : callable\n+ Custom callback to be executed on fetched from url's results.\n+\n+ Attributes\n+ ----------\n+ urls_processed : [str, str, ...]\n+ URL's which are processed and on which no valid data was found.\n+\n+ result :\n+ Return value of `parser_method` function or None.\n+ \"\"\"\n+ def __init__(self, urls, timeout, parser_method):\n+ self.timeout = timeout\n+ self.urls = urls\n+ self._parser_method = parser_method\n+ self.urls_processed = []\n+ self.results = None\n+ self._multicurl = None\n+ self._buffers = {}\n+ self._curls_failed = []\n+\n+ @property\n+ def curls(self):\n+ return self._buffers.keys()\n+\n+ @property\n+ def _result_found(self):\n+ return bool(self.results)\n+\n+ def setup(self):\n+ self.urls_processed = []\n+ self.results = None\n+ self._multicurl = pycurl.CurlMulti()\n+ self._buffers = {}\n+ self._curls_failed = []\n+ self._initialize()\n+ logger.info('DataFetcher: curls setup in process')\n+ for curl in self.curls:\n+ self._multicurl.add_handle(curl)\n+\n+ def _initialize(self):\n+ for url in self.urls:\n+ logger.debug('DataFetcher: Buffered curl creation for url \"%s\" in process', url)\n+ buffer = BytesIO()\n+ curl = pycurl.Curl()\n+ curl.setopt(pycurl.URL, url)\n+ curl.setopt(pycurl.TIMEOUT, self.timeout)\n+ curl.setopt(pycurl.CONNECTTIMEOUT, self.timeout)\n+ curl.setopt(pycurl.WRITEFUNCTION, buffer.write)\n+ curl.setopt(pycurl.WRITEDATA, buffer)\n+ self._buffers.update({curl: buffer})\n+\n+ def read_data(self):\n+ while not self._result_found:\n+ ret, num_handles = self._multicurl.perform()\n+ if ret != pycurl.E_CALL_MULTI_PERFORM:\n+ break\n+\n+ while num_handles:\n+ self._multicurl.select(MULTICURL_SELECT_TIMEOUT)\n+ while not self._result_found:\n+ ret, num_handles = self._multicurl.perform()\n+ self._read_multicurl_info()\n+ if self._result_found:\n+ return\n+ if ret != pycurl.E_CALL_MULTI_PERFORM:\n+ break\n+ self._process_fetch_failure()\n+\n+ def _read_multicurl_info(self):\n+ _, successful_curls, failed_curls = self._multicurl.info_read()\n+ self._curls_failed.extend(failed_curls)\n+ for curl in successful_curls:\n+ self._process_successful_curl(curl)\n+ if self._result_found:\n+ return\n+\n+ def _process_successful_curl(self, curl):\n+ curl_results = self._buffers[curl].getvalue()\n+ url_processed = curl.getinfo(pycurl.EFFECTIVE_URL)\n+ self.urls_processed.append(url_processed)\n+ logger.info('DataFetcher: Trying to parse curl response from \"%s\"', url_processed)\n+ try:\n+ self.results = self._parser_method(curl_results)\n+ logger.info('DataFetcher: Results from \"%s\" is processed successfully', url_processed)\n+ except NoDataReceivedFromCaster:\n+ self.results = None\n+ logger.info('DataFetcher: No valid data found in curl response from \"%s\"', url_processed)\n+\n+ def _process_fetch_failure(self):\n+ \"\"\"- If the number of processed URL's is equal to the number of URL's\n+ which are requested to poll, this means that no data received from casters.\n+ - If in failed curls list timeout error exist, use it as a fail reason.\n+ - If no curls with exceeded timeout are found, throw UnableToConnect\n+ with first failed curl reason.\n+ - Otherwise, there are no failed curls and all curls which are succeeds\n+ received no data from the caster, so throw a NoDataReceivedFromCaster.\n+ \"\"\"\n+ logger.info('DataFetcher: No valid result is received')\n+ if len(self.urls_processed) == len(self.urls):\n+ raise NoDataReceivedFromCaster()\n+ for _, error_code, error_text in self._curls_failed:\n+ if error_code == PYCURL_TIMEOUT_ERRNO:\n+ raise ExceededTimeoutError(error_text)\n+ if self._curls_failed:\n+ _, _, error_text = self._curls_failed[0]\n+ raise UnableToConnect(error_text)\n+ raise NoDataReceivedFromCaster()\n+\n+ def teardown(self):\n+ for curl in self.curls:\n+ self._multicurl.remove_handle(curl)\n+ self._multicurl.close()\n+ for curl in self.curls:\n+ curl.close()\n+ logger.info('DataFetcher: Curls are closed succesfully')\n+ self._buffers = {}\n+\n+\n class NtripBrowser(object):\n def __init__(self, host, port=2101, timeout=4, # pylint: disable-msg=too-many-arguments\n coordinates=None, maxdist=None):\n@@ -59,6 +184,7 @@ def __init__(self, host, port=2101, timeout=4, # pylint: disable-msg=too-many-a\n self.timeout = timeout\n self.coordinates = coordinates\n self.maxdist = maxdist\n+ self._fetcher = DataFetcher(self.urls, self.timeout, self._process_raw_data)\n \n @property\n def host(self):\n@@ -79,42 +205,10 @@ def urls(self):\n return [http_url, http_sourcetable_url, https_url, https_sourcetable_url]\n \n def get_mountpoints(self):\n- for url in self.urls:\n- logger.debug('Trying to read NTRIP data from %s', url)\n- raw_data = self._read_data(url)\n- try:\n- return self._process_raw_data(raw_data)\n- except NoDataFoundOnPage:\n- logger.info('No data found on the %s', url)\n-\n- raise NoDataReceivedFromCaster()\n-\n- def _read_data(self, url):\n- buffer = BytesIO()\n- curl = pycurl.Curl()\n- curl.setopt(pycurl.URL, url)\n- curl.setopt(pycurl.TIMEOUT, self.timeout)\n- curl.setopt(pycurl.CONNECTTIMEOUT, self.timeout)\n- curl.setopt(pycurl.WRITEDATA, buffer)\n- self._perform_data_reading(curl)\n- return buffer.getvalue()\n-\n- @staticmethod\n- def _perform_data_reading(curl):\n- try:\n- curl.perform()\n- except pycurl.error as error:\n- errno = error.args[0]\n- errstr = error.args[1]\n- if errno in (PYCURL_COULD_NOT_RESOLVE_HOST_ERRNO, PYCURL_CONNECTION_FAILED_ERRNO):\n- raise UnableToConnect(errstr)\n- if errno == PYCURL_TIMEOUT_ERRNO:\n- raise ExceededTimeoutError(errstr)\n- if errno == PYCURL_HANDSHAKE_ERRNO:\n- raise HandshakeFiledError()\n- logger.error('pycurl.error(%s) while reading data from url: %s', errno, errstr)\n- finally:\n- curl.close()\n+ self._fetcher.setup()\n+ self._fetcher.read_data()\n+ self._fetcher.teardown()\n+ return self._fetcher.results\n \n def _process_raw_data(self, raw_data):\n decoded_raw_ntrip = self._decode_data(raw_data)\n@@ -125,13 +219,13 @@ def _process_raw_data(self, raw_data):\n \n @staticmethod\n def _decode_data(data):\n- data_encoding = chardet.detect(data)['encoding']\n+ data_encoding = cchardet.detect(data)['encoding']\n return data.decode('utf8' if not data_encoding else data_encoding)\n \n def _get_ntrip_tables(self, data):\n ntrip_tables = self._extract_ntrip_entry_strings(data)\n if not any(ntrip_tables):\n- raise NoDataFoundOnPage()\n+ raise NoDataReceivedFromCaster()\n return ntrip_tables\n \n @staticmethod\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -2,11 +2,11 @@\n \n setup(\n name='ntripbrowser',\n- version='2.1.0',\n+ version='2.2.0',\n author='Andrew Yushkevich, Alexander Yashin',\n author_email='andrew.yushkevich@emlid.com, alexandr.yashin@emlid.com',\n packages=['ntripbrowser'],\n- install_requires=['chardet', 'geopy>=1.14', 'texttable', 'pager', 'pycurl', 'cachecontrol>=0.12.4'],\n+ install_requires=['cchardet>=2.1.4', 'geopy>=1.14', 'texttable', 'pager', 'pycurl', 'cachecontrol>=0.12.4'],\n tests_requires=['pytest', 'mock', 'tox'],\n license='BSD-3-Clause',\n url='https://github.com/emlid/ntripbrowser.git',\n", "test_patch": "diff --git a/tests/test_ntripbrowser.py b/tests/test_ntripbrowser.py\n--- a/tests/test_ntripbrowser.py\n+++ b/tests/test_ntripbrowser.py\n@@ -1,9 +1,8 @@\n import pytest\n-from mock import patch\n from collections import namedtuple\n \n from ntripbrowser import (NtripBrowser, UnableToConnect, ExceededTimeoutError,\n- NoDataReceivedFromCaster, HandshakeFiledError)\n+ NoDataReceivedFromCaster)\n import testing_content\n \n \n@@ -22,7 +21,7 @@ def run_caster_test(caster):\n browser = NtripBrowser(caster.url, caster.port)\n try:\n browser.get_mountpoints()\n- except (UnableToConnect, ExceededTimeoutError, HandshakeFiledError):\n+ except (UnableToConnect, ExceededTimeoutError):\n pass\n \n \n@@ -81,17 +80,15 @@ def test_reassign_parameters():\n ] == browser.urls\n \n \n-@patch.object(NtripBrowser, '_read_data', lambda self, url: b'<Some invalid NTRIP data>')\n def test_invalid_data():\n browser = NtripBrowser('example', 1234)\n with pytest.raises(NoDataReceivedFromCaster):\n- browser.get_mountpoints()\n+ browser._process_raw_data(b'<Some invalid NTRIP data>')\n \n \n-@patch.object(NtripBrowser, '_read_data', lambda self, url: testing_content.VALID_NET_NTRIP)\n def test_valid_net_data():\n browser = NtripBrowser('test', 1234)\n- assert browser.get_mountpoints() == {\n+ assert browser._process_raw_data(testing_content.VALID_NET_NTRIP) == {\n 'cas': [],\n 'net': [\n {\n@@ -110,10 +107,9 @@ def test_valid_net_data():\n }\n \n \n-@patch.object(NtripBrowser, '_read_data', lambda self, url: testing_content.VALID_STR_NTRIP)\n def test_valid_str_data():\n browser = NtripBrowser('test', 1234)\n- assert browser.get_mountpoints() == {\n+ assert browser._process_raw_data(testing_content.VALID_STR_NTRIP) == {\n 'cas': [],\n 'net': [],\n 'str': [\n@@ -132,10 +128,9 @@ def test_valid_str_data():\n }\n \n \n-@patch.object(NtripBrowser, '_read_data', lambda self, url: testing_content.VALID_CAS_NTRIP)\n def test_valid_cas_data():\n browser = NtripBrowser('test', 1234)\n- assert browser.get_mountpoints() == {\n+ assert browser._process_raw_data(testing_content.VALID_CAS_NTRIP) == {\n 'cas': [\n {\n 'Country': 'Null',\n@@ -157,10 +152,9 @@ def test_valid_cas_data():\n }\n \n \n-@patch.object(NtripBrowser, '_read_data', lambda self, url: testing_content.VALID_NTRIP)\n def test_valid_data():\n browser = NtripBrowser('test', 1234)\n- assert browser.get_mountpoints() == {\n+ assert browser._process_raw_data(testing_content.VALID_NTRIP) == {\n 'cas': [\n {\n 'Country': 'Null',\n@@ -206,10 +200,9 @@ def test_valid_data():\n }\n \n \n-@patch.object(NtripBrowser, '_read_data', lambda self, url: testing_content.VALID_NTRIP)\n def test_add_coordinates():\n browser = NtripBrowser('test', 1234, coordinates=(1.0, 2.0))\n- assert browser.get_mountpoints() == {\n+ assert browser._process_raw_data(testing_content.VALID_NTRIP) == {\n 'cas': [\n {\n 'Country': 'Null',\n", "problem_statement": "", "hints_text": "", "created_at": "2019-08-15T13:36:26Z"} | |